From rustompmody at gmail.com Sun Jul 1 00:07:50 2012 From: rustompmody at gmail.com (rusi) Date: Sat, 30 Jun 2012 21:07:50 -0700 (PDT) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4f137ec3-1906-4119-ad69-9780714ce63d@po9g2000pbb.googlegroups.com> On Jul 1, 8:23?am, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 10:37:05 +1000, Chris Angelico wrote: > > On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney > > wrote: > >> Thomas Jollans writes: > > >>> My sole point, really, is that "normally", one would expect these two > >>> expressions to be equivalent: > > >>> a < b < c > >>> (a < b) < c > > >> What norm gives you that expectation? That's not how those operators > >> work in mathematical notation. I know of no programming language that > >> would give a newcomer to Python that expectation. So where is the norm > >> you're referring to? > > > C, SQL, REXX, and many other languages. > > All the worse for those languages, since they violate the semantics of > mathematical notation. > > The more I learn about C, the less I want to know about C. What sort of > crazy language designer thought that having > > 2 == 2 == 2 > > return 0 (false) was a good idea? Kernighan and Ritchie admit they made a design mistake with their operator precedences: http://en.wikipedia.org/wiki/C_%28programming_language%29#Criticism That those mistakes are repeated and replicated is more unfortunate. The second bullet above to be read along with http://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Assignment_versus_equality From steve+comp.lang.python at pearwood.info Sun Jul 1 00:17:54 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Jul 2012 04:17:54 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 12:20:52 +1000, Chris Angelico wrote: > On Sun, Jul 1, 2012 at 12:06 PM, Steven D'Aprano > wrote: >> You can't just arbitrarily stick parentheses around parts of >> expressions and expect the result to remain unchanged. Order of >> evaluation matters: >> >> 2**3**4 != (2**3)**4 > > But that's because ** binds right to left. It _is_ valid to say: > > 2**3**4 = 2**(3**4) Yes, but my point is that you can't just add parentheses arbitrarily without understanding what you're doing. If you're used to some feeble $2 calculator that doesn't implement operator precedence, you might expect that you could do this too: 1+2*3 (1+2)*3 But you can't. It's your expectations that are skewed, not Python. If you (generic you) are used to some feeble $2 language that doesn't implement chained comparisons, it is your expectations that are skewed, not Python. Comparisons were invented long before C, or even computers, and they have had chained semantics long before Python. Languages like C force you to unlearn the standard semantics of comparisons, and substitute something that is less expressive, less powerful, less efficient, and more likely to contain a bug. This is almost always wrong in languages without chained comparisons: a < func(x) < b This is inefficient, and still wrong, if x has side-effects or isn't reentrant: a < func(x) and func(x) < b This is too verbose for such a simple comparison: tmp = func(x) (a < tmp) and (tmp < b) [...] > Everyone who knows algebra knows that the parens are optional, but > nobody would expect them to change the evaluation of the expression. Nonsense. Of course parens change the evaluation of the expression. That's what parens are for! There may be some specific cases where they don't, because you have happened to put them in a specially crafted position where they don't actually change the order of evaluation. E.g. putting parens around the entire expression, or putting them around a single atom, or around another pair of parentheses: 2*(3+4) => (2*(3+4)) # unchanged => (2)*(3+4) => 2*((3+4)) but just because there are *some* places you can add redundant parens doesn't mean that you can add them *anywhere*. You have to understand the semantics of expression, including the precedence rules. If you don't understand them, you might as well be just adding parens in random positions, in which case you should expect the semantics to change. [...] > (a > is, incidentally, a valid expression, as long as you accept that False > is less than True. Right. I'm not saying that there's never any need to evaluate a comparison, and then compare it to the result of another comparison. That's a perfectly valid thing to do. And you know what? You can do it, using parens, exactly as shown. Chained comparisons is the common case, it should have the simple syntax. That's why mathematicians write {x : a < x < b} instead of {x: a < x} ? {x: x < b}. The uncommon case, treating a bool as a value to be compared to another value, should be possible, which it is. -- Steven From rosuav at gmail.com Sun Jul 1 00:20:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 1 Jul 2012 14:20:57 +1000 Subject: code review In-Reply-To: <4f137ec3-1906-4119-ad69-9780714ce63d@po9g2000pbb.googlegroups.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4f137ec3-1906-4119-ad69-9780714ce63d@po9g2000pbb.googlegroups.com> Message-ID: On Sun, Jul 1, 2012 at 2:07 PM, rusi wrote: > Kernighan and Ritchie admit they made a design mistake with their > operator precedences: > > http://en.wikipedia.org/wiki/C_%28programming_language%29#Criticism > The examples given there have nothing to do with the chaining of comparisons and how it's to be interpreted. Yes, "x & 1 == 0" is evaluated oddly. Doesn't affect "x == 1 == y". Python's interpretation is more algebraic than C's. That doesn't mean that C is wrong and Python is right, nor does it mean the converse. ChrisA From rosuav at gmail.com Sun Jul 1 00:23:36 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 1 Jul 2012 14:23:36 +1000 Subject: code review In-Reply-To: <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 1, 2012 at 2:17 PM, Steven D'Aprano wrote: > Nonsense. Of course parens change the evaluation of the expression. > That's what parens are for! The whole point of my example was that it wouldn't. ChrisA From contropinion at gmail.com Sun Jul 1 00:25:57 2012 From: contropinion at gmail.com (contro opinion) Date: Sun, 1 Jul 2012 00:25:57 -0400 Subject: how to use tkinter in python3.2? Message-ID: tiger at ocean:~$ python3.2 Python 3.2.3 (default, Jul 1 2012, 11:07:14) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.2/tkinter/__init__.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> i have installed tk ,how to use tkinker in python3.2? in my computer ,i can use tkinter in python3 tiger at ocean:~$ python3 Python 3.1.3 (r313:86834, Nov 28 2010, 11:28:10) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>> what is the matter? -------------- next part -------------- An HTML attachment was scrubbed... URL: From driscoll at cs.wisc.edu Sun Jul 1 00:45:25 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Sat, 30 Jun 2012 23:45:25 -0500 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <4FEFD5E5.5060802@cs.wisc.edu> On 6/30/2012 19:37, Chris Angelico wrote: > On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney wrote: >> I know of no programming language that >> would give a newcomer to Python that expectation. So where is the norm >> you're referring to? > > C, SQL, REXX, and many other languages. Some others: Lua, Javascript, Ruby, O'Caml. In fact, the only language I can find that uses infix notation (i.e. no Lisp) where it's *not* true that "a < b < c" is equivalent to "(a < b) < c" is Haskell -- and that's because < is not associative and "a < b < c" is a syntax error. (FWIW this is my favorite approach.) You may also want to put Java in there as well, as < is effectively not commutative in that language. (I didn't try C#.) I've been programming in Python for a few years and this is the first time I've seen this. If I had seen that in a program, I'd have assumed it was a bug. Evan -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 552 bytes Desc: OpenPGP digital signature URL: From driscoll at cs.wisc.edu Sun Jul 1 00:57:36 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Sat, 30 Jun 2012 23:57:36 -0500 Subject: code review In-Reply-To: <4FEFD5E5.5060802@cs.wisc.edu> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4FEFD5E5.5060802@cs.wisc.edu> Message-ID: <4FEFD8C0.9090502@cs.wisc.edu> On 6/30/2012 23:45, Evan Driscoll wrote: > You may also > want to put Java in there as well, as < is effectively not commutative > in that language. (I didn't try C#.) I guess you could actually put Lua and Ruby into the roughly same category as Java too. But things get a little nastier in ==, as 'false == false == false' evaluates as '(false == false) == false' to 'false' in Java and Lua. (Ruby produces a syntax error for this, roughly the Haskell approach.) But we have Javascript: 1 < 1 < 2 => true false == false == false => false O'Caml: # false == false == false;; - : bool = false # 1 < 2 < true;; - : bool = false Java: System.out.println(false == false == false); (outputs) false Lua: > print(false == false == false) false C and C++: std::cout << (1 < 1 < 3) << "\n"; (outputs) 1 std::cout << (false == false == false) << "\n"; (outputs) 0 Evan -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 552 bytes Desc: OpenPGP digital signature URL: From tjreedy at udel.edu Sun Jul 1 01:23:25 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Jul 2012 01:23:25 -0400 Subject: how to use tkinter in python3.2? In-Reply-To: References: Message-ID: On 7/1/2012 12:25 AM, contro opinion wrote: I am on Windows, but... > tiger at ocean:~$ python3.2 > Python 3.2.3 (default, Jul 1 2012, 11:07:14) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import tkinter > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.2/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter _tkinter is the compiled C module that directly interfaces to tk. It is imported by the python module tkinter. For whatever reason, it was not compiled for your installation. Who did the compilation? > i have installed tk ,how to use tkinker in python3.2? > > in my computer ,i can use tkinter in python3 > tiger at ocean:~$ python3 > Python 3.1.3 (r313:86834, Nov 28 2010, 11:28:10) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import tkinter and who compiled that (correctly)? -- Terry Jan Reedy From steve+usenet at pearwood.info Sun Jul 1 02:27:37 2012 From: steve+usenet at pearwood.info (Steven D'Aprano) Date: 01 Jul 2012 06:27:37 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 14:23:36 +1000, Chris Angelico wrote: > On Sun, Jul 1, 2012 at 2:17 PM, Steven D'Aprano > wrote: >> Nonsense. Of course parens change the evaluation of the expression. >> That's what parens are for! > > The whole point of my example was that it wouldn't. Yes, you can find specially crafted examples where adding parentheses in certain places, but not others, doesn't change the overall evaluation of the expression. So what? IN GENERAL, adding parentheses changes the evaluation of the expression -- that is what they are for. Therefore, IN GENERAL you should expect that adding parentheses will change the result, unless you carefully place them where you know that they will have no effect. Even in C, I can't just do this: 2+3*4 => (2+3)*4 with the expectation that you can stick parentheses around the left-most term without changing the value. The fact that you can do for some expressions is irrelevant. In general, if you don't know the semantics of an expression (including the operator precedence), you cannot just assume that adding parens is harmless. -- Steven From rosuav at gmail.com Sun Jul 1 02:33:15 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 1 Jul 2012 16:33:15 +1000 Subject: code review In-Reply-To: <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 1, 2012 at 4:27 PM, Steven D'Aprano wrote: > Yes, you can find specially crafted examples where adding parentheses in > certain places, but not others, doesn't change the overall evaluation of > the expression. My point was that adding parentheses around the tightest-binding operator is a common, clear, and usually insignificant, way of demonstrating operator precedence. So FOR THAT USE they must not change evaluation of the expression. Obviously if you put them anywhere else, they change evaluation. Nice job knocking down a straw man. ChrisA From steve+comp.lang.python at pearwood.info Sun Jul 1 02:54:01 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Jul 2012 06:54:01 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 13:48:04 +1000, Chris Angelico wrote: > On Sun, Jul 1, 2012 at 1:23 PM, Steven D'Aprano > wrote: >> All the worse for those languages, since they violate the semantics of >> mathematical notation. > > Not so. It simply means that booleans are nothing special. In REXX, > there are no data types at all, and "1" and "0" are your booleans. In C, > boolean and comparison operations return integers, either 1 or 0. This has nothing to do with the presence of a Boolean type or not. It is about syntax, not types. Python didn't have bools until relatively recently but it still had chained comparisons. In Python2.1 and older, boolean and comparison operations return integers, either 1 or 0, precisely the same as C. You can even use chained comparisons for types that don't interpret the operators as comparisons: py> class Funny: ... def __init__(self, x): ... self.x = x ... def __lt__(self, other): ... return Funny(self.x + 3*other.x) ... def __str__(self): ... return str(self.x) ... py> a = Funny(2) py> b = Funny(3) py> c = Funny(4) py> py> print a < b < c 15 py> print (a < b) and (b < c) 15 Although the interpretation of such may not be useful. > Same > was true of Python early on, if I understand correctly. It's not > shameful. The first public release of Python, 0.9, included chained comparisons. This was even before the language had == for equality tests! steve at runes:~$ ./python0.9.1 >>> print 2 < 3 < 4 1 >>> print 2 = 2 = 2 1 >>> print (2 = 2) = 2 0 So no, Python has always included chained comparisons, and yes, it is shameful that a language would force you to unlearn standard notation in favour of a foolish consistency with other operators. Comparisons aren't special because they return bools. They are special because of the way they are used. C treats comparison operators as if they were arithmetic operators, and so the behaviour of a chained comparison is the same as the behaviour as a sequence of arithmetic operators: a foolish consistency. Python treats comparison operators as comparison operators, and gives them behaviour appropriate to comparisons. The fact that so many languages do the wrong thing here, and so few emulate standard mathematical notation, is symptomatic of the lousy state of language design. Pascal might be verbose, but at least it makes it harder to write code that silently does the wrong thing -- it prevents you from writing chained comparisons which do the wrong thing, and forces you to be explicit. C has the worst of both worlds: - it allows the standard concise mathematical notation a < x < b - but it quietly changes the semantics to something that the user hardly ever wants thus giving the maximum number of bugs with the minimum amount of convenience. >> The more I learn about C, the less I want to know about C. What sort of >> crazy language designer thought that having >> >> 2 == 2 == 2 >> >> return 0 (false) was a good idea? > > It makes perfect sense though; Not in English-speaking countries with a culture of writing chained comparisons in mathematics and allowing them in natural language: "Rock is beaten by Paper, is beaten by Scissors". -- Steven From PointedEars at web.de Sun Jul 1 02:57:04 2012 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 01 Jul 2012 08:57:04 +0200 Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <1922878.ANPrPdclya@PointedEars.de> Evan Driscoll wrote: > On 6/30/2012 19:37, Chris Angelico wrote: >> On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney >> wrote: >>> I know of no programming language that >>> would give a newcomer to Python that expectation. So where is the norm >>> you're referring to? >> >> C, SQL, REXX, and many other languages. > > Some others: Lua, Javascript, Ruby, O'Caml. JFTR: Contrary to popular belief there is no programming language named "Javascript". In your second point, you are talking about ECMAScript implementations; one of which is _JavaScript_, Netscape's and later Mozilla.org's ECMAScript implementation. Other implementations include that of Microsoft, JScript. -- PointedEars Please do not Cc: me. / Bitte keine Kopien per E-Mail. From rosuav at gmail.com Sun Jul 1 02:59:00 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 1 Jul 2012 16:59:00 +1000 Subject: code review In-Reply-To: <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 1, 2012 at 4:54 PM, Steven D'Aprano wrote: > Not in English-speaking countries with a culture of writing chained > comparisons in mathematics and allowing them in natural language: > > "Rock is beaten by Paper, is beaten by Scissors". I would write that as: Rock is beaten by Paper, and beats Scissors. That's natural language. Unless you put a "which" in the middle, the grammar of English demands that the subject be common, not a promoted object. ChrisA From PointedEars at web.de Sun Jul 1 03:04:22 2012 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 01 Jul 2012 09:04:22 +0200 Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4FEFD5E5.5060802@cs.wisc.edu> Message-ID: <2379377.kQmhC9yAxR@PointedEars.de> Evan Driscoll wrote: > On 6/30/2012 23:45, Evan Driscoll wrote: >> You may also >> want to put Java in there as well, as < is effectively not commutative >> in that language. (I didn't try C#.) > > I guess you could actually put Lua and Ruby into the roughly same > category as Java too. > > But things get a little nastier in ==, as 'false == false == false' > evaluates as '(false == false) == false' to 'false' in Java and Lua. > (Ruby produces a syntax error for this, roughly the Haskell approach.) > > But we have Javascript: s/Javascript/ECMAScript (implementations)/g > 1 < 1 < 2 > => true > false == false == false > => false Correct, because 0. 1 < 1 < 2 1. (1 < 1) < 2 2. false < 2 3. 0 < 2 4. true and 0. false == false == false 1. (false == false) == false 2. true == false 3. false See also the ECMAScript Language Specification, 5.1 Edition, section 11.9: -- PointedEars Please do not Cc: me. / Bitte keine Kopien per E-Mail. From ben+python at benfinney.id.au Sun Jul 1 03:28:20 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 01 Jul 2012 17:28:20 +1000 Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <87395cq6sr.fsf@benfinney.id.au> Chris Angelico writes: > On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney wrote: > > Thomas Jollans writes: > > > >> My sole point, really, is that "normally", one would expect these two > >> expressions to be equivalent: > >> > >> a < b < c > >> (a < b) < c > > > > What norm gives you that expectation? That's not how those operators > > work in mathematical notation. I know of no programming language > > that would give a newcomer to Python that expectation. So where is > > the norm you're referring to? > > C, SQL, REXX, and many other languages. So, languages without strong typing then. In that case, I revise my statement: I know of no programming language with strong typing that would give a newcomer to Python the above expectation. Since Python does have strong typing, norms about operations from weakly-typed languages should not be expected to apply. (Incidentally, PostgreSQL was the SQL implementation I went to, and:: postgres=# SELECT (1 < 2) < 3; ERROR: operator does not exist: boolean < integer LINE 1: SELECT (1 < 2) < 3; ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So not all SQL implementations make the mistake of weak typing.) -- \ ?Try adding ?as long as you don't breach the terms of service ? | `\ according to our sole judgement? to the end of any cloud | _o__) computing pitch.? ?Simon Phipps, 2010-12-11 | Ben Finney From t at jollybox.de Sun Jul 1 03:35:40 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 01 Jul 2012 09:35:40 +0200 Subject: code review In-Reply-To: <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FEFFDCC.5050907@jollybox.de> On 07/01/2012 04:06 AM, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote: > >> As soon as you read it as a ternary operator, > > Well that's your problem. Why are you reading it as a ternary operator? > It isn't one. It is a pair of chained binary operator. > > How can you tell that it is a pair of binary operators, rather than a > single ternary operator? > > 1) There are TWO operators, hence a pair, not a single ternary operator; > > 2) each operator takes TWO arguments, not three. This is simply wrong. The comparisons are not acting as binary operators. > You can't just arbitrarily stick parentheses around parts of expressions > and expect the result to remain unchanged. Order of evaluation matters: > > 2**3**4 != (2**3)**4 > > Comparisons are no different. You can't just toss in some arbitrary > brackets and expect the result to be the same. In the second case, the > parentheses explicitly turn the comparison into the equivalent of this: As Chris points out, 2**3**4 == 2**(3**4) For any chain of actual binary operators, it is possible to place brackets around binary sub-expressions such that the meaning of the total expression stays the same. This is true of ALL infix-notated strictly binary operators. This is not true of Python comparison operators. If you're inclined to look at operators in terms of how many arguments they take, then the inescapable conclusion is that a chain of N comparison operators forms one single (N+1)-term operator because it cannot be grouped into binary expressions without rephrasing the expression using "and". From t at jollybox.de Sun Jul 1 03:46:56 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 01 Jul 2012 09:46:56 +0200 Subject: code review In-Reply-To: <87395cq6sr.fsf@benfinney.id.au> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> Message-ID: <4FF00070.2030002@jollybox.de> On 07/01/2012 09:28 AM, Ben Finney wrote: > Chris Angelico writes: > >> On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney wrote: >>> Thomas Jollans writes: >>> >>>> My sole point, really, is that "normally", one would expect these two >>>> expressions to be equivalent: >>>> >>>> a < b < c >>>> (a < b) < c >>> >>> What norm gives you that expectation? That's not how those operators >>> work in mathematical notation. I know of no programming language >>> that would give a newcomer to Python that expectation. So where is >>> the norm you're referring to? >> >> C, SQL, REXX, and many other languages. > > So, languages without strong typing then. In that case, I revise my > statement: I know of no programming language with strong typing that > would give a newcomer to Python the above expectation. > > Since Python does have strong typing, norms about operations from > weakly-typed languages should not be expected to apply. > > (Incidentally, PostgreSQL was the SQL implementation I went to, and:: > > postgres=# SELECT (1 < 2) < 3; > ERROR: operator does not exist: boolean < integer > LINE 1: SELECT (1 < 2) < 3; > ^ > HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. > > So not all SQL implementations make the mistake of weak typing.) I don't have PostgeSQL handy just now - what is the result of (1 < 2 < 3) ? I bet it's the same error, which means the two are still equivalent. Look through the part of this thread about languages, and you will see how unique Python is in this regard. You argument about strong typing doesn't really hold: in Python, as in some other languages, bool is an integer type, so it can actually be compared to numbers, so even if Python used the same rules as Java, chaining comparison operators would still be valid syntax (if a little silly in most cases) From panceisto at gmail.com Sun Jul 1 05:13:23 2012 From: panceisto at gmail.com (Panceisto) Date: Sun, 1 Jul 2012 02:13:23 -0700 (PDT) Subject: changes made to my python coded com servers are not taking effect Message-ID: <613bbae0-2631-4b84-ba58-a7369a423a33@v15g2000yqi.googlegroups.com> I assume the old code keeps running in some process somewhere. How to fix this? From jeanpierreda at gmail.com Sun Jul 1 05:18:09 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 1 Jul 2012 05:18:09 -0400 Subject: code review In-Reply-To: <87395cq6sr.fsf@benfinney.id.au> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> Message-ID: On Sun, Jul 1, 2012 at 3:28 AM, Ben Finney wrote: > Chris Angelico writes: >> C, SQL, REXX, and many other languages. > > So, languages without strong typing then. In that case, I revise my > statement: I know of no programming language with strong typing that > would give a newcomer to Python the above expectation. OCaml is a language with absurdly strong typing, where a < b < c is equivalent to (a < b) < c. Obviously, this only works if c is a boolean, and if a and b are the same type. Otherwise it is a type error. Also, you claimed earlier that the notion of associative "<" is not founded in mathematical notation. It really depends on whose mathematical notation you use -- there's more than one, you know. For example, it's reasonable to expect < to be left- or right-associative in a system like Rick Hehner's Unified Algebra: http://www.cs.toronto.edu/~hehner/UA.pdf (although, he himself doesn't specify it as being one or the other, so by default one would assume 'a < b < c' to be nonsensical.) -- Devin From alister.ware at ntlworld.com Sun Jul 1 05:40:43 2012 From: alister.ware at ntlworld.com (Alister) Date: Sun, 01 Jul 2012 09:40:43 GMT Subject: changes made to my python coded com servers are not taking effect References: <613bbae0-2631-4b84-ba58-a7369a423a33@v15g2000yqi.googlegroups.com> Message-ID: On Sun, 01 Jul 2012 02:13:23 -0700, Panceisto wrote: > I assume the old code keeps running in some process somewhere. How to > fix this? stop & restart the servers after making the changes -- Smoking is the leading cause of statistics. From alister.ware at ntlworld.com Sun Jul 1 05:54:55 2012 From: alister.ware at ntlworld.com (Alister) Date: Sun, 01 Jul 2012 09:54:55 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: On Sat, 30 Jun 2012 23:45:25 -0500, Evan Driscoll wrote: > On 6/30/2012 19:37, Chris Angelico wrote: >> On Sun, Jul 1, 2012 at 10:08 AM, Ben Finney >> wrote: >>> I know of no programming language that would give a newcomer to Python >>> that expectation. So where is the norm you're referring to? >> >> C, SQL, REXX, and many other languages. > > Some others: Lua, Javascript, Ruby, O'Caml. > > In fact, the only language I can find that uses infix notation (i.e. no > Lisp) where it's *not* true that "a < b < c" is equivalent to "(a < b) < > c" is Haskell -- and that's because < is not associative and "a < b < c" > is a syntax error. (FWIW this is my favorite approach.) You may also > want to put Java in there as well, as < is effectively not commutative > in that language. (I didn't try C#.) > > I've been programming in Python for a few years and this is the first > time I've seen this. If I had seen that in a program, I'd have assumed > it was a bug. > > Evan You would? I have only been using python for 6 - 12 months but in my past I programmed microcontrollers in assembly. as soon as i saw it i understood it & thought great, like a light bulb going on. I suppose I have the advantage that it is only the taint of BASIC (in the home computer era) that I have had to overcome and my programming style has not been unduly influenced by c & others. it is easy to write C, or Pascal or even BASIC in python but why bother, why not just use C, Pascal or BASIC in that case? -- I respect faith, but doubt is what gives you an education. -- Wilson Mizner From tjreedy at udel.edu Sun Jul 1 05:55:24 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 01 Jul 2012 05:55:24 -0400 Subject: code review In-Reply-To: <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/1/2012 2:54 AM, Steven D'Aprano wrote: > So no, Python has always included chained comparisons, and yes, it is > shameful that a language would force you to unlearn standard notation in > favour of a foolish consistency with other operators. Comparisons aren't > special because they return bools. They are special because of the way > they are used. > > C treats comparison operators as if they were arithmetic operators, and > so the behaviour of a chained comparison is the same as the behaviour as > a sequence of arithmetic operators: a foolish consistency. Python treats > comparison operators as comparison operators, and gives them behaviour > appropriate to comparisons. I considered this a great feature of Python when I first learned it. Reading about how rare it is among programming languages to treat comparisons in the standard way in mathematics reinforces that. -- Terry Jan Reedy From sdl.web at gmail.com Sun Jul 1 07:56:12 2012 From: sdl.web at gmail.com (Leo) Date: Sun, 01 Jul 2012 19:56:12 +0800 Subject: [ANN] IPython 0.13 is officially out! References: Message-ID: On 2012-07-01 01:55 +0800, Fernando Perez wrote: > - ~6 months of work. > - 373 pull requests merged. > - 742 issues closed (non-pull requests). > - contributions from 62 authors. > - 1760 commits. > - a diff of 114226 lines. Thank you for the hard work. Leo From rappeli82 at googlemail.com Sun Jul 1 08:41:56 2012 From: rappeli82 at googlemail.com (Fabian Doerfler) Date: Sun, 1 Jul 2012 14:41:56 +0200 Subject: Fwd: Python-list Digest, Vol 106, Issue 1 Message-ID: (a2 + b2 = c2) = (e < | > P a P b P c) Beschreibt eine Disonanz in Genese. ---------- Weitergeleitete Nachricht ---------- Von: Datum: 30.06.2012 23:09 Betreff: Python-list Digest, Vol 106, Issue 1 An: Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." Today's Topics: 1. Re: code review (Alister) 2. Re: code review (Alister) 3. Re: code review (Thomas Jollans) 4. Re: code review (Alain Ketterlin) 5. Re: code review (Thomas Jollans) 6. Re: tiffany 0.6.1 released (Christian Heimes) 7. Re: code review (Terry Reedy) 8. Re: code review (Martin P. Hellwig) 9. Re: code review (Thomas Jollans) 10. Re: code review (Alain Ketterlin) ---------- Weitergeleitete Nachricht ---------- From: Alister To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 20:25:39 GMT Subject: Re: code review On Sat, 30 Jun 2012 12:29:31 +0200, Peter Otten wrote: > Alister wrote: > >> I think I may be on firmer grounds with the next few: >> >> isValidPassword can be simplified to >> >> def isValidPassword(password: >> count=len(password) >> return count>= mud.minpass and count<= mud.maxpass >> >> ( I used count to save finding the length of password twice although it >> probably makes no difference in this scenario) > > If you spell it > > def is_valid_password(password): > return mud.minpass <= len(password) <= mud.maxpass > > it is even easier to see that you are performing an interval check. I realise that was possible, that is brilliant! it is exactly how you would write it ass a mathematical definition. -- "The only real way to look younger is not to be born so soon." -- Charles Schulz, "Things I've Had to Learn Over and Over and Over" ---------- Weitergeleitete Nachricht ---------- From: Alister To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 20:30:45 GMT Subject: Re: code review On Sat, 30 Jun 2012 21:38:58 +0200, Thomas Jollans wrote: > On 06/30/2012 08:39 PM, Thomas 'PointedEars' Lahn wrote: >> Peter Otten wrote: >> >>> If you spell it >>> >>> def is_valid_password(password): >>> return mud.minpass <= len(password) <= mud.maxpass >>> >>> it is even easier to see that you are performing an interval check. >> >> This is probably a tautology around here, but *what* *a* *great* >> *programming* *language*. >> >> > Personally, I don't like this feature of the language. I find a ternary > operator that uses symbols that can also be binary operators confusing > and inconsistent with the way operators usually work/the way terms are > usually associated. > > It has the charm of being something you'd "naturally" write in the > context of non-programming mathematics, at the cost of being very odd > indeed in the context of programming in general and Python in > particular. Surely this fits perfectly with the lines 1 & 7 in the zen of python (import this) "Beautifull is better than ugly" and "Readability counts" I find that construct both beautiful and readable, if it cannot be used in the languages then that is their loss. -- Removing the straw that broke the camel's back does not necessarily allow the camel to walk again. ---------- Weitergeleitete Nachricht ---------- From: Thomas Jollans To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 22:50:43 +0200 Subject: Re: code review On 06/30/2012 10:30 PM, Alister wrote: > On Sat, 30 Jun 2012 21:38:58 +0200, Thomas Jollans wrote: > >> On 06/30/2012 08:39 PM, Thomas 'PointedEars' Lahn wrote: >>> Peter Otten wrote: >>> >>>> If you spell it >>>> >>>> def is_valid_password(password): >>>> return mud.minpass <= len(password) <= mud.maxpass >>>> >>>> it is even easier to see that you are performing an interval check. >>> >>> This is probably a tautology around here, but *what* *a* *great* >>> *programming* *language*. >>> >>> >> Personally, I don't like this feature of the language. I find a ternary >> operator that uses symbols that can also be binary operators confusing >> and inconsistent with the way operators usually work/the way terms are >> usually associated. >> >> It has the charm of being something you'd "naturally" write in the >> context of non-programming mathematics, at the cost of being very odd >> indeed in the context of programming in general and Python in >> particular. > > Surely this fits perfectly with the lines 1 & 7 in the zen of python > (import this) > "Beautifull is better than ugly" and "Readability counts" > > I find that construct both beautiful and readable, if it cannot be used > in the languages then that is their loss. Are we quoting the Zen now? Contra: In re usual operator rules: "Special cases aren't special enough to break the rules." Which of the two comparisons is done first anyway? "In the face of ambiguity, refuse the temptation to guess." Speaking of two comparisons, no "and"! "Explicit is better than implicit." Then again, pro: "Beautiful is better than ugly." "Readability counts." "[Although] practicality beats purity." I can see the appeal. It's quite elegant in and of itself. However, I find that in the context of the whole Python language, it's a bit of a glitch and reduces elegance. (I'm probably in the minority on this one) ---------- Weitergeleitete Nachricht ---------- From: Alain Ketterlin To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 23:07:41 +0200 Subject: Re: code review Thomas Jollans writes: >>>>> def is_valid_password(password): >>>>> return mud.minpass <= len(password) <= mud.maxpass > Which of the two comparisons is done first anyway? > "In the face of ambiguity, refuse the temptation to guess." There is no ambiguity. See the language reference: "Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once." The last restriction (single evaluation of involved expressions) makes this a bit more than raw syntactic sugar. -- Alain. ---------- Weitergeleitete Nachricht ---------- From: Thomas Jollans To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 23:35:19 +0200 Subject: Re: code review On 06/30/2012 11:07 PM, Alain Ketterlin wrote: > Thomas Jollans writes: > >>>>>> def is_valid_password(password): >>>>>> return mud.minpass <= len(password) <= mud.maxpass > >> Which of the two comparisons is done first anyway? >> "In the face of ambiguity, refuse the temptation to guess." > > There is no ambiguity. See the language reference: Of course it's technically clearly defined, but the syntax isn't explicit. To know what the order is (or whether there is an order!) one has to consult the language reference (which shouldn't be necessary), or make an educated guess, which would almost certainly be correct, but we're supposed to refuse the temptation to guess, right? > "Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN > are comparison operators, then a op1 b op2 c ... y opN z is equivalent > to a op1 b and b op2 c and ... y opN z, except that each expression is > evaluated at most once." > > The last restriction (single evaluation of involved expressions) makes > this a bit more than raw syntactic sugar. ---------- Weitergeleitete Nachricht ---------- From: Christian Heimes To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 23:35:31 +0200 Subject: Re: tiffany 0.6.1 released Am 30.06.2012 18:25, schrieb Paul Rubin: > Christian Tismer writes: >> Tiffany stands for any tiff. The tiny module solves a large set of >> problems, has no dependencies and just works wherever Python works. >> Tiffany was developed in the course of the *DiDoCa* project and will >> always appear on PyPi. > > This sounds pretty neat. I didn't comment on it earlier because I > haven't tried it out, since I haven't had occasion to deal with tiff > files anytime recently. But I've had to process them for some projects > in the past, and tiffany would have been useful then. It's good to know > that it's out there. I've developed smc.freeimage exclusively to process large amounts of TIFF images. I estimate that we have processed more than twelve million unique TIFF images with about half a petabyte of data. The packages uses Cython to wrap FreeImage (containing libtiff, libpng, libjpeg, libraw and more) and LittleCMS2. The package is mostly fitted to our needs, a bit limited (e.g. no conversion of CMYK to RGB with color management) and doesn't follow recent best practices for Cython code, but it does it job well. I need to clean up the code base some day when more people get interested in the lib. Christian ---------- Weitergeleitete Nachricht ---------- From: Terry Reedy To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 17:47:55 -0400 Subject: Re: code review On 6/30/2012 5:35 PM, Thomas Jollans wrote: > On 06/30/2012 11:07 PM, Alain Ketterlin wrote: > >> Thomas Jollans writes: >> >> def is_valid_password(password): >>>>>>> return mud.minpass <= len(password) <= mud.maxpass >>>>>>> >>>>>> >> Which of the two comparisons is done first anyway? >>> "In the face of ambiguity, refuse the temptation to guess." >>> >> >> There is no ambiguity. See the language reference: >> > > Of course it's technically clearly defined, but the syntax isn't > explicit. To know what the order is (or whether there is an order!) one > has to consult the language reference (which shouldn't be necessary), or > make an educated guess, which would almost certainly be correct, but > we're supposed to refuse the temptation to guess, right? > Python pretty consistently evaluates expressions and equal precedence operators left to right. One really should learn that. No 'implementation defined' ambiguity. -- Terry Jan Reedy ---------- Weitergeleitete Nachricht ---------- From: "Martin P. Hellwig" To: python-list at python.org Cc: Date: Sat, 30 Jun 2012 14:48:16 -0700 (PDT) Subject: Re: code review On Saturday, 30 June 2012 21:30:45 UTC+1, Alister wrote: > On Sat, 30 Jun 2012 21:38:58 +0200, Thomas Jollans wrote: > > > On 06/30/2012 08:39 PM, Thomas 'PointedEars' Lahn wrote: > >> Peter Otten wrote: > >> > >>> If you spell it > >>> > >>> def is_valid_password(password): > >>> return mud.minpass <= len(password) <= mud.maxpass > >>> > Surely this fits perfectly with the lines 1 & 7 in the zen of python > (import this) > "Beautifull is better than ugly" and "Readability counts" > Agree, however I like to stress the "don't make me unnecessary read with care" rule. Meaning if I read that line, I have to read it carefully to make sure I understand what is happening, the following would not do that although syntax wise equal: def length_between_min_max(password): return(mud.minpass <= len(password) <= mud.maxpass) def is_valid_password(password): valid = True if not length_between_max_min(password): valid = False if some_other_test(password): valid = False return(valid) This I can read, typically I would not even read what the function length_beteen_max_min does as long as there is no bug in it because, it is perfectly english clear what the intention is. -- mph ---------- Weitergeleitete Nachricht ---------- From: Thomas Jollans To: python-list at python.org Cc: Date: Sun, 01 Jul 2012 00:05:26 +0200 Subject: Re: code review On 06/30/2012 11:47 PM, Terry Reedy wrote: > On 6/30/2012 5:35 PM, Thomas Jollans wrote: >> On 06/30/2012 11:07 PM, Alain Ketterlin wrote: >>> Thomas Jollans writes: >>> >>>>>>>> def is_valid_password(password): >>>>>>>> return mud.minpass <= len(password) <= mud.maxpass >>> >>>> Which of the two comparisons is done first anyway? >>>> "In the face of ambiguity, refuse the temptation to guess." >>> >>> There is no ambiguity. See the language reference: >> >> Of course it's technically clearly defined, but the syntax isn't >> explicit. To know what the order is (or whether there is an order!) one >> has to consult the language reference (which shouldn't be necessary), or >> make an educated guess, which would almost certainly be correct, but >> we're supposed to refuse the temptation to guess, right? > > Python pretty consistently evaluates expressions and equal precedence > operators left to right. Yes. My sole point, really, is that "normally", one would expect these two expressions to be equivalent: a < b < c (a < b) < c This is clearly not true. That's the inconsistency here with the rest of the language. As soon as you read it as a ternary operator, the two comparisons are logically simultaneous. Doing the left hand comparison first is clearly the intuitive thing to do, but it's still, strictly speaking, arbitrary. Intuitive, clearly defined, but arbitrary. The ternary conditional operator is a different beast because its sub-operators "if" and "else" aren't also binary operators, so it's obvious that it's parsed differently. > One really should learn that. No > 'implementation defined' ambiguity. ---------- Weitergeleitete Nachricht ---------- From: Alain Ketterlin To: python-list at python.org Cc: Date: Sun, 01 Jul 2012 01:03:14 +0200 Subject: Re: code review Thomas Jollans writes: > On 06/30/2012 11:47 PM, Terry Reedy wrote: >>>>>>>>> def is_valid_password(password): >>>>>>>>> return mud.minpass <= len(password) <= mud.maxpass >>>> >>>>> Which of the two comparisons is done first anyway? >>>>> "In the face of ambiguity, refuse the temptation to guess." >>>> >>>> There is no ambiguity. See the language reference: >>> Of course it's technically clearly defined, but the syntax isn't >>> explicit. >> Python pretty consistently evaluates expressions and equal precedence >> operators left to right. > > Yes. My sole point, really, is that "normally", one would expect these > two expressions to be equivalent: > > a < b < c > (a < b) < c > > This is clearly not true. That's the inconsistency here with the rest of > the language. No, comparison operators are different from arithmetic operators in that they always evaluate to a boolean. There are only rare cases where it makes sense to compare comparisons. > As soon as you read it as a ternary operator, the two comparisons are > logically simultaneous. There is no ternary operator, you can chain as many as you want, using whatever operators: if a <= b < c > d >= e: ... Once you view this as a conjonction of conditions, you find back the semantics of "and": short-circuit, left to right evaluation. I find this consistent. -- Alain. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vs at it.uu.se Sun Jul 1 10:20:27 2012 From: vs at it.uu.se (Virgil Stokes) Date: Sun, 01 Jul 2012 16:20:27 +0200 Subject: [ANN] IPython 0.13 is officially out! In-Reply-To: References: Message-ID: <4FF05CAB.4010005@it.uu.se> On 01-Jul-2012 13:56, Leo wrote: > On 2012-07-01 01:55 +0800, Fernando Perez wrote: >> - ~6 months of work. >> - 373 pull requests merged. >> - 742 issues closed (non-pull requests). >> - contributions from 62 authors. >> - 1760 commits. >> - a diff of 114226 lines. > Thank you for the hard work. > > Leo I have tried to update 0.12 in Ubuntu 12.04 but as of now it can not find 0.13. Any suggestions on how to get it into Ubuntu 12.04 would be appreciated. From storchaka at gmail.com Sun Jul 1 10:31:40 2012 From: storchaka at gmail.com (Serhiy Storchaka) Date: Sun, 01 Jul 2012 17:31:40 +0300 Subject: how to use tkinter in python3.2? In-Reply-To: References: Message-ID: On 01.07.12 07:25, contro opinion wrote: > i have installed tk ,how to use tkinker in python3.2? You must install tk-dev (or whatever it's called on your system) before Python building (don't forget to rerun configure). From levinie001 at gmail.com Sun Jul 1 10:48:39 2012 From: levinie001 at gmail.com (levi nie) Date: Sun, 1 Jul 2012 22:48:39 +0800 Subject: hello everyone! i'm a new member from China Message-ID: i love python very much.it's powerful,easy and useful. i got it from Openstack.And i'm a new guy on python. Can i ask some stupid questions in days? haha... -------------- next part -------------- An HTML attachment was scrubbed... URL: From driscoll at cs.wisc.edu Sun Jul 1 11:48:40 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Sun, 01 Jul 2012 10:48:40 -0500 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <4FF07158.7030603@cs.wisc.edu> On 7/1/2012 4:54, Alister wrote: > On Sat, 30 Jun 2012 23:45:25 -0500, Evan Driscoll wrote: >> If I had seen that in a program, I'd have assumed it was a bug. > > You would? > I have only been using python for 6 - 12 months but in my past I > programmed microcontrollers in assembly. > > as soon as i saw it i understood it & thought great, like a light bulb > going on. It's not a matter of "I wouldn't have understood what the author was trying to do" (with a small caveat), it's a matter of "I'd have assumed that the author didn't understand the language semantics." I'm pretty sure it goes contrary to *every other programming language I've ever used* (and a couple that I haven't). I understand why Python does it, and it certainly is nice in that it matches typical mathematical notation, but the surprise quotient is *very* high in the PL world IMO. Evan From davecook at nowhere.net Sun Jul 1 12:03:23 2012 From: davecook at nowhere.net (Dave Cook) Date: 01 Jul 2012 16:03:23 GMT Subject: [ANN] IPython 0.13 is officially out! References: Message-ID: <4ff074cb$0$45195$c3e8da3$b280bf18@news.astraweb.com> On 2012-07-01, Virgil Stokes wrote: > I have tried to update 0.12 in Ubuntu 12.04 but as of now it can not find 0.13. > Any suggestions on how to get it into Ubuntu 12.04 would be appreciated. Install pip and use it to upgrade ipython: sudo apt-get install python-pip sudo pip install --upgrade ipython Dave Cook From dmitrey15 at gmail.com Sun Jul 1 13:51:19 2012 From: dmitrey15 at gmail.com (dmitrey) Date: Sun, 1 Jul 2012 10:51:19 -0700 (PDT) Subject: when "normal" parallel computations in CPython will be implemented at last? Message-ID: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> hi all, are there any information about upcoming availability of parallel computations in CPython without modules like multiprocessing? I mean something like parallel "for" loops, or, at least, something without forking with copying huge amounts of RAM each time and possibility to involve unpiclable data (vfork would be ok, but AFAIK it doesn't work with CPython due to GIL). AFAIK in PyPy some progress have been done ( http://morepypy.blogspot.com/2012/06/stm-with-threads.html ) Thank you in advance, D. From drsalists at gmail.com Sun Jul 1 14:44:49 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 1 Jul 2012 11:44:49 -0700 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: If something happens with this for CPython, it'll likely come from Pypy developers first. They seem to be interested in doing things in a way that is (or can be made) compatible with CPython. If you want to help them along, they're taking donations to fund the work, or you could donate your own time. Bear in mind that CPython threads fine for I/O-heavy workloads. It's CPU-bound workloads that CPython doesn't thread super well. Last I heard, both Jython and IronPython thread well today, and there's little reason not to try them if you have a (rather rare) application that truly needs Java-like threading. Granted, they don't run C extension modules, but there's quite a bit of portability synergy to be had from coming up with Pure Python alternatives; it's quite feasible to run the same code on CPython 2.x, CPython 3.x, Pypy and Jython. IronPython, sadly, lacks a python standard library. If CPython has trouble with CoW, it's probably because of reference counting, not the GIL. Last I heard, CPython used both reference counting and garbage collection. Also, vfork is a bit of a hack... just plain fork is often a better way to go. On Sun, Jul 1, 2012 at 10:51 AM, dmitrey wrote: > hi all, > are there any information about upcoming availability of parallel > computations in CPython without modules like multiprocessing? I mean > something like parallel "for" loops, or, at least, something without > forking with copying huge amounts of RAM each time and possibility to > involve unpiclable data (vfork would be ok, but AFAIK it doesn't work > with CPython due to GIL). > > AFAIK in PyPy some progress have been done ( > http://morepypy.blogspot.com/2012/06/stm-with-threads.html ) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Sun Jul 1 14:53:13 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 01 Jul 2012 20:53:13 +0200 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: <4FF09C99.8090800@jollybox.de> On 07/01/2012 07:51 PM, dmitrey wrote: > hi all, > are there any information about upcoming availability of parallel > computations in CPython without modules like multiprocessing? I mean > something like parallel "for" loops, or, at least, something without > forking with copying huge amounts of RAM each time and possibility to > involve unpiclable data (vfork would be ok, but AFAIK it doesn't work > with CPython due to GIL). > > AFAIK in PyPy some progress have been done ( > http://morepypy.blogspot.com/2012/06/stm-with-threads.html ) As far as I can tell, there are no concrete plans to integrate concurrency better, or get rid of the GIL, at the moment. To quote http://wiki.python.org/moin/GlobalInterpreterLock """Getting rid of the GIL is an occasional topic on the python-dev mailing list. No one has managed it yet.""" There are currently no open or accepted PEPs on the subject of concurrency. http://www.python.org/dev/peps/ There is, of course, Stackless Python. http://stackless.com/ From t at jollybox.de Sun Jul 1 14:58:43 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 01 Jul 2012 20:58:43 +0200 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: <4FF09DE3.9020808@jollybox.de> On 07/01/2012 08:44 PM, Dan Stromberg wrote: > IronPython, sadly, lacks a python standard library. Beg pardon? https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib From bahamutzero8825 at gmail.com Sun Jul 1 15:09:51 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 01 Jul 2012 14:09:51 -0500 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: <4FF09C99.8090800@jollybox.de> References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> <4FF09C99.8090800@jollybox.de> Message-ID: <4FF0A07F.8040305@gmail.com> On 7/1/2012 1:53 PM, Thomas Jollans wrote: > As far as I can tell, there are no concrete plans to integrate > concurrency better, or get rid of the GIL, at the moment. To quote > http://wiki.python.org/moin/GlobalInterpreterLock > > """Getting rid of the GIL is an occasional topic on the python-dev > mailing list. No one has managed it yet.""" There's also this, recently written by one of CPython's core devs: http://python-notes.boredomandlaziness.org/en/latest/python3/questions_and_answers.html#but-but-surely-fixing-the-gil-is-more-important-than-fixing-unicode -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 From drsalists at gmail.com Sun Jul 1 15:28:02 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 1 Jul 2012 12:28:02 -0700 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: <4FF09DE3.9020808@jollybox.de> References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> <4FF09DE3.9020808@jollybox.de> Message-ID: On Sun, Jul 1, 2012 at 11:58 AM, Thomas Jollans wrote: > On 07/01/2012 08:44 PM, Dan Stromberg wrote: > > IronPython, sadly, lacks a python standard library. > > > Beg pardon? > > > https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib > Perhaps things have changed. When I last checked the situation, IronPython came with no standard library, but you could bolt one on that hadn't been tested well - IIRC, just a simple "import os" gave a traceback. FePy was IronPython with a standard library and some degree of testing, but their emphasis was windows-only. I'd be open to using FePy instead, and I might even call it IronPython, but I'm not in the habit of happily using software that is Windows only. -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Sun Jul 1 15:36:25 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 01 Jul 2012 21:36:25 +0200 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> <4FF09DE3.9020808@jollybox.de> Message-ID: <4FF0A6B9.6070609@jollybox.de> On 07/01/2012 09:28 PM, Dan Stromberg wrote: > > > On Sun, Jul 1, 2012 at 11:58 AM, Thomas Jollans > wrote: > > On 07/01/2012 08:44 PM, Dan Stromberg wrote: > > IronPython, sadly, lacks a python standard library. > > > Beg pardon? > > https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib > > Perhaps things have changed. > > When I last checked the situation, IronPython came with no standard > library, but you could bolt one on that hadn't been tested well - IIRC, > just a simple "import os" gave a traceback. FePy was IronPython with a > standard library and some degree of testing, but their emphasis was > windows-only. > > I'd be open to using FePy instead, and I might even call it IronPython, > but I'm not in the habit of happily using software that is Windows only. > That must have been quite a while ago? I haven't tested it recently, but I'm fairly sure that IronPython includes a Python standard library which works reasonably well, and it's not Windows-only. (it works with Mono) From rridge at csclub.uwaterloo.ca Sun Jul 1 16:03:25 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Sun, 01 Jul 2012 16:03:25 -0400 Subject: when "normal" parallel computations in CPython will be implemented at last? References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: Thomas Jollans wrote: >There is, of course, Stackless Python. >http://stackless.com/ Stackless Python doesn't really address the original poster's problem as the GIL still effectively limits Python code running in one thread at a time. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From nobody at someplace.invalid Sun Jul 1 16:53:48 2012 From: nobody at someplace.invalid (HoneyMonster) Date: Sun, 1 Jul 2012 20:53:48 +0000 (UTC) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> Message-ID: On Sun, 01 Jul 2012 09:46:56 +0200, Thomas Jollans wrote: > I don't have PostgeSQL handy just now - what is the result of (1 < 2 < > 3) ? I bet it's the same error, which means the two are still > equivalent. $ psql misc psql (9.1.4) Type "help" for help. misc=# select (1 < 2); ?column? ---------- t (1 row) misc=# select (1 < 2 < 3); ERROR: syntax error at or near "<" LINE 1: select (1 < 2 < 3); ^ misc=# From steve+comp.lang.python at pearwood.info Sun Jul 1 20:41:32 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 00:41:32 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> Message-ID: <4ff0ee3b$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 05:18:09 -0400, Devin Jeanpierre wrote: > Also, you claimed earlier that the notion of associative "<" is not > founded in mathematical notation. It really depends on whose > mathematical notation you use -- there's more than one, you know. For > example, it's reasonable to expect < to be left- or right-associative in > a system like Rick Hehner's Unified Algebra: > http://www.cs.toronto.edu/~hehner/UA.pdf (although, he himself doesn't > specify it as being one or the other, so by default one would assume 'a > < b < c' to be nonsensical.) Sheesh guys. Don't go hunting through the most obscure corners of mathematics for examples of computer scientists who have invented their own maths notation. (Which, by your own admission, is under-specified and therefore incomplete.) Who uses Hehner's "Unified Algebra" notation? Apart from Hehner, if he even uses it himself. Pick up any standard maths book and you will see chained comparisons used with exactly the meaning that Python gives them. For example, Wolfram MathWorld uses it: http://mathworld.wolfram.com/Inequality.html Chained comparisons in the Python sense may be rare in computer languages, but it is the standard in mathematics and hardly needs to be explained to anyone over the age of twelve. That is a terrible indictment on the state of programming language design. -- Steven From steve+comp.lang.python at pearwood.info Sun Jul 1 20:43:44 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 00:43:44 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff0eebf$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 09:35:40 +0200, Thomas Jollans wrote: > On 07/01/2012 04:06 AM, Steven D'Aprano wrote: >> On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote: >> >>> As soon as you read it as a ternary operator, >> >> Well that's your problem. Why are you reading it as a ternary operator? >> It isn't one. It is a pair of chained binary operator. >> >> How can you tell that it is a pair of binary operators, rather than a >> single ternary operator? >> >> 1) There are TWO operators, hence a pair, not a single ternary >> operator; >> >> 2) each operator takes TWO arguments, not three. > > This is simply wrong. The comparisons are not acting as binary > operators. Of course they are. Take this chained comparison: a < b == c There are exactly TWO operators. Each one takes TWO arguments. The < operator takes a and b as arguments. That's TWO, not three. The == operator takes b and c arguments. Again, that's TWO, not three. If you want to claim that this is a ternary operator, you need to explain: 1) What is the operator in this expression? Is it < or == or something else? 2) What double-underscore special method does it call? Where is this mysterious, secret, undocumented method implemented? 3) Why do the Python docs lie that a < b == c is exactly equivalent to the short-circuit expression (a < b) and (b == c) with b evaluated once? 4) And how do you explain that the compiled byte code actually calls the regular two-argument binary operators instead of your imaginary three- argument ternary operator? py> from dis import dis py> dis(compile("a < b == c", "", "single")) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 0 (<) 11 JUMP_IF_FALSE_OR_POP 23 14 LOAD_NAME 2 (c) 17 COMPARE_OP 2 (==) 20 JUMP_FORWARD 2 (to 25) >> 23 ROT_TWO 24 POP_TOP >> 25 PRINT_EXPR 26 LOAD_CONST 0 (None) 29 RETURN_VALUE -- Steven From skippy.hammond at gmail.com Sun Jul 1 21:26:49 2012 From: skippy.hammond at gmail.com (Mark Hammond) Date: Mon, 02 Jul 2012 11:26:49 +1000 Subject: changes made to my python coded com servers are not taking effect In-Reply-To: <613bbae0-2631-4b84-ba58-a7369a423a33@v15g2000yqi.googlegroups.com> References: <613bbae0-2631-4b84-ba58-a7369a423a33@v15g2000yqi.googlegroups.com> Message-ID: <4FF0F8D9.6060207@gmail.com> On 1/07/2012 7:13 PM, Panceisto wrote: > I assume the old code keeps running in some process somewhere. How to > fix this? > The client of your server still has a reference to the old server. The simplest solution is to restart those clients. Mark From steve+comp.lang.python at pearwood.info Sun Jul 1 21:26:57 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 01:26:57 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <4fefc2a8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4feff408$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 05:55:24 -0400, Terry Reedy wrote: > On 7/1/2012 2:54 AM, Steven D'Aprano wrote: > >> So no, Python has always included chained comparisons, and yes, it is >> shameful that a language would force you to unlearn standard notation >> in favour of a foolish consistency with other operators. Comparisons >> aren't special because they return bools. They are special because of >> the way they are used. >> >> C treats comparison operators as if they were arithmetic operators, and >> so the behaviour of a chained comparison is the same as the behaviour >> as a sequence of arithmetic operators: a foolish consistency. Python >> treats comparison operators as comparison operators, and gives them >> behaviour appropriate to comparisons. > > I considered this a great feature of Python when I first learned it. > Reading about how rare it is among programming languages to treat > comparisons in the standard way in mathematics reinforces that. Apart from Python, Mathematica, Perl 6, CoffeeScript, Cobra and Clay give chained comparisons the standard meaning. It is, or was, a feature request for Boo, but I can't tell whether it has been implemented or not. C-like semantics are next to useless, except perhaps for obfuscation: http://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true/ And surprising: http://answers.yahoo.com/question/index?qid=20090923172909AA4O9Hx C-like semantics are a clear case of purity of implementation overruling functional usefulness. -- Steven From steve+comp.lang.python at pearwood.info Sun Jul 1 21:28:25 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 01:28:25 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 16:33:15 +1000, Chris Angelico wrote: > On Sun, Jul 1, 2012 at 4:27 PM, Steven D'Aprano > wrote: >> Yes, you can find specially crafted examples where adding parentheses >> in certain places, but not others, doesn't change the overall >> evaluation of the expression. > > My point was that adding parentheses around the tightest-binding > operator is a common, clear, and usually insignificant, way of > demonstrating operator precedence. So FOR THAT USE they must not change > evaluation of the expression. Obviously if you put them anywhere else, > they change evaluation. Nice job knocking down a straw man. We *really did have* somebody arguing that chained comparisons are Bad because you can't stick parentheses around bits of it without changing the semantics. That was an actual argument, not a straw-man. It's a stupid argument, but don't blame me for pointing out it's stupidity. The author *assumed* that a chain of < must be left- associative in the same way that a chain of + operators is left- associative, but it isn't. That's an invalid and unsafe assumption -- even in C-like languages, there are operators which aren't left- associative, e.g. exponentiation ** which is usually right-associative. (For the record, C itself doesn't have an exponentiation operator.) When you make unsafe assumptions about an operator, and get bitten by it, the *correct* conclusion should be that the assumption was wrong, not that the language is wrong. Technically, < in Python is left-associative: a < b < c first evaluates a, not b or c. But it is left-associative under the rules of comparison operator chaining, not arithmetic operator chaining. -- Steven From jeanpierreda at gmail.com Sun Jul 1 21:40:34 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 1 Jul 2012 21:40:34 -0400 Subject: code review In-Reply-To: <4ff0ee3b$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> <4ff0ee3b$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 1, 2012 at 8:41 PM, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 05:18:09 -0400, Devin Jeanpierre wrote: > Sheesh guys. Don't go hunting through the most obscure corners of > mathematics for examples of computer scientists who have invented their > own maths notation. (Which, by your own admission, is under-specified and > therefore incomplete.) Who uses Hehner's "Unified Algebra" notation? > Apart from Hehner, if he even uses it himself. I didn't hunt, I was taught it in university. -- Devin (Of course, it shouldn't be hard to guess who the professor was :) From jeanpierreda at gmail.com Sun Jul 1 21:50:29 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 1 Jul 2012 21:50:29 -0400 Subject: code review In-Reply-To: <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 1, 2012 at 9:28 PM, Steven D'Aprano wrote: > Technically, < in Python is left-associative: a < b < c first evaluates > a, not b or c. But it is left-associative under the rules of comparison > operator chaining, not arithmetic operator chaining. Left-associativity is when a < b < c is equivalent to (a < b) < c. You're talking about evaluation order, which can be different. For example, hypothetically, (a < b) < c could evaluate c first, then b, then a. However, Python always evaluates operands left-to-right. A particular case where this comes into play is the ** operator, which is right-associative but still has a left-to-right evaluation order. -- Devin From rosuav at gmail.com Sun Jul 1 22:04:29 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 2 Jul 2012 12:04:29 +1000 Subject: code review In-Reply-To: <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 2, 2012 at 11:28 AM, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 16:33:15 +1000, Chris Angelico wrote: > >> On Sun, Jul 1, 2012 at 4:27 PM, Steven D'Aprano >> wrote: >>> Yes, you can find specially crafted examples where adding parentheses >>> in certain places, but not others, doesn't change the overall >>> evaluation of the expression. >> >> My point was that adding parentheses around the tightest-binding >> operator is a common, clear, and usually insignificant, way of >> demonstrating operator precedence. So FOR THAT USE they must not change >> evaluation of the expression. Obviously if you put them anywhere else, >> they change evaluation. Nice job knocking down a straw man. > > We *really did have* somebody arguing that chained comparisons are Bad > because you can't stick parentheses around bits of it without changing > the semantics. That was an actual argument, not a straw-man. Okay, I take back the "straw man" accusation, and apologize for it. But you were quoting my text at the time, so I thought you were aiming at my argument - which, not being that, was what led me to think you were answering what you weren't answering. > Chained comparisons in the Python sense may be rare in computer > languages, but it is the standard in mathematics and hardly needs to be > explained to anyone over the age of twelve. That is a terrible indictment > on the state of programming language design. I'd say that proves that Python is a good language for expressing mathematics in, then. That's all. Doesn't necessarily mean it's good for any other task (doesn't mean it's bad either of course). Python does not, meanwhile, have inbuilt operators for calculus, nor does it have an equation solver. Do we absolutely need them? Empirically no. Python can be an excellent language without making every bit of mathematical notation executable. There are, I am sure, plenty of cases where it would be nice to go: x = y+2 x*3 = y*4+7 print("x = %d, y = %d",x,y) You can argue that Python ought to have more-different operators for comparison and assignment, but the fact of algebra is that it has neither - the equals sign is more of a declaration of truth. Algebra simply isn't imperative. It's fine (and fits the Eliza principle) to evaluate expressions algebraically, but equations aren't assignment. ChrisA From rustompmody at gmail.com Sun Jul 1 22:28:07 2012 From: rustompmody at gmail.com (rusi) Date: Sun, 1 Jul 2012 19:28:07 -0700 (PDT) Subject: IPython 0.13 is officially out! References: <4ff074cb$0$45195$c3e8da3$b280bf18@news.astraweb.com> Message-ID: <3592fb87-5ebd-4f3b-8f9b-8965c4016d7a@st3g2000pbc.googlegroups.com> On Jul 1, 9:03?pm, Dave Cook wrote: > On 2012-07-01, Virgil Stokes wrote: > > > I have tried to update 0.12 in Ubuntu 12.04 but as of now it can not find 0.13. > > Any suggestions on how to get it into Ubuntu 12.04 would be appreciated. > > Install pip and use it to upgrade ipython: > > sudo apt-get install python-pip > sudo pip install --upgrade ipython > > Dave Cook Would that not cause path-problems if the earlier one were not pip- installed?? Better to remove the earlier one first From ormax3 at mail.com Sun Jul 1 23:40:10 2012 From: ormax3 at mail.com (Mero) Date: Mon, 02 Jul 2012 06:40:10 +0300 Subject: distutils that supports msvc10 and that can be backfitted into Python 2.6 In-Reply-To: References: Message-ID: On 26/06/2012 23:24, KACVINSKY Tom wrote: > I have need for a distutils that supports msvc10, and which can be > back-fitted into Python 2.6. Is there such a beast? One trick I found was to define an environment variable *VS90COMNTOOLS* that points to the actual VS2010 location: VS90COMNTOOLS=%VS100COMNTOOLS% This is because distutils looks for VS2008 in the registry and falls back to the env. var. above, hence we trick it to detect VS2010 and call `vcvarsall.bat` when compiling extensions: python setup.py build --compiler=msvc Just keep in mind that it is recommended that "extension modules be compiled with the same compiler that was used to compile Python" which is still VS2008 to this day.. From research at johnohagan.com Mon Jul 2 00:43:00 2012 From: research at johnohagan.com (John O'Hagan) Date: Mon, 2 Jul 2012 14:43:00 +1000 Subject: code review In-Reply-To: References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <87395cq6sr.fsf@benfinney.id.au> Message-ID: <20120702144300.8ec61414ddbbcaa57cc137ce@johnohagan.com> On Sun, 01 Jul 2012 13:41:20 -0400 Dennis Lee Bieber wrote: > I'd think a true newcomer (to programming) would have NO > expectations... And if they'd had any complex math classes may actually > consider > if 1 < x < 10: > to be the norm [...] +1 I've only ever known Python (well, I've almost forgotten Bash), and when I first needed a range test, I guessed at the above form and was pleasantly surprised that it worked: it seemed too good to be true that Python was smart enough to know I wanted the same "x" to be an operand in two comparisons at once. John P.S. I know I'm not helping, but I'm starting to feel sorry for the guy who wanted his code reviewed! John From steve+comp.lang.python at pearwood.info Mon Jul 2 03:29:37 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 07:29:37 GMT Subject: code review References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff14de1$0$30001$c3e8da3$5496439d@news.astraweb.com> On Sun, 01 Jul 2012 21:50:29 -0400, Devin Jeanpierre wrote: > On Sun, Jul 1, 2012 at 9:28 PM, Steven D'Aprano > wrote: >> Technically, < in Python is left-associative: a < b < c first evaluates >> a, not b or c. But it is left-associative under the rules of comparison >> operator chaining, not arithmetic operator chaining. > > Left-associativity is when a < b < c is equivalent to (a < b) < c. > > You're talking about evaluation order, which can be different. For > example, hypothetically, (a < b) < c could evaluate c first, then b, > then a. However, Python always evaluates operands left-to-right. > > A particular case where this comes into play is the ** operator, which > is right-associative but still has a left-to-right evaluation order. Yes, you are right, my mistake. -- Steven From __peter__ at web.de Mon Jul 2 03:50:05 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Jul 2012 09:50:05 +0200 Subject: hello everyone! i'm a new member from China References: Message-ID: levi nie wrote: > i love python very much.it's powerful,easy and useful. > i got it from Openstack.And i'm a new guy on python. Welcome! > Can i ask some stupid questions in days? haha... Sure, but we cannot guarantee that the answer will be stupid, too ;) From rosuav at gmail.com Mon Jul 2 03:51:03 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 2 Jul 2012 17:51:03 +1000 Subject: hello everyone! i'm a new member from China In-Reply-To: References: Message-ID: On Mon, Jul 2, 2012 at 12:48 AM, levi nie wrote: > i love python very much.it's powerful,easy and useful. > i got it from Openstack.And i'm a new guy on python. > Can i ask some stupid questions in days? haha... Of course you can. Everyone else does! :) Just remember to give it a good subject line, state your question clearly, and so on - you'll be fine. Welcome! Chris Angelico From steve+comp.lang.python at pearwood.info Mon Jul 2 04:11:16 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Jul 2012 08:11:16 GMT Subject: code review References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> On Mon, 02 Jul 2012 12:04:29 +1000, Chris Angelico wrote: >> Chained comparisons in the Python sense may be rare in computer >> languages, but it is the standard in mathematics and hardly needs to be >> explained to anyone over the age of twelve. That is a terrible >> indictment on the state of programming language design. > > I'd say that proves that Python is a good language for expressing > mathematics in, then. That's all. No. Python is a terrible language for expressing mathematics in. As you point out, I can't do things like: x = y+2 x*3 = y*4+7 print("x = %d, y = %d",x,y) and sensibly get x = 1, y = -1. But Python is an excellent language for expressing a series of comparisons in, which has applications beyond pure maths or algebra. For example: "c" < first_word < second_word == third_word < "x" I'm sure I don't have to explain what that means -- that standard chained notation for comparisons is obvious and simple. In Python, you write it the normal way, as above. But some other languages force you into verbosity: ("c" < first_word) and (first_word < second_word) and (second_word == third_word) and (third_word < "x") Worst of all are those languages which allow you to write the expression as normal, but evaluate it in a way that you almost never want: the maximum number of bugs with the minimum convenience. This has nothing to do with algebra. It is about picking semantics for chained comparisons which is sensible and useful and matches what people expect from regular language. If you write 2+2 = 2*2 = 4, nearly everyone will agree that, yes, that is true. Interpreting it as 1 == 4 is neither sensible nor useful and it is certainly not what people expect. -- Steven From rosuav at gmail.com Mon Jul 2 04:20:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 2 Jul 2012 18:20:57 +1000 Subject: code review In-Reply-To: <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 2, 2012 at 6:11 PM, Steven D'Aprano wrote: > "c" < first_word < second_word == third_word < "x" > > I'm sure I don't have to explain what that means -- that standard chained > notation for comparisons is obvious and simple. > > In Python, you write it the normal way, as above. But some other > languages force you into verbosity: > > ("c" < first_word) and (first_word < second_word) and (second_word == > third_word) and (third_word < "x") Uhh, actually you DO have to explain that, because I interpreted it quite differently: (("c" < first_word) and (first_word < second_word)) == (third_word < "x") And even if you can prove that my interpretation is wrong, it's still plausible enough that I, as a programmer, would have to dive to the manual (or test in interactive interpreter) to find out which way the language evaluates this. ChrisA From levinie001 at gmail.com Mon Jul 2 06:00:39 2012 From: levinie001 at gmail.com (levi nie) Date: Mon, 2 Jul 2012 18:00:39 +0800 Subject: Is Django v1.3 documentation the newest version? Message-ID: Is Django v1.3 documentation the newest version? i use the Django book 2.0. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jtnharris at googlemail.com Mon Jul 2 07:03:10 2012 From: jtnharris at googlemail.com (Jonathan Harris) Date: Mon, 2 Jul 2012 12:03:10 +0100 Subject: Is Django v1.3 documentation the newest version? In-Reply-To: References: Message-ID: Hello It isn't Having been frustrated with out of date books, specifically the Apress published 'Definitive Guide To Django', I've downloaded the Kindle edition of Django 1.4 documentation It's a good tutorial J On Mon, Jul 2, 2012 at 11:00 AM, levi nie wrote: > Is Django v1.3 documentation the newest version? > i use the Django book 2.0. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From contropinion at gmail.com Mon Jul 2 09:28:59 2012 From: contropinion at gmail.com (contro opinion) Date: Mon, 2 Jul 2012 09:28:59 -0400 Subject: how to use tkinter in python3.2? In-Reply-To: References: Message-ID: apt-get install tk-dev cd ./python3.2.3 ./cpnfigure make make install ok root at ocean:/home/tiger/Python-3.2.3# python3.2 Python 3.2.3 (default, Jul 2 2012, 21:23:34) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>> haha,think Serhiy Storchaka 2012/7/1 Serhiy Storchaka > On 01.07.12 07:25, contro opinion wrote: > >> i have installed tk ,how to use tkinker in python3.2? >> > > You must install tk-dev (or whatever it's called on your system) before > Python building (don't forget to rerun configure). > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at egenix.com Mon Jul 2 09:52:20 2012 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 02 Jul 2012 15:52:20 +0200 Subject: ANN: eGenix PyRun - One file Python Runtime 1.0.0 Message-ID: <4FF1A794.8030608@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix PyRun - One file Python Runtime Version 1.0.0 An easy-to-use single file relocatable Python run-time - available for Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-PyRun-1.0.0.html ________________________________________________________________________ INTRODUCTION Our new eGenix PyRun combines a Python interpreter with an almost complete Python standard library into a single easy-to-use executable, that does not require a system wide installation and is fully relocatable. eGenix PyRun's executable only needs 12MB, but still supports most Python application and scripts - and it can be further compressed to 3-4MB using gzexe or upx. Compared to a regular Python installation of typically 100MB on disk, this makes eGenix PyRun ideal for applications and scripts that need to be distributed to many target machines, client installations or customers. It makes "installing" Python on a Unix based system as simple as copying a single file. http://www.egenix.com/products/python/PyRun/ ________________________________________________________________________ NEWS This is the first public release of eGenix PyRun. We have been using the product internally in our mxODBC Connect Server since 2008 with great success and have now extracted it into a stand-alone open-source product. We provide both the source archive to build your own eGenix PyRun, as well as provide pre-compiled binaries for Linux, FreeBSD and Mac OS X, for the resp. 32- and 64-bit platforms. Presentation at EuroPython 2012 ------------------------------- Marc-Andr?, CEO of eGenix, will be giving a presentation about eGenix PyRun at EuroPython 2012 in Florence, Italy on Wednesday, July 4th in the Room Tagliatelle. He will also be available during the conference to answer questions. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the product can be found at: http://www.egenix.com/products/python/PyRun/ _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. ________________________________________________________________________ MORE INFORMATION For more information about eGenix PyRun, licensing and download instructions, please visit our web-site or write to sales at egenix.com. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From contropinion at gmail.com Mon Jul 2 10:02:35 2012 From: contropinion at gmail.com (contro opinion) Date: Mon, 2 Jul 2012 10:02:35 -0400 Subject: how to solve this tclerror? Message-ID: i want to install a software, please see the manul page 2 http://www.openfiling.info/wp-content/upLoads/data/ArelleUsersManual.pdf when i input the command to install Arelle : tiger at ocean:~$ cd /home/tiger/Arelle tiger at ocean:~/Arelle$ python3.2 arelleGUI.pyw Traceback (most recent call last): File "arelleGUI.pyw", line 11, in CntlrWinMain.main() File "/home/tiger/Arelle/arelle/CntlrWinMain.py", line 1113, in main cntlrWinMain = CntlrWinMain(application) File "/home/tiger/Arelle/arelle/CntlrWinMain.py", line 164, in __init__ windowFrame = Frame(self.parent) File "/usr/local/lib/python3.2/tkinter/ttk.py", line 761, in __init__ Widget.__init__(self, master, "ttk::frame", kw) File "/usr/local/lib/python3.2/tkinter/ttk.py", line 559, in __init__ _load_tile(master) File "/usr/local/lib/python3.2/tkinter/ttk.py", line 47, in _load_tile master.tk.eval('package require tile') # TclError may be raised here _tkinter.TclError: can't find package tile how to solve this problem? i have installed python3.2 ,tk-dev ,lxml ,tkinter tiger at ocean:~/Arelle$ python3.2 Python 3.2.3 (default, Jul 2 2012, 21:23:34) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>> import lxml >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From contropinion at gmail.com Mon Jul 2 10:14:58 2012 From: contropinion at gmail.com (contro opinion) Date: Mon, 2 Jul 2012 10:14:58 -0400 Subject: how to solve this tclerror? In-Reply-To: References: Message-ID: i solve it myself 1.download tile-0.8.4.0.tar.gz 2. ./configure 3. make 4 make install tiger at ocean:~$ cd /home/tiger/Arelle tiger at ocean:~/Arelle$ python3.2 arelleGUI.pyw i get what i want ,haha..... 2012/7/2 contro opinion > i want to install a software, > > please see the manul page 2 > http://www.openfiling.info/wp-content/upLoads/data/ArelleUsersManual.pdf > > when i input the command to install Arelle : > > > tiger at ocean:~$ cd /home/tiger/Arelle > tiger at ocean:~/Arelle$ python3.2 arelleGUI.pyw > Traceback (most recent call last): > File "arelleGUI.pyw", line 11, in > CntlrWinMain.main() > File "/home/tiger/Arelle/arelle/CntlrWinMain.py", line 1113, in main > cntlrWinMain = CntlrWinMain(application) > File "/home/tiger/Arelle/arelle/CntlrWinMain.py", line 164, in __init__ > windowFrame = Frame(self.parent) > File "/usr/local/lib/python3.2/tkinter/ttk.py", line 761, in __init__ > Widget.__init__(self, master, "ttk::frame", kw) > File "/usr/local/lib/python3.2/tkinter/ttk.py", line 559, in __init__ > _load_tile(master) > File "/usr/local/lib/python3.2/tkinter/ttk.py", line 47, in _load_tile > master.tk.eval('package require tile') # TclError may be raised here > _tkinter.TclError: can't find package tile > > how to solve this problem? > > i have installed python3.2 ,tk-dev ,lxml ,tkinter > > tiger at ocean:~/Arelle$ python3.2 > Python 3.2.3 (default, Jul 2 2012, 21:23:34) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import tkinter > >>> import lxml > >>> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Mon Jul 2 10:26:02 2012 From: t at jollybox.de (Thomas Jollans) Date: Mon, 02 Jul 2012 16:26:02 +0200 Subject: code review In-Reply-To: <4ff0eebf$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0eebf$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FF1AF7A.3010307@jollybox.de> On 07/02/2012 02:43 AM, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 09:35:40 +0200, Thomas Jollans wrote: >> This is simply wrong. The comparisons are not acting as binary >> operators. > > Of course they are. Take this chained comparison: Technically, yes - two-input operations are happening. Syntactically, no. Read my post. > 1) What is the operator in this expression? Is it < or == or something > else? I think I've answered this - it's the combination. > 2) What double-underscore special method does it call? Where is this > mysterious, secret, undocumented method implemented? > > 3) Why do the Python docs lie that a < b == c is exactly equivalent to > the short-circuit expression (a < b) and (b == c) with b evaluated once? > > 4) And how do you explain that the compiled byte code actually calls the > regular two-argument binary operators instead of your imaginary three- > argument ternary operator? In this context, I don't care what actually happens. I'm talking about how the code can be parsed (by the generic reader, not necessarily the python interpreter). From rdsteph at mac.com Mon Jul 2 10:28:24 2012 From: rdsteph at mac.com (rdsteph at mac.com) Date: Mon, 2 Jul 2012 07:28:24 -0700 (PDT) Subject: hello everyone! i'm a new member from China References: Message-ID: <9f17a0dd-c539-4749-bf5c-76e886a2c93c@d6g2000pbt.googlegroups.com> On Jul 2, 12:50?am, Peter Otten <__pete... at web.de> wrote: > levi nie wrote: > > i love python very much.it's powerful,easy and useful. > > i got it from Openstack.And i'm a new guy on python. > > Welcome! > > > Can i ask some stupid questions in days? haha... > > Sure, but we cannot guarantee that the answer will be stupid, too ;) Hello and welcome, What part of China do you live in? I have visited many cities in China on business and had wonderful experiences. I think Python is kind of like the Middle Kingdom of programming languages. :-) Ron Stephens Awaretek From t at jollybox.de Mon Jul 2 10:41:49 2012 From: t at jollybox.de (Thomas Jollans) Date: Mon, 02 Jul 2012 16:41:49 +0200 Subject: code review In-Reply-To: <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FF1B32D.1040903@jollybox.de> On 07/02/2012 03:28 AM, Steven D'Aprano wrote: > We *really did have* somebody arguing that chained comparisons are Bad > because you can't stick parentheses around bits of it without changing > the semantics. That was an actual argument, not a straw-man. Ahem. It may have been sub-optimally phrased in a way that opened itself up to attack, but I was arguing that Python comparisons operators are anomalous because they're not associative. (and, going back to the root of the argument, this makes them Bad because "Special cases aren't special enough to break the rules.") On Sun, 01 Jul 2012 21:50:29 -0400, Devin Jeanpierre wrote: > On Sun, Jul 1, 2012 at 9:28 PM, Steven D'Aprano > wrote: >> Technically, < in Python is left-associative: a < b < c first evaluates >> a, not b or c. But it is left-associative under the rules of comparison >> operator chaining, not arithmetic operator chaining. > > Left-associativity is when a < b < c is equivalent to (a < b) < c. From theller at ctypes.org Mon Jul 2 11:02:32 2012 From: theller at ctypes.org (Thomas Heller) Date: Mon, 02 Jul 2012 17:02:32 +0200 Subject: 2to6 ? In-Reply-To: References: Message-ID: Am 27.06.2012 20:06, schrieb Terry Reedy: > On 6/27/2012 10:36 AM, Thomas Heller wrote: >> Is there a tool, similar to 2to3, which converts python2 code >> to code using six.py, so that it runs unchanged with python2 >> *and* python 3? > > Others have expressed a similar wish, but I do not know that anyone has > actually revised 2to3 to make a 2to6, or how feasible that would be. > Has nobody heard of, or even tried, modernize? http://pypi.python.org/pypi/modernize Thomas From rantingrickjohnson at gmail.com Mon Jul 2 11:16:24 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 08:16:24 -0700 (PDT) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> On Jun 30, 9:06?pm, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote: > > Yes. My sole point, really, is that "normally", one would expect these > > two expressions to be equivalent: > > > a < b < c > > (a < b) < c > > Good grief. Why would you expect that? > > You can't just arbitrarily stick parentheses around parts of expressions > and expect the result to remain unchanged. Order of evaluation matters: > > 2**3**4 != (2**3)**4 Yes but as Chris points out in the next message, you can inject the following parenthesis without changing a thing!: py> 1 + 3 * 4 13 py> 1 + (3 * 4) 13 Of course i understand the rules of operator precedence, however i have never liked them AND i continue to believe that such functionality breeds bugs and is in fact bad language design. I believe all evaluations should be cumulative: py> 1 + 3 * 4 should ALWAYS equal 16! With parenthesis only used for grouping: py> a + (b*c) + d Which seems like the most consistent approach to me. From tjreedy at udel.edu Mon Jul 2 11:33:11 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 02 Jul 2012 11:33:11 -0400 Subject: code review In-Reply-To: References: <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/2/2012 1:20 AM, Dennis Lee Bieber wrote: > Obviously, someone coming over from VB or R or any other single language x > who hasn't read the Python reference is going to be surprised as something or other. So what. The manuals, including the tutorial, are there for a reason. The main points of the language take just a few hours to review. Perhaps my advantage learning Python was that I had written code in over 10 other languages and dialects and so had few expectations and made few assumptions. -- Terry Jan Reedy From wanderer at dialup4less.com Mon Jul 2 11:45:49 2012 From: wanderer at dialup4less.com (Wanderer) Date: Mon, 2 Jul 2012 08:45:49 -0700 (PDT) Subject: WxSlider Mouse Wheel Resolution Message-ID: Is there a way to set the mouse wheel resolution for the wxPython wx.Slider? I would like to use the graphic slider for coarse control and the mouse wheel for fine control. Right now the mouse wheel makes the slider jump ten counts and I would like it to be a single count. Thanks From tjreedy at udel.edu Mon Jul 2 11:52:20 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 02 Jul 2012 11:52:20 -0400 Subject: how to solve this tclerror? In-Reply-To: References: Message-ID: On 7/2/2012 10:14 AM, contro opinion wrote: > i solve it myself > 1.download tile-0.8.4.0.tar.gz Or install the latest tcl/tk 8.5(.11), which includes tile/tkk and bug fixes, instead of the rather old 8.4.?. -- Terry Jan Reedy From rantingrickjohnson at gmail.com Mon Jul 2 11:57:14 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 08:57:14 -0700 (PDT) Subject: code review References: <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 2, 3:20?am, Chris Angelico wrote: > On Mon, Jul 2, 2012 at 6:11 PM, Steven D'Aprano > > wrote: > > "c" < first_word < second_word == third_word < "x" > > > I'm sure I don't have to explain what that means -- that standard chained > > notation for comparisons is obvious and simple. > > > In Python, you write it the normal way, as above. But some other > > languages force you into verbosity: > > > ("c" < first_word) and (first_word < second_word) and (second_word == > > third_word) and (third_word < "x") > > Uhh, actually you DO have to explain that, because I interpreted it > quite differently: > > (("c" < first_word) and (first_word < second_word)) == (third_word < "x") Poor Chris. That's because you've been brainwashed into believing you must spoon feed your interpreter to get your code working correctly. Stop applying these naive assumptions to Python code. Python knows when you reach the end of a statement, no need for redundant semicolons! Python knows when its reached the end of block and needs to drop back one level, no need for redundant road signs. Python knows Chris; Python KNOWS! From rosuav at gmail.com Mon Jul 2 12:42:49 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 3 Jul 2012 02:42:49 +1000 Subject: code review In-Reply-To: References: <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 3, 2012 at 1:57 AM, Rick Johnson wrote: > Poor Chris. That's because you've been brainwashed into believing you > must spoon feed your interpreter to get your code working correctly. > Stop applying these naive assumptions to Python code. Python knows > when you reach the end of a statement, no need for redundant > semicolons! Python knows when its reached the end of block and needs > to drop back one level, no need for redundant road signs. Python > knows Chris; Python KNOWS! Why "poor", Ralph? I am poor in the essence of ignorance's bliss, rich only in the never-ending thirst for knowledge and more languages. In me there meet a combination of antithetical elements which are at eternal war with one another... I hope I make myself clear, lady? Oops, wrong mailing list. Near enough. Python is not magic. It's not that it "knows" when I reach the end of a statement; it simply rules that line ends correspond to statement ends unless ordered otherwise. It has been told that the reduction of indentation level is a lexer token. Rick, do you realize that you have to spoon-feed the interpreter with spaces/tabs when other interpreters just KNOW to drop back an indentation level when you close a brace? I simply need to make sure that the interpreter and I have the same understanding of the code. It will then work correctly. There's nothing special about one syntax or another, they're all just communication from my brain to a CPU, and different syntaxes are suited to different tasks. There's nothing inherently wrong with: right_length = len(x) > 5, < 20 being a valid way of expressing a double condition. It puts the query first and the bounds after it, so hey, it's justifiably sane. (No, I'm not advocating adding this. It's just for argument's sake.) Whatever you're writing with, you need to have the same rules in your head as the compiler/interpreter uses; beyond that there's a huge amount of personal preference (I quite like braces, myself, but many others don't) and only a relatively small amount of actual logic (use ASCII mathematical symbols to represent mathematical operations). ChrisA From rosuav at gmail.com Mon Jul 2 12:55:48 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 3 Jul 2012 02:55:48 +1000 Subject: code review In-Reply-To: <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> Message-ID: On Tue, Jul 3, 2012 at 1:16 AM, Rick Johnson wrote: > py> 1 + 3 * 4 > should ALWAYS equal 16! > > With parenthesis only used for grouping: > py> a + (b*c) + d > > Which seems like the most consistent approach to me. Oh yes, absolutely consistent. Consistency. It's a CR 1/2 monster found on page 153 of the 3.5th Edition Monster Manual. Let's see. By your principle, we should evaluate the ** before the - in: 2**-1 Have fun. ChrisA From nagle at animats.com Mon Jul 2 13:51:36 2012 From: nagle at animats.com (John Nagle) Date: Mon, 02 Jul 2012 10:51:36 -0700 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: On 7/1/2012 10:51 AM, dmitrey wrote: > hi all, > are there any information about upcoming availability of parallel > computations in CPython without modules like multiprocessing? I mean > something like parallel "for" loops, or, at least, something without > forking with copying huge amounts of RAM each time and possibility to > involve unpiclable data (vfork would be ok, but AFAIK it doesn't work > with CPython due to GIL). > > AFAIK in PyPy some progress have been done ( > http://morepypy.blogspot.com/2012/06/stm-with-threads.html ) > > Thank you in advance, D. > It would be "un-Pythonic" to have real concurrency in Python. You wouldn't be able to patch code running in one thread from another thread. Some of the dynamic features of Python would break. If you want fine-grained concurrency, you need controlled isolation between concurrent tasks, so they interact only at well-defined points. That's un-Pythonic. John Nagle From rantingrickjohnson at gmail.com Mon Jul 2 14:22:35 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 11:22:35 -0700 (PDT) Subject: code review References: <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 2, 11:42?am, Chris Angelico wrote: > Rick, do you realize that you have > to spoon-feed the interpreter with spaces/tabs when other interpreters > just KNOW to drop back an indentation level when you close a brace? Yes. And significant white space is my favorite attribute of Python source code. But the difference here is like night and day. While your getting bogged down playing "match-the-brackets", i'm writing code and being productive. I don't need to put any mental effort into pressing the Enter+Tab keys. On the contrary, you must constantly break your mental focus to "corral" the braces, and the sad part is, you're still formatting your code like mine (with tabs and newlines!) however your simultaneously juggling superfluously archaic syntax! Why Chris? WHY? > I simply need to make sure that the interpreter and I have the same > understanding of the code. It will then work correctly. There's > nothing special about one syntax or another, I agree in the sense of: "to each his own". However. There are methods of writing code that are more productive, and methods that are less productive, and your emotive agenda of defending such nostalgic pedantry is quite self-defeating. > they're all just > communication from my brain to a CPU, and different syntaxes are > suited to different tasks. There's nothing inherently wrong with: > > right_length = len(x) > 5, < 20 Agreed. I wish we had one language. One which had syntactical directives for scoping, blocks, assignments, etc, etc... BLOCK_INDENT_MARKER -> \t BLOCK_DEDENT_MARKER -> \n STATEMENT_TERMINATOR -> \n ASSIGNMENT_OPERATOR -> := CONDITIONAL_IF_SPELLING -> IF CONDITIONAL_ELSE_SPELLING -> EL ... > (I quite like braces, myself, [...] and only a relatively small > amount of actual logic. So you have a penchant for confinement and an aversion to logic? Hmm, interesting! From stefan_ml at behnel.de Mon Jul 2 14:37:01 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 02 Jul 2012 20:37:01 +0200 Subject: when "normal" parallel computations in CPython will be implemented at last? In-Reply-To: References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> <4FF09DE3.9020808@jollybox.de> Message-ID: Dan Stromberg, 01.07.2012 21:28: > On Sun, Jul 1, 2012 at 11:58 AM, Thomas Jollans wrote: >> On 07/01/2012 08:44 PM, Dan Stromberg wrote: >>> IronPython, sadly, lacks a python standard library. >> >> Beg pardon? >> >> https://github.com/IronLanguages/main/tree/master/External.LCA_RESTRICTED/Languages/IronPython/27/Lib > > Perhaps things have changed. Yes, they have. The original restriction came from Microsoft enforcing a clean-room implementation for their code, which obviously excluded the standard library - which is well tested and licence cleared and all that, but nevertheless non-MS. When they dropped the IronPython project, it became free to integrate with other software. Clearly a cultural thing. Stefan From t at jollybox.de Mon Jul 2 15:06:46 2012 From: t at jollybox.de (Thomas Jollans) Date: Mon, 02 Jul 2012 21:06:46 +0200 Subject: code review In-Reply-To: References: <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FF1F146.8080709@jollybox.de> On 07/02/2012 08:22 PM, Rick Johnson wrote: > Agreed. I wish we had one language. One which had syntactical > directives for scoping, blocks, assignments, etc, etc... > > BLOCK_INDENT_MARKER -> \t > BLOCK_DEDENT_MARKER -> \n > STATEMENT_TERMINATOR -> \n > ASSIGNMENT_OPERATOR -> := > CONDITIONAL_IF_SPELLING -> IF > CONDITIONAL_ELSE_SPELLING -> EL > ... You must be joking. In C, for example, it is possible to "create your own language" by going #define IF(cond) if (cond) { #define ELSE } else { #define ELIF(cond) } else if (cond) { #define ENDIF } and so on. There's a reason nobody does it. From ian.g.kelly at gmail.com Mon Jul 2 15:16:26 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 2 Jul 2012 13:16:26 -0600 Subject: code review In-Reply-To: <4FEF66A3.9040805@jollybox.de> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <4FEF66A3.9040805@jollybox.de> Message-ID: On Sat, Jun 30, 2012 at 2:50 PM, Thomas Jollans wrote: > Which of the two comparisons is done first anyway? > "In the face of ambiguity, refuse the temptation to guess." I would consider that a pro, not a con, because the C-like way is much worse in this regard. Using operator chaining, is "1 < 2 < 3" equivalent to: 1 < 2 and 2 < 3 # assuming left-to-right evaluation order for "and" 2 < 3 and 1 < 2 The former seems pretty obvious to me (since it more closely matches the original syntax) and also turns out to be correct, but more to the point, most of the time it really doesn't matter which is evaluated first. It's only relevant if: a) your comparison operator has side-effects (bad programmer! bad!); or b) one of the comparisons is significantly faster than the other -- but since usually both comparisons will be of the same type (e.g. both comparing two numbers), this is also a corner case. On the other hand, using the C-like interpretation, is "1 < 2 < 3" equivalent to: (1 < 2) < 3 1 < (2 < 3) I would guess the former is more common, but I really have no basis for that guess beyond some experience with languages that use this syntax. I can see no particular advantages to either interpretation and can certainly imagine that some languages might choose the latter instead. Moreover, the distinction actually matters in this case, because the first expression is true (at least in Python) while the second is false. I will take ambiguity that is mostly unimportant over ambiguity that is critical to the meaning of the expression any day of the week. Cheers, Ian From tjreedy at udel.edu Mon Jul 2 15:24:58 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 02 Jul 2012 15:24:58 -0400 Subject: 2to6 ? In-Reply-To: References: Message-ID: On 7/2/2012 11:02 AM, Thomas Heller wrote: > Am 27.06.2012 20:06, schrieb Terry Reedy: >> On 6/27/2012 10:36 AM, Thomas Heller wrote: >>> Is there a tool, similar to 2to3, which converts python2 code >>> to code using six.py, so that it runs unchanged with python2 >>> *and* python 3? >> >> Others have expressed a similar wish, but I do not know that anyone has >> actually revised 2to3 to make a 2to6, or how feasible that would be. >> > > Has nobody heard of, or even tried, modernize? > > http://pypi.python.org/pypi/modernize I had not, obviously. I'm glad you found it and hope it works for you. -- Terry Jan Reedy From rantingrickjohnson at gmail.com Mon Jul 2 15:35:08 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 12:35:08 -0700 (PDT) Subject: code review References: <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5940a10f-b19c-4936-b41f-e4a03c42560a@l32g2000yqb.googlegroups.com> On Jul 2, 2:06?pm, Thomas Jollans wrote: > On 07/02/2012 08:22 PM, Rick Johnson wrote: > > > Agreed. I wish we had one language. One which had syntactical > > directives for scoping, blocks, assignments, etc, etc... > > > BLOCK_INDENT_MARKER -> \t > > BLOCK_DEDENT_MARKER -> \n > > STATEMENT_TERMINATOR -> \n > > ASSIGNMENT_OPERATOR -> := > > CONDITIONAL_IF_SPELLING -> IF > > CONDITIONAL_ELSE_SPELLING -> EL > > ... > > You must be joking. Well i was slightly serious, but mostly sarcastic. Whist customizable syntax would be a great benefit to the individual, it would be a nightmare to the community -- the real solution lies in assimilation! I am reminded of a story: A few years back a very nice old woman offered to give me her typewriter. She said: "i might need to type a letter one day and it would good to have around". It was a nice typewriter for 1956, but she had no idea her little "machine" was reduced to no less than a paper weight thanks to something called the PC. Her machine had been extinct for decades. Effectually, SHE had been extinct for decades. When i hear people like Chris evangelizing about slavish syntax, i am reminded of the nice old lady. Her intentions where virtuous, however her logic was flawed. She is still clinging to old technology. Like the Luddites she refuses to see the importance technological advancements. And by harboring this nostalgia she is actually undermining the future evolution of an entire species. Lifespans are limited for a very important evolutionary reason! From rantingrickjohnson at gmail.com Mon Jul 2 16:45:49 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 13:45:49 -0700 (PDT) Subject: WxSlider Mouse Wheel Resolution References: Message-ID: <4f92b566-101b-4b40-aa2e-6eb72147c751@v15g2000yqi.googlegroups.com> On Jul 2, 10:45?am, Wanderer wrote: > Is there a way to set the mouse wheel resolution for the wxPython > wx.Slider? I would like to use the graphic slider for coarse control > and the mouse wheel for fine control. Right now the mouse wheel makes > the slider jump ten counts and I would like it to be a single count. > > Thanks I have always found GUI mouse wheel events (and others) to be lacking in the "user tuned control" category. NOTE: Instead of forcing your lib users to configure specifics or re-bind events like(course, medium, fine) simply pre-bind the following events and empower the end user: MouseWheel -> cb(MEDIUM) MouseWheel+ControlKey -> cb(FINE) MouseWheel+ShiftKey -> cb(COURSE) What a novel FREAKING idea! *school-bell-rings* From rantingrickjohnson at gmail.com Mon Jul 2 16:57:13 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 2 Jul 2012 13:57:13 -0700 (PDT) Subject: WxSlider Mouse Wheel Resolution References: <4f92b566-101b-4b40-aa2e-6eb72147c751@v15g2000yqi.googlegroups.com> Message-ID: <962ecb53-6fbd-476e-a537-af2ebf3e415d@n32g2000yqd.googlegroups.com> On Jul 2, 3:45?pm, Rick Johnson wrote: > [...] > ? MouseWheel -> cb(MEDIUM) > ? MouseWheel+ControlKey -> cb(FINE) > ? MouseWheel+ShiftKey -> cb(COURSE) Of course some could even argue that three levels of control are not good enough; for which i wholeheartedly agree! A REAL pro would provide a configurable method to the user for which a slider (or numerical range) would pop up to micro-adjust the increment. However! I think all widgets should expose every configurable option to the end user. All configure options would be available by default and the developer can restrict ANY configure option(s) which would have disastrous side-effects for that particular GUI. From rosuav at gmail.com Mon Jul 2 17:57:50 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 3 Jul 2012 07:57:50 +1000 Subject: code review In-Reply-To: <4FF1F146.8080709@jollybox.de> References: <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> <4FF1F146.8080709@jollybox.de> Message-ID: On Tue, Jul 3, 2012 at 5:06 AM, Thomas Jollans wrote: > On 07/02/2012 08:22 PM, Rick Johnson wrote: >> Agreed. I wish we had one language. One which had syntactical >> directives for scoping, blocks, assignments, etc, etc... >> >> BLOCK_INDENT_MARKER -> \t >> BLOCK_DEDENT_MARKER -> \n >> STATEMENT_TERMINATOR -> \n >> ASSIGNMENT_OPERATOR -> := >> CONDITIONAL_IF_SPELLING -> IF >> CONDITIONAL_ELSE_SPELLING -> EL >> ... > > You must be joking. > > In C, for example, it is possible to "create your own language" by going > > #define IF(cond) if (cond) { > #define ELSE } else { > #define ELIF(cond) } else if (cond) { > #define ENDIF } > > > and so on. There's a reason nobody does it. I'll go one further. The "create your own language" is just a plain text file, is in fact is NO LANGUAGE. If it's that flexible, what's the use of calling it the same language? Actually there is a lot of use in having that sort of commonality, but at a different level: source control. Tools like git are language-agnostic; I can have a repository with Javascript, PHP (ugh), Pike (that atones), Python, C++, etc source files, a single makefile that in the darkness binds them, and so on. But they're still all different languages. Oh and Rick? Nice troll there with the ellipsis. You fail grammar forever, but hey, at least you win at trolling. ChrisA From ian.g.kelly at gmail.com Mon Jul 2 19:13:01 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 2 Jul 2012 17:13:01 -0600 Subject: Evolution (was: code review) Message-ID: On Mon, Jul 2, 2012 at 1:35 PM, Rick Johnson wrote: > I am reminded of a story: A few years back a very nice old woman > offered to give me her typewriter. She said: "i might need to type a > letter one day and it would good to have around". It was a nice > typewriter for 1956, but she had no idea her little "machine" was > reduced to no less than a paper weight thanks to something called the > PC. Her machine had been extinct for decades. Effectually, SHE had > been extinct for decades. It's called "retirement", not "extinction", and there's nothing at all wrong with typing out letters; it's just slower. If we ever have a nuclear war or even just get hit by a large enough coronal mass ejection, you might find yourself wishing you had that typewriter instead of your suddenly useless laptop -- just as the dinosaurs (had they been sentient) might have found themselves wishing they had not evolved to be so darn *large* 65 million years ago. > When i hear people like Chris evangelizing about slavish syntax, i am > reminded of the nice old lady. Her intentions where virtuous, however > her logic was flawed. She is still clinging to old technology. Like > the Luddites she refuses to see the importance technological > advancements. And by harboring this nostalgia she is actually > undermining the future evolution of an entire species. That's not nostalgia; that's lack of necessity. There is nothing so "important" about technological advancement that it must be thrust upon nice old ladies who have set habits and no good reason to change them. And I can't see for the life of me how people failing to jump on the email bandwagon have anything at all to do with evolution. > Lifespans are limited for a very important evolutionary reason! If that is true, then when your singularity finally arrives and we all become immortal, will that not interfere with evolution? All kidding aside, evolution is a natural process, not a purpose. The ultimate point of evolution will occur when the universe is no longer entropically able to support life in any form, transcended or otherwise, and we will all finally be extinct. Then what? The universe just carries on without us, and goes through a whole series of cosmological epochs that will be observed by nobody at all, for far longer than the entirety of our brief, chaotic existence. It's often suggested that the Big Bang is the cause of our existence, but the Big Bang is much bigger than us. The Big Bang is like a rock thrown into a still pond. First there is a big splash, then there are some ripples, and after a short time the pond becomes boringly still again. We aren't really part of the pond; we're just riding the ripples, and when they vanish, so do we. You made the claim once in another thread that individuals are not important in the grand scheme of things (I disagree; from our limited societal vantage point, individuals *are* the grand scheme of things). I am trying here to demonstrate the point that the universe doesn't care one whit about evolution either. Hopefully I succeeded, because I don't want to get sucked into another huge, completely off-topic thread, and so I won't be posting on this again. From simoncropper at fossworkflowguides.com Mon Jul 2 20:41:01 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Tue, 03 Jul 2012 10:41:01 +1000 Subject: ANN: eGenix PyRun - One file Python Runtime 1.0.0 In-Reply-To: <4FF1A794.8030608@egenix.com> References: <4FF1A794.8030608@egenix.com> Message-ID: <4FF23F9D.2050807@fossworkflowguides.com> On 02/07/12 23:52, eGenix Team: M.-A. Lemburg wrote: > ________________________________________________________________________ > ANNOUNCING > > eGenix PyRun - One file Python Runtime > > Version 1.0.0 > > > An easy-to-use single file relocatable Python run-time - > available for Windows, Mac OS X and Unix platforms > > > This announcement is also available on our web-site for online reading: > http://www.egenix.com/company/news/eGenix-PyRun-1.0.0.html > > ________________________________________________________________________ > INTRODUCTION > > Our new eGenix PyRun combines a Python interpreter with an almost > complete Python standard library into a single easy-to-use > executable, that does not require a system wide installation and > is fully relocatable. > > eGenix PyRun's executable only needs 12MB, but still supports > most Python application and scripts - and it can be further > compressed to 3-4MB using gzexe or upx. > > Compared to a regular Python installation of typically 100MB on > disk, this makes eGenix PyRun ideal for applications and scripts > that need to be distributed to many target machines, client > installations or customers. > > It makes "installing" Python on a Unix based system as simple as > copying a single file. > > http://www.egenix.com/products/python/PyRun/ > > ________________________________________________________________________ > NEWS > > This is the first public release of eGenix PyRun. We have been > using the product internally in our mxODBC Connect Server since > 2008 with great success and have now extracted it into a > stand-alone open-source product. > > We provide both the source archive to build your own eGenix > PyRun, as well as provide pre-compiled binaries for Linux, > FreeBSD and Mac OS X, for the resp. 32- and 64-bit platforms. > > Presentation at EuroPython 2012 > ------------------------------- > > Marc-Andr?, CEO of eGenix, will be giving a presentation about > eGenix PyRun at EuroPython 2012 in Florence, Italy on Wednesday, > July 4th in the Room Tagliatelle. > > He will also be available during the conference to answer > questions. > > ________________________________________________________________________ > DOWNLOADS > > The download archives and instructions for installing the product > can be found at: > > http://www.egenix.com/products/python/PyRun/ > > _______________________________________________________________________ > SUPPORT > > Commercial support for these packages is available from eGenix.com. > Please see > > http://www.egenix.com/services/support/ > > for details about our support offerings. > > ________________________________________________________________________ > MORE INFORMATION > > For more information about eGenix PyRun, licensing and download > instructions, please visit our web-site or write to > sales at egenix.com. > > Enjoy, > Hello, Are you able to indicate what size the installation would be WITH ALL the mentioned dependencies on various typical systems (MS Windows 32/64, Ubuntu, etc)? Saying something is only 12-13 MB in size is one thing but noting that you need 283MB+* of other packages means that in order to get this package to work on another machine you would need to install more than a 12-13MB executable, particularly on a Windows machine. OpenSSL on Windows 20MB -- http://slproweb.com/products zlib binary on Windows 0.012MB-- /Win32OpenSSL.html -- http://gnuwin32.sourceforge.net/packages/zlib.htm SQLite binary for Windows 262.59 MB -- http://www.sqlite.org/download.html/ BZip tarball 0.75 MB -- http://www.bzip.org/downloads.html Also, do you have a page that indicates what standard libraries have been included? How can someone tell whether they would need to distribute or include any additional modules to get a script to work? -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From howmuchistoday at gmail.com Mon Jul 2 20:49:17 2012 From: howmuchistoday at gmail.com (self.python) Date: Mon, 2 Jul 2012 17:49:17 -0700 (PDT) Subject: helping with unicode Message-ID: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> it's a simple source view program. the codec of the target website is utf-8 so I read it and print the decoded -------------------------------------------------------------- #-*-coding:utf8-*- import urllib2 rf=urllib2.urlopen(r"http://gall.dcinside.com/list.php?id=programming") print rf.read().decode('utf-8') raw_input() --------------------------------------------------------------- It works fine on python shell but when I make the file "wrong.py" and run it, Error rises. ---------------------------------------------------------------- Traceback (most recent call last): File "C:wrong.py", line 8, in print rf.read().decode('utf-8') UnicodeEncodeError: 'cp949' codec can't encode character u'u1368' in position 5 5122: illegal multibyte sequence --------------------------------------------------------------------- cp949 is the basic codec of sys.stdout and cmd.exe but I have no idea why it doesn't works. printing without decode('utf-8') works fine on IDLE but on cmd, it print broken characters(Ascii portion is still fine, problem is only about the Korean) the question may look silly:( but I want to know what is the problem or how to print the not broken strings. thanks for reading. From steve+comp.lang.python at pearwood.info Mon Jul 2 20:57:40 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Jul 2012 00:57:40 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> Message-ID: <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> On Tue, 03 Jul 2012 02:55:48 +1000, Chris Angelico wrote: > On Tue, Jul 3, 2012 at 1:16 AM, Rick Johnson > wrote: >> py> 1 + 3 * 4 >> should ALWAYS equal 16! >> >> With parenthesis only used for grouping: py> a + (b*c) + d >> >> Which seems like the most consistent approach to me. > > Oh yes, absolutely consistent. Consistency. It's a CR 1/2 monster found > on page 153 of the 3.5th Edition Monster Manual. GvR is fond of quoting Ralph Waldo Emerson: "A foolish consistency is the hobgoblin of little minds." Perhaps the world would be better off if mathematicians threw out the existing precedence rules and replaced them with a strict left-to-right precedence. (Personally, I doubt it.) But until they do, consistency with mathematics is far more important than the foolish consistency of left-to-right precedence. -- Steven From bahamutzero8825 at gmail.com Mon Jul 2 21:14:24 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 02 Jul 2012 20:14:24 -0500 Subject: helping with unicode In-Reply-To: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> References: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> Message-ID: <4FF24770.3000805@gmail.com> On 7/2/2012 7:49 PM, self.python wrote: > ---------------------------------------------------------------- > Traceback (most recent call last): > File "C:wrong.py", line 8, in > print rf.read().decode('utf-8') > UnicodeEncodeError: 'cp949' codec can't encode character u'u1368' in position 5 > 5122: illegal multibyte sequence > --------------------------------------------------------------------- > > cp949 is the basic codec of sys.stdout and cmd.exe > but I have no idea why it doesn't works. > printing without decode('utf-8') works fine on IDLE but on cmd, it print broken characters(Ascii portion is still fine, problem is only about the Korean) Your terminal can't display those characters. You could try using other code pages with chcp (a CLI utility that is part of Windows). IDLE is a GUI, so it does not have to work with code pages. Python 3.3 supports cp65001 (which is the equivalent of UTF-8 for Windows terminals), but unfortunately, previous versions do not. -- CPython 3.3.0a4 | Windows NT 6.1.7601.17803 From python at mrabarnett.plus.com Mon Jul 2 21:21:23 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 03 Jul 2012 02:21:23 +0100 Subject: helping with unicode In-Reply-To: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> References: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> Message-ID: <4FF24913.7000401@mrabarnett.plus.com> On 03/07/2012 01:49, self.python wrote: > it's a simple source view program. > > the codec of the target website is utf-8 > so I read it and print the decoded > > -------------------------------------------------------------- > #-*-coding:utf8-*- > import urllib2 > > rf=urllib2.urlopen(r"http://gall.dcinside.com/list.php?id=programming") > > print rf.read().decode('utf-8') > > raw_input() > --------------------------------------------------------------- > > It works fine on python shell > > but when I make the file "wrong.py" and run it, > Error rises. > > ---------------------------------------------------------------- > Traceback (most recent call last): > File "C:wrong.py", line 8, in > print rf.read().decode('utf-8') > UnicodeEncodeError: 'cp949' codec can't encode character u'u1368' in position 5 > 5122: illegal multibyte sequence > --------------------------------------------------------------------- > > cp949 is the basic codec of sys.stdout and cmd.exe > but I have no idea why it doesn't works. > printing without decode('utf-8') works fine on IDLE but on cmd, it print broken characters(Ascii portion is still fine, problem is only about the Korean) > > the question may look silly:( > but I want to know what is the problem or how to print the not broken strings. > > thanks for reading. > The encoding of your console is 'cp949', so when you try to print the Unicode string, Python tries to encode it as 'cp949'. Unfortunately, the character (actually, when talking about Unicode the correct term is 'codepoint') u'\u1368' cannot be encoded into 'cp949' because that codepoint does not exist in that encoding, in the same way that ASCII doesn't have Korean characters. So what is that codepoint? >>> import unicodedata >>> unicodedata.name(u'\u1368') 'ETHIOPIC PARAGRAPH SEPARATOR' Apparently 'cp949', which is for the Korean language, doesn't support Ethiopic codepoints. Somehow that doesn't surprise me! :-) From rosuav at gmail.com Mon Jul 2 21:22:55 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 3 Jul 2012 11:22:55 +1000 Subject: code review In-Reply-To: <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 3, 2012 at 10:57 AM, Steven D'Aprano wrote: > On Tue, 03 Jul 2012 02:55:48 +1000, Chris Angelico wrote: >> Oh yes, absolutely consistent. Consistency. It's a CR 1/2 monster found >> on page 153 of the 3.5th Edition Monster Manual. > > GvR is fond of quoting Ralph Waldo Emerson: > > "A foolish consistency is the hobgoblin of little minds." Yeah, that's what I was referring to. Dungeons and Dragons has specs for a hobgoblin warrior :) > Perhaps the world would be better off if mathematicians threw out the > existing precedence rules and replaced them with a strict left-to-right > precedence. (Personally, I doubt it.) > > But until they do, consistency with mathematics is far more important > than the foolish consistency of left-to-right precedence. And if they ever do, it'll break consistency with past centuries of mathematical writing. Imagine (taking this to another realm) that it's decided that since Wolfram is now called Tungsten, it should have the chemical symbol 'T' instead of 'W'. This is far more consistent, right? And Iron should be I, not Fe. We'll move Iodine to Io (and Europium to Europa and Gallium to Ganymede?), and tritium (the isotope of hydrogen) can become H3. It'd make today's chemistry notes look as archaic and unreadable as those using alchemical symbols, only the actual symbols are the same, making it ambiguous. Nope. Better to stick with what's standardized. ChrisA From tjreedy at udel.edu Mon Jul 2 21:39:08 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 02 Jul 2012 21:39:08 -0400 Subject: helping with unicode In-Reply-To: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> References: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> Message-ID: On 7/2/2012 8:49 PM, self.python wrote: > it's a simple source view program. > > the codec of the target website is utf-8 > so I read it and print the decoded which re-encodes before printing > -------------------------------------------------------------- > #-*-coding:utf8-*- > import urllib2 > > rf=urllib2.urlopen(r"http://gall.dcinside.com/list.php?id=programming") > > print rf.read().decode('utf-8') > > raw_input() > --------------------------------------------------------------- > > It works fine on python shell Do you mean the Windows Command Prompt shell? > > but when I make the file "wrong.py" and run it, > Error rises. > > ---------------------------------------------------------------- > Traceback (most recent call last): > File "C:wrong.py", line 8, in > print rf.read().decode('utf-8') > UnicodeEncodeError: 'cp949' codec can't encode character u'u1368' in position 5 > 5122: illegal multibyte sequence > --------------------------------------------------------------------- > > cp949 is the basic codec of sys.stdout and cmd.exe > but I have no idea why it doesn't works. cp949 is a Euro-Korean multibyte encoding whose mapping is given at http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP949.TXT u1368 is not in the mapping. There is no reason the utf-8 site would restrict itself to the cp949 subset. Perhap it prints in the interpreter because 2.x uses errors = 'replace' rather than 'strict' (as in 3.x). Try print rf.read().decode('utf-8').encode('cp949', errors = 'replace') Non-cp949 chars will print as '?'. > printing without decode('utf-8') works fine on IDLE because IDLE encodes to utf-8, and x.decode('utf-8').encode('utf-8') == x > but on cmd, it print broken characters Printing utf-8 encoded bytes as if cp949 encoded bytes is pretty hilariour > > the question may look silly:( but I want to know what is the problem or how to print the not broken strings. > > thanks for reading. > -- Terry Jan Reedy From tjreedy at udel.edu Mon Jul 2 21:39:32 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 02 Jul 2012 21:39:32 -0400 Subject: helping with unicode In-Reply-To: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> References: <56e3cafd-ec4f-4ae4-ad6c-685f2d991403@googlegroups.com> Message-ID: On 7/2/2012 8:49 PM, self.python wrote: > it's a simple source view program. > > the codec of the target website is utf-8 > so I read it and print the decoded which re-encodes before printing > -------------------------------------------------------------- > #-*-coding:utf8-*- > import urllib2 > > rf=urllib2.urlopen(r"http://gall.dcinside.com/list.php?id=programming") > > print rf.read().decode('utf-8') > > raw_input() > --------------------------------------------------------------- > > It works fine on python shell Do you mean the Windows Command Prompt shell? > > but when I make the file "wrong.py" and run it, > Error rises. > > ---------------------------------------------------------------- > Traceback (most recent call last): > File "C:wrong.py", line 8, in > print rf.read().decode('utf-8') > UnicodeEncodeError: 'cp949' codec can't encode character u'u1368' in position 5 > 5122: illegal multibyte sequence > --------------------------------------------------------------------- > > cp949 is the basic codec of sys.stdout and cmd.exe > but I have no idea why it doesn't works. cp949 is a Euro-Korean multibyte encoding whose mapping is given at http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP949.TXT u1368 is not in the mapping. There is no reason the utf-8 site would restrict itself to the cp949 subset. Perhap it prints in the interpreter because 2.x uses errors = 'replace' rather than 'strict' (as in 3.x). Try print rf.read().decode('utf-8').encode('cp949', errors = 'replace') Non-cp949 chars will print as '?'. > printing without decode('utf-8') works fine on IDLE because IDLE encodes to utf-8, and x.decode('utf-8').encode('utf-8') == x > but on cmd, it print broken characters Printing utf-8 encoded bytes as if cp949 encoded bytes is pretty hilariour > > the question may look silly:( but I want to know what is the problem or how to print the not broken strings. > > thanks for reading. > -- Terry Jan Reedy From research at johnohagan.com Mon Jul 2 22:25:59 2012 From: research at johnohagan.com (John O'Hagan) Date: Tue, 3 Jul 2012 12:25:59 +1000 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> On Tue, 3 Jul 2012 11:22:55 +1000 Chris Angelico wrote: > On Tue, Jul 3, 2012 at 10:57 AM, Steven D'Aprano > wrote: > > > Perhaps the world would be better off if mathematicians threw out the > > existing precedence rules and replaced them with a strict left-to-right > > precedence. (Personally, I doubt it.) > > > > But until they do, consistency with mathematics is far more important > > than the foolish consistency of left-to-right precedence. > > And if they ever do, it'll break consistency with past centuries of > mathematical writing. Imagine (taking this to another realm) that it's > decided that since Wolfram is now called Tungsten, it should have the > chemical symbol 'T' instead of 'W'. This is far more consistent, > right? And Iron should be I, not Fe. We'll move Iodine to Io (and > Europium to Europa and Gallium to Ganymede?), and tritium (the isotope > of hydrogen) can become H3. It'd make today's chemistry notes look as > archaic and unreadable as those using alchemical symbols, only the > actual symbols are the same, making it ambiguous. Nope. Better to > stick with what's standardized. > I agree to some extent, but as a counter-example, when I was a child there a subject called "Weights and Measures" which is now redundant because of the Metric system. I don't miss hogsheads and fathoms at all. Music is another field which could do with a "metrification": I get tired of explaining to beginners why there's no B#, except when it's C. Check out http://musicnotation.org If legacy systems get too far out of sync with current practice, they become an unnecessary layer of complexity and a hurdle to understanding, and at some point you have to take the plunge, old books be damned. -- John From lalithaprasad at gmail.com Mon Jul 2 23:36:46 2012 From: lalithaprasad at gmail.com (Lalitha Prasad K) Date: Tue, 3 Jul 2012 09:06:46 +0530 Subject: Tkinter and Chess problems Message-ID: Dear All Recently I have been playing with Tkinter. I wrote two scripts to solve well known chess problems: eight queens and knight's tour. Both are available here: https://github.com/LalithaPrasad/PythonScripts All are welcome to download and improve them if required. Hope to rewrite them using the other GUI libraries for comparison purposes. But I think, though Tkinter is considered primitive, It is extremely easy to use. Cheers Lalitha Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From anujkumar.87 at gmail.com Mon Jul 2 23:36:53 2012 From: anujkumar.87 at gmail.com (anuj kumar) Date: Tue, 3 Jul 2012 09:06:53 +0530 Subject: New member from India Message-ID: Hello Everyone, Warm greetings to all of you... I have to learn Python.So i recently join the python mailing list .Can you please send me some sample programs from where i can start. Thanks, Anuj -------------- next part -------------- An HTML attachment was scrubbed... URL: From pgiri at yahoo.com Mon Jul 2 23:38:42 2012 From: pgiri at yahoo.com (Giridhar Pemmasani) Date: Mon, 2 Jul 2012 20:38:42 -0700 (PDT) Subject: [ANN]: asyncoro: Framework for asynchronous, concurrent, distributed programming Message-ID: <1341286722.18908.YahooMailNeo@web160604.mail.bf1.yahoo.com> Hi, I would like to announce asyncoro (http://asyncoro.sourceforge.net), a Python framework for?developing concurrent, distributed programs with asynchronous?completions and coroutines. asyncoro features include ? * Asynchronous (non-blocking) sockets ? * Efficient polling mechanisms epoll, kqueue, /dev/poll ? ? (and poll and select if necessary), and Windows I/O Completion Ports (IOCP) ? ? for high performance and scalability ? * SSL for security ? * Timers, including non-blocking sleep ? * Locking primitives similar to Python threading module ? * Thread pools with asynchronous task completions (for executing ? ? time consuming synchronous tasks) ? * Asynchronous database cursor operations (using asynchronous thread pool) ? * Communicating coroutines with messages ? * Remote execution of coroutines ? * Coroutines monitoring other coroutines (to get exit status notifications) ? * Hot-swapping and restarting of coroutine functions Programs developed with asyncoro have same logic and structure as programs with threads, except for a few syntactic changes. With asyncoro's message communication, coroutines can exchange messages one-to-one or through (broadcasting) channels. Coroutines exchanging messages can be local (within single asyncoro instance) or distributed (in many asyncoro instances across network). Cheers, Giri -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Jul 2 23:54:53 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 3 Jul 2012 13:54:53 +1000 Subject: New member from India In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 1:36 PM, anuj kumar wrote: > Hello Everyone, > > Warm greetings to all of you... > > I have to learn Python.So i recently join the python mailing list .Can you > please send me some sample programs from where i can start. Welcome! Start here... http://docs.python.org/py3k/tutorial/ Chris Angelico From steve+comp.lang.python at pearwood.info Tue Jul 3 00:11:22 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Jul 2012 04:11:22 GMT Subject: code review References: <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff270ea$0$11103$c3e8da3@news.astraweb.com> On Tue, 03 Jul 2012 12:25:59 +1000, John O'Hagan wrote: > On Tue, 3 Jul 2012 11:22:55 +1000 > Chris Angelico wrote: > >> On Tue, Jul 3, 2012 at 10:57 AM, Steven D'Aprano >> wrote: >> >> > Perhaps the world would be better off if mathematicians threw out the >> > existing precedence rules and replaced them with a strict >> > left-to-right precedence. (Personally, I doubt it.) >> > >> > But until they do, consistency with mathematics is far more important >> > than the foolish consistency of left-to-right precedence. >> >> And if they ever do, it'll break consistency with past centuries of >> mathematical writing. Imagine (taking this to another realm) that it's >> decided that since Wolfram is now called Tungsten, it should have the >> chemical symbol 'T' instead of 'W'. This is far more consistent, right? >> And Iron should be I, not Fe. We'll move Iodine to Io (and Europium to >> Europa and Gallium to Ganymede?), and tritium (the isotope of hydrogen) >> can become H3. It'd make today's chemistry notes look as archaic and >> unreadable as those using alchemical symbols, only the actual symbols >> are the same, making it ambiguous. Nope. Better to stick with what's >> standardized. >> >> > I agree to some extent, but as a counter-example, when I was a child > there a subject called "Weights and Measures" which is now redundant > because of the Metric system. I don't miss hogsheads and fathoms at all. Don't mistake tradition for consistency. There's little consistency in the legacy weights and measures used before the metric system. The introduction of the Imperial system in 1824 at least got rid of *some* of the more wacky measures, and standardised the rest, but there was still damn little consistency: e.g. a finger was 7/8 of an inch, and an ell was 45 inches, meaning an ell is 39 and 3/8th fingers. One of my favourites is the league, which in the Middle Ages was actually defined as the distance that a man, or a horse, could walk in an hour. -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 3 01:03:36 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Jul 2012 05:03:36 GMT Subject: Dictless classes Message-ID: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> You can create instances without a __dict__ by setting __slots__: py> class Dictless: ... __slots__ = ['a', 'b', 'c'] ... py> Dictless().__dict__ Traceback (most recent call last): File "", line 1, in AttributeError: 'Dictless' object has no attribute '__dict__' But the class itself still has a __dict__: py> Dictless.__dict__ dict_proxy({'a': , 'c': , 'b': , '__module__': '__main__', '__slots__': ['a', 'b', 'c'], '__doc__': None}) I wonder whether there is some metaclass magic one can do to create a class without a __dict__? I don't have a use-case for this. But I have some code which assumes that every class will have a __dict__, and I wonder whether that is a safe assumption. -- Steven From gmspro at yahoo.com Tue Jul 3 01:08:56 2012 From: gmspro at yahoo.com (gmspro) Date: Mon, 2 Jul 2012 22:08:56 -0700 (PDT) Subject: How can i do python form post request? Message-ID: <1341292136.76763.YahooMailClassic@web164601.mail.gq1.yahoo.com> form.html:
? ?
p.py: #!/usr/bin/python #what to write here... Both files are put in /var/www/ , now from http://localhost/form.html, if i click the submit button would i execute the p.py? and how can i get the value of textbox? Any answer will be highly appreciated. Thanks in advanced. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Tue Jul 3 01:10:00 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 2 Jul 2012 22:10:00 -0700 (PDT) Subject: code review References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3f15d831-45bb-471c-8d49-a2db21e67c7a@nl1g2000pbc.googlegroups.com> On Jul 3, 7:25?am, John O'Hagan wrote: > > I agree to some extent, but as a counter-example, when I was a child there > a subject called "Weights and Measures" which is now redundant because of the > Metric system. I don't miss hogsheads and fathoms at all. > > Music is another field which could do with a "metrification": I get tired of > explaining to beginners why there's no B#, except when it's C. Check outhttp://musicnotation.org You assume that equal temperament is the only way to have music. Apart from the fact that there are non-tempered musics all over the world, even Bach Mozart and Beethoven did not write for/to equal temperament. In a pure/untempered C-scale A-flat is almost half a semitone sharper than G-sharp -- 8/5 vs 25/16. Similar for standardized languages: Python's indentation is nice -- except when you have to embed it into say, html From ben+python at benfinney.id.au Tue Jul 3 01:46:07 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 03 Jul 2012 15:46:07 +1000 Subject: code review References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <3f15d831-45bb-471c-8d49-a2db21e67c7a@nl1g2000pbc.googlegroups.com> Message-ID: <87pq8dpfc0.fsf@benfinney.id.au> rusi writes: > Similar for standardized languages: Python's indentation is nice -- > except when you have to embed it into say, html If you can't write a ?pre? element for pre-formatted text, you don't have HTML . -- \ ?Pinky, are you pondering what I'm pondering?? ?Uh, I think so, | `\ Brain, but we'll never get a monkey to use dental floss.? | _o__) ?_Pinky and The Brain_ | Ben Finney From wuwei23 at gmail.com Tue Jul 3 01:50:58 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 2 Jul 2012 22:50:58 -0700 (PDT) Subject: Dictless classes References: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> Message-ID: <6a9a2166-db2f-4af1-a4be-d2f1e327fa4a@d6g2000pbt.googlegroups.com> On Jul 3, 3:03?pm, Steven D'Aprano wrote: > I don't have a use-case for this. But I have some code which assumes that > every class will have a __dict__, and I wonder whether that is a safe > assumption. Remember the recent thread on using a different implementation for .__dict__? https://groups.google.com/group/python-ideas/browse_frm/thread/f15ef3c7b702a1fa Given it was impossible to have it *not* create a conventional dict via metaclasses, I would assume that there will always be a .__dict__. From t at jollybox.de Tue Jul 3 05:24:57 2012 From: t at jollybox.de (Thomas Jollans) Date: Tue, 03 Jul 2012 11:24:57 +0200 Subject: How can i do python form post request? In-Reply-To: <1341292136.76763.YahooMailClassic@web164601.mail.gq1.yahoo.com> References: <1341292136.76763.YahooMailClassic@web164601.mail.gq1.yahoo.com> Message-ID: <4FF2BA69.4040902@jollybox.de> On 07/03/2012 07:08 AM, gmspro wrote: > > form.html: >
> > >
> > p.py: > #!/usr/bin/python > > #what to write here... > > Both files are put in /var/www/ , now from http://localhost/form.html, > if i click the submit button would i execute the p.py and how can i get > the value of textbox? > > Any answer will be highly appreciated. > Thanks in advanced. First, you need to tell the web server to execute your Python script. What you do next depends on how you've done that. The simplest way is probably to pub p.py in your cgi-bin directory. This could be in /var/www/cgi-bin or elsewhere, like /usr/lib/cgi-bin. You may need to enable CGI, check the relevant documentation (or with the admin). When you've made sure the script is executed as a CGI script, you can use the cgi module to get all the information you need. http://docs.python.org/library/cgi.html A better way to write web applications in Python is with WSGI. You can run WSGI scripts in a number of ways, including CGI and other, more efficient ways that integrate with the web server. Maybe somebody else knows of a good tutorial on WSGI that they'll link here, otherwise, I'm sure Google is your friend. Thomas From duncan.booth at invalid.invalid Tue Jul 3 05:38:05 2012 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jul 2012 09:38:05 GMT Subject: Dictless classes References: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > You can create instances without a __dict__ by setting __slots__: That is a necessary but not a sufficient condition. An instance of a class can be created without a dict only if (either you set __slots__ or you implement it in C without a __dict__ attribute) AND none of its base classes require a dict. Setting __slots__ when a base class requires that its instances have a __dict__ doesn't prevent creation of the __dict__. > > But the class itself still has a __dict__: The class is an instance of 'type'. Instances of 'type' require a dict therefore every class requires a dict. Except of course for old style classes in Python 2.x but they have a __dict__ too. Also you cannot create a subclass of 'type' with non-empty slots (it throws a type error "nonempty __slots__ not supported for subtype of 'type'"). However I don't think that's really relevant as even if they did allow you to use __slots__ it wouldn't prevent the creation of a __dict__ for the 'type' base class. > I don't have a use-case for this. But I have some code which assumes > that every class will have a __dict__, and I wonder whether that is a > safe assumption. I believe so. -- Duncan Booth http://kupuguy.blogspot.com From miheer.dew at gmail.com Tue Jul 3 07:11:05 2012 From: miheer.dew at gmail.com (Miheer Dewaskar) Date: Tue, 3 Jul 2012 16:41:05 +0530 Subject: Best data structure for DFS on large graphs Message-ID: I want to make a combinatorial game solver in python.The algorithm is to perform Depth First Search (DFS) on the states of the game. For DFS I,would need to keep a record of the visited states.What is the best data structure for it,keeping in mind that the number of states could be large? I was thinking about using Dictionary or a Binary Search Tree (BST) ,assuming that the states can be made hashable and totally ordered respectively. I am not sure,but if there are large number of states Dictionaries wont help much right? Anyway, does python have a built-in BST like data-structure ? Thanks, Miheer -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Jul 3 07:23:58 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 03 Jul 2012 13:23:58 +0200 Subject: Best data structure for DFS on large graphs In-Reply-To: References: Message-ID: Miheer Dewaskar, 03.07.2012 13:11: > I want to make a combinatorial game solver in python.The algorithm is to > perform Depth First Search (DFS) on the states of the game. > For DFS I,would need to keep a record of the visited states.What is the > best data structure for it,keeping in mind that the number of states could > be large? > > I was thinking about using Dictionary or a Binary Search Tree (BST) > ,assuming that the states can be made hashable and totally ordered > respectively. > I am not sure,but if there are large number of states Dictionaries wont > help much right? Dicts are fast for lookup, not for searching. > Anyway, does python have a built-in BST like data-structure ? It has lists and bisect: http://docs.python.org/library/bisect.html Stefan From neilc at norwich.edu Tue Jul 3 08:19:49 2012 From: neilc at norwich.edu (Neil Cerutti) Date: 3 Jul 2012 12:19:49 GMT Subject: code review References: <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefcf72$0$29988$c3e8da3$5496439d@news.astraweb.com> <4fefedd8$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff0f939$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff157a4$0$30001$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2012-07-02, Chris Angelico wrote: > On Tue, Jul 3, 2012 at 1:57 AM, Rick Johnson > wrote: >> Poor Chris. That's because you've been brainwashed into believing you >> must spoon feed your interpreter to get your code working correctly. >> Stop applying these naive assumptions to Python code. Python knows >> when you reach the end of a statement, no need for redundant >> semicolons! Python knows when its reached the end of block and needs >> to drop back one level, no need for redundant road signs. Python >> knows Chris; Python KNOWS! > > Why "poor", Ralph? > > I am poor in the essence of ignorance's bliss, rich only in the > never-ending thirst for knowledge and more languages. In me there meet > a combination of antithetical elements which are at eternal war with > one another... I hope I make myself clear, lady? His simple eloquence goes to my very heart! -- Neil Cerutti From roy at panix.com Tue Jul 3 08:28:01 2012 From: roy at panix.com (Roy Smith) Date: Tue, 03 Jul 2012 08:28:01 -0400 Subject: Dictless classes References: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> Message-ID: In article , Duncan Booth wrote: > Also you cannot create a subclass of 'type' with non-empty slots (it throws > a type error "nonempty __slots__ not supported for subtype of 'type'"). > However I don't think that's really relevant as even if they did allow you > to use __slots__ it wouldn't prevent the creation of a __dict__ for the > 'type' base class. I played around a bit trying to write a metaclass which implemented: def __getattribute__(self, name): if name == "__dict__": raise AttributeError but didn't get very far. Maybe somebody with stronger metaclass-fu than I have could run with this idea? From gmspro at yahoo.com Tue Jul 3 08:32:40 2012 From: gmspro at yahoo.com (gmspro) Date: Tue, 3 Jul 2012 05:32:40 -0700 (PDT) Subject: How can i do python form post request? Message-ID: <1341318760.22221.YahooMailClassic@web164606.mail.gq1.yahoo.com> @Thomas, >First, you need to tell the web server to execute your Python script. What you do next depends on how you've done that. >The simplest way is probably to pub p.py in your cgi-bin directory. This could be in /var/www/cgi-bin or elsewhere, like /usr/lib/cgi-bin. You may need to enable CGI, check the relevant documentation (or with the admin). >When you've made sure the script is executed as a CGI script, you can use the cgi module to get all the information you need. http://docs.python.org/library/cgi.html >A better way to write web applications in Python is with WSGI. You can run WSGI scripts in a number of ways, including CGI and other, more efficient ways that integrate with the web server. Maybe somebody else knows of a good tutorial on WSGI that they'll link here, otherwise, I'm sure Google is your friend. I don't want to use CGI, i followed this example, this works fine, http://webpython.codepoint.net/wsgi_request_parsing_post But the html is embeded there. But i want html form as a seperate file. How can i do it? form.html:
? ?
Typing text when i click the submit button, browser prompts me to download the p.py file. That's not what i want. I want to execute the p.py file after click. Is it possible in WSGI. I have installed: libapache2-mod-wsgi Any answer will be highly appreciate. Thanks in advanced. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Tue Jul 3 08:33:38 2012 From: roy at panix.com (Roy Smith) Date: Tue, 03 Jul 2012 08:33:38 -0400 Subject: code review References: <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff270ea$0$11103$c3e8da3@news.astraweb.com> Message-ID: In article , Dennis Lee Bieber wrote: > On 03 Jul 2012 04:11:22 GMT, Steven D'Aprano > declaimed the following in > gmane.comp.python.general: > > > > One of my favourites is the league, which in the Middle Ages was actually > > defined as the distance that a man, or a horse, could walk in an hour. > > From the "Explanatory Supplement to the Astronomical Almanac" [1992 > University Science Books], Table 15.15, the speed of light is > > 1.80261750E12 furlongs/fortnight And sure enough, that's what units says: $ units 500 units, 54 prefixes You have: c You want: furlongs/fortnight * 1.8026175e+12 / 5.5474886e-13 From wanderer at dialup4less.com Tue Jul 3 08:49:35 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 3 Jul 2012 05:49:35 -0700 (PDT) Subject: WxSlider Mouse Wheel Resolution In-Reply-To: References: Message-ID: <929f56e9-9de5-48c3-8678-5efe76d8d84f@googlegroups.com> On Monday, July 2, 2012 6:53:36 PM UTC-4, Dennis Lee Bieber wrote: > On Mon, 2 Jul 2012 08:45:49 -0700 (PDT), Wanderer > declaimed the following in > gmane.comp.python.general: > > > Is there a way to set the mouse wheel resolution for the wxPython > > wx.Slider? I would like to use the graphic slider for coarse control > > and the mouse wheel for fine control. Right now the mouse wheel makes > > the slider jump ten counts and I would like it to be a single count. > > > Isn't that a condition of the OS Mouse driver? > > My LogiTech driver (WinXP) has "scroller: 1, 3, 6 lines" > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ Maybe there are some system settings but I believe they can be overridden by the application. Check out the Firefox options for the mouse wheel. http://www.pcworld.com/article/163639/change_the_speed_of_mousewheel_scrolling_in_firefox.html From wanderer at dialup4less.com Tue Jul 3 08:49:35 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 3 Jul 2012 05:49:35 -0700 (PDT) Subject: WxSlider Mouse Wheel Resolution In-Reply-To: References: Message-ID: <929f56e9-9de5-48c3-8678-5efe76d8d84f@googlegroups.com> On Monday, July 2, 2012 6:53:36 PM UTC-4, Dennis Lee Bieber wrote: > On Mon, 2 Jul 2012 08:45:49 -0700 (PDT), Wanderer > declaimed the following in > gmane.comp.python.general: > > > Is there a way to set the mouse wheel resolution for the wxPython > > wx.Slider? I would like to use the graphic slider for coarse control > > and the mouse wheel for fine control. Right now the mouse wheel makes > > the slider jump ten counts and I would like it to be a single count. > > > Isn't that a condition of the OS Mouse driver? > > My LogiTech driver (WinXP) has "scroller: 1, 3, 6 lines" > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ Maybe there are some system settings but I believe they can be overridden by the application. Check out the Firefox options for the mouse wheel. http://www.pcworld.com/article/163639/change_the_speed_of_mousewheel_scrolling_in_firefox.html From t at jollybox.de Tue Jul 3 08:58:11 2012 From: t at jollybox.de (Thomas Jollans) Date: Tue, 03 Jul 2012 14:58:11 +0200 Subject: How can i do python form post request? In-Reply-To: <1341318760.22221.YahooMailClassic@web164606.mail.gq1.yahoo.com> References: <1341318760.22221.YahooMailClassic@web164606.mail.gq1.yahoo.com> Message-ID: <4FF2EC63.5060704@jollybox.de> On 07/03/2012 02:32 PM, gmspro wrote: > @Thomas, > >>First, you need to tell the web server to execute your Python script. > What you do next depends on how you've done that. > >>The simplest way is probably to pub p.py in your cgi-bin directory. This > could be in /var/www/cgi-bin or elsewhere, like /usr/lib/cgi-bin. You > may need to enable CGI, check the relevant documentation (or with the > admin). > >>When you've made sure the script is executed as a CGI script, you can > use the cgi module to get all the information you need. > http://docs.python.org/library/cgi.html > >>A better way to write web applications in Python is with WSGI. You can > run WSGI scripts in a number of ways, including CGI and other, more > efficient ways that integrate with the web server. Maybe somebody else > knows of a good tutorial on WSGI that they'll link here, otherwise, I'm > sure Google is your friend. > > I don't want to use CGI, i followed this example, this works fine, > http://webpython.codepoint.net/wsgi_request_parsing_post > > But the html is embeded there. But i want html form as a seperate file. > How can i do it? That makes absolutely no difference. Have you been able to run that example script? They're using wsgi.simple_server, of course, but you could start by removing that part and configuring mod_wsgi to run your WSGI script. http://ubuntuforums.org/showthread.php?t=833766 could be helpful, search the web for howtos on mod_wsgi to get started. Once you have your web server running the WSGI code, the rest should be trivial. > > form.html: >
> > >
> > Typing text when i click the submit button, browser prompts me to > download the p.py file. > That's not what i want. I want to execute the p.py file after click. Is > it possible in WSGI. > > I have installed: libapache2-mod-wsgi > > Any answer will be highly appreciate. > Thanks in advanced. > > > > From miheer.dew at gmail.com Tue Jul 3 09:39:44 2012 From: miheer.dew at gmail.com (Miheer Dewaskar) Date: Tue, 3 Jul 2012 19:09:44 +0530 Subject: Best data structure for DFS on large graphs In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 4:53 PM, Stefan Behnel wrote: > > Miheer Dewaskar, 03.07.2012 13:11: > > I am not sure,but if there are large number of states Dictionaries wont > > help much right? > > Dicts are fast for lookup, not for searching. > What do you mean by searching in the context of Dicts? > > Anyway, does python have a built-in BST like data-structure ? > > It has lists and bisect: > > http://docs.python.org/library/bisect.html But insertion and deletion in a list is o(n): http://wiki.python.org/moin/TimeComplexity/#list -- Miheer Dewaskar From python.list at tim.thechases.com Tue Jul 3 10:40:10 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 03 Jul 2012 09:40:10 -0500 Subject: Best data structure for DFS on large graphs In-Reply-To: References: Message-ID: <4FF3044A.9060206@tim.thechases.com> On 07/03/12 08:39, Miheer Dewaskar wrote: > On Tue, Jul 3, 2012 at 4:53 PM, Stefan Behnel wrote: >> >> Miheer Dewaskar, 03.07.2012 13:11: >>> I am not sure,but if there are large number of states Dictionaries wont >>> help much right? >> >> Dicts are fast for lookup, not for searching. >> > What do you mean by searching in the context of Dicts? It took me a while to parse Stefan's post, and I *think* he means that key-indexing (direct lookup) is fast O(1), and that by "searching" he means something like "find all keys/values matching property $FOO" such as between a range. One of the important things you omit is how you define "large". Is this a couple thousand? Hundreds of thousands? Millions? Also, what sort of information are you keeping in the state? Just available transitions? Or do you want additional metadata? If it's just transition mappings (A->B) rather than complex objects, I'd try using a dict first, and if it's too large, I'd reach for the "anydbm" module to store them to disk. -tkc From research at johnohagan.com Tue Jul 3 10:59:19 2012 From: research at johnohagan.com (John O'Hagan) Date: Wed, 4 Jul 2012 00:59:19 +1000 Subject: code review In-Reply-To: <3f15d831-45bb-471c-8d49-a2db21e67c7a@nl1g2000pbc.googlegroups.com> References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <3f15d831-45bb-471c-8d49-a2db21e67c7a@nl1g2000pbc.googlegroups.com> Message-ID: <20120704005919.bf29fbdbd0579def3bb874bc@johnohagan.com> On Mon, 2 Jul 2012 22:10:00 -0700 (PDT) rusi wrote: > On Jul 3, 7:25?am, John O'Hagan wrote: > > > > I agree to some extent, but as a counter-example, when I was a child there > > a subject called "Weights and Measures" which is now redundant because of > > the Metric system. I don't miss hogsheads and fathoms at all. > > > > Music is another field which could do with a "metrification": I get tired of > > explaining to beginners why there's no B#, except when it's C. Check > > outhttp://musicnotation.org > > You assume that equal temperament is the only way to have music. > Apart from the fact that there are non-tempered musics all over the > world, even Bach Mozart and Beethoven did not write for/to equal > temperament. In a pure/untempered C-scale A-flat is almost half a > semitone sharper than G-sharp -- 8/5 vs 25/16. > [...] I don't assume that at all :) If you didn't already, have look at the link. I was talking about notation of the normal everyday contemporary tempered system where there is no pitch difference between Ab and G#. But even in a just system, any difference between them depends on the system itself, the key, and whether you choose to call them that. I've never heard anyone claim that C is sharper than B#, although in the key of E the relationship would be the same. AIUI there is any number of whole number ratios which fall between seven and nine tempered semitones above the fundamental (to take your example), and in C, any one of them could be called either Ab or G# depending on the key signature or other context. IMHO, that's the aspect that could benefit from a simplified representation. To the OP, I'm deeply sorry! -- John From miheer.dew at gmail.com Tue Jul 3 11:08:05 2012 From: miheer.dew at gmail.com (Miheer Dewaskar) Date: Tue, 3 Jul 2012 20:38:05 +0530 Subject: Best data structure for DFS on large graphs In-Reply-To: <4FF3044A.9060206@tim.thechases.com> References: <4FF3044A.9060206@tim.thechases.com> Message-ID: On Tue, Jul 3, 2012 at 8:10 PM, Tim Chase wrote: > On 07/03/12 08:39, Miheer Dewaskar wrote: >> On Tue, Jul 3, 2012 at 4:53 PM, Stefan Behnel wrote: >>> >>> Miheer Dewaskar, 03.07.2012 13:11: >>>> I am not sure,but if there are large number of states Dictionaries wont >>>> help much right? >>> >>> Dicts are fast for lookup, not for searching. >>> >> What do you mean by searching in the context of Dicts? > > It took me a while to parse Stefan's post, and I *think* he means > that key-indexing (direct lookup) is fast O(1), and that by > "searching" he means something like "find all keys/values matching > property $FOO" such as between a range. > > One of the important things you omit is how you define "large". Is > this a couple thousand? Hundreds of thousands? Millions? I want it to be a generic Game solver.So the number of states depends on the game. For a simple tic-tac-toe the upper bound is 3^9 states.But for more complex games it could be much larger. I would like to assume that the number of states can grow arbitrarily large. > Also, what sort of information are you keeping in the state? Just > available transitions? Or do you want additional metadata? If it's > just transition mappings (A->B) rather than complex objects, I'd try > using a dict first, and if it's too large, I'd reach for the > "anydbm" module to store them to disk. The state just has 'state data'.The transitions are obtained by functions analyzing the state. So that I should not be able to identify between two same states that have been reached by different means. For example in the tic-tac-toe game the states can be a 3x3 box of integers 0 -> unoccupied 1 -> x 2-> o ( (2,0,1), o - x (1,1,0), -> x x - (2,0,0) ) o - - -- Miheer Dewaskar From breamoreboy at yahoo.co.uk Tue Jul 3 11:50:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Jul 2012 16:50:15 +0100 Subject: code review In-Reply-To: <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> References: <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> Message-ID: On 03/07/2012 03:25, John O'Hagan wrote: > On Tue, 3 Jul 2012 11:22:55 +1000 > > I agree to some extent, but as a counter-example, when I was a child there > a subject called "Weights and Measures" which is now redundant because of the > Metric system. I don't miss hogsheads and fathoms at all. > > John > I weigh 13st 8lb - does this make me redundant? -- Cheers. Mark Lawrence. From rosuav at gmail.com Tue Jul 3 11:53:12 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 4 Jul 2012 01:53:12 +1000 Subject: code review In-Reply-To: References: <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> Message-ID: On Wed, Jul 4, 2012 at 1:50 AM, Mark Lawrence wrote: > On 03/07/2012 03:25, John O'Hagan wrote: >> >> On Tue, 3 Jul 2012 11:22:55 +1000 >> >> I agree to some extent, but as a counter-example, when I was a child there >> a subject called "Weights and Measures" which is now redundant because of >> the >> Metric system. I don't miss hogsheads and fathoms at all. >> >> John >> > > I weigh 13st 8lb - does this make me redundant? Yes, because somewhere in the world is someone who weighs (... pulls out calculator...) 86kg. After all, the French had a bloody revolution to get us a new system without any of the old baggage. We don't want to disappoint the French now, do we! ChrisA lemme just dislodge my tongue from my cheek, it seems to be stuck... From breamoreboy at yahoo.co.uk Tue Jul 3 11:53:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Jul 2012 16:53:37 +0100 Subject: code review In-Reply-To: References: <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ff270ea$0$11103$c3e8da3@news.astraweb.com> Message-ID: On 03/07/2012 07:09, Dennis Lee Bieber wrote: > On 03 Jul 2012 04:11:22 GMT, Steven D'Aprano > declaimed the following in > gmane.comp.python.general: > > >> One of my favourites is the league, which in the Middle Ages was actually >> defined as the distance that a man, or a horse, could walk in an hour. > > From the "Explanatory Supplement to the Astronomical Almanac" [1992 > University Science Books], Table 15.15, the speed of light is > > 1.80261750E12 furlongs/fortnight > +1 most useless piece of information garnered this week. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Jul 3 12:05:24 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Jul 2012 17:05:24 +0100 Subject: code review In-Reply-To: References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> Message-ID: On 03/07/2012 16:53, Chris Angelico wrote: > On Wed, Jul 4, 2012 at 1:50 AM, Mark Lawrence wrote: >> On 03/07/2012 03:25, John O'Hagan wrote: >>> >>> On Tue, 3 Jul 2012 11:22:55 +1000 >>> >>> I agree to some extent, but as a counter-example, when I was a child there >>> a subject called "Weights and Measures" which is now redundant because of >>> the >>> Metric system. I don't miss hogsheads and fathoms at all. >>> >>> John >>> >> >> I weigh 13st 8lb - does this make me redundant? > > Yes, because somewhere in the world is someone who weighs (... pulls > out calculator...) 86kg. After all, the French had a bloody revolution > to get us a new system without any of the old baggage. We don't want > to disappoint the French now, do we! > > ChrisA > lemme just dislodge my tongue from my cheek, it seems to be stuck... > If I go to the moon I will weigh 2st 10lb (if my sums are correct :) but the equivalent Frenchman will still be 86kg. I hereby put this forward as proof that the metric system is rubbish and we should revert back to imperial goodies. -- Cheers. Mark Lawrence. From drsalists at gmail.com Tue Jul 3 12:19:26 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 3 Jul 2012 16:19:26 +0000 Subject: Best data structure for DFS on large graphs In-Reply-To: References: <4FF3044A.9060206@tim.thechases.com> Message-ID: On Tue, Jul 3, 2012 at 3:08 PM, Miheer Dewaskar wrote: > On Tue, Jul 3, 2012 at 8:10 PM, Tim Chase > wrote: > I want it to be a generic Game solver.So the number of states depends > on the game. > Keep in mind that it would probably be a generic game solver for games that have simple board evaluation functions. For something like Go, despite its simple rules, much more is required. > For a simple tic-tac-toe the upper bound is 3^9 states.But for more > complex games it could be much larger. > I would like to assume that the number of states can grow arbitrarily > large. > > For example in the tic-tac-toe game the states can be a 3x3 box of integers > > 0 -> unoccupied > 1 -> x > 2-> o > > ( (2,0,1), o - x > (1,1,0), -> x x - > (2,0,0) ) o - - > For just saving game board states to avoid re-traversal, I'd think a set (if you require no ancillary information) or dict (if you do) would be appropriate. But perhaps consider Zobrist hashing: http://en.wikipedia.org/wiki/Zobrist_hashing -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Tue Jul 3 13:53:34 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 3 Jul 2012 23:23:34 +0530 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jun 30, 2012 at 3:34 PM, Alister wrote: > On Fri, 29 Jun 2012 09:03:22 -0600, Littlefield, Tyler wrote: > >> On 6/29/2012 1:31 AM, Steven D'Aprano wrote: >>> On Thu, 28 Jun 2012 20:58:15 -0700, alex23 wrote: >>> >>>> On Jun 29, 12:57 pm, "Littlefield, Tyler" wrote: >>>>> I was curious if someone wouldn't mind poking at some code. The >>>>> project page is at:http://code.google.com/p/pymud Any information is >>>>> greatly appreciated. >>>> I couldn't find any actual code at that site, the git repository is >>>> currently empty. >> >> OOPS, sorry. Apparently I'm not as good with git as I thought. >> Everything's in the repo now. > > I think I may be on firmer grounds with the next few: > > isValidPassword can be simplified to > > def isValidPassword(password: > count=len(password) > return count>= mud.minpass and count<= mud.maxpass > I haven't actually seen the rest of the code, but I would like to point out that applications placing maximum length limits on passwords are extremely annoying. > -- regards, kushal From gordon at panix.com Tue Jul 3 14:18:13 2012 From: gordon at panix.com (John Gordon) Date: Tue, 3 Jul 2012 18:18:13 +0000 (UTC) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In Kushal Kumaran writes: > I haven't actually seen the rest of the code, but I would like to > point out that applications placing maximum length limits on passwords > are extremely annoying. As a practical matter, doesn't there have to be *some* sort of limit? For example if the (encrypted) password is stored in a database, you can't exceed the table column width. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From ian.g.kelly at gmail.com Tue Jul 3 14:19:25 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 12:19:25 -0600 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 3, 2012 at 11:53 AM, Kushal Kumaran wrote: > On Sat, Jun 30, 2012 at 3:34 PM, Alister wrote: >> On Fri, 29 Jun 2012 09:03:22 -0600, Littlefield, Tyler wrote: >> >>> On 6/29/2012 1:31 AM, Steven D'Aprano wrote: >>>> On Thu, 28 Jun 2012 20:58:15 -0700, alex23 wrote: >>>> >>>>> On Jun 29, 12:57 pm, "Littlefield, Tyler" wrote: >>>>>> I was curious if someone wouldn't mind poking at some code. The >>>>>> project page is at:http://code.google.com/p/pymud Any information is >>>>>> greatly appreciated. >>>>> I couldn't find any actual code at that site, the git repository is >>>>> currently empty. >>> >>> OOPS, sorry. Apparently I'm not as good with git as I thought. >>> Everything's in the repo now. >> >> I think I may be on firmer grounds with the next few: >> >> isValidPassword can be simplified to >> >> def isValidPassword(password: >> count=len(password) >> return count>= mud.minpass and count<= mud.maxpass >> > > I haven't actually seen the rest of the code, but I would like to > point out that applications placing maximum length limits on passwords > are extremely annoying. They're annoying when the maximum length is unreasonably small, but you have to have a maximum length to close off one DoS attack vector. Without a limit, if a "user" presents a 1 GB password, then guess what? Your system has to hash that GB of data before it can reject it. And if you're serious about security then it will be a cryptographic hash, and that means slow. To prevent that, the system needs to reject outright password attempts that are longer than some predetermined reasonable length, and if the system won't authenticate those passwords, then it can't allow the user to set them either. Cheers, Ian From ian.g.kelly at gmail.com Tue Jul 3 14:27:05 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 12:27:05 -0600 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 3, 2012 at 12:18 PM, John Gordon wrote: > In Kushal Kumaran writes: > >> I haven't actually seen the rest of the code, but I would like to >> point out that applications placing maximum length limits on passwords >> are extremely annoying. > > As a practical matter, doesn't there have to be *some* sort of limit? > For example if the (encrypted) password is stored in a database, you can't > exceed the table column width. Hopefully you're storing password hashes, not encrypted passwords (which can all too easily be DEcrypted), and the length of the hash is not dependent on the length of the password. But yes, there are certainly practical concerns here. From d at davea.name Tue Jul 3 16:13:50 2012 From: d at davea.name (Dave Angel) Date: Tue, 03 Jul 2012 16:13:50 -0400 Subject: code review In-Reply-To: References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> Message-ID: <4FF3527E.40305@davea.name> On 07/03/2012 12:05 PM, Mark Lawrence wrote: > On 03/07/2012 16:53, Chris Angelico wrote: >> On Wed, Jul 4, 2012 at 1:50 AM, Mark Lawrence >> wrote: >>> On 03/07/2012 03:25, John O'Hagan wrote: >>>> >>>> On Tue, 3 Jul 2012 11:22:55 +1000 >>>> >>>> I agree to some extent, but as a counter-example, when I was a >>>> child there >>>> a subject called "Weights and Measures" which is now redundant >>>> because of >>>> the >>>> Metric system. I don't miss hogsheads and fathoms at all. >>>> >>>> John >>>> >>> >>> I weigh 13st 8lb - does this make me redundant? >> >> Yes, because somewhere in the world is someone who weighs (... pulls >> out calculator...) 86kg. After all, the French had a bloody revolution >> to get us a new system without any of the old baggage. We don't want >> to disappoint the French now, do we! >> >> ChrisA >> lemme just dislodge my tongue from my cheek, it seems to be stuck... >> > > If I go to the moon I will weigh 2st 10lb (if my sums are correct :) > but the equivalent Frenchman will still be 86kg. I hereby put this > forward as proof that the metric system is rubbish and we should > revert back to imperial goodies. > 86 kg is not a weight, it's a mass. So it doesn't depend on the local gravity situation. DaveA -- DaveA From drsalists at gmail.com Tue Jul 3 16:40:57 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 3 Jul 2012 20:40:57 +0000 Subject: Why site-packages? Message-ID: Why is it that so much 3rd party python code gets installed to site-packages? Even for things that are almost certainly going to be used by a single application? Even for things you might only use once? Even for things that might require one version for one app, and another version for another app? Why not stash an application's python modules in /usr/local/lib/[appname], and stash a little frontend in /usr/local/bin that adds /usr/local/lib/[appname] to sys.path? Here's a thread on stackoverflow today asking why python starts up so slowly, and making it clear that this is because so much stuff ends up in site-packages: http://stackoverflow.com/questions/11318028/is-it-safe-to-use-pythons-s-option The response "Because that's where things are supposed to go" makes me ask "Who made this decision and why?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Jul 3 17:04:17 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 15:04:17 -0600 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 2:40 PM, Dan Stromberg wrote: > > Why is it that so much 3rd party python code gets installed to > site-packages? Because that's what site-packages is for? > Even for things that are almost certainly going to be used by a single > application? > > Even for things you might only use once? > > Even for things that might require one version for one app, and another > version for another app? For these types of uses, I suggest using virtualenv if you don't want to pollute your site-packages. Or Python 3.3 with the new built-in virtual environment option. > Why not stash an application's python modules in /usr/local/lib/[appname], > and stash a little frontend in /usr/local/bin that adds > /usr/local/lib/[appname] to sys.path? What if you then write an application that you find needs two of these libraries? You write yet another frontend that adds both of them to sys.path? > Here's a thread on stackoverflow today asking why python starts up so > slowly, and making it clear that this is because so much stuff ends up in > site-packages: > http://stackoverflow.com/questions/11318028/is-it-safe-to-use-pythons-s-option I think you may be misunderstanding that thread. They're saying that starting Python with the -S option (i.e. not automatically importing the site module) significantly cuts down on Python's startup time. The site module has to process any .pth files in the site-packages, but apart from that, I think the actual amount of stuff in site-packages should be irrelevant. Nothing in site-packages is actually imported or otherwise processed until the application requests it. You could have a completely empty site-packages, or you could have 20 gigs of third-party packages, and the time to import site would be basically the same. From drsalists at gmail.com Tue Jul 3 17:34:50 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 3 Jul 2012 21:34:50 +0000 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 9:04 PM, Ian Kelly wrote: > On Tue, Jul 3, 2012 at 2:40 PM, Dan Stromberg wrote: > > > > Why is it that so much 3rd party python code gets installed to > > site-packages? > > Because that's what site-packages is for? > Agh. But -why- is it because that's what it's for? "Who made this rule"? > > Even for things that are almost certainly going to be used by a single > > application? > > > > Even for things you might only use once? > > > > Even for things that might require one version for one app, and another > > version for another app? > > For these types of uses, I suggest using virtualenv if you don't want > to pollute your site-packages. Or Python 3.3 with the new built-in > virtual environment option. > Virtualenv is worth thinking about, but it kind of does the same thing, just less of it. > > Why not stash an application's python modules in > /usr/local/lib/[appname], > > and stash a little frontend in /usr/local/bin that adds > > /usr/local/lib/[appname] to sys.path? > > What if you then write an application that you find needs two of these > libraries? You write yet another frontend that adds both of them to > sys.path? > If it was intended to be reusable code, I'd think it -should- go in site-packages. But so much code in site-packages isn't intended to be reusable. And even for stuff that's reusable, there are advantages to just duplicating them for the purposes of each application, because you never know when one of them is going to need a different version from another. If we weren't stashing so much stuff in site-packages, there probably wouldn't have been a desire for something like virtualenv. > > Here's a thread on stackoverflow today asking why python starts up so > > slowly, and making it clear that this is because so much stuff ends up in > > site-packages: > > > http://stackoverflow.com/questions/11318028/is-it-safe-to-use-pythons-s-option > > I think you may be misunderstanding that thread. They're saying that > starting Python with the -S option (i.e. not automatically importing > the site module) significantly cuts down on Python's startup time. > Yes... > The site module has to process any .pth files in the site-packages, > but apart from that, I think the actual amount of stuff in > site-packages should be irrelevant. Irrelevant to what? More stuff in site slowing things down? Are .pth's not correlated with more stuff in site-packages? Aren't they actually a thing In site? > Nothing in site-packages is > actually imported or otherwise processed until the application > requests it. Other than .pth's, apparently. > You could have a completely empty site-packages, or you > could have 20 gigs of third-party packages, and the time to import > site would be basically the same. > Well, I'd guess that a large directory would slow things down before causing filesystem complaints, but I see your point. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Jul 3 17:51:18 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 4 Jul 2012 07:51:18 +1000 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Jul 4, 2012 at 4:27 AM, Ian Kelly wrote: > On Tue, Jul 3, 2012 at 12:18 PM, John Gordon wrote: >> As a practical matter, doesn't there have to be *some* sort of limit? >> For example if the (encrypted) password is stored in a database, you can't >> exceed the table column width. > > Hopefully you're storing password hashes, not encrypted passwords > (which can all too easily be DEcrypted), and the length of the hash is > not dependent on the length of the password. But yes, there are > certainly practical concerns here. With a hash length of N bits, there's not much use accepting passwords longer than about N/4 or N/2 bytes. (It would be N/8 except that most people don't invent passwords that use the entire available alphabet. And of course, this ignores issues of encodings, but I'm pretty sure all current crypto hashes work with bytes not characters anyway.) But please, don't limit password lengths too much. Make your password system XKCD 936 compliant: http://xkcd.com/936/ Permit long passwords consisting of nothing but lowercase letters. They really aren't as insecure as some people think! ChrisA From rosuav at gmail.com Tue Jul 3 17:54:46 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 4 Jul 2012 07:54:46 +1000 Subject: code review In-Reply-To: <4FF3527E.40305@davea.name> References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> <4FF3527E.40305@davea.name> Message-ID: On Wed, Jul 4, 2012 at 6:13 AM, Dave Angel wrote: > On 07/03/2012 12:05 PM, Mark Lawrence wrote: >> If I go to the moon I will weigh 2st 10lb (if my sums are correct :) >> but the equivalent Frenchman will still be 86kg. I hereby put this >> forward as proof that the metric system is rubbish and we should >> revert back to imperial goodies. >> > > 86 kg is not a weight, it's a mass. So it doesn't depend on the local > gravity situation. Indeed it is, as he says. But I believe he may be right in that 'stone' is a unit of weight. Hard to be sure, though, given that it's not an SI unit (for instance, the Wikipedia article text refers to weight, but its picture shows a man measuring mass). ChrisA From t at jollybox.de Tue Jul 3 17:58:30 2012 From: t at jollybox.de (Thomas Jollans) Date: Tue, 03 Jul 2012 23:58:30 +0200 Subject: Why site-packages? In-Reply-To: References: Message-ID: <4FF36B06.9020203@jollybox.de> On 07/03/2012 11:34 PM, Dan Stromberg wrote: > On Tue, Jul 3, 2012 at 9:04 PM, Ian Kelly > wrote: > > On Tue, Jul 3, 2012 at 2:40 PM, Dan Stromberg > wrote: > > > > Why is it that so much 3rd party python code gets installed to > > site-packages? > > Because that's what site-packages is for? > > > Agh. But -why- is it because that's what it's for? > > "Who made this rule"? It's (reasonably) consistent with the way things are usually done on UNIX. Libraries go in /usr/lib. That's all libraries, not just core system libraries. Similarly, Python modules go in /usr/lib/python. That's all Python modules, not just the standard library. That means that you can use them in scripts without faffing around because the interpreter will find them, even if you're in a completely random directory. The point of site-packages then is to make sure that user-installed packages are cleanly separated from standard and distribution-installed packages, similarly to the way /usr/local/ is used in general (and can be used for Python packages, of course) > > > > Even for things that are almost certainly going to be used by a single > > application? > > > > Even for things you might only use once? > > > > Even for things that might require one version for one app, and > another > > version for another app? > > For these types of uses, I suggest using virtualenv if you don't want > to pollute your site-packages. Or Python 3.3 with the new built-in > virtual environment option. > > Virtualenv is worth thinking about, but it kind of does the same thing, > just less of it. > > > > Why not stash an application's python modules in > /usr/local/lib/[appname], > > and stash a little frontend in /usr/local/bin that adds > > /usr/local/lib/[appname] to sys.path? > > What if you then write an application that you find needs two of these > libraries? You write yet another frontend that adds both of them to > sys.path? > > If it was intended to be reusable code, I'd think it -should- go in > site-packages. > > But so much code in site-packages isn't intended to be reusable. > > And even for stuff that's reusable, there are advantages to just > duplicating them for the purposes of each application, because you never > know when one of them is going to need a different version from another. > > If we weren't stashing so much stuff in site-packages, there probably > wouldn't have been a desire for something like virtualenv. > > > > Here's a thread on stackoverflow today asking why python starts up so > > slowly, and making it clear that this is because so much stuff > ends up in > > site-packages: > > > http://stackoverflow.com/questions/11318028/is-it-safe-to-use-pythons-s-option > > I think you may be misunderstanding that thread. They're saying that > starting Python with the -S option (i.e. not automatically importing > the site module) significantly cuts down on Python's startup time. > > Yes... > > > The site module has to process any .pth files in the site-packages, > but apart from that, I think the actual amount of stuff in > site-packages should be irrelevant. > > Irrelevant to what? More stuff in site slowing things down? Are > .pth's not correlated with more stuff in site-packages? Aren't they > actually a thing In site? > > > Nothing in site-packages is > actually imported or otherwise processed until the application > requests it. > > Other than .pth's, apparently. > > > You could have a completely empty site-packages, or you > could have 20 gigs of third-party packages, and the time to import > site would be basically the same. > > Well, I'd guess that a large directory would slow things down before > causing filesystem complaints, but I see your point. > > > From ian.g.kelly at gmail.com Tue Jul 3 18:04:45 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 16:04:45 -0600 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 3:34 PM, Dan Stromberg wrote: > If it was intended to be reusable code, I'd think it -should- go in > site-packages. > > But so much code in site-packages isn't intended to be reusable. Can you give some examples? Looking through my site-packages directory, everything in there is either used by multiple applications or at least has the potential to be. Frankly, if you've installed a third-party package and written your own code against it, even if only in one little script, isn't that already reuse? > And even for stuff that's reusable, there are advantages to just duplicating > them for the purposes of each application, because you never know when one > of them is going to need a different version from another. Definitely a situation for virtualenv, IMO. >> The site module has to process any .pth files in the site-packages, >> but apart from that, I think the actual amount of stuff in >> site-packages should be irrelevant. > > Irrelevant to what? More stuff in site slowing things down? Are .pth's > not correlated with more stuff in site-packages? Aren't they actually a > thing In site? Yes, but I just don't expect the .pth files to grow that fast. I've got something like 30 packages in my site-packages and only 6 .pth files, and most of those are one-liners. Right now this all seems highly speculative to me. I think it might be informative, either to you or to me, to do an actual timing test. Why don't you try setting up two side-by-side installations of Python, one with all the site-packages cruft, and one trimmed down to only what you think should be in there, and see if you can measure a real difference in startup time? From drsalists at gmail.com Tue Jul 3 18:38:26 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 3 Jul 2012 22:38:26 +0000 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 10:04 PM, Ian Kelly wrote: > > >> The site module has to process any .pth files in the site-packages, > >> but apart from that, I think the actual amount of stuff in > >> site-packages should be irrelevant. > > > > Irrelevant to what? More stuff in site slowing things down? Are .pth's > > not correlated with more stuff in site-packages? Aren't they actually a > > thing In site? > > Yes, but I just don't expect the .pth files to grow that fast. I've > got something like 30 packages in my site-packages and only 6 .pth > files, and most of those are one-liners. > It's not the Lines of Code, it's the track to track seeks. > Right now this all seems highly speculative to me. I think it might > be informative, either to you or to me, to do an actual timing test. > Why don't you try setting up two side-by-side installations of Python, > one with all the site-packages cruft, and one trimmed down to only > what you think should be in there, and see if you can measure a real > difference in startup time? > In the original stackoverflow thread I mentioned, there's a speed comparison. It's possible they were seeing a cache effect, though it didn't really sound like it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Jul 3 19:06:10 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 17:06:10 -0600 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 4:38 PM, Dan Stromberg wrote: >> Right now this all seems highly speculative to me. I think it might >> be informative, either to you or to me, to do an actual timing test. >> Why don't you try setting up two side-by-side installations of Python, >> one with all the site-packages cruft, and one trimmed down to only >> what you think should be in there, and see if you can measure a real >> difference in startup time? > > In the original stackoverflow thread I mentioned, there's a speed > comparison. That's just comparing using -S against not using -S, though. As I understand it, you don't want to use -S; you still want to import site but just want to pare down your site-packages for a speedup. From howmuchistoday at gmail.com Tue Jul 3 19:12:48 2012 From: howmuchistoday at gmail.com (self.python) Date: Tue, 3 Jul 2012 16:12:48 -0700 (PDT) Subject: exe made by py2exe do not run certain computer Message-ID: <27300d23-adf1-4638-a980-8568e1e74d0d@googlegroups.com> http://makeitmine.tistory.com/attachment/cfile8.uf at 192588384FF2C587070EF7.zip it's a kind of site viewer program and I made it the EXE file using py2exe It works fine on my computer and some other computer don't have python interpreter(it's Windows 7). But the same file also do not work on another computer(it's Windows xp) why does it happen? is there something difference about windows? I want to distribute my application who don't have Python:( From tjreedy at udel.edu Tue Jul 3 19:25:42 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 03 Jul 2012 19:25:42 -0400 Subject: Dictless classes In-Reply-To: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> References: <4ff27d28$0$11103$c3e8da3@news.astraweb.com> Message-ID: On 7/3/2012 1:03 AM, Steven D'Aprano wrote: > You can create instances without a __dict__ by setting __slots__: Each *instance* does not have its own dict because each would be equal, therefore only one hidden mapping is needed, somewhere. But attribute names must be mapped to objects somehow. > I wonder whether there is some metaclass magic one can do to create a > class without a __dict__? If every 'class' instance of the metaclass has the same attributes, then it would not be necessary for each 'class' to have its individual dict. But would you call such things 'classes'? > I don't have a use-case for this. But I have some code which assumes > that every class will have a __dict__, and I wonder whether that is a > safe assumption. It depends what you mean by a class. A 'metaclass' is just a callable that accepts 3 args. The only constraint appears that its return must be callable (and accept at least one arg). class M(): __slots__ = () def __init__(*args): pass def __call__(*args): pass class C(metaclass = M): pass c=C() print(type(C), C, c, hasattr(C, '__dict__')) # <__main__.M object at 0x000000000220A1C0> None False Is C a dictless class? Your choice ;-). Actually, Python thinks not. If we add class Mclassob(object): pass and have __call__ return an instance thereof and try c.__class__ = C we get TypeError: __class__ must be set to a class, not 'M' object -- Terry Jan Reedy From ian.g.kelly at gmail.com Tue Jul 3 19:44:05 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 3 Jul 2012 17:44:05 -0600 Subject: Why site-packages? In-Reply-To: References: Message-ID: On Tue, Jul 3, 2012 at 5:06 PM, Ian Kelly wrote: > On Tue, Jul 3, 2012 at 4:38 PM, Dan Stromberg wrote: >>> Right now this all seems highly speculative to me. I think it might >>> be informative, either to you or to me, to do an actual timing test. >>> Why don't you try setting up two side-by-side installations of Python, >>> one with all the site-packages cruft, and one trimmed down to only >>> what you think should be in there, and see if you can measure a real >>> difference in startup time? >> >> In the original stackoverflow thread I mentioned, there's a speed >> comparison. > > That's just comparing using -S against not using -S, though. As I > understand it, you don't want to use -S; you still want to import site > but just want to pare down your site-packages for a speedup. I ran a quick test where I copied my Python 2.5 installation on Windows and cleared out the site-packages folder and ran the test from the stackoverflow thread. With crufty site-packages: 0.18s With empty site-packages: 0.16s With -S (either installation): 0.10s So there does appear to be some improvement, but only a fraction of what I get by using -S. From miki.tebeka at gmail.com Tue Jul 3 19:46:27 2012 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 3 Jul 2012 16:46:27 -0700 (PDT) Subject: exe made by py2exe do not run certain computer In-Reply-To: <27300d23-adf1-4638-a980-8568e1e74d0d@googlegroups.com> References: <27300d23-adf1-4638-a980-8568e1e74d0d@googlegroups.com> Message-ID: > It works fine on my computer and some other computer don't have python interpreter(it's Windows 7). > But the same file also do not work on another computer(it's Windows xp) > why does it happen? My *guess* is that you're missing some DLLs (probably some Visual Studio runtime ones). You can run http://www.dependencywalker.com/ on the generated exe and see which DLLs it uses. If you do it on the machine with the problems, these DLLs will be highlighted. From skippy.hammond at gmail.com Tue Jul 3 21:23:41 2012 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 04 Jul 2012 11:23:41 +1000 Subject: exe made by py2exe do not run certain computer In-Reply-To: References: <27300d23-adf1-4638-a980-8568e1e74d0d@googlegroups.com> Message-ID: <4FF39B1D.6070306@gmail.com> On 4/07/2012 9:46 AM, Miki Tebeka wrote: >> It works fine on my computer and some other computer don't have >> python interpreter(it's Windows 7). But the same file also do not >> work on another computer(it's Windows xp) why does it happen? > My *guess* is that you're missing some DLLs (probably some Visual > Studio runtime ones). > > You can run http://www.dependencywalker.com/ on the generated exe and > see which DLLs it uses. If you do it on the machine with the > problems, these DLLs will be highlighted. Another possibility is that py2exe is erroneously picking up *other* DLLs from the OS, which you are packaging and installing. So check your distribution for *all* .dll files - most Python extension modules are .pyd, so the actual number of .dll files needed should be quite small and relatively stable across different py2exe invocations. Mark From kushal.kumaran+python at gmail.com Tue Jul 3 22:57:32 2012 From: kushal.kumaran+python at gmail.com (kushal.kumaran+python at gmail.com) Date: Wed, 04 Jul 2012 08:27:32 +0530 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> Ian Kelly wrote: >On Tue, Jul 3, 2012 at 11:53 AM, Kushal Kumaran > wrote: >> On Sat, Jun 30, 2012 at 3:34 PM, Alister >wrote: >>> On Fri, 29 Jun 2012 09:03:22 -0600, Littlefield, Tyler wrote: >>> >>>> On 6/29/2012 1:31 AM, Steven D'Aprano wrote: >>>>> On Thu, 28 Jun 2012 20:58:15 -0700, alex23 wrote: >>>>> >>>>>> On Jun 29, 12:57 pm, "Littlefield, Tyler" >wrote: >>>>>>> I was curious if someone wouldn't mind poking at some code. The >>>>>>> project page is at:http://code.google.com/p/pymud Any >information is >>>>>>> greatly appreciated. >>>>>> I couldn't find any actual code at that site, the git repository >is >>>>>> currently empty. >>>> >>>> OOPS, sorry. Apparently I'm not as good with git as I thought. >>>> Everything's in the repo now. >>> >>> I think I may be on firmer grounds with the next few: >>> >>> isValidPassword can be simplified to >>> >>> def isValidPassword(password: >>> count=len(password) >>> return count>= mud.minpass and count<= mud.maxpass >>> >> >> I haven't actually seen the rest of the code, but I would like to >> point out that applications placing maximum length limits on >passwords >> are extremely annoying. > >They're annoying when the maximum length is unreasonably small, but >you have to have a maximum length to close off one DoS attack vector. >Without a limit, if a "user" presents a 1 GB password, then guess >what? Your system has to hash that GB of data before it can reject >it. And if you're serious about security then it will be a >cryptographic hash, and that means slow. > Well, if you waited until you had the password (however long) in a variable before you applied your maximum limits, the DoS ship has probably sailed already. >To prevent that, the system needs to reject outright password attempts >that are longer than some predetermined reasonable length, and if the >system won't authenticate those passwords, then it can't allow the >user to set them either. > >Cheers, >Ian -- regards, kushal From timr at probo.com Tue Jul 3 23:16:29 2012 From: timr at probo.com (Tim Roberts) Date: Tue, 03 Jul 2012 20:16:29 -0700 Subject: when "normal" parallel computations in CPython will be implemented at last? References: <339f28b0-1305-43b9-b2b1-02e332bc80e3@q29g2000vby.googlegroups.com> Message-ID: John Nagle wrote: > > It would be "un-Pythonic" to have real concurrency in Python. >You wouldn't be able to patch code running in one thread from >another thread. Some of the dynamic features of Python >would break. If you want fine-grained concurrency, you need >controlled isolation between concurrent tasks, so they interact >only at well-defined points. That's un-Pythonic. I disagree. The situation in Python is no different than the situation in other programming languages. If you have shared state, you protect it with some kind of lock. After all, you don't patch code on a byte-by-byte basis -- you just change function bindings. That can be done atomically. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rosuav at gmail.com Tue Jul 3 23:53:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 4 Jul 2012 13:53:57 +1000 Subject: code review In-Reply-To: <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> Message-ID: On Wed, Jul 4, 2012 at 12:57 PM, wrote: > Well, if you waited until you had the password (however long) in a variable before you applied your maximum limits, the DoS ship has probably sailed already. Only because data transfer is usually more expensive than hashing. But I'd say that'll always be true. ChrisA From levinie001 at gmail.com Wed Jul 4 00:12:53 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 12:12:53 +0800 Subject: a problem about "print" Message-ID: aList is a list.i want to get the output seem this "aList is [x,x,x,x,x,x,x,x,x]" how can i get this? it's wrong when i write this, print "aList is "+[x,x,x,x,x,x,x,x,x] -------------- next part -------------- An HTML attachment was scrubbed... URL: From levinie001 at gmail.com Wed Jul 4 00:16:10 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 12:16:10 +0800 Subject: a problem about "print" In-Reply-To: References: Message-ID: print "aList is "+string(aList) ? 2012/7/4 levi nie > aList is a list.i want to get the output seem this "aList is > [x,x,x,x,x,x,x,x,x]" > how can i get this? > it's wrong when i write this, print "aList is "+[x,x,x,x,x,x,x,x,x] > -------------- next part -------------- An HTML attachment was scrubbed... URL: From harrison.morgan at gmail.com Wed Jul 4 00:31:31 2012 From: harrison.morgan at gmail.com (Harrison Morgan) Date: Wed, 4 Jul 2012 00:31:31 -0400 Subject: a problem about "print" In-Reply-To: References: Message-ID: On Wed, Jul 4, 2012 at 12:16 AM, levi nie wrote: > print "aList is "+string(aList) ? > > > 2012/7/4 levi nie > >> aList is a list.i want to get the output seem this "aList is >> [x,x,x,x,x,x,x,x,x]" >> how can i get this? >> it's wrong when i write this, print "aList is "+[x,x,x,x,x,x,x,x,x] >> > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Try this: print "aList is", aList That shows it like your example. The problem with how you were trying it is, you have a string and a list and you're trying to combine (concatenate) them. That doesn't work. One way to get around that is to change the list into a string, like your second post (it would be str(aList), by the way). By separating them with a comma instead of a plus, the print statement does that for you, and also inserts a space in-between them. -------------- next part -------------- An HTML attachment was scrubbed... URL: From simoncropper at fossworkflowguides.com Wed Jul 4 00:55:41 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Wed, 04 Jul 2012 14:55:41 +1000 Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> Message-ID: <4FF3CCCD.8070309@fossworkflowguides.com> On 04/07/12 13:53, Chris Angelico wrote: > On Wed, Jul 4, 2012 at 12:57 PM, wrote: >> Well, if you waited until you had the password (however long) in a variable before you applied your maximum limits, the DoS ship has probably sailed already. > > Only because data transfer is usually more expensive than hashing. But > I'd say that'll always be true. > > ChrisA > Some questions to Tyler Littlefield, who started this thread. Q1 -- Did you get any constructive feedback on your code? Q2 -- Did you feel that the process of submitting your code for review met your expectation? Q3 -- Would you recommend others doing this either on this forum or other fora? It appears to me - third party watching the ongoing dialog - that the tread has gone right off topic (some time ago) and someone should really start a new thread under a new title/subject. Most of what I have read does not appear to be discussing your code or how you could improve your code. Following the last few posts, I was wondering whether some other off-list dialog is going on or whether I am missing something. -- Cheers Simon From tyler at tysdomain.com Wed Jul 4 01:39:20 2012 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Tue, 03 Jul 2012 23:39:20 -0600 Subject: code review In-Reply-To: <4FF3CCCD.8070309@fossworkflowguides.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> Message-ID: <4FF3D708.6090405@tysdomain.com> On 7/3/2012 10:55 PM, Simon Cropper wrote: > Some questions to Tyler Littlefield, who started this thread. > > Q1 -- Did you get any constructive feedback on your code? I did get some, which I appreciated. someone mentioned using PyLint. From reading, I found it was really really pedantic, so I used PyFlakes instead. > > Q2 -- Did you feel that the process of submitting your code for review > met your expectation? There wasn't much more to review, so yes. The info I got was helpful and farther than it was before I started. > Q3 -- Would you recommend others doing this either on this forum or > other fora? > > It appears to me - third party watching the ongoing dialog - that the > tread has gone right off topic (some time ago) and someone should > really start a new thread under a new title/subject. Most of what I > have read does not appear to be discussing your code or how you could > improve your code. > I basically just stopped after a while. It got into a my language is better than your language, so I didn't see much constructive info. I've started reading from the bottom though, where it looks like it's back, and I do appreciate the rest of the info given, as well. Thanks again for the feedback. > Following the last few posts, I was wondering whether some other > off-list dialog is going on or whether I am missing something. > -- Take care, Ty http://tds-solutions.net The aspen project: a barebones light-weight mud engine: http://code.google.com/p/aspenmud He that will not reason is a bigot; he that cannot reason is a fool; he that dares not reason is a slave. From Shambhu.Rajak at kpitcummins.com Wed Jul 4 02:03:20 2012 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Wed, 4 Jul 2012 06:03:20 +0000 Subject: a problem about "print" In-Reply-To: References: Message-ID: <408F64D89899604FB24015E64E10490C3B7D4C8B@KCHJEXMB01.kpit.com> You can use : print "aList is "+repr([x,x,x,x,x,x,x,x,x]) -Shambhu From: levi nie [mailto:levinie001 at gmail.com] Sent: 04/07/2012 9:43 AM To: python-list at python.org Subject: a problem about "print" aList is a list.i want to get the output seem this "aList is [x,x,x,x,x,x,x,x,x]" how can i get this? it's wrong when i write this, print "aList is "+[x,x,x,x,x,x,x,x,x] -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Jul 4 02:17:02 2012 From: wuwei23 at gmail.com (alex23) Date: Tue, 3 Jul 2012 23:17:02 -0700 (PDT) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> Message-ID: On Jul 4, 3:39?pm, "Littlefield, Tyler" wrote: > I basically just stopped after a while. It got into a my language is > better than your language, so I didn't see much constructive info. To be fair, it's more "my vision of the language is better than yours" :) But yes, it should've been forked into a separate thread ages okay. It did get me wondering, though, if there's much in the way of support for code review in repository sites like github? Being able to aggregate comments around the actual code itself could be really handy. From rustompmody at gmail.com Wed Jul 4 03:05:14 2012 From: rustompmody at gmail.com (rusi) Date: Wed, 4 Jul 2012 00:05:14 -0700 (PDT) Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> Message-ID: <0e9822e4-51e2-4f33-acb6-deb9248a6e3b@q5g2000pba.googlegroups.com> On Jul 4, 11:17?am, alex23 wrote: > On Jul 4, 3:39?pm, "Littlefield, Tyler" wrote: > > > I basically just stopped after a while. It got into a my language is > > better than your language, so I didn't see much constructive info. > > To be fair, it's more "my vision of the language is better than > yours" :) But yes, it should've been forked into a separate thread > ages okay. A program is a product of a person's creativity as is a programming language. They have an analogous relation as say a sculpture to chisels. This thread is a good example of how longwindedness of a discussion correlates with its uselessness. However the reverse error is more insidious: programs are made by humans and should be critiqued, whereas programming languages (in particular python) is sacrosanct and cannot be questioned. Too often I find that responders on this list treat as personal affront anyone who questions python whereas the most appropriate response would be: Nice idea but too invasive for serious consideration. [I am saying this in general and not for this thread:Whats wrong with a < b < c is quite beyond me!] > > It did get me wondering, though, if there's much in the way of support > for code review in repository sites like github? Being able to > aggregate comments around the actual code itself could be really > handy. From levinie001 at gmail.com Wed Jul 4 03:22:39 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 15:22:39 +0800 Subject: No subject Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From levinie001 at gmail.com Wed Jul 4 03:28:17 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 15:28:17 +0800 Subject: a problem about "print" In-Reply-To: References: Message-ID: Hi,Harrison. Your method is cool. But i doubt this, if bList and aList just are attached to the same List when i write bList=aList,but why the output of the following two code are different? code1: aList=[1,2,3,4,5,6,7,8,9,10] bList=aList bList=str(bList) print aList print aList[2] code2: aList=[1,2,3,4,5,6,7,8,9,10] aList=str(aList) print aList print aList[2] i'm puzzled now. 2012/7/4 Harrison Morgan > > > On Wed, Jul 4, 2012 at 12:38 AM, levi nie wrote: > >> that's good,thanks. >> new problem. >> when i write >> bList=aList >> del bList[2] >> bList and aList both change,how can i make aList not changed? >> >>> >> > Lists are mutable. That means that when you do bList = aList, you're just > creating another reference to aList. They both point to the same list, just > using different names. You should read up a bit on immutable vs. mutable > objects. Here's something that I found that might explain it a bit better. > http://henry.precheur.org/python/copy_list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Jul 4 03:40:44 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 4 Jul 2012 17:40:44 +1000 Subject: a problem about "print" In-Reply-To: References: Message-ID: On Wed, Jul 4, 2012 at 5:28 PM, levi nie wrote: > aList=str(aList) > print aList > print aList[2] The str() function takes pretty much anything and returns a string. When you subscript a string, you get characters. It's not a list of numbers any more. (Technically str is a class, not a function, but that distinction doesn't matter.) ChrisA From matteo.boscolo at boscolini.eu Wed Jul 4 03:51:17 2012 From: matteo.boscolo at boscolini.eu (Matteo Boscolo) Date: Wed, 04 Jul 2012 09:51:17 +0200 Subject: a problem about "print" In-Reply-To: References: Message-ID: <4FF3F5F5.7070009@boscolini.eu> in the code2 aList=[1,2,3,4,5,6,7,8,9,10] aList=str(aList) #<--- here you convert the list in a string print aList print aList[2] #<-- here you are printing the third caracter of the string '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' not the list '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' regards Matteo Il 04/07/2012 09:28, levi nie ha scritto: > Hi,Harrison. > Your method is cool. > But i doubt this, if bList and aList just are attached to the same > List when i write bList=aList,but why the output of the following two > code are different? > > code1: > aList=[1,2,3,4,5,6,7,8,9,10] > bList=aList > bList=str(bList) > print aList > print aList[2] > > code2: > aList=[1,2,3,4,5,6,7,8,9,10] > aList=str(aList) > print aList > print aList[2] > > i'm puzzled now. > > 2012/7/4 Harrison Morgan > > > > > On Wed, Jul 4, 2012 at 12:38 AM, levi nie > wrote: > > that's good,thanks. > new problem. > when i write > bList=aList > del bList[2] > bList and aList both change,how can i make aList not changed? > > > > Lists are mutable. That means that when you do bList = aList, > you're just creating another reference to aList. They both point > to the same list, just using different names. You should read up a > bit on immutable vs. mutable objects. Here's something that I > found that might explain it a bit better. > http://henry.precheur.org/python/copy_list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From levinie001 at gmail.com Wed Jul 4 04:15:09 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 16:15:09 +0800 Subject: a problem about "print" In-Reply-To: References: Message-ID: Yes,you are right. 2012/7/4 Chris Angelico > On Wed, Jul 4, 2012 at 5:28 PM, levi nie wrote: > > aList=str(aList) > > print aList > > print aList[2] > > The str() function takes pretty much anything and returns a string. > When you subscript a string, you get characters. It's not a list of > numbers any more. > > (Technically str is a class, not a function, but that distinction > doesn't matter.) > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From levinie001 at gmail.com Wed Jul 4 04:21:27 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 16:21:27 +0800 Subject: a problem about "print" In-Reply-To: <4FF3F5F5.7070009@boscolini.eu> References: <4FF3F5F5.7070009@boscolini.eu> Message-ID: Yes,you're right. I got it now.I mistaked that aList also had be changed in code1 before. Thanks a lot. 2012/7/4 Matteo Boscolo > in the code2 > > aList=[1,2,3,4,5,6,7,8,9,10] > aList=str(aList) #<--- here you convert the list in a string > > print aList > print aList[2] #<-- here you are printing the third caracter of the string > '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' not the list '[1, 2, 3, 4, 5, 6, 7, 8, > 9, 10]' > > regards > Matteo > > > > Il 04/07/2012 09:28, levi nie ha scritto: > > Hi,Harrison. > Your method is cool. > But i doubt this, if bList and aList just are attached to the same List > when i write bList=aList,but why the output of the following two code are > different? > > code1: > aList=[1,2,3,4,5,6,7,8,9,10] > bList=aList > bList=str(bList) > print aList > print aList[2] > > code2: > aList=[1,2,3,4,5,6,7,8,9,10] > aList=str(aList) > print aList > print aList[2] > > i'm puzzled now. > > 2012/7/4 Harrison Morgan > >> >> >> On Wed, Jul 4, 2012 at 12:38 AM, levi nie wrote: >> >>> that's good,thanks. >>> new problem. >>> when i write >>> bList=aList >>> del bList[2] >>> bList and aList both change,how can i make aList not changed? >>> >>>> >>> >> Lists are mutable. That means that when you do bList = aList, you're >> just creating another reference to aList. They both point to the same list, >> just using different names. You should read up a bit on immutable vs. >> mutable objects. Here's something that I found that might explain it a bit >> better. http://henry.precheur.org/python/copy_list >> > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Jul 4 04:24:48 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 04 Jul 2012 09:24:48 +0100 Subject: a problem about "print" In-Reply-To: <4FF3F5F5.7070009@boscolini.eu> References: <4FF3F5F5.7070009@boscolini.eu> Message-ID: @Matteo, @Levi, please don't top post it makes following a thread very difficult, no other comments, TIA. On 04/07/2012 08:51, Matteo Boscolo wrote: > in the code2 > > aList=[1,2,3,4,5,6,7,8,9,10] > aList=str(aList) #<--- here you convert the list in a string > > print aList > print aList[2] #<-- here you are printing the third caracter of the > string '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' not the list '[1, 2, 3, 4, 5, > 6, 7, 8, 9, 10]' > > regards > Matteo > > > > Il 04/07/2012 09:28, levi nie ha scritto: >> Hi,Harrison. >> Your method is cool. >> But i doubt this, if bList and aList just are attached to the same >> List when i write bList=aList,but why the output of the following two >> code are different? >> >> code1: >> aList=[1,2,3,4,5,6,7,8,9,10] >> bList=aList >> bList=str(bList) >> print aList >> print aList[2] >> >> code2: >> aList=[1,2,3,4,5,6,7,8,9,10] >> aList=str(aList) >> print aList >> print aList[2] >> >> i'm puzzled now. >> >> 2012/7/4 Harrison Morgan > > >> >> >> >> On Wed, Jul 4, 2012 at 12:38 AM, levi nie > > wrote: >> >> that's good,thanks. >> new problem. >> when i write >> bList=aList >> del bList[2] >> bList and aList both change,how can i make aList not changed? >> >> >> >> Lists are mutable. That means that when you do bList = aList, >> you're just creating another reference to aList. They both point >> to the same list, just using different names. You should read up a >> bit on immutable vs. mutable objects. Here's something that I >> found that might explain it a bit better. >> http://henry.precheur.org/python/copy_list >> >> >> >> > > > > > -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Wed Jul 4 04:28:26 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 04 Jul 2012 09:28:26 +0100 Subject: code review In-Reply-To: References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> <4FF3527E.40305@davea.name> Message-ID: On 03/07/2012 22:54, Chris Angelico wrote: > On Wed, Jul 4, 2012 at 6:13 AM, Dave Angel wrote: >> On 07/03/2012 12:05 PM, Mark Lawrence wrote: >>> If I go to the moon I will weigh 2st 10lb (if my sums are correct :) >>> but the equivalent Frenchman will still be 86kg. I hereby put this >>> forward as proof that the metric system is rubbish and we should >>> revert back to imperial goodies. >>> >> >> 86 kg is not a weight, it's a mass. So it doesn't depend on the local >> gravity situation. > > Indeed it is, as he says. But I believe he may be right in that > 'stone' is a unit of weight. Hard to be sure, though, given that it's > not an SI unit (for instance, the Wikipedia article text refers to > weight, but its picture shows a man measuring mass). > > ChrisA > Stone is a unit of weight (Brits know important things like this). And with the consistency that the English language is reknowned for the plural is, yes you've guessed it, stone :) -- Cheers. Mark Lawrence. From paul.nospam at rudin.co.uk Wed Jul 4 05:29:21 2012 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 04 Jul 2012 10:29:21 +0100 Subject: code review References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> Message-ID: <87y5mz7u32.fsf@no-fixed-abode.cable.virginmedia.net> Mark Lawrence writes: > On 03/07/2012 03:25, John O'Hagan wrote: >> On Tue, 3 Jul 2012 11:22:55 +1000 >> >> I agree to some extent, but as a counter-example, when I was a child there >> a subject called "Weights and Measures" which is now redundant because of the >> Metric system. I don't miss hogsheads and fathoms at all. >> >> John >> > > I weigh 13st 8lb - does this make me redundant? It might mean that you have some redundant weight :) From nospam at nospam.com Wed Jul 4 05:30:01 2012 From: nospam at nospam.com (Gilles) Date: Wed, 04 Jul 2012 11:30:01 +0200 Subject: Using a CMS for small site? Message-ID: Hello Someone I know with no computer knowledge has a studio appartment to rent in Paris and spent four months building a small site in Joomla to find short-time renters. The site is just... - a few web pages that include text (in four languages) and pictures displayed in a Flash slide show - a calendar to show availability - a form to send e-mail with anti-SPAM support - (ASAP) online payment Out of curiosity, are there CMS/frameworks in Python that can do this? Django? Other? Is a full-fledged CMS even needed for something like that? Thank you. From andrea.crotti.0 at gmail.com Wed Jul 4 05:42:56 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 4 Jul 2012 10:42:56 +0100 Subject: adding a simulation mode Message-ID: I'm writing a program which has to interact with many external resources, at least: - mysql database - perforce - shared mounts - files on disk And the logic is quite complex, because there are many possible paths to follow depending on some other parameters. This program even needs to run on many virtual machines at the same time so the interaction is another thing I need to check... Now I successfully managed to mock the database with sqlalchemy and only the fields I actually need, but I now would like to simulate also everything else. I would like for example that if I simulate I can pass a fake database, a fake configuration and get the log of what exactly would happen. But I'm not sure how to implement it now.. One possibility would be to have a global variable (PRETEND_ONLY = False) that if set should be checked before every potentially system-dependent command. For example copytree(src, dest) becomes: if not PRETEND_ONLY: copytree(src, dest) But I don't like it too much because I would have to add a lot of garbage around.. Another way is maybe to set the sys.excepthook to something that catchs all the exceptions that would be thrown by these comands, but I'm not sure is a good idea either.. Any suggestion? From roy at panix.com Wed Jul 4 06:28:09 2012 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jul 2012 06:28:09 -0400 Subject: Using a CMS for small site? References: Message-ID: In article , Gilles wrote: > Hello > > Someone I know with no computer knowledge has a studio appartment to > rent in Paris and spent four months building a small site in Joomla to > find short-time renters. > > The site is just... > - a few web pages that include text (in four languages) and pictures > displayed in a Flash slide show > - a calendar to show availability > - a form to send e-mail with anti-SPAM support > - (ASAP) online payment > > Out of curiosity, are there CMS/frameworks in Python that can do this? > Django? Other? You probably want to look at https://www.django-cms.org/. It's not something that a person with "no computer knowledge" could set up, but once it's set up, that person could use it to build pages. But, to be honest, for somebody who really doesn't know anything, some much more pre-canned solution like WordPress might be what they're looking for. From levinie001 at gmail.com Wed Jul 4 07:06:18 2012 From: levinie001 at gmail.com (levi nie) Date: Wed, 4 Jul 2012 19:06:18 +0800 Subject: code review In-Reply-To: <87y5mz7u32.fsf@no-fixed-abode.cable.virginmedia.net> References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> <87y5mz7u32.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: 2012/7/4 Paul Rudin > Mark Lawrence writes: > > > On 03/07/2012 03:25, John O'Hagan wrote: > >> On Tue, 3 Jul 2012 11:22:55 +1000 > >> > >> I agree to some extent, but as a counter-example, when I was a child > there > >> a subject called "Weights and Measures" which is now redundant because > of the > Just a Test.I didn't familiar about maillist. > >> Metric system. I don't miss hogsheads and fathoms at all. > >> > >> J > >> > > > > I weigh 13st 8lb - does this make me redundant? > > It might mean that you have some redundant weight :) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eisoab at gmail.com Wed Jul 4 07:56:20 2012 From: eisoab at gmail.com (eisoab at gmail.com) Date: Wed, 4 Jul 2012 04:56:20 -0700 (PDT) Subject: locals().update(...) Message-ID: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> I expected this to work: def f(**args): locals().update(args) print locals() print a d=dict(a=1) f(**d) but: > global name 'a' is not defined Where is my mistake? This does work: globals().update({'a':1}) print a 1 -E From lists at cheimes.de Wed Jul 4 08:14:38 2012 From: lists at cheimes.de (Christian Heimes) Date: Wed, 04 Jul 2012 14:14:38 +0200 Subject: locals().update(...) In-Reply-To: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> References: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> Message-ID: Am 04.07.2012 13:56, schrieb eisoab at gmail.com: > I expected this to work: It doesn't work and that's documented: http://docs.python.org/library/functions.html?highlight=locals#locals From steve+comp.lang.python at pearwood.info Wed Jul 4 09:41:56 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 04 Jul 2012 13:41:56 GMT Subject: adding a simulation mode References: Message-ID: <4ff44823$0$29988$c3e8da3$5496439d@news.astraweb.com> On Wed, 04 Jul 2012 10:42:56 +0100, andrea crotti wrote: > I'm writing a program which has to interact with many external > resources, at least: > - mysql database > - perforce > - shared mounts > - files on disk > > And the logic is quite complex, because there are many possible paths to > follow depending on some other parameters. This program even needs to > run on many virtual machines at the same time so the interaction is > another thing I need to check... > > Now I successfully managed to mock the database with sqlalchemy and only > the fields I actually need, but I now would like to simulate also > everything else. > > I would like for example that if I simulate I can pass a fake database, > a fake configuration and get the log of what exactly would happen. But > I'm not sure how to implement it now.. One possibility would be to have > a global variable (PRETEND_ONLY = False) that if set should be checked > before every potentially system-dependent command. I think a better way would be to use a mock database, etc. For each thing which you want to simulate, create a class that has the same interface but a simulated implementation. Then, have your code accept the thing as an argument. E.g. instead of having a hard-coded database connection, allow the database connection to be set (perhaps as an argument, perhaps as a config option, etc.). There are libraries to help with mocks, e.g.: http://garybernhardt.github.com/python-mock-comparison/ > For example > > copytree(src, dest) becomes: > if not PRETEND_ONLY: > copytree(src, dest) Ewww :( Mocking the file system is probably the hardest part, because you generally don't have a "FileSystem" object available to be replaced. In effect, your program has one giant global variable, the file system. Worse, it's not even a named variable, it's hard-coded everywhere you use it. I don't know of any good solution for that. I've often thought about it, but don't have an answer. I suppose you could monkey-patch a bunch of stuff: if ONLY_PRETEND: open = my_mock_open copytree = my_mock_copytree # etc. main() # run your application but that would also be painful. -- Steven From frank at chagford.com Wed Jul 4 09:46:46 2012 From: frank at chagford.com (Frank Millman) Date: Wed, 04 Jul 2012 15:46:46 +0200 Subject: Question about weakref Message-ID: Hi all I have a situation where I thought using weakrefs would save me a bit of effort. I have a basic publish/subscribe scenario. The publisher maintains a list of listener objects, and has a method whereby a listener can subscribe to the list by passing in 'self', whereupon it gets added to the list. When the publisher has something to say, it calls a pre-defined method on each of the listeners. Simple, but it works. The listeners are fairly transient, so when they go out of scope, I need to remove them from the list maintained by the publisher. Instead of keeping track of all of them and removing them explicitly, I thought of using weakrefs and let them be removed automatically. It almost works. Here is an example - import weakref class A: # the publisher class def __init__(self): self.array = [] def add_b(self, b): self.array.append(weakref.ref(b, self.del_b)) def del_b(self, b): self.array.remove(b) def chk_b(self, ref): for b in self.array: b().hallo(ref) class B: # the listener class def __init__(self, a, name): self.name = name a.add_b(self) def hallo(self, ref): print(self.name, 'hallo from', ref) def __del__(self): print('%s deleted' % self.name) a = A() x = B(a, 'test x') y = B(a, 'test y') z = B(a, 'test z') a.chk_b(1) del x a.chk_b(2) del y a.chk_b(3) del z a.chk_b(4) print(a.array) The output is as expected - test x hallo from 1 test y hallo from 1 test z hallo from 1 test x deleted test y hallo from 2 test z hallo from 2 test y deleted test z hallo from 3 test z deleted [] Then I tried weakref.proxy. I changed self.array.append(weakref.ref(b, self.del_b)) to self.array.append(weakref.proxy(b, self.del_b)) and b().hallo(ref) to b.hallo(ref) I got the same result. Then I varied the order of deletion - instead of x, then y, then z, I tried x, then z, then y. Now I get the following traceback - test x hallo from 1 test y hallo from 1 test z hallo from 1 test x deleted test y hallo from 2 test z hallo from 2 Exception ReferenceError: 'weakly-referenced object no longer exists' in > ignored test z deleted test y hallo from 3 Traceback (most recent call last): File "F:\junk\weaklist.py", line 70, in a.chk_b(3) File "F:\junk\weaklist.py", line 51, in chk_b b.hallo(ref) ReferenceError: weakly-referenced object no longer exists test y deleted If I go back to using weakref.ref, but with the new deletion order, it works. So now I am confused. 1. Why do I get the traceback? 2. Can I rely on using weakref.ref, or does that also have some problem that has just not appeared yet? Any advice will be appreciated. BTW, I am using python 3.2.2. Thanks Frank Millman From andrea.crotti.0 at gmail.com Wed Jul 4 09:59:55 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 4 Jul 2012 14:59:55 +0100 Subject: adding a simulation mode In-Reply-To: <4ff44823$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <4ff44823$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2012/7/4 Steven D'Aprano : > > Then, have your code accept the thing as an argument. > > E.g. instead of having a hard-coded database connection, allow the > database connection to be set (perhaps as an argument, perhaps as a > config option, etc.). > > There are libraries to help with mocks, e.g.: > > http://garybernhardt.github.com/python-mock-comparison/ Ah yes this part is already done, I pass an object to the entry point of the program which represents the database connection, which looks like this: class MockMysqlEngine(MySqlEngine): # TODO: make the engine more generic would avoid this dirty hack def __init__(self, *args, **kwargs): # self.engine = create_engine('sqlite:////home/andrea/testdb.sqlite', echo=True) self.engine = create_engine('sqlite://', echo=True) self.meta = MetaData(bind=self.engine) self.session_maker = sessionmaker(bind=self.engine) Now I populate statically the schema and populate with some test data too, but I'm also implementing a weay to just pass some CSV files so that other people can easily write some test cases with some other possible database configurations. (And I use mock for a few other things) > > >> For example >> >> copytree(src, dest) becomes: >> if not PRETEND_ONLY: >> copytree(src, dest) > > Ewww :( > > Mocking the file system is probably the hardest part, because you > generally don't have a "FileSystem" object available to be replaced. In > effect, your program has one giant global variable, the file system. > Worse, it's not even a named variable, it's hard-coded everywhere you use > it. > > I don't know of any good solution for that. I've often thought about it, > but don't have an answer. > > I suppose you could monkey-patch a bunch of stuff: > > if ONLY_PRETEND: > open = my_mock_open > copytree = my_mock_copytree > # etc. > main() # run your application > > > > but that would also be painful. > Yes there is no easy solution apparently.. But I'm also playing around with vagrant and virtual machine generations, suppose I'm able to really control what will be on the machine at time X, creating it on demand with what I need, it might be a good way to solve my problems (a bit overkill and slow maybe though). I'll try the sys.excepthook trick first, any error should give me an exception, so if I catch them all I think it might work already.. From jiangwen365 at gmail.com Wed Jul 4 10:02:59 2012 From: jiangwen365 at gmail.com (=?GB2312?B?va3OxA==?=) Date: Wed, 4 Jul 2012 22:02:59 +0800 Subject: PyPyODBC 0.6 released! (A Pure Python ODBC module) Message-ID: PyPyODBC - A Pure Python ctypes ODBC module Changes in version 0.6: Added Cursor.commit() and Cursor.rollback(). It is now possible to use only a cursor in your code instead of keeping track of a connection and a cursor. Added readonly keyword to connect. If set to True, SQLSetConnectAttr SQL_ATTR_ACCESS_MODE is set to SQL_MODE_READ_ONLY. This may provide better locking semantics or speed for some drivers. Features - Pure Python, compatible with PyPy (tested on Win32) - Almost totally same usage as pyodbc You can simply try pypyodbc in your existing pyodbc powered script with the following changes: #import pyodbc <-- Comment out the original pyodbc importing line import pypyodbc as pyodbc # Let pypyodbc "pretend" the pyodbc pyodbc.connect(...) # This is pypyodbc pretending pyodbc! They have same APIs! ... Homepage: http://code.google.com/p/pypyodbc/ Demo Script: http://code.google.com/p/pypyodbc/source/browse/trunk/pypyodbc/test.py From andrea.crotti.0 at gmail.com Wed Jul 4 10:19:15 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 4 Jul 2012 15:19:15 +0100 Subject: adding a simulation mode In-Reply-To: References: <4ff44823$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: > Yes there is no easy solution apparently.. But I'm also playing > around with vagrant and virtual machine generations, suppose I'm able > to really control what will be on the machine at time X, creating it > on demand with what I need, it might be a good way to solve my > problems (a bit overkill and slow maybe though). > > I'll try the sys.excepthook trick first, any error should give me an > exception, so if I catch them all I think it might work already.. I actually thought that the sys.excepthook would be easy but it's not so trivial apparently: This simple sample never reaches the print("here"), because even if the exception is catched it still quits with return code=1. I also tried to catch the signal but same result, how do I make it continue and just don't complain? The other option if of course to do a big try/except, but I would prefer the excepthook solution.. import sys from shutil import copy def my_except_hook(etype, value, tb): print("got an exception of type", etype) if __name__ == '__main__': sys.excepthook = my_except_hook copy('sdflsdk') print("here") From nospam at nospam.com Wed Jul 4 10:24:32 2012 From: nospam at nospam.com (Gilles) Date: Wed, 04 Jul 2012 16:24:32 +0200 Subject: Using a CMS for small site? References: Message-ID: <7fk8v7pijp359t62clgj5g4n3d4acvap3k@4ax.com> On Wed, 04 Jul 2012 06:28:09 -0400, Roy Smith wrote: >You probably want to look at https://www.django-cms.org/. It's not >something that a person with "no computer knowledge" could set up, but >once it's set up, that person could use it to build pages. > >But, to be honest, for somebody who really doesn't know anything, some >much more pre-canned solution like WordPress might be what they're >looking for. Thanks for the input. Considering that contents won't change, I was wondering if a full-fledged CMS was even necessary. From roy at panix.com Wed Jul 4 11:21:42 2012 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jul 2012 11:21:42 -0400 Subject: Using a CMS for small site? References: <7fk8v7pijp359t62clgj5g4n3d4acvap3k@4ax.com> Message-ID: In article <7fk8v7pijp359t62clgj5g4n3d4acvap3k at 4ax.com>, Gilles wrote: > On Wed, 04 Jul 2012 06:28:09 -0400, Roy Smith wrote: > >You probably want to look at https://www.django-cms.org/. It's not > >something that a person with "no computer knowledge" could set up, but > >once it's set up, that person could use it to build pages. > > > >But, to be honest, for somebody who really doesn't know anything, some > >much more pre-canned solution like WordPress might be what they're > >looking for. > > Thanks for the input. Considering that contents won't change, I was > wondering if a full-fledged CMS was even necessary. If the content is truly never going to change, there's nothing to prevent you from creating some static html files with your favorite text editor. This is really getting quite far afield for a Python group. There are better forums for these kinds of questions. From mcfletch at vrplumber.com Wed Jul 4 11:30:46 2012 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Wed, 04 Jul 2012 11:30:46 -0400 Subject: adding a simulation mode In-Reply-To: References: Message-ID: <4FF461A6.6060805@vrplumber.com> On 12-07-04 05:42 AM, andrea crotti wrote: ... > copytree(src, dest) becomes: > if not PRETEND_ONLY: > copytree(src, dest) import globalsub, unittest class MyTest( unittest.TestCase ): def setUp( self ): globalsub.subs( shutil.copytree ) def tearDown( self ): globalsub.restore( shutil.copytree ) You can also pass a function to subs like so: def setUp( self ): self.copied_trees = [] def fake_copytree( src, dest ): assert os.path.exists( src ) self.copied_trees.append( (src, dest )) return dest # or whatever the thing should return globalsub.subs( shutil.copytree, fake_copytree ) $ pip install globalsub HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From jeanpierreda at gmail.com Wed Jul 4 12:08:38 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 4 Jul 2012 12:08:38 -0400 Subject: adding a simulation mode In-Reply-To: References: Message-ID: For what it's worth, this is the reason that Allen Short wrote Exocet. > This way, you can test your code without having to resort to sys.modules > hackery, and you can better factor your applications by separating > configuration and environment concerns from the rest of your code. See: - http://washort.twistedmatrix.com/2011/01/introducing-exocet.html - http://washort.twistedmatrix.com/2011/03/exocet-second-look.html -- Devin From breamoreboy at yahoo.co.uk Wed Jul 4 12:25:33 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 04 Jul 2012 17:25:33 +0100 Subject: code review In-Reply-To: <87y5mz7u32.fsf@no-fixed-abode.cable.virginmedia.net> References: <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <4fefb0ad$0$29988$c3e8da3$5496439d@news.astraweb.com> <43f27741-bd1b-4c15-9822-c196b8b0396e@x39g2000yqx.googlegroups.com> <4ff24384$0$29988$c3e8da3$5496439d@news.astraweb.com> <20120703122559.2b794310d1a98a11c1a725ab@johnohagan.com> <87y5mz7u32.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: On 04/07/2012 10:29, Paul Rudin wrote: > Mark Lawrence writes: > >> On 03/07/2012 03:25, John O'Hagan wrote: >>> On Tue, 3 Jul 2012 11:22:55 +1000 >>> >>> I agree to some extent, but as a counter-example, when I was a child there >>> a subject called "Weights and Measures" which is now redundant because of the >>> Metric system. I don't miss hogsheads and fathoms at all. >>> >>> John >>> >> >> I weigh 13st 8lb - does this make me redundant? > > It might mean that you have some redundant weight :) > True indeed, although my beer free diet of the last 10 days (yes, 10 whole days) has at least got it down from 14 stone 2 pounds. -- Cheers. Mark Lawrence. From no.email at nospam.invalid Wed Jul 4 13:01:48 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 04 Jul 2012 10:01:48 -0700 Subject: adding a simulation mode References: Message-ID: <7x7guj4g03.fsf@ruckus.brouhaha.com> andrea crotti writes: > copytree(src, dest) becomes: > if not PRETEND_ONLY: > copytree(src, dest) > > But I don't like it too much because I would have to add a lot of > garbage around.. I've had good results writing the module under test in the style of a java applet, i.e. one of its args is a class instance representing the "outside world", and ALL interaction that you might want to simulate is done through this object: def your_prog(parent): conn = parent.db.make_connection(...) blah = parent.copytree(...) Then you make "real" and "mock" versions of the external interface, and pass in an appropriate instance. From phr-2012 at nightsong.com Wed Jul 4 15:37:25 2012 From: phr-2012 at nightsong.com (Paul Rubin) Date: Wed, 04 Jul 2012 12:37:25 -0700 Subject: 2 + 2 = 5 Message-ID: <7x7guj2u8a.fsf@ruckus.brouhaha.com> I just came across this (https://gist.github.com/1208215): import sys import ctypes pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) five = ctypes.cast(id(5), pyint_p) print(2 + 2 == 5) # False five.contents[five.contents[:].index(5)] = 4 print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) Heh. The author is apparently anonymous, I guess for good reason. From stefan_ml at behnel.de Wed Jul 4 15:53:36 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 04 Jul 2012 21:53:36 +0200 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin, 04.07.2012 21:37: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) > > Heh. The author is apparently anonymous, I guess for good reason. That's not portable, though. ;) Stefan From marianoa.dangelo at gmail.com Wed Jul 4 16:27:29 2012 From: marianoa.dangelo at gmail.com (Mariano DAngelo) Date: Wed, 4 Jul 2012 13:27:29 -0700 (PDT) Subject: import class from string Message-ID: Hi I'm trying to create a class from a string.... This is my code, but is not working.... 'myshop.models.base' module_name, class_name = model.rsplit(".", 1) module = importlib.import_module(module_name) class_ = getattr(module, class_name)() Anyone know what I'm doing wrong.... or another way? thanks From gmx at ross.cx Wed Jul 4 16:37:16 2012 From: gmx at ross.cx (Michael Ross) Date: Wed, 04 Jul 2012 22:37:16 +0200 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: Am 04.07.2012, 21:37 Uhr, schrieb Paul Rubin : > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 > there...) > > Heh. The author is apparently anonymous, I guess for good reason. Neat. Playing with it, i'm wondering: This: import sys import ctypes pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) five = ctypes.cast(id(5), pyint_p) five.contents[five.contents[:].index(5)] = 4 print ( 2 + 2 == 5 ) print 5 print 5 - 2 put into a script and run prints: True 4 3 while entered at the python prompt it prints: True 4 2 ?? Regards, Michael From breamoreboy at yahoo.co.uk Wed Jul 4 17:24:34 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 04 Jul 2012 22:24:34 +0100 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: On 04/07/2012 20:37, Paul Rubin wrote: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) > > Heh. The author is apparently anonymous, I guess for good reason. > The author got confused trying to switch from imperial to metric numbers or vice versa? -- Cheers. Mark Lawrence. From nospam at nospam.com Wed Jul 4 18:34:49 2012 From: nospam at nospam.com (Gilles) Date: Thu, 05 Jul 2012 00:34:49 +0200 Subject: Using a CMS for small site? References: <7fk8v7pijp359t62clgj5g4n3d4acvap3k@4ax.com> Message-ID: <17h9v7l5e4nkb0f97f1bine6viq70lna7b@4ax.com> On Wed, 04 Jul 2012 11:21:42 -0400, Roy Smith wrote: >This is really getting quite far afield for a Python group. There are >better forums for these kinds of questions. Probably. I'll keep that in mind while checking Python web frameworks. Thanks. From t at jollybox.de Wed Jul 4 18:45:38 2012 From: t at jollybox.de (Thomas Jollans) Date: Thu, 05 Jul 2012 00:45:38 +0200 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <4FF4C792.3050502@jollybox.de> On 07/04/2012 09:37 PM, Paul Rubin wrote: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) > > Heh. The author is apparently anonymous, I guess for good reason. > I'm reminded of the swap(a,b) function I wrote a couple of years back. http://blog.jollybox.de/archives/62-python-swap From d at davea.name Wed Jul 4 18:48:08 2012 From: d at davea.name (Dave Angel) Date: Wed, 04 Jul 2012 18:48:08 -0400 Subject: locals().update(...) In-Reply-To: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> References: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> Message-ID: <4FF4C828.3020807@davea.name> On 07/04/2012 07:56 AM, eisoab at gmail.com wrote: > I expected this to work: > > > def f(**args): > locals().update(args) > print locals() > print a > > d=dict(a=1) > > f(**d) > > but: >> global name 'a' is not defined > Where is my mistake? Chris has given you the place where it's documented that it generally won't work. I'll try to explain why, at least for local variables inside functions, and for CPython implementation. The generated byte code for a function does *not* look up each symbol by name during execution. The compiler builds a list of known local symbol names, and gives them each an index (a small positive integer). At run time that list is fixed in size and meaning; no new locals can be added. The locals() function just creates a dictionary that approximates what the semantics of the symbols are. But changes to that dictionary have no effect on the running function. That's one reason that copying a global value to a local symbol inside a function can make that function run faster. Globals always require a dictionary lookup, while function locals are just an integer offset away. > This does work: > > globals().update({'a':1}) > > print a > > 1 > > -E > As i said above, the rules are different for globals, and they are even if you use locals() to access them. However, i'd consider it prudent never to assume you can write to the dictionary constructed by either the locals() or the globals() functions. -- DaveA From steve+comp.lang.python at pearwood.info Wed Jul 4 18:51:02 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 04 Jul 2012 22:51:02 GMT Subject: import class from string References: Message-ID: <4ff4c8d5$0$29988$c3e8da3$5496439d@news.astraweb.com> On Wed, 04 Jul 2012 13:27:29 -0700, Mariano DAngelo wrote: > Hi I'm trying to create a class from a string.... This is my code, but > is not working.... > > 'myshop.models.base' > module_name, class_name = model.rsplit(".", 1) > module = importlib.import_module(module_name) > class_ = getattr(module, class_name)() > > > Anyone know what I'm doing wrong.... What version of Python are you using? What result do you expect? What result do you actually get? When asking for help, please take the time to create a short, self- contained, correct example that anyone can actually run: http://sscce.org/ In the above, you have a bare string that does nothing; a name "model" that is undefined; and what looks like a module that isn't imported (importlib). We have no idea of what problem *you* see, because we can't run your code and you don't show us the error. But the general idea is correct, at least in Python 3.2: import importlib model = 'unittest.suite.BaseTestSuite' module_name, class_name = model.rsplit(".", 1) module = importlib.import_module(module_name) class_ = getattr(module, class_name) At the end of which, class_ is the expected BaseTestSuite class. I suspect that your error is that after you get the class object using getattr, you then *call* the class object but give no arguments, and the class requires arguments. You say: class_ = getattr(module, class_name)() # note the extra () brackets I say: class_ = getattr(module, class_name) Either that or you have a bug in your module and it can't be imported. Or you have misspelled the module name, or the class. Or forgotten to import importlib. Or are shadowing it with your own module. Who knows? Without seeing the error, I'm just guessing. -- Steven From t at jollybox.de Wed Jul 4 18:55:05 2012 From: t at jollybox.de (Thomas Jollans) Date: Thu, 05 Jul 2012 00:55:05 +0200 Subject: import class from string In-Reply-To: References: Message-ID: <4FF4C9C9.9080805@jollybox.de> On 07/04/2012 10:27 PM, Mariano DAngelo wrote: > Hi I'm trying to create a class from a string.... > This is my code, but is not working.... It would be helpful if you posted an error message. Then, we could know what's actually going on. > 'myshop.models.base' > module_name, class_name = model.rsplit(".", 1) > module = importlib.import_module(module_name) > class_ = getattr(module, class_name)() ......................................^^ These brackets may be causing problems? In principle, you're doing the right thing. This works for me: Python 3.2.3 (default, May 3 2012, 15:51:42) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import importlib >>> objname = 'os.path.join' >>> module_name, member_name = objname.rsplit('.', 1) >>> module = importlib.import_module(module_name) >>> member = getattr(module, member_name) >>> member >>> From steve+comp.lang.python at pearwood.info Wed Jul 4 18:57:33 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 04 Jul 2012 22:57:33 GMT Subject: locals().update(...) References: <451cfda5-3fe6-4066-94f3-31f4fe747233@googlegroups.com> Message-ID: <4ff4ca5c$0$29988$c3e8da3$5496439d@news.astraweb.com> On Wed, 04 Jul 2012 18:48:08 -0400, Dave Angel wrote: > As i said above, the rules are different for globals, and they are even > if you use locals() to access them. However, i'd consider it prudent > never to assume you can write to the dictionary constructed by either > the locals() or the globals() functions. globals() is implicitly documented as being writable: "This is always the dictionary of the current module..." -- unless you have a module with a read-only dict, that is writable. http://docs.python.org/release/3.2/library/functions.html#globals There are tricks to getting read-only namespaces, but you can legitimately expect to write to globals(). -- Steven From subhabangalore at gmail.com Wed Jul 4 19:21:46 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Wed, 4 Jul 2012 16:21:46 -0700 (PDT) Subject: Discussion on some Code Issues Message-ID: Dear Group, I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to discuss some coding issues. If any one of this learned room can shower some light I would be helpful enough. I got to code a bunch of documents which are combined together. Like, 1)A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing. 2) The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. 3) A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. The task is to separate the documents on the fly and to parse each of the documents with a definite set of rules. Now, the way I am processing is: I am clubbing all the documents together, as, A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. But they are separated by a tag set, like, A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.$ The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection.$ A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. To detect the document boundaries, I am splitting them into a bag of words and using a simple for loop as, for i in range(len(bag_words)): if bag_words[i]=="$": print (bag_words[i],i) There is no issue. I am segmenting it nicely. I am using annotated corpus so applying parse rules. The confusion comes next, As per my problem statement the size of the file (of documents combined together) won?t increase on the fly. So, just to support all kinds of combinations I am appending in a list the ?I? values, taking its length, and using slice. Works perfect. Question is, is there a smarter way to achieve this, and a curious question if the documents are on the fly with no preprocessed tag set like ?$? how may I do it? From a bunch without EOF isn?t it a classification problem? There is no question on parsing it seems I am achieving it independent of length of the document. If any one in the group can suggest how I am dealing with the problem and which portions should be improved and how? Thanking You in Advance, Best Regards, Subhabrata Banerjee. From steve+comp.lang.python at pearwood.info Wed Jul 4 20:02:44 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Jul 2012 00:02:44 GMT Subject: Discussion on some Code Issues References: Message-ID: <4ff4d9a3$0$29864$c3e8da3$5496439d@news.astraweb.com> On Wed, 04 Jul 2012 16:21:46 -0700, subhabangalore wrote: [...] > I got to code a bunch of documents which are combined together. [...] > The task is to separate the documents on the fly and to parse each of > the documents with a definite set of rules. > > Now, the way I am processing is: > I am clubbing all the documents together, as, [...] > But they are separated by a tag set [...] > To detect the document boundaries, Let me see if I understand your problem. You have a bunch of documents. You stick them all together into one enormous lump. And then you try to detect the boundaries between one file and the next within the enormous lump. Why not just process each file separately? A simple for loop over the list of files, before consolidating them into one giant file, will avoid all the difficulty of trying to detect boundaries within files. Instead of: merge(output_filename, list_of_files) for word in parse(output_filename): if boundary_detected: do_something() process(word) Do this instead: for filename in list_of_files: do_something() for word in parse(filename): process(word) > I am splitting them into a bag of > words and using a simple for loop as, > for i in range(len(bag_words)): > if bag_words[i]=="$": > print (bag_words[i],i) What happens if a file already has a $ in it? > There is no issue. I am segmenting it nicely. I am using annotated > corpus so applying parse rules. > > The confusion comes next, > > As per my problem statement the size of the file (of documents combined > together) won?t increase on the fly. So, just to support all kinds of > combinations I am appending in a list the ?I? values, taking its length, > and using slice. Works perfect. I don't understand this. What sort of combinations do you think you need to support? What are "I" values, and why are they important? -- Steven From wuwei23 at gmail.com Wed Jul 4 20:04:15 2012 From: wuwei23 at gmail.com (alex23) Date: Wed, 4 Jul 2012 17:04:15 -0700 (PDT) Subject: 2 + 2 = 5 References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <965cb582-e0bd-4359-a8a4-edb6daa22356@km7g2000pbc.googlegroups.com> On Jul 5, 5:37?am, Paul Rubin wrote: > ? ? print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) I believe CCP use a variant of this approach in EvE with Stackless Python. From rantingrickjohnson at gmail.com Wed Jul 4 20:08:23 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Wed, 4 Jul 2012 17:08:23 -0700 (PDT) Subject: Discussion on some Code Issues References: Message-ID: <59b3e7c3-83d8-43a7-9d24-1df682f0a353@j10g2000yqd.googlegroups.com> On Jul 4, 6:21?pm, subhabangal... at gmail.com wrote: > [...] > To detect the document boundaries, I am splitting them into a bag > of words and using a simple for loop as, > > for i in range(len(bag_words)): > ? ? ? ? if bag_words[i]=="$": > ? ? ? ? ? ? print (bag_words[i],i) Ignoring that you are attacking the problem incorrectly: that is very poor method of splitting a string since especially the Python gods have given you *power* over string objects. But you are going to have an even greater problem if the string contains a "$" char that you DID NOT insert :-O. You'd be wise to use a sep that is not likely to be in the file data. For example: "" or "". But even that approach is naive! Why not streamline the entire process and pass a list of file paths to a custom parser object instead? From wuwei23 at gmail.com Wed Jul 4 20:09:40 2012 From: wuwei23 at gmail.com (alex23) Date: Wed, 4 Jul 2012 17:09:40 -0700 (PDT) Subject: Using a CMS for small site? References: <7fk8v7pijp359t62clgj5g4n3d4acvap3k@4ax.com> Message-ID: <898fafd5-fd37-4c32-9074-8396bf203e5e@y3g2000pbc.googlegroups.com> On Jul 5, 1:21?am, Roy Smith wrote: > If the content is truly never going to change, there's nothing to > prevent you from creating some static html files with your favorite text > editor. > > This is really getting quite far afield for a Python group. ?There are > better forums for these kinds of questions. Not necessarily! There are several static site generators written in Python :) One that I see being updating a lot is Nikola: http://nikola.ralsina.com.ar/ From gedwards2 at gmail.com Wed Jul 4 20:14:02 2012 From: gedwards2 at gmail.com (Greg Edwards) Date: Thu, 5 Jul 2012 10:14:02 +1000 Subject: Help using Tix and tix.balloon in tkinter.ttk Gui on Py 3.2.3, Mac OS X 10.6.8 Message-ID: Hi, I'm trying to get Tix installed and working, in order to use Tix.balloon in the first instance. I'm using Python 3.2.3 on Mac OS X 10.6.8, installed from direct package download from Python.org. Have also installed Py 2.7.3, and the native Mac Py 2.6.1 and 2.5.4 are all working fine as well and not tromping on each other. Building a variety of Gui's under 2.7.3 and 3.2.3 with tkinter, ttk and all going well. I'm recreating a pile of Gui's I have had for years under plain Tcl/Tk (on Linux and Irix). I can't get Tix working at all, doesn't seem to be supplied with any of the Python dists. Example: ~/lang/python/tkinter/devpanel $ py3 Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. ~/.pythonstartup >>> import tkinter >>> import tkinter.ttk >>> import tkinter.tix >>> root = tkinter.tix.Tk() Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/tix.py", line 225, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix My Python is still elementary, I may be importing and invoking Tix badly. I've searched the Python, Tkinter, Tix sites for a few hours, searched my Mac for tixlib files, no luck. Looks like you can build Tix from source and install, but web posts indicate this is very hard and I don't see any useful traffic on that in the last 2 or 3 years, never a good sign. Any pointers appreciated ! Hope I don't get flamed, I see this group has some epic flame wars. Cheers, -- Greg Edwards, Port Jackson Bioinformatics gedwards2 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Wed Jul 4 20:29:10 2012 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 5 Jul 2012 02:29:10 +0200 Subject: simpler increment of time values? Message-ID: Hi all, I'd like to ask about the possibilities to do some basic manipulation on timestamps - such as incrementing a given time (hour.minute - string) by some minutes. Very basic notion of "time" is assumed, i.e. dateless, timezone-unaware, DST-less etc. I first thought, it would be possible to just add a timedelta to a time object, but, it doesn't seem to be the case. The code I came up with (using time and datetime modules) seems rather convoluted and I would like to ask about some possible more straightforward alternatives I missed. The equivalent function (lacking validation) without the (date)time libraries seems simple enough (for this limited and individual task). Although it is probably mostly throw-away code, which seems to do what I need, I'd be interested in better/more elegant... solutions. # # # import time import datetime import re print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45", "%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M")) # 9.15 # # # # # # # # # def add_minutes(hour_min_str, separator=".", minutes_to_add=0): h, m = [int(s) for s in hour_min_str.split(separator)] sum_minutes = h * 60 + m + minutes_to_add h, m = divmod(sum_minutes, 60) h = h % 24 return "%s%s%s" % (h, separator, m) print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30) # 9.15 # # # # # # # # # Is it true, that timedelta cannot be used with dateless time values? (Is there some other possibility than the current one, where strptime actually infers 1. 1. 1900?) Is there some simpler way to adapt the incompatible output of strptime as the input of datetime? Is it possible to get one-digit hours formatted without the leading zero? Thanks in advance for any suggestions or remarks; regards, Vlastimil Brom From driscoll at cs.wisc.edu Wed Jul 4 20:39:21 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Wed, 04 Jul 2012 19:39:21 -0500 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <4FF4E239.8060603@cs.wisc.edu> On 7/4/2012 14:37, Paul Rubin wrote: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) > > Heh. The author is apparently anonymous, I guess for good reason. Probably just nostalgic for old Fortran, which, supposedly, allowed you to change the values of literals by passing them to a function by reference and then modifying the value. Evan -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 552 bytes Desc: OpenPGP digital signature URL: From rosuav at gmail.com Wed Jul 4 21:09:50 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 5 Jul 2012 11:09:50 +1000 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Thu, Jul 5, 2012 at 10:29 AM, Vlastimil Brom wrote: > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. My first suggestion would be to work with Unix times (that is, store your time as "seconds since 1970", also called a time_t). That's forced to be on UTC (but ignoring leap seconds) so you don't have to worry about timezones or DST, and incrementing by X minutes is simply adding X*60 to it. It makes your job a lot easier! ChrisA From cs at zip.com.au Wed Jul 4 22:06:07 2012 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 5 Jul 2012 12:06:07 +1000 Subject: 2 + 2 = 5 In-Reply-To: <4FF4E239.8060603@cs.wisc.edu> References: <4FF4E239.8060603@cs.wisc.edu> Message-ID: <20120705020607.GA2611@cskk.homeip.net> On 04Jul2012 19:39, Evan Driscoll wrote: | On 7/4/2012 14:37, Paul Rubin wrote: | > I just came across this (https://gist.github.com/1208215): | > | > import sys | > import ctypes | > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) | > five = ctypes.cast(id(5), pyint_p) | > print(2 + 2 == 5) # False | > five.contents[five.contents[:].index(5)] = 4 | > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) | > | > Heh. The author is apparently anonymous, I guess for good reason. | | Probably just nostalgic for old Fortran, which, supposedly, allowed you | to change the values of literals by passing them to a function by | reference and then modifying the value. Yeah, I was thinking that too. Because all parameters were pass-by-reference in early fortran IIRC. You could, for example, set pi to 3. -- Cameron Simpson If I have seen farther than others, it is because I was standing on the shoulders of giants. - Isaac Newton If I have not seen as far as others, it is because giants were standing on my shoulders. - Hal Abelson In computer science, we stand on each other's feet. - Brian K. Reed From breamoreboy at yahoo.co.uk Wed Jul 4 22:35:29 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 05 Jul 2012 03:35:29 +0100 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On 05/07/2012 01:29, Vlastimil Brom wrote: > Hi all, > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. > I first thought, it would be possible to just add a timedelta to a > time object, but, it doesn't seem to be the case. > > The code I came up with (using time and datetime modules) seems rather > convoluted and I would like to ask about some possible more > straightforward alternatives I missed. > The equivalent function (lacking validation) without the (date)time > libraries seems simple enough (for this limited and individual task). > Although it is probably mostly throw-away code, which seems to do what > I need, I'd be interested in better/more elegant... solutions. > > # # # > import time > import datetime > import re > > print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45", > "%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M")) > # 9.15 > > # # # # # # # # # > > def add_minutes(hour_min_str, separator=".", minutes_to_add=0): > h, m = [int(s) for s in hour_min_str.split(separator)] > sum_minutes = h * 60 + m + minutes_to_add > h, m = divmod(sum_minutes, 60) > h = h % 24 > return "%s%s%s" % (h, separator, m) > > print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30) > # 9.15 > > # # # # # # # # # > > Is it true, that timedelta cannot be used with dateless time values? > (Is there some other possibility than the current one, where strptime > actually infers 1. 1. 1900?) > Is there some simpler way to adapt the incompatible output of strptime > as the input of datetime? > Is it possible to get one-digit hours formatted without the leading zero? > > Thanks in advance for any suggestions or remarks; > regards, > Vlastimil Brom > from dateutil.relativedelta import relativedelta should simplify things for you google and ye shall find :) -- Cheers. Mark Lawrence. From howmuchistoday at gmail.com Wed Jul 4 23:10:47 2012 From: howmuchistoday at gmail.com (self.python) Date: Wed, 4 Jul 2012 20:10:47 -0700 (PDT) Subject: how to interact with Windows cmd? Message-ID: <5c91bf76-36de-4759-938a-92a9e801e38e@g4g2000pbn.googlegroups.com> what I want to do is 1.open cmd 2.waiting for user's typing 3.when I type "dir" 4.print the result of "dir" 5.then I type some other commands, printing the result until I type 'exit' I used p=subprocess.Popen('cmd',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) p=communicate('dir') it shows the first result but the problem is 1. it's too long so the cmd split the result with "more?", so result is not perfect 2. after this, I typed like "cd .." but I/O is already closed so I can't do another things.. Is there any good way? From subhabangalore at gmail.com Wed Jul 4 23:25:14 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Wed, 4 Jul 2012 20:25:14 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: Message-ID: <34484d3d-d4c2-463b-8f83-dba57ce0511d@googlegroups.com> On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote: > Dear Group, > > I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to discuss some coding issues. If any one of this learned room can shower some light I would be helpful enough. > > I got to code a bunch of documents which are combined together. > Like, > > 1)A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing. > 2) The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. > 3) A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > The task is to separate the documents on the fly and to parse each of the documents with a definite set of rules. > > Now, the way I am processing is: > I am clubbing all the documents together, as, > > A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > But they are separated by a tag set, like, > A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.$ > The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection.$ > A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > To detect the document boundaries, I am splitting them into a bag of words and using a simple for loop as, > for i in range(len(bag_words)): > if bag_words[i]=="$": > print (bag_words[i],i) > > There is no issue. I am segmenting it nicely. I am using annotated corpus so applying parse rules. > > The confusion comes next, > > As per my problem statement the size of the file (of documents combined together) won?t increase on the fly. So, just to support all kinds of combinations I am appending in a list the ?I? values, taking its length, and using slice. Works perfect. Question is, is there a smarter way to achieve this, and a curious question if the documents are on the fly with no preprocessed tag set like ?$? how may I do it? From a bunch without EOF isn?t it a classification problem? > > There is no question on parsing it seems I am achieving it independent of length of the document. > > If any one in the group can suggest how I am dealing with the problem and which portions should be improved and how? > > Thanking You in Advance, > > Best Regards, > Subhabrata Banerjee. Hi Steven, It is nice to see your post. They are nice and I learnt so many things from you. "I" is for index of the loop. Now my clarification I thought to do "import os" and process files in a loop but that is not my problem statement. I have to make a big lump of text and detect one chunk. Looping over the line number of file I am not using because I may not be able to take the slices-this I need. I thought to give re.findall a try but that is not giving me the slices. Slice spreads here. The power issue of string! I would definitely give it a try. Happy Day Ahead Regards, Subhabrata Banerjee. From tjreedy at udel.edu Wed Jul 4 23:38:17 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 04 Jul 2012 23:38:17 -0400 Subject: 2 + 2 = 5 In-Reply-To: References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: On 7/4/2012 4:37 PM, Michael Ross wrote: > Am 04.07.2012, 21:37 Uhr, schrieb Paul Rubin : > >> I just came across this (https://gist.github.com/1208215): >> >> import sys >> import ctypes >> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) >> five = ctypes.cast(id(5), pyint_p) >> print(2 + 2 == 5) # False >> five.contents[five.contents[:].index(5)] = 4 >> print(2 + 2 == 5) # True (must be sufficiently large values of 2 >> there...) >> >> Heh. The author is apparently anonymous, I guess for good reason. > > > Neat. > > Playing with it, i'm wondering: > > > This: > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > five.contents[five.contents[:].index(5)] = 4 > > print ( 2 + 2 == 5 ) > print 5 > print 5 - 2 > > put into a script and run prints: > > True > 4 > 3 The compile-time optimizer computed the contant 5-2 in C. > while entered at the python prompt it prints: > > True > 4 > 2 It must not run for interactive input with the undisclosed version you are running. If I run the script in 3.3 Idle, I get the same output you got. If I then enter '5-2' interactively, I still get 3. Maybe the constant folder is always on now. -- Terry Jan Reedy From maillist.tom at gmail.com Thu Jul 5 00:37:38 2012 From: maillist.tom at gmail.com (tom z) Date: Thu, 5 Jul 2012 12:37:38 +0800 Subject: Help: PYMALLOC_DBUG and PIL Message-ID: Hi~ all, I encounter a odd problem, when i compile Python with PYMALLOC_DEBUG, the PIL module can't work fine, it always make core-dump like this [Switching to Thread 182897301792 (LWP 16102)] 0x00000000004df264 in PyObject_Malloc (nbytes=64) at Objects/obmalloc.c:804 804 if ((pool->freeblock = *(block **)bp) != NULL) { Current language: auto; currently c (gdb) bt #0 0x00000000004df264 in PyObject_Malloc (nbytes=64) at Objects/obmalloc.c:804 #1 0x00000000004dfb97 in _PyObject_DebugMallocApi (id=109 'm', nbytes=32) at Objects/obmalloc.c:1461 #2 0x00000000004dfd22 in _PyObject_DebugReallocApi (api=109 'm', p=0x0, nbytes=32) at Objects/obmalloc.c:1523 #3 0x00000000004dfac0 in _PyMem_DebugRealloc (p=0x0, nbytes=32) at Objects/obmalloc.c:1416 #4 0x00000000004c68d9 in list_resize (self=0x2a988409b8, newsize=1) at Objects/listobject.c:62 #5 0x00000000004c6f63 in app1 (self=0x2a988409b8, v=0x2a958cea90) at Objects/listobject.c:277 #6 0x00000000004c6fdd in PyList_Append (op=0x2a988409b8, newitem=0x2a958cea90) at Objects/listobject.c:289 #7 0x0000000000558c7f in symtable_add_def (st=0x2a99a4ca68, name=0x2a958cea90, flag=4) at Python/symtable.c:910 #8 0x000000000055a953 in symtable_visit_params (st=0x2a99a4ca68, args=0x924380, toplevel=1) at Python/symtable.c:1318 #9 0x000000000055aaa7 in symtable_visit_arguments (st=0x2a99a4ca68, a=0x9243c8) at Python/symtable.c:1365 #10 0x0000000000558f3d in symtable_visit_stmt (st=0x2a99a4ca68, s=0x9244d0) at Python/symtable.c:1012 #11 0x000000000055919e in symtable_visit_stmt (st=0x2a99a4ca68, s=0x924500) at Python/symtable.c:1029 #12 0x00000000005574d7 in PySymtable_Build (mod=0x931798, filename=0x7fbfffa2c0 "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", future=0x2a9883aae0) at Python/symtable.c:240 #13 0x0000000000531f14 in PyAST_Compile (mod=0x931798, filename=0x7fbfffa2c0 "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", flags=0x7fbfff9020, arena=0x8eedd0) at Python/compile.c:282 #14 0x0000000000545967 in parse_source_module ( pathname=0x7fbfffa2c0 "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at Python/import.c:843 #15 0x0000000000545e75 in load_source_module (name=0x7fbfffb3e0 "PIL.BmpImagePlugin", pathname=0x7fbfffa2c0 "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at Python/import.c:1027 i've no idea about this, someone could get me help~ --- thanks a lot -------------- next part -------------- An HTML attachment was scrubbed... URL: From jason at powerpull.net Thu Jul 5 00:57:23 2012 From: jason at powerpull.net (Jason Friedman) Date: Wed, 4 Jul 2012 22:57:23 -0600 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: > Hi all, > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. > I first thought, it would be possible to just add a timedelta to a > time object, but, it doesn't seem to be the case. > > The code I came up with (using time and datetime modules) seems rather > convoluted and I would like to ask about some possible more > straightforward alternatives I missed. > The equivalent function (lacking validation) without the (date)time > libraries seems simple enough (for this limited and individual task). > Although it is probably mostly throw-away code, which seems to do what > I need, I'd be interested in better/more elegant... solutions. I have some thoughts on a solution, but first, what is 12:45 plus 12 hours? What is 12:45 minus 13 hours? From jeanpierreda at gmail.com Thu Jul 5 01:05:45 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 5 Jul 2012 01:05:45 -0400 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Thu, Jul 5, 2012 at 12:57 AM, Jason Friedman wrote: > I have some thoughts on a solution, but first, what is 12:45 plus 12 > hours? What is 12:45 minus 13 hours? Is there anything unusual that can happen for a notion of time that is dateless, timezone-unaware, and DST-free? I would imagine that under these constraints the answers are always 0:45 and 23:45 respectively. Although I guess it doesn't hurt to check. -- Devin From k.sahithi2862 at gmail.com Thu Jul 5 01:19:03 2012 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Wed, 4 Jul 2012 22:19:03 -0700 (PDT) Subject: EXTRAORDINARY HOT PHOTOS AND VIDEOS Message-ID: ALL INTERVIEW QUESTIONS& STUDY MATERIAL http://newdotnetinterviewquestions.blogspot.in/ TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING http://datingsitesdatingtips.blogspot.in/ FOR LATEST MOVIE UPDATED LINKS HANSIKA MOTWANI LATEST HOT PICS http://actressgallery-kalyani.blogspot.in/2012/07/hansika-motwani-actress.html HOT NEETHU CHANDRA LATEST PICS http://actressgallery-kalyani.blogspot.in/2012/07/neetu-chandra-actress.html ACTRESS AMRUTHA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/amrutha-actress.html SELATHUPONNU MOVIE HOT PHOTOS http://actressgallery-kalyani.blogspot.in/2012/07/selathuponnu-movie-stills.html SULAGNA PANIGRAHI HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/06/sulagna-panigrahi-actress.html RUBY PARIHAR HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.com/2012/06/actress-ruby-parihar.html ACTRESS YAMI GOUTHAM LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/06/yami-gautam-actress.html ACTRESS HOT STILLS IN SIIMA AWARDS 2012 http://actressgallery-kalyani.blogspot.in/2012/06/actress-siima-awards-2012-stills.html EM BABU LADDU KAVALA MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/06/em-babu-laddu-kavala-movie-stills.html SRMANARAYANA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/06/srimannarayana-movie-stills.html KAJAL AGARWAL LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/06/kajal-agarwal-latest-stills.html SANA KHAN LATEST HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/sana-khan-latest-stills.html COOL BOYS HOT GIRLS MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/06/cool-boys-hot-girls-movie-stills.html MITAAYI MOVIE LATEST GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/mitaayi-movie-stills.html NAGARJUNA DAMARUKAM MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/damarukam-movie-stills.html ALLU ARJUN JULAYI MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/julayi-movie-stills.html SUDIGADU MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/sudigadu-movie-stills.html MR 7 MOVIE FILM GALLERY http://actressgallery-kalyani.blogspot.in/2012/05/mr7-movie-stills.html ALL THE BEST MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/all-best-movie-stills.html Midatha Telugu movie Hot Namitha Stills http://actressgallery-kalyani.blogspot.com/2012/05/midatha-movie-stills.html OKA COLLEGE LOVE STORY MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/oka-college-love-story-movie-stills.html KATRINA KAIF LATEST UNSEENED PHOTOS http://actressgallery-kalyani.blogspot.com/2012/05/katrina-kaif-latest-pics.html TAMIL ACTRESS ARUNDHATI HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/05/arundhati-tamil-actress.html THANDHAVAM MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/05/thandavam-movie-stills.html EEGA MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.com/2012/04/eega-movie-stills.html Mem Vayasuku Vacham Latest Hot Stills http://actressgallery-kalyani.blogspot.com/2012/04/mem-vayasuku-vacham-stills.html ILEANA LATEST HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/01/ileana-latest-stills.html ACTREESS SUPRIYA SHAILJA LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/02/supriya-shailja-stills.html SHEELA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/01/sheela-latest-stills.html KATRINA KAIF ITEM SONG STILLS http://actressgallery-kalyani.blogspot.com/2012/01/katrina-kaif-item-song-stills.html RITU KAUR LATEST PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2012/01/ritu-kaur-stills.html SHRUTI HASSAN HOT IN 3 MOVIE http://actressgallery-kalyani.blogspot.com/2011/11/shruti-hassan-in-3-movie.html HOT LINKS FOR YOUTH ONLY PRANEETHA HOT SPICY IMAGES http://actressimages-9.blogspot.in/2012/06/praneetha-latest-stills.html SHRUTHI HASSAN HALF SAREE STILLS http://actressimages-9.blogspot.in/2012/05/shruti-hassan-half-saree-stills.html TAMANNA HOT NAVEL PHOTOS http://actressimages-9.blogspot.in/2012/05/tamanna-navel-photos.html TRISHA LATEST HOT STILLS http://actressgallery9.blogspot.in/2012/05/trisha.html MONIKA LATEST HOT HD STLLS http://actressgallery9.blogspot.in/2012/05/monika-stills.html MALLIKA KAPOOR HOT SIZZLING STILLS http://actressimages-9.blogspot.in/2012/05/mallika-kapoor.html Richa Panai Stills http://actressimages-9.blogspot.com/2012/04/richa-panai-stills.html MADHAVI LATHA LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/04/madhavi-latha-stills.html KRITI KHARBANDA HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/kriti-kharbanda.html NEELAM UPADHYAY HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/neelam-upadhyay.html SAMANTHA LATEST HOT ROMANTIC STILLS http://actressimages-9.blogspot.in/2012/03/samantha-latest-stills.html NAYANTHARA HOT WALLPAPERS http://actressimages-9.blogspot.in/2012/01/nayanthara.html ANU SMRUTHI LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/02/anu-smirthi-stills.html AISHWARYA RAI LATEST HOT PICS http://actressimages-9.blogspot.in/2012/01/aishwarya-rai.html From steve+comp.lang.python at pearwood.info Thu Jul 5 01:32:48 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Jul 2012 05:32:48 GMT Subject: 2 + 2 = 5 References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <4ff52700$0$30000$c3e8da3$5496439d@news.astraweb.com> On Wed, 04 Jul 2012 23:38:17 -0400, Terry Reedy wrote: > If I run the script in 3.3 Idle, I get the same output you got. If I > then enter '5-2' interactively, I still get 3. Maybe the constant folder > is always on now. Yes, I believe constant folding is always on, since Python 2.4 if I remember correctly. Somebody who cares more than me can possibly check the "What's New" documents :) -- Steven From mspadaccino at gmail.com Thu Jul 5 03:22:01 2012 From: mspadaccino at gmail.com (Maurizio Spadaccino) Date: Thu, 5 Jul 2012 09:22:01 +0200 Subject: Which way is best to execute a Python script in Excel? Message-ID: Hi all I'm new to Python but soon after a few days of studying its features I find it my favourite mean of programming scripts to allow for data storing and mining. My idea would be to inplement python scripts from inside an excel sheet that would store and fetch data from a Mysql database. So i need the script to be launched, say, by pressing a button in excel and, for instance, retrieve immediately data from the mysql table. For what I found in the net, it seems there are three ways to control python from excel: 1) run my python script via shell using the Run command in VBA, which seems to me the easiest (but maybe slower?) way; 2) creating a COM server, for which I need more training since it doesnt appear that easy; 3) via Microsoft Script Control, for which I saw some example around where It looks like I can 'simulate' a python shell via the 'executeStatement' command. What would you suggest would be the more performing way to achieve my goals as described above? Thanks for you help Maurizio -- Maurizio www.mauriziospadaccino.com --------------- If you can avoid printing this e-mail, you are only doing good for our planet. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kliateni at gmail.com Thu Jul 5 03:26:33 2012 From: kliateni at gmail.com (Karim) Date: Thu, 05 Jul 2012 09:26:33 +0200 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: References: Message-ID: <4FF541A9.1090806@gmail.com> Le 05/07/2012 09:22, Maurizio Spadaccino a ?crit : > Hi all > > I'm new to Python but soon after a few days of studying its features I > find it my favourite mean of programming scripts to allow for data > storing and mining. My idea would be to inplement python scripts from > inside an excel sheet that would store and fetch data from a Mysql > database. So i need the script to be launched, say, by pressing a > button in excel and, for instance, retrieve immediately data from the > mysql table. For what I found in the net, it seems there are three > ways to control python from excel: > 1) run my python script via shell using the Run command in VBA, which > seems to me the easiest (but maybe slower?) way; > 2) creating a COM server, for which I need more training since it > doesnt appear that easy; > 3) via Microsoft Script Control, for which I saw some example around > where It looks like I can 'simulate' a python shell via the > 'executeStatement' command. > > What would you suggest would be the more performing way to achieve my > goals as described above? > > Thanks for you help > Maurizio > > > -- > Maurizio > > > www.mauriziospadaccino.com > --------------- > If you can avoid printing this e-mail, you are only doing good for our > planet. > > Look at PyUNO from OpenOffice very large API: http://www.openoffice.org/api/docs I use to create all my documention (Excell, Writer, etc...) on this API. Cheers Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jul 5 03:30:12 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Jul 2012 09:30:12 +0200 Subject: Discussion on some Code Issues References: <34484d3d-d4c2-463b-8f83-dba57ce0511d@googlegroups.com> Message-ID: subhabangalore at gmail.com wrote: > On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote: >> Dear Group, >> >> I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to >> discuss some coding issues. If any one of this learned room can shower >> some light I would be helpful enough. >> >> I got to code a bunch of documents which are combined together. >> Like, >> >> 1)A Mumbai-bound aircraft with 99 passengers on board was struck by >> lightning on Tuesday evening that led to complete communication failure >> in mid-air and forced the pilot to make an emergency landing. 2) The >> discovery of a new sub-atomic particle that is key to understanding how >> the universe is built has an intrinsic Indian connection. 3) A bomb >> explosion outside a shopping mall here on Tuesday left no one injured, >> but Nigerian authorities put security agencies on high alert fearing more >> such attacks in the city. >> >> The task is to separate the documents on the fly and to parse each of the >> documents with a definite set of rules. >> >> Now, the way I am processing is: >> I am clubbing all the documents together, as, >> >> A Mumbai-bound aircraft with 99 passengers on board was struck by >> lightning on Tuesday evening that led to complete communication failure >> in mid-air and forced the pilot to make an emergency landing.The >> discovery of a new sub-atomic particle that is key to understanding how >> the universe is built has an intrinsic Indian connection. A bomb >> explosion outside a shopping mall here on Tuesday left no one injured, >> but Nigerian authorities put security agencies on high alert fearing more >> such attacks in the city. >> >> But they are separated by a tag set, like, >> A Mumbai-bound aircraft with 99 passengers on board was struck by >> lightning on Tuesday evening that led to complete communication failure >> in mid-air and forced the pilot to make an emergency landing.$ The >> discovery of a new sub-atomic particle that is key to understanding how >> the universe is built has an intrinsic Indian connection.$ A bomb >> explosion outside a shopping mall here on Tuesday left no one injured, >> but Nigerian authorities put security agencies on high alert fearing more >> such attacks in the city. >> >> To detect the document boundaries, I am splitting them into a bag of >> words and using a simple for loop as, for i in range(len(bag_words)): >> if bag_words[i]=="$": >> print (bag_words[i],i) >> >> There is no issue. I am segmenting it nicely. I am using annotated corpus >> so applying parse rules. >> >> The confusion comes next, >> >> As per my problem statement the size of the file (of documents combined >> together) won?t increase on the fly. So, just to support all kinds of >> combinations I am appending in a list the ?I? values, taking its length, >> and using slice. Works perfect. Question is, is there a smarter way to >> achieve this, and a curious question if the documents are on the fly with >> no preprocessed tag set like ?$? how may I do it? From a bunch without >> EOF isn?t it a classification problem? >> >> There is no question on parsing it seems I am achieving it independent of >> length of the document. >> >> If any one in the group can suggest how I am dealing with the problem and >> which portions should be improved and how? >> >> Thanking You in Advance, >> >> Best Regards, >> Subhabrata Banerjee. > > > Hi Steven, It is nice to see your post. They are nice and I learnt so many > things from you. "I" is for index of the loop. Now my clarification I > thought to do "import os" and process files in a loop but that is not my > problem statement. I have to make a big lump of text and detect one chunk. > Looping over the line number of file I am not using because I may not be > able to take the slices-this I need. I thought to give re.findall a try > but that is not giving me the slices. Slice spreads here. The power issue > of string! I would definitely give it a try. Happy Day Ahead Regards, > Subhabrata Banerjee. Then use re.finditer(): start = 0 for match in re.finditer(r"\$", data): end = match.start() print(start, end) print(data[start:end]) start = match.end() This will omit the last text. The simplest fix is to put another "$" separator at the end of your data. From dieter at handshake.de Thu Jul 5 04:27:40 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 05 Jul 2012 10:27:40 +0200 Subject: Using a CMS for small site? References: Message-ID: <87pq8ar4sj.fsf@handshake.de> Gilles writes: > The site is just... > - a few web pages that include text (in four languages) and pictures > displayed in a Flash slide show > - a calendar to show availability > - a form to send e-mail with anti-SPAM support > - (ASAP) online payment > > Out of curiosity, are there CMS/frameworks in Python that can do this? > Django? Other? There is also "Plone" ("http://plone.org") -- easy to set up. You likely need third party extensions for the "anti-SPAM" support and the onlie payment. Unfortunately, "Plone" is quite resource hungry -- especially it wants quite some memory. From dieter at handshake.de Thu Jul 5 04:39:44 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 05 Jul 2012 10:39:44 +0200 Subject: adding a simulation mode References: Message-ID: <87liiyr48f.fsf@handshake.de> andrea crotti writes: > I'm writing a program which has to interact with many external > resources, at least: > - mysql database > - perforce > - shared mounts > - files on disk > > And the logic is quite complex, because there are many possible paths to > follow depending on some other parameters. > This program even needs to run on many virtual machines at the same time > so the interaction is another thing I need to check... > > Now I successfully managed to mock the database with sqlalchemy and only > the fields I actually need, but I now would like to simulate also > everything else. There is a paradigm called "inversion of control" which can be used to handle those requirements. With "inversion of control", the components interact on the bases of interfaces. The components themselves do not know each other, they know only the interfaces they want to interact with. For the interaction to really take place, a component asks a registry "give me a component satisfying this interface", gets it and uses the interface. If you follow this paradigm, it is easy to switch components: just register different alternatives for the interface at hand. "zope.interface" and "zope.component" are python packages that support this paradigm. Despite the "zope" in their name, they can be used outside of "Zope". "zope.interface" models interfaces, while "zope.component" provides so called "utilities" (e.g. "database utility", "filesystem utility", ...) and "adapters" and the corresponding registries. Of course, they contain only the infrastructure for the "inversion of control" paradigm. Up to you to provide the implementation for the various mocks. From dieter at handshake.de Thu Jul 5 04:46:20 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 05 Jul 2012 10:46:20 +0200 Subject: Question about weakref References: Message-ID: <87hatmr3xf.fsf@handshake.de> Frank Millman writes: > I have a situation where I thought using weakrefs would save me a bit > of effort. Instead of the low level "weakref", you might use a "WeakKeyDictionary". From shilparani9030 at gmail.com Thu Jul 5 05:01:21 2012 From: shilparani9030 at gmail.com (SHILPA) Date: Thu, 5 Jul 2012 02:01:21 -0700 (PDT) Subject: EXTRAORDINARY HOT PHOTOS AND VIDEOS Message-ID: <72457ffb-a9f6-4943-b5c1-316ca449ddf1@lq16g2000pbb.googlegroups.com> ALL INTERVIEW QUESTIONS& STUDY MATERIAL http://newdotnetinterviewquestions.blogspot.in/ TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING http://datingsitesdatingtips.blogspot.in/ FOR LATEST MOVIE UPDATED LINKS HANSIKA MOTWANI LATEST HOT PICS http://actressgallery-kalyani.blogspot.in/2012/07/hansika-motwani-actress.html HOT NEETHU CHANDRA LATEST PICS http://actressgallery-kalyani.blogspot.in/2012/07/neetu-chandra-actress.html ACTRESS AMRUTHA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/amrutha-actress.html SELATHUPONNU MOVIE HOT PHOTOS http://actressgallery-kalyani.blogspot.in/2012/07/selathuponnu-movie-stills.html SULAGNA PANIGRAHI HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/06/sulagna-panigrahi-actress.html RUBY PARIHAR HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.com/2012/06/actress-ruby-parihar.html ACTRESS YAMI GOUTHAM LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/06/yami-gautam-actress.html ACTRESS HOT STILLS IN SIIMA AWARDS 2012 http://actressgallery-kalyani.blogspot.in/2012/06/actress-siima-awards-2012-stills.html EM BABU LADDU KAVALA MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/06/em-babu-laddu-kavala-movie-stills.html SRMANARAYANA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/06/srimannarayana-movie-stills.html KAJAL AGARWAL LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/06/kajal-agarwal-latest-stills.html SANA KHAN LATEST HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/sana-khan-latest-stills.html COOL BOYS HOT GIRLS MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/06/cool-boys-hot-girls-movie-stills.html MITAAYI MOVIE LATEST GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/mitaayi-movie-stills.html NAGARJUNA DAMARUKAM MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/damarukam-movie-stills.html ALLU ARJUN JULAYI MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/julayi-movie-stills.html SUDIGADU MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/sudigadu-movie-stills.html MR 7 MOVIE FILM GALLERY http://actressgallery-kalyani.blogspot.in/2012/05/mr7-movie-stills.html ALL THE BEST MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/all-best-movie-stills.html Midatha Telugu movie Hot Namitha Stills http://actressgallery-kalyani.blogspot.com/2012/05/midatha-movie-stills.html OKA COLLEGE LOVE STORY MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/oka-college-love-story-movie-stills.html KATRINA KAIF LATEST UNSEENED PHOTOS http://actressgallery-kalyani.blogspot.com/2012/05/katrina-kaif-latest-pics.html TAMIL ACTRESS ARUNDHATI HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/05/arundhati-tamil-actress.html THANDHAVAM MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/05/thandavam-movie-stills.html EEGA MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.com/2012/04/eega-movie-stills.html Mem Vayasuku Vacham Latest Hot Stills http://actressgallery-kalyani.blogspot.com/2012/04/mem-vayasuku-vacham-stills.html ILEANA LATEST HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/01/ileana-latest-stills.html ACTREESS SUPRIYA SHAILJA LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/02/supriya-shailja-stills.html SHEELA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/01/sheela-latest-stills.html KATRINA KAIF ITEM SONG STILLS http://actressgallery-kalyani.blogspot.com/2012/01/katrina-kaif-item-song-stills.html RITU KAUR LATEST PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2012/01/ritu-kaur-stills.html SHRUTI HASSAN HOT IN 3 MOVIE http://actressgallery-kalyani.blogspot.com/2011/11/shruti-hassan-in-3-movie.html HOT LINKS FOR YOUTH ONLY PRANEETHA HOT SPICY IMAGES http://actressimages-9.blogspot.in/2012/06/praneetha-latest-stills.html SHRUTHI HASSAN HALF SAREE STILLS http://actressimages-9.blogspot.in/2012/05/shruti-hassan-half-saree-stills.html TAMANNA HOT NAVEL PHOTOS http://actressimages-9.blogspot.in/2012/05/tamanna-navel-photos.html TRISHA LATEST HOT STILLS http://actressgallery9.blogspot.in/2012/05/trisha.html MONIKA LATEST HOT HD STLLS http://actressgallery9.blogspot.in/2012/05/monika-stills.html MALLIKA KAPOOR HOT SIZZLING STILLS http://actressimages-9.blogspot.in/2012/05/mallika-kapoor.html Richa Panai Stills http://actressimages-9.blogspot.com/2012/04/richa-panai-stills.html MADHAVI LATHA LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/04/madhavi-latha-stills.html KRITI KHARBANDA HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/kriti-kharbanda.html NEELAM UPADHYAY HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/neelam-upadhyay.html SAMANTHA LATEST HOT ROMANTIC STILLS http://actressimages-9.blogspot.in/2012/03/samantha-latest-stills.html NAYANTHARA HOT WALLPAPERS http://actressimages-9.blogspot.in/2012/01/nayanthara.html ANU SMRUTHI LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/02/anu-smirthi-stills.html AISHWARYA RAI LATEST HOT PICS http://actressimages-9.blogspot.in/2012/01/aishwarya-rai.html From t at jollybox.de Thu Jul 5 05:12:37 2012 From: t at jollybox.de (Thomas Jollans) Date: Thu, 05 Jul 2012 11:12:37 +0200 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <4FF541A9.1090806@gmail.com> References: <4FF541A9.1090806@gmail.com> Message-ID: <4FF55A85.2040002@jollybox.de> On 07/05/2012 09:26 AM, Karim wrote: > Look at PyUNO from OpenOffice very large API: > http://www.openoffice.org/api/docs > > I use to create all my documention (Excell, Writer, etc...) on this API. Note that this API is for OpenOffice, not Microsoft Excel. However, as you probably know, you can open most Excel files in OpenOffice's Calc. I urge you to consider LibreOffice, a fork of OpenOffice that is now broadly considered its successor. Its API can also be used in Python http://api.libreoffice.org/ If you want to program Microsoft Office, your only option is, as far as I know, VBA, but it may be possible to call Python from VBA using the Windows Script Host. I assume that the Windows Script Control uses this, but I doubt that's much easier to use than the standard WScript API. (then again, I wouldn't know) All in all, if you're going to script Microsoft office, by far the easiest way is to simply stick to VBA and forget about Python in this particular environment. If it's an option, try LibreOffice. Thomas From andrea.crotti.0 at gmail.com Thu Jul 5 05:22:02 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 5 Jul 2012 10:22:02 +0100 Subject: adding a simulation mode In-Reply-To: <87liiyr48f.fsf@handshake.de> References: <87liiyr48f.fsf@handshake.de> Message-ID: 2012/7/5 Dieter Maurer : > > There is a paradigm called "inversion of control" which can be used > to handle those requirements. > > With "inversion of control", the components interact on the bases > of interfaces. The components themselves do not know each other, they > know only the interfaces they want to interact with. For the interaction > to really take place, a component asks a registry "give me a component > satisfying this interface", gets it and uses the interface. > > If you follow this paradigm, it is easy to switch components: just > register different alternatives for the interface at hand. > > > "zope.interface" and "zope.component" are python packages that > support this paradigm. Despite the "zope" in their name, they can be > used outside of "Zope". > > "zope.interface" models interfaces, while "zope.component" provides > so called "utilities" (e.g. "database utility", "filesystem utility", ...) > and "adapters" and the corresponding registries. > > > Of course, they contain only the infrastructure for the "inversion of control" > paradigm. Up to you to provide the implementation for the various > mocks. > Thanks that's a good point, in short I could do something like: class FSActions: @classmethod def copy_directories(cls, src, dest) raise NotImplementedError @classmethod .... And then have different implementations of this interface. This would work, but I don't really like the idea of constructing interfaces that provide only the few things I need. Instead of being good APIs they might become just random functionalities put together to make my life easier, and at that point maybe just some clear mocking might be even better.. From diolu at bigfoot.com Thu Jul 5 06:29:24 2012 From: diolu at bigfoot.com (Olive) Date: Thu, 5 Jul 2012 12:29:24 +0200 Subject: Creating an instance when the argument is already an instance. Message-ID: <20120705122924.481a546b@bigfoot.com> I am learning python -:) I am creating a new class: package (to analyse the packages database in some linux distros). I have created a class package such that package("string") give me an instance of package if string is a correct representation of a package. I would like that if pack is already an instance of package then package(pack) just return pack. This is exactly the behaviour of many of the built-in types. For example: [code] [oesser at pcolivier ~]$ python2 Python 2.7.3 (default, Apr 24 2012, 00:06:13) [GCC 4.7.0 20120414 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=complex(2,3) >>> b=complex(a) >>> a is b True [/code] I note here that b is not a new instance of complex, it is another name for a (as we can see with a is b). I would like to implement such behaviour but I do not not how. Olive From rosuav at gmail.com Thu Jul 5 06:47:52 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 5 Jul 2012 20:47:52 +1000 Subject: Creating an instance when the argument is already an instance. In-Reply-To: <20120705122924.481a546b@bigfoot.com> References: <20120705122924.481a546b@bigfoot.com> Message-ID: On Thu, Jul 5, 2012 at 8:29 PM, Olive wrote: > I am creating a new class: package (to analyse the packages database in > some linux distros). I have created a class package such that > package("string") give me an instance of package if string is a correct > representation of a package. I would like that if pack is already an > instance of package then package(pack) just return pack. One way would be to make the name "package" actually a wrapper function, not the class itself: >>> class _package: def __init__(self,arg): # blah blah self.asdf=arg >>> def package(arg): if isinstance(arg,_package): return arg return _package(arg) >>> a=package("Test") >>> b=package(a) >>> a is b True The leading underscore is a common convention meaning "private implementation detail". Chris Angelico From frank at chagford.com Thu Jul 5 07:21:38 2012 From: frank at chagford.com (Frank Millman) Date: Thu, 05 Jul 2012 13:21:38 +0200 Subject: Question about weakref In-Reply-To: <87hatmr3xf.fsf@handshake.de> References: <87hatmr3xf.fsf@handshake.de> Message-ID: On 05/07/2012 10:46, Dieter Maurer wrote: > Frank Millman writes: > >> I have a situation where I thought using weakrefs would save me a bit >> of effort. > > Instead of the low level "weakref", you might use a "WeakKeyDictionary". > Thanks, Dieter. I could do that. In fact, a WeakSet suits my purposes better. I tested it with my original example, and it works correctly. It also saves me the step of deleting the weak reference once the original object is deleted, as it seems to do that automatically. I just need to double-check that I would never have the same listener-object try to register itself with the publisher twice, as that would obviously fail with a Set, as it would with a Dict. I would still like to know why weakref.proxy raised an exception. I have re-read the manual several times, and googled for similar problems, but am none the wiser. Naturally I feel a bit uneasy using a feature of the language which sometimes fails mysteriously, so if anyone has an explanation, I would really appreciate it. Frank From steve+comp.lang.python at pearwood.info Thu Jul 5 07:55:33 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Jul 2012 11:55:33 GMT Subject: Creating an instance when the argument is already an instance. References: <20120705122924.481a546b@bigfoot.com> Message-ID: <4ff580b4$0$29988$c3e8da3$5496439d@news.astraweb.com> On Thu, 05 Jul 2012 12:29:24 +0200, Olive wrote: > I am learning python -:) > > I am creating a new class: package (to analyse the packages database in > some linux distros). I have created a class package such that > package("string") give me an instance of package if string is a correct > representation of a package. I would like that if pack is already an > instance of package then package(pack) just return pack. The built-in types only do this for immutable objects, those which cannot be modified. py> a = float('42.5') py> b = float(a) py> a is b True But note carefully that this is not a guarantee of the language. Other versions of Python may not do this. Also note carefully that it is only immutable objects which do this. Mutable objects do not behave this way: py> a = ['a', 1, None] py> b = list(a) py> a is b False By default, most custom-made classes are mutable, and so re-using instances is the wrong thing to do. Unfortunately, it is moderately tricky to make mutable classes in Python. One way is described here: http://northernplanets.blogspot.com.au/2007/01/immutable-instances-in-python.html You can also look at the source code for Decimal (warning: it's BIG) or Fraction: http://hg.python.org/cpython/file/2.7/Lib/decimal.py http://hg.python.org/cpython/file/2.7/Lib/fractions.py But suppose you make your class immutable. Then it's quite safe, and easy, to get the behaviour you want: class Package(object): def __new__(cls, argument): if isinstance(argument, Package): return argument return object.__new__(cls, argument) or similar, I haven't actually tested the above. But the important trick is to use __new__, the constructor, rather than __init__, which runs after the instance is already created, and to use an isinstance test to detect when you already have an instance. Good luck! -- Steven From nospam at nospam.com Thu Jul 5 09:01:33 2012 From: nospam at nospam.com (Gilles) Date: Thu, 05 Jul 2012 15:01:33 +0200 Subject: Using a CMS for small site? References: <7fk8v7pijp359t62clgj5g4n3d4acvap3k@4ax.com> <898fafd5-fd37-4c32-9074-8396bf203e5e@y3g2000pbc.googlegroups.com> Message-ID: On Wed, 4 Jul 2012 17:09:40 -0700 (PDT), alex23 wrote: >Not necessarily! There are several static site generators written in >Python :) > >One that I see being updating a lot is Nikola: http://nikola.ralsina.com.ar/ I'll check it out, thanks. From nospam at nospam.com Thu Jul 5 09:02:03 2012 From: nospam at nospam.com (Gilles) Date: Thu, 05 Jul 2012 15:02:03 +0200 Subject: Using a CMS for small site? References: Message-ID: On Thu, 05 Jul 2012 10:27:40 +0200, Dieter Maurer wrote: >There is also "Plone" ("http://plone.org") -- easy to set up. > >You likely need third party extensions for the "anti-SPAM" support >and the onlie payment. I'll see what extensions it offers. Thanks. From vlastimil.brom at gmail.com Thu Jul 5 09:18:09 2012 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 5 Jul 2012 15:18:09 +0200 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: Many thanks to all for your suggestions! @ChrisA Yes, the calculations with seconds since the Unix epoch is very convenient for real times, but trying to make it dateless seemed to make it more complicated for me. The expected output for the increments asked by Jason was already correctly stated by Devin; i.e.: 12:45 plus 12 hours is 0:45 and 12:45 minus 13 hours is 23:45. Thanks for reminding me of dateutil.relativedelta, Mark, I didn't think of it in this context (I always thought, the "relative" stands for time and date calculations with regard to the current time and date). There doesn't seem to be a way to use dateless time either (unless I missed it), however, it turns out, that one can probably work with this naive "times" like with deltas (possibly ignoring other units than hours and minutes in the result): >>> td = dateutil.relativedelta.relativedelta(hours=9, minutes=45) + dateutil.relativedelta.relativedelta(minutes=30) >>> "%s.%s" % (td.hours, td.minutes) '10.15' >>> Which is probably the simplest and the most robust way, I found sofar. It likely isn't the expected use case for relativedelta, but it seems to work ok. (Are there maybe some drawbacks I am missing?) (Well I just found one possible pitfall , if floats are passed: >>> td = dateutil.relativedelta.relativedelta(hours=9, minutes=45) + dateutil.relativedelta.relativedelta(minutes=30.5) >>> "%s.%s" % (td.hours, td.minutes) '10.0.15.5' , but its beyond my current use case, and the validation can always be added.) The same would be doable using the built in timedelta too, but there are no hours and minutes in its output, hence these are to be converted from the seconds count. >>> dttd=datetime.timedelta(hours=9, minutes=45) + datetime.timedelta(minutes=30) >>> dttd datetime.timedelta(0, 36900) >>> dttd.seconds 36900 >>> s = dttd.seconds >>> h,s = divmod(s,3600) >>> m,s = divmod(s,60) >>> h,m,s (10, 15, 0) >>> "%s.%s" % (h, m) '10.15' >>> Any thoughts? thanks again, vbr From rosuav at gmail.com Thu Jul 5 09:56:37 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 5 Jul 2012 23:56:37 +1000 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Thu, Jul 5, 2012 at 11:18 PM, Vlastimil Brom wrote: > Yes, the calculations with seconds since the Unix epoch is very > convenient for real times, but trying to make it dateless seemed to > make it more complicated for me. > > The expected output for the increments asked by Jason was already > correctly stated by Devin; i.e.: 12:45 plus 12 hours is 0:45 and 12:45 > minus 13 hours is 23:45. I'm not familiar with the Python classes (I tend to think in terms of language-agnostic algorithms first, and specific libraries/modules/etc second), but if you're working with simple integer seconds, your datelessness is just modulo arithmetic. time1 + time2 --> (time1 + time2) % 86400 time1 - time2 --> (time1 + 86400 - time2) % 86400 Or alternatively, bounding afterward: if time > 86400: time-=86400 if time < 86400: time+=86400 (The "magic number" 86400 is a well-known number, being seconds in a day. Feel free to replace it with 24*60*60 if it makes you feel better; I'm pretty sure Python will translate it into a constant at parse time. Or alternatively, have a module-level constant SECONDS_IN_A_DAY = 86400, in case that number should ever change.) ChrisA From hansmu at xs4all.nl Thu Jul 5 09:57:53 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 05 Jul 2012 15:57:53 +0200 Subject: 2 + 2 = 5 In-Reply-To: <4ff52700$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff52700$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ff59d61$0$6880$e4fe514c@news2.news.xs4all.nl> On 5/07/12 07:32:48, Steven D'Aprano wrote: > On Wed, 04 Jul 2012 23:38:17 -0400, Terry Reedy wrote: > >> If I run the script in 3.3 Idle, I get the same output you got. If I >> then enter '5-2' interactively, I still get 3. Maybe the constant folder >> is always on now. > > Yes, I believe constant folding is always on, since Python 2.4 if I > remember correctly. Somebody who cares more than me can possibly check > the "What's New" documents :) It's not a difference between 2.4 and 3.3; the difference is between Idle and the command-line version of the interactive interpreter. If I type the same code into Idle and the interactive interpreter (both using 3.3alpha1), I get 3 in Idle and 2 in Terminal. I don't quite understand why this difference exists. Confused, -- HansM From demianbrecht at gmail.com Thu Jul 5 10:06:09 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Thu, 5 Jul 2012 07:06:09 -0700 (PDT) Subject: OAuth 2.0 implementation In-Reply-To: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> Message-ID: <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> FWIW, this package has undergone a major overhaul (474 LOC down to much happier 66) and is available at https://github.com/demianbrecht/sanction. Also available from PyPI. From gdamjan at gmail.com Thu Jul 5 10:10:11 2012 From: gdamjan at gmail.com (Damjan) Date: Thu, 05 Jul 2012 16:10:11 +0200 Subject: Confusing datetime.datetime Message-ID: I've been struggling with an app that uses Postgresql/Psycopg2/SQLAlchemy and I've come to this confusing behaviour of datetime.datetime. First of all, the "Seconds since Epoch" timestamps are always in UTC, so shouldn't change with timezones. So I'd expect that a round trip of a timestamp through datetime.datetime, shouldn't change it. Now, all is good when I use a naive datetime.datetime -- TZ=UTC python >>> from datetime import datetime >>> dt = datetime.fromtimestamp(1341446400) >>> dt datetime.datetime(2012, 7, 5, 0, 0) >>> dt.strftime('%s') '1341446400' -- TZ=Asia/Tokyo python >>> from datetime import datetime >>> dt = datetime.fromtimestamp(1341446400) >>> dt datetime.datetime(2012, 7, 5, 9, 0) >>> dt.strftime('%s') '1341446400' But when I use an timezone aware datetime.datetime objects, the timestamp roundtrip is destroyed. I get 2 different timestamps. Am I missing something here, I've been reading the datetime documentation several times, but I can't understand what is the intended behaviour. -- TZ=UTC python >>> from datetime import datetime >>> import pytz >>> tz = pytz.timezone('Europe/Skopje') >>> dt = datetime.fromtimestamp(1341446400, tz) >>> dt datetime.datetime(2012, 7, 5, 2, 0, tzinfo=) >>> dt.strftime('%s') '1341453600' -- TZ=Asia/Tokyo python >>> from datetime import datetime >>> import pytz >>> tz = pytz.timezone('Europe/Skopje') >>> dt = datetime.fromtimestamp(1341446400, tz) >>> dt datetime.datetime(2012, 7, 5, 2, 0, tzinfo=) >>> dt.strftime('%s') '1341421200' Python 2.7.3, pytz 2012c -- damjan From rurpy at yahoo.com Thu Jul 5 10:11:38 2012 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 5 Jul 2012 07:11:38 -0700 (PDT) Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Wednesday, July 4, 2012 6:29:10 PM UTC-6, Vlastimil Brom wrote: > Hi all, > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. > I first thought, it would be possible to just add a timedelta to a > time object, but, it doesn't seem to be the case. > > The code I came up with (using time and datetime modules) seems rather > convoluted and I would like to ask about some possible more > straightforward alternatives I missed. > The equivalent function (lacking validation) without the (date)time > libraries seems simple enough (for this limited and individual task). > Although it is probably mostly throw-away code, which seems to do what > I need, I'd be interested in better/more elegant... solutions. > > # # # > import time > import datetime > import re > > print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45", > "%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M")) > # 9.15 > > # # # # # # # # # > > def add_minutes(hour_min_str, separator=".", minutes_to_add=0): > h, m = [int(s) for s in hour_min_str.split(separator)] > sum_minutes = h * 60 + m + minutes_to_add > h, m = divmod(sum_minutes, 60) > h = h % 24 > return "%s%s%s" % (h, separator, m) > > print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30) > # 9.15 > > # # # # # # # # # > > Is it true, that timedelta cannot be used with dateless time values? > (Is there some other possibility than the current one, where strptime > actually infers 1. 1. 1900?) > Is there some simpler way to adapt the incompatible output of strptime > as the input of datetime? > Is it possible to get one-digit hours formatted without the leading zero? > > Thanks in advance for any suggestions or remarks; > regards, > Vlastimil Brom If it's any consolation, I had to add a small constant time delta to all the times in a video subtitles file and my code ended up looking very much like yours. What should have take five minutes to write took several hours, I remain surprised and disappointed that doing something so simple (read time text into time object, add timedelta, print result) was so awkward in Python. From rurpy at yahoo.com Thu Jul 5 10:11:38 2012 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 5 Jul 2012 07:11:38 -0700 (PDT) Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Wednesday, July 4, 2012 6:29:10 PM UTC-6, Vlastimil Brom wrote: > Hi all, > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. > I first thought, it would be possible to just add a timedelta to a > time object, but, it doesn't seem to be the case. > > The code I came up with (using time and datetime modules) seems rather > convoluted and I would like to ask about some possible more > straightforward alternatives I missed. > The equivalent function (lacking validation) without the (date)time > libraries seems simple enough (for this limited and individual task). > Although it is probably mostly throw-away code, which seems to do what > I need, I'd be interested in better/more elegant... solutions. > > # # # > import time > import datetime > import re > > print re.sub(r"^0","", (datetime.datetime(*list(time.strptime("8.45", > "%H.%M"))[:6]) + datetime.timedelta(minutes=30)).strftime("%H.%M")) > # 9.15 > > # # # # # # # # # > > def add_minutes(hour_min_str, separator=".", minutes_to_add=0): > h, m = [int(s) for s in hour_min_str.split(separator)] > sum_minutes = h * 60 + m + minutes_to_add > h, m = divmod(sum_minutes, 60) > h = h % 24 > return "%s%s%s" % (h, separator, m) > > print add_minutes(hour_min_str="8.45", separator='.', minutes_to_add=30) > # 9.15 > > # # # # # # # # # > > Is it true, that timedelta cannot be used with dateless time values? > (Is there some other possibility than the current one, where strptime > actually infers 1. 1. 1900?) > Is there some simpler way to adapt the incompatible output of strptime > as the input of datetime? > Is it possible to get one-digit hours formatted without the leading zero? > > Thanks in advance for any suggestions or remarks; > regards, > Vlastimil Brom If it's any consolation, I had to add a small constant time delta to all the times in a video subtitles file and my code ended up looking very much like yours. What should have take five minutes to write took several hours, I remain surprised and disappointed that doing something so simple (read time text into time object, add timedelta, print result) was so awkward in Python. From emile at fenx.com Thu Jul 5 10:28:39 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 05 Jul 2012 07:28:39 -0700 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: References: Message-ID: On 7/5/2012 12:22 AM Maurizio Spadaccino said... > Hi all > > I'm new to Python but soon after a few days of studying its features I > find it my favourite mean of programming scripts to allow for data > storing and mining. My idea would be to inplement python scripts from > inside an excel sheet that would store and fetch data from a Mysql > database. Look again at the com interface -- I've created excel commands implemented entirely in python this way and it will do everything you're looking for. Just start with some of the examples and extend from there. See http://oreilly.com/catalog/pythonwin32/chapter/ch12.html I did this ten years ago so things have likely changed, but the bits of the python script that set up com then looked like this: class fenxUtilities: _public_methods_ = [ 'FirstPartInsp' ] _reg_progid_ = "fenxDCom.Util" _reg_clsid_ = "{3EAD7AB4-2978-4360-8F7D-33FB36E9E146}" def FirstPartInsp(self,nomDiam, numFlutes, nomOAL, nomLOC): return EMSpecs(nomDiam, numFlutes, nomOAL, nomLOC).retvals if __name__=='__main__': print "Registering COM server..." import win32com.server.register win32com.server.register.UseCommandLine(fenxUtilities) HTH, Emile > So i need the script to be launched, say, by pressing a button > in excel and, for instance, retrieve immediately data from the mysql > table. For what I found in the net, it seems there are three ways to > control python from excel: > 1) run my python script via shell using the Run command in VBA, which > seems to me the easiest (but maybe slower?) way; > 2) creating a COM server, for which I need more training since it doesnt > appear that easy; > 3) via Microsoft Script Control, for which I saw some example around > where It looks like I can 'simulate' a python shell via the > 'executeStatement' command. > > What would you suggest would be the more performing way to achieve my > goals as described above? > > Thanks for you help > Maurizio > > > -- > Maurizio > > > www.mauriziospadaccino.com > --------------- > If you can avoid printing this e-mail, you are only doing good for our > planet. > > From aclark at aclark.net Thu Jul 5 10:30:40 2012 From: aclark at aclark.net (Alex Clark) Date: Thu, 05 Jul 2012 10:30:40 -0400 Subject: Using a CMS for small site? In-Reply-To: <87pq8ar4sj.fsf@handshake.de> References: <87pq8ar4sj.fsf@handshake.de> Message-ID: On 7/5/12 4:27 AM, Dieter Maurer wrote: > Gilles writes: > >> The site is just... >> - a few web pages that include text (in four languages) and pictures >> displayed in a Flash slide show >> - a calendar to show availability >> - a form to send e-mail with anti-SPAM support >> - (ASAP) online payment >> >> Out of curiosity, are there CMS/frameworks in Python that can do this? >> Django? Other? > > There is also "Plone" ("http://plone.org") -- easy to set up. > > You likely need third party extensions for the "anti-SPAM" support > and the onlie payment. > > Unfortunately, "Plone" is quite resource hungry -- especially it wants > quite some memory. Actually with Plone 4 (and 4.2 in particular) that is becoming less true, I recently shrunk http://aclark.net to a 256MB vhost on rackspace cloud. > -- Alex Clark ? http://pythonpackages.com From subhabangalore at gmail.com Thu Jul 5 10:33:27 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Thu, 5 Jul 2012 07:33:27 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <34484d3d-d4c2-463b-8f83-dba57ce0511d@googlegroups.com> Message-ID: <996c1d6a-f297-401e-94a4-99be159a0801@googlegroups.com> Dear Peter, That is a nice one. I am thinking if I can write "for lines in f" sort of code that is easy but then how to find out the slices then, btw do you know in any case may I convert the index position of file to the list position provided I am writing the list for the same file we are reading. Best Regards, Subhabrata. On Thursday, July 5, 2012 1:00:12 PM UTC+5:30, Peter Otten wrote: > subhabangalore at gmail.com wrote: > > > On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote: > >> Dear Group, > >> > >> I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to > >> discuss some coding issues. If any one of this learned room can shower > >> some light I would be helpful enough. > >> > >> I got to code a bunch of documents which are combined together. > >> Like, > >> > >> 1)A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing. 2) The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection. 3) A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> The task is to separate the documents on the fly and to parse each of the > >> documents with a definite set of rules. > >> > >> Now, the way I am processing is: > >> I am clubbing all the documents together, as, > >> > >> A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing.The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection. A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> But they are separated by a tag set, like, > >> A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing.$ The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection.$ A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> To detect the document boundaries, I am splitting them into a bag of > >> words and using a simple for loop as, for i in range(len(bag_words)): > >> if bag_words[i]=="$": > >> print (bag_words[i],i) > >> > >> There is no issue. I am segmenting it nicely. I am using annotated corpus > >> so applying parse rules. > >> > >> The confusion comes next, > >> > >> As per my problem statement the size of the file (of documents combined > >> together) won?t increase on the fly. So, just to support all kinds of > >> combinations I am appending in a list the ?I? values, taking its length, > >> and using slice. Works perfect. Question is, is there a smarter way to > >> achieve this, and a curious question if the documents are on the fly with > >> no preprocessed tag set like ?$? how may I do it? From a bunch without > >> EOF isn?t it a classification problem? > >> > >> There is no question on parsing it seems I am achieving it independent of > >> length of the document. > >> > >> If any one in the group can suggest how I am dealing with the problem and > >> which portions should be improved and how? > >> > >> Thanking You in Advance, > >> > >> Best Regards, > >> Subhabrata Banerjee. > > > > > > Hi Steven, It is nice to see your post. They are nice and I learnt so many > > things from you. "I" is for index of the loop. Now my clarification I > > thought to do "import os" and process files in a loop but that is not my > > problem statement. I have to make a big lump of text and detect one chunk. > > Looping over the line number of file I am not using because I may not be > > able to take the slices-this I need. I thought to give re.findall a try > > but that is not giving me the slices. Slice spreads here. The power issue > > of string! I would definitely give it a try. Happy Day Ahead Regards, > > Subhabrata Banerjee. > > Then use re.finditer(): > > start = 0 > for match in re.finditer(r"\$", data): > end = match.start() > print(start, end) > print(data[start:end]) > start = match.end() > > This will omit the last text. The simplest fix is to put another "$" > separator at the end of your data. From subhabangalore at gmail.com Thu Jul 5 10:33:27 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Thu, 5 Jul 2012 07:33:27 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <34484d3d-d4c2-463b-8f83-dba57ce0511d@googlegroups.com> Message-ID: <996c1d6a-f297-401e-94a4-99be159a0801@googlegroups.com> Dear Peter, That is a nice one. I am thinking if I can write "for lines in f" sort of code that is easy but then how to find out the slices then, btw do you know in any case may I convert the index position of file to the list position provided I am writing the list for the same file we are reading. Best Regards, Subhabrata. On Thursday, July 5, 2012 1:00:12 PM UTC+5:30, Peter Otten wrote: > subhabangalore at gmail.com wrote: > > > On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote: > >> Dear Group, > >> > >> I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to > >> discuss some coding issues. If any one of this learned room can shower > >> some light I would be helpful enough. > >> > >> I got to code a bunch of documents which are combined together. > >> Like, > >> > >> 1)A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing. 2) The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection. 3) A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> The task is to separate the documents on the fly and to parse each of the > >> documents with a definite set of rules. > >> > >> Now, the way I am processing is: > >> I am clubbing all the documents together, as, > >> > >> A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing.The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection. A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> But they are separated by a tag set, like, > >> A Mumbai-bound aircraft with 99 passengers on board was struck by > >> lightning on Tuesday evening that led to complete communication failure > >> in mid-air and forced the pilot to make an emergency landing.$ The > >> discovery of a new sub-atomic particle that is key to understanding how > >> the universe is built has an intrinsic Indian connection.$ A bomb > >> explosion outside a shopping mall here on Tuesday left no one injured, > >> but Nigerian authorities put security agencies on high alert fearing more > >> such attacks in the city. > >> > >> To detect the document boundaries, I am splitting them into a bag of > >> words and using a simple for loop as, for i in range(len(bag_words)): > >> if bag_words[i]=="$": > >> print (bag_words[i],i) > >> > >> There is no issue. I am segmenting it nicely. I am using annotated corpus > >> so applying parse rules. > >> > >> The confusion comes next, > >> > >> As per my problem statement the size of the file (of documents combined > >> together) won?t increase on the fly. So, just to support all kinds of > >> combinations I am appending in a list the ?I? values, taking its length, > >> and using slice. Works perfect. Question is, is there a smarter way to > >> achieve this, and a curious question if the documents are on the fly with > >> no preprocessed tag set like ?$? how may I do it? From a bunch without > >> EOF isn?t it a classification problem? > >> > >> There is no question on parsing it seems I am achieving it independent of > >> length of the document. > >> > >> If any one in the group can suggest how I am dealing with the problem and > >> which portions should be improved and how? > >> > >> Thanking You in Advance, > >> > >> Best Regards, > >> Subhabrata Banerjee. > > > > > > Hi Steven, It is nice to see your post. They are nice and I learnt so many > > things from you. "I" is for index of the loop. Now my clarification I > > thought to do "import os" and process files in a loop but that is not my > > problem statement. I have to make a big lump of text and detect one chunk. > > Looping over the line number of file I am not using because I may not be > > able to take the slices-this I need. I thought to give re.findall a try > > but that is not giving me the slices. Slice spreads here. The power issue > > of string! I would definitely give it a try. Happy Day Ahead Regards, > > Subhabrata Banerjee. > > Then use re.finditer(): > > start = 0 > for match in re.finditer(r"\$", data): > end = match.start() > print(start, end) > print(data[start:end]) > start = match.end() > > This will omit the last text. The simplest fix is to put another "$" > separator at the end of your data. From gandalf at shopzeus.com Thu Jul 5 10:34:22 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 05 Jul 2012 16:34:22 +0200 Subject: 2 + 2 = 5 In-Reply-To: <7x7guj2u8a.fsf@ruckus.brouhaha.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <4FF5A5EE.9050308@shopzeus.com> On 2012-07-04 21:37, Paul Rubin wrote: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) > > Heh. The author is apparently anonymous, I guess for good reason. >>> five.contents[five.contents[:].index(5)] = 4 >>> 5 4 >>> 5 is 4 True But this I don't understand: >>> 5+0 4 >>> 5+1 4 >>> 5+2 6 From hansmu at xs4all.nl Thu Jul 5 10:43:44 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 05 Jul 2012 16:43:44 +0200 Subject: Creating an instance when the argument is already an instance. In-Reply-To: References: <20120705122924.481a546b@bigfoot.com> Message-ID: <4ff5a820$0$6982$e4fe514c@news2.news.xs4all.nl> On 5/07/12 12:47:52, Chris Angelico wrote: > On Thu, Jul 5, 2012 at 8:29 PM, Olive wrote: >> I am creating a new class: package (to analyse the packages database in >> some linux distros). I have created a class package such that >> package("string") give me an instance of package if string is a correct >> representation of a package. I would like that if pack is already an >> instance of package then package(pack) just return pack. > > One way would be to make the name "package" actually a wrapper > function, not the class itself: > >>>> class _package: > def __init__(self,arg): > # blah blah > self.asdf=arg > >>>> def package(arg): > if isinstance(arg,_package): return arg > return _package(arg) > >>>> a=package("Test") >>>> b=package(a) >>>> a is b > True > > The leading underscore is a common convention meaning "private > implementation detail". I think using a factory function is the right idea, but the code above doesn't solve the problem as stated. Olive needs a factory function that takes a string argument and returns a _package object. Maybe: class _package: def __init__(self, name): self.name = name # etc. packages = dict() def package(name): if name not in packages: packages[name] = _package(name) return packages[name] Hope this helps, -- HansM From mshroyer at awaredigital.com Thu Jul 5 10:47:02 2012 From: mshroyer at awaredigital.com (Mark Shroyer) Date: Thu, 5 Jul 2012 10:47:02 -0400 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: References: Message-ID: <20120705144702.GA4385@mshroyer-d> On Thu, Jul 05, 2012 at 03:22:01AM -0400, Maurizio Spadaccino wrote: > Hi all > > I'm new to Python but soon after a few days of studying its features I > find it my favourite mean of programming scripts to allow for data > storing and mining. My idea would be to inplement python scripts from > inside an excel sheet that would store and fetch data from a Mysql > database. So i need the script to be launched, say, by pressing a > button in excel and, for instance, retrieve immediately data from the > mysql table. For what I found in the net, it seems there are three > ways to control python from excel: 1) run my python script via shell > using the Run command in VBA, which seems to me the easiest (but maybe > slower?) way; 2) creating a COM server, for which I need more training > since it doesnt appear that easy; 3) via Microsoft Script Control, for > which I saw some example around where It looks like I can 'simulate' a > python shell via the 'executeStatement' command. > > What would you suggest would be the more performing way to achieve my > goals as described above? One thing you could check out is IronSpread: http://www.ironspread.com/ (Despite the name, it's based on CPython rather than IronPython.) It presents a simplified interface for communicating with Excel compared to what you get with win32com / plain OLE automation. I'm a little hazy on whether the Python scripts created with this plugin are saved within the Excel file or somewhere on the local system, though... From steve+comp.lang.python at pearwood.info Thu Jul 5 11:19:35 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Jul 2012 15:19:35 GMT Subject: simpler increment of time values? References: Message-ID: <4ff5b086$0$29988$c3e8da3$5496439d@news.astraweb.com> On Thu, 05 Jul 2012 23:56:37 +1000, Chris Angelico wrote: > (The "magic number" 86400 is a well-known number, being seconds in a > day. Does that include leap seconds? > Feel free to replace it with 24*60*60 if it makes you feel better; > I'm pretty sure Python will translate it into a constant at parse time. > Or alternatively, have a module-level constant SECONDS_IN_A_DAY = 86400, > in case that number should ever change.) "In case"? The number of seconds in a day (true solar day) varies by between 13 and 30 seconds depending on the time of the year and the position of the sun. The mean solar day fluctuates randomly by about 5ms due to friction between the core and the mantle; it is also systematically slowing due to tidal friction. The 2004 Indian Ocean earthquake reduced the length of a day by about 3ms; the 2011 Japan earthquake slowed it down by about 2ms. Apart from these random changes, there are systematic changes of the order of 1ms per year, so in a mere thousand years, the length of the mean solar day will be about a second longer. Imagine how much extra work we'll be able to get done! The stellar day (Earth's rotational period relative to the distant stars) is slightly more than 86164.098 seconds; the sidereal day is slightly more than 86164.090 seconds. Both are approximately 3 minutes 56 seconds shorter than the mean solar day. -- Steven From alec.taylor6 at gmail.com Thu Jul 5 11:19:41 2012 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Fri, 6 Jul 2012 01:19:41 +1000 Subject: OAuth 2.0 implementation In-Reply-To: <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> Message-ID: On Fri, Jul 6, 2012 at 12:06 AM, Demian Brecht wrote: > FWIW, this package has undergone a major overhaul (474 LOC down to much happier 66) and is available at https://github.com/demianbrecht/sanction. Also available from PyPI. Thanks for this, I've now shared it on my favourite web-framework (which unfortunately recommends Janrain) as an alternative: https://groups.google.com/forum/#!topic/web2py/XjUEewfP5Xg From python at mrabarnett.plus.com Thu Jul 5 11:20:25 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 05 Jul 2012 16:20:25 +0100 Subject: 2 + 2 = 5 In-Reply-To: <4FF5A5EE.9050308@shopzeus.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4FF5A5EE.9050308@shopzeus.com> Message-ID: <4FF5B0B9.9080407@mrabarnett.plus.com> On 05/07/2012 15:34, Laszlo Nagy wrote: > On 2012-07-04 21:37, Paul Rubin wrote: >> I just came across this (https://gist.github.com/1208215): >> >> import sys >> import ctypes >> pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) >> five = ctypes.cast(id(5), pyint_p) >> print(2 + 2 == 5) # False >> five.contents[five.contents[:].index(5)] = 4 >> print(2 + 2 == 5) # True (must be sufficiently large values of 2 there...) >> >> Heh. The author is apparently anonymous, I guess for good reason. > > >>> five.contents[five.contents[:].index(5)] = 4 > >>> 5 > 4 > >>> 5 is 4 > True > > But this I don't understand: > > >>> 5+0 > 4 5 is interned as 4, 0 is interned as 0, 4+0 is calculated as 4 and then interned as 4. > >>> 5+1 > 4 5 is interned as 4, 1 is interned as 1, 4+1 is calculated as 5 and then interned as 4. > >>> 5+2 > 6 > 5 is interned as 4, 2 is interned as 2, 4+2 is calculated as 6 and then interned and 6. Simple really! :-) From jeanpierreda at gmail.com Thu Jul 5 11:21:14 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 5 Jul 2012 11:21:14 -0400 Subject: 2 + 2 = 5 In-Reply-To: <4FF5A5EE.9050308@shopzeus.com> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4FF5A5EE.9050308@shopzeus.com> Message-ID: On Thu, Jul 5, 2012 at 10:34 AM, Laszlo Nagy wrote: >>>> 5+1 > 4 4 + 1 is 5 is 4. (e.g. try 2+3 as well). -- Devin From kelebrinir at gmail.com Thu Jul 5 11:36:46 2012 From: kelebrinir at gmail.com (Roman Putilov) Date: Thu, 5 Jul 2012 21:36:46 +0600 Subject: Help: PYMALLOC_DBUG and PIL In-Reply-To: References: Message-ID: 2012/7/5 tom z > Hi~ all, > I encounter a odd problem, when i compile Python with PYMALLOC_DEBUG, the > PIL module can't work fine, it always make core-dump like this > > [Switching to Thread 182897301792 (LWP 16102)] > 0x00000000004df264 in PyObject_Malloc (nbytes=64) at Objects/obmalloc.c:804 > 804 if ((pool->freeblock = *(block **)bp) != NULL) { > Current language: auto; currently c > (gdb) bt > #0 0x00000000004df264 in PyObject_Malloc (nbytes=64) at > Objects/obmalloc.c:804 > #1 0x00000000004dfb97 in _PyObject_DebugMallocApi (id=109 'm', nbytes=32) > at Objects/obmalloc.c:1461 > #2 0x00000000004dfd22 in _PyObject_DebugReallocApi (api=109 'm', p=0x0, > nbytes=32) at Objects/obmalloc.c:1523 > #3 0x00000000004dfac0 in _PyMem_DebugRealloc (p=0x0, nbytes=32) at > Objects/obmalloc.c:1416 > #4 0x00000000004c68d9 in list_resize (self=0x2a988409b8, newsize=1) at > Objects/listobject.c:62 > #5 0x00000000004c6f63 in app1 (self=0x2a988409b8, v=0x2a958cea90) at > Objects/listobject.c:277 > #6 0x00000000004c6fdd in PyList_Append (op=0x2a988409b8, > newitem=0x2a958cea90) at Objects/listobject.c:289 > #7 0x0000000000558c7f in symtable_add_def (st=0x2a99a4ca68, > name=0x2a958cea90, flag=4) at Python/symtable.c:910 > #8 0x000000000055a953 in symtable_visit_params (st=0x2a99a4ca68, > args=0x924380, toplevel=1) at Python/symtable.c:1318 > #9 0x000000000055aaa7 in symtable_visit_arguments (st=0x2a99a4ca68, > a=0x9243c8) at Python/symtable.c:1365 > #10 0x0000000000558f3d in symtable_visit_stmt (st=0x2a99a4ca68, > s=0x9244d0) at Python/symtable.c:1012 > #11 0x000000000055919e in symtable_visit_stmt (st=0x2a99a4ca68, > s=0x924500) at Python/symtable.c:1029 > #12 0x00000000005574d7 in PySymtable_Build (mod=0x931798, > filename=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", > future=0x2a9883aae0) at Python/symtable.c:240 > #13 0x0000000000531f14 in PyAST_Compile (mod=0x931798, > filename=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", flags=0x7fbfff9020, > arena=0x8eedd0) at Python/compile.c:282 > #14 0x0000000000545967 in parse_source_module ( > pathname=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at > Python/import.c:843 > #15 0x0000000000545e75 in load_source_module (name=0x7fbfffb3e0 > "PIL.BmpImagePlugin", > pathname=0x7fbfffa2c0 > "../lib/python2.7/site-packages/PIL/BmpImagePlugin.py", fp=0x91a060) at > Python/import.c:1027 > > i've no idea about this, someone could get me help~ > > --- > thanks a lot > > -- > http://mail.python.org/mailman/listinfo/python-list > > PYMALLOC_DEBUG requires WITH_PYMALLOC. It's enabled? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrickjohnson at gmail.com Thu Jul 5 11:39:03 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Thu, 5 Jul 2012 08:39:03 -0700 (PDT) Subject: simpler increment of time values? References: <4ff5b086$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 5, 10:19?am, Steven D'Aprano wrote: > The number of seconds in a day (true solar day) varies by between 13 and > 30 seconds depending on the time of the year and the position of the sun. Indeed. Which proves that a time keeping system based on the haphazard movements of celestial bodies is antiquated technology. Talk about job security! From rosuav at gmail.com Thu Jul 5 11:53:19 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 6 Jul 2012 01:53:19 +1000 Subject: simpler increment of time values? In-Reply-To: <4ff5b086$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <4ff5b086$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Jul 6, 2012 at 1:19 AM, Steven D'Aprano wrote: > On Thu, 05 Jul 2012 23:56:37 +1000, Chris Angelico wrote: > >> (The "magic number" 86400 is a well-known number, being seconds in a >> day. > > Does that include leap seconds? No it doesn't, hence... >> Feel free to replace it with 24*60*60 if it makes you feel better; >> I'm pretty sure Python will translate it into a constant at parse time. >> Or alternatively, have a module-level constant SECONDS_IN_A_DAY = 86400, >> in case that number should ever change.) > > "In case"? ... this not being entirely tongue-in-cheek. I believe the UTC spec allows for a progressive increase in the number of leap seconds, from the current "maybe one a year" at either Dec or June to having them multiple months a year, to having a leap second optionally every day, to having one a day and multiple leap seconds on some days. But it's not until we're actually in that last state (or close to it) that I would consider changing SECONDS_IN_A_DAY to 86401. Leap seconds are largely outside the concept of "dateless time". > The number of seconds in a day (true solar day) varies ... > it is also systematically slowing due to tidal friction. > ... in a mere thousand years, the length of the > mean solar day will be about a second longer. Yes. It's rather more likely to be an issue than, say, "PI = 3.14159" needing to change, but you do still have to consider what your definition of time is. If you're actually counting real time-since-epoch, then you need to either include leap seconds in your count (like TAI does) or ignore them (like Unix time does - divide Unix time by 86400 and you get the number of days since 1970, but a second's worth of Unix times "happen twice" when a positive leap second occurs). However, I think it would only surprise people if: 23:30 + 03:45 = 03:14:59 and they'd think it was an easter egg for displaying one of a geek's favorite numbers. > Imagine how much extra work we'll be able to get done! Oh, I reckon most people will waste it on sleep... ChrisA From rosuav at gmail.com Thu Jul 5 11:59:19 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 6 Jul 2012 01:59:19 +1000 Subject: simpler increment of time values? In-Reply-To: References: <4ff5b086$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Jul 6, 2012 at 1:39 AM, Rick Johnson wrote: > On Jul 5, 10:19 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> The number of seconds in a day (true solar day) varies by between 13 and >> 30 seconds depending on the time of the year and the position of the sun. > > Indeed. Which proves that a time keeping system based on the haphazard > movements of celestial bodies is antiquated technology. Talk about job > security! The current *time keeping system* is based atomic clocks. It's only when you want to display this thing called "civil time" (so-called because it causes very uncivil arguments) that you concern yourself with astronomy, base 60, base 24, and other constructs. Now, if you want to argue about a poor choice of standard, look at so-called "Internet Time" that a Swiss watch company invented, which divides a day into 1000 beats. Why use the day as your basis and make it hard to convert to SI units reliably? ChrisA From nobody at nowhere.com Thu Jul 5 12:11:32 2012 From: nobody at nowhere.com (Nobody) Date: Thu, 05 Jul 2012 17:11:32 +0100 Subject: how to interact with Windows cmd? References: <5c91bf76-36de-4759-938a-92a9e801e38e@g4g2000pbn.googlegroups.com> Message-ID: On Wed, 04 Jul 2012 20:10:47 -0700, self.python wrote: > 2. after this, I typed like "cd .." but I/O is already closed so I > can't do another things.. Don't use .communicate() if you want to keep the child process alive. Write to p.stdin and read p.stdout and p.stderr. In general, you'll need to use a separate thread for each stream, otherwise you risk deadlock. Look at the source code for the .communicate() method for an example. Also, unless you specifically need stdout and stderr to be separated, use "stderr=subprocess.STDOUT". The problem with separating them is that there's no way to determine the order in which data was written, so there's no way to reconstruct the output as it would have appeared on the console. From steve+comp.lang.python at pearwood.info Thu Jul 5 12:16:17 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Jul 2012 16:16:17 GMT Subject: 2 + 2 = 5 References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff52700$0$30000$c3e8da3$5496439d@news.astraweb.com> <4ff59d61$0$6880$e4fe514c@news2.news.xs4all.nl> Message-ID: <4ff5bdd1$0$29988$c3e8da3$5496439d@news.astraweb.com> On Thu, 05 Jul 2012 15:57:53 +0200, Hans Mulder wrote: > On 5/07/12 07:32:48, Steven D'Aprano wrote: >> On Wed, 04 Jul 2012 23:38:17 -0400, Terry Reedy wrote: >> >>> If I run the script in 3.3 Idle, I get the same output you got. If I >>> then enter '5-2' interactively, I still get 3. Maybe the constant >>> folder is always on now. >> >> Yes, I believe constant folding is always on, since Python 2.4 if I >> remember correctly. Somebody who cares more than me can possibly check >> the "What's New" documents :) > > It's not a difference between 2.4 and 3.3; the difference is between > Idle and the command-line version of the interactive interpreter. > > If I type the same code into Idle and the interactive interpreter (both > using 3.3alpha1), I get 3 in Idle and 2 in Terminal. > > I don't quite understand why this difference exists. This difference exists because you are mucking about with implementation details of Python, changing things which are not guaranteed by the language, in ways that you are not supposed to change them. Since changing the value of the int 2 into that of 3 is not supported, you can hardly expect consistent behaviour. You're lucky that you don't get a segfault. (In fact, if you keep playing around with it, you likely will get a segfault.) Idle does many things differently to the basic Python interpreter. This should not surprise you. You should be surprised if it *does* work the same in Idle and the basic Python interpreter. -- Steven From news at blinne.net Thu Jul 5 13:03:57 2012 From: news at blinne.net (Alexander Blinne) Date: Thu, 05 Jul 2012 19:03:57 +0200 Subject: 2 + 2 = 5 In-Reply-To: References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> On 05.07.2012 16:34, Laszlo Nagy wrote: >>>> five.contents[five.contents[:].index(5)] = 4 >>>> 5 > 4 >>>> 5 is 4 > True That's surprising, because even after changing 5 to 4 both objects still have different id()s (tested on Py2.7), so 5 is 4 /should/ still be False (But isn't on my 2.7). But that's some implementation detail we are not supposed to play with ;) > But this I don't understand: > >>>> 5+0 > 4 >>>> 5+1 > 4 >>>> 5+2 > 6 That's easy: 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4. 5+1 is actually 4+1, which is 5, but 5 is again 4. 5+2 is 4+2 which is 6. Greetings From ian.g.kelly at gmail.com Thu Jul 5 13:06:41 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 5 Jul 2012 11:06:41 -0600 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Thu, Jul 5, 2012 at 7:56 AM, Chris Angelico wrote: > I'm not familiar with the Python classes (I tend to think in terms of > language-agnostic algorithms first, and specific libraries/modules/etc > second), but if you're working with simple integer seconds, your > datelessness is just modulo arithmetic. > > time1 + time2 --> (time1 + time2) % 86400 > time1 - time2 --> (time1 + 86400 - time2) % 86400 The "+ 86400" is redundant; you'll get the same answer with or without it. There is nothing to fear from going negative when doing modulo arithmetic, because unlike C, Python actually has well-defined semantics regarding modulo division of negative numbers. >>> (13382 + 86400 - 42597) % 86400 57185 >>> (13382 - 42597) % 86400 57185 Cheers, Ian From rosuav at gmail.com Thu Jul 5 13:16:16 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 6 Jul 2012 03:16:16 +1000 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On Fri, Jul 6, 2012 at 3:06 AM, Ian Kelly wrote: > The "+ 86400" is redundant; you'll get the same answer with or without > it. There is nothing to fear from going negative when doing modulo > arithmetic, because unlike C, Python actually has well-defined > semantics regarding modulo division of negative numbers. > >>>> (13382 + 86400 - 42597) % 86400 > 57185 >>>> (13382 - 42597) % 86400 > 57185 Ah good. There's a lot of languages like that these days, but I've gotten so into the habit of not depending on it that I just automatically add N first. It's redundant but insignificant. So it's even easier than I said. And bonus lesson for the day: Try things in the interactive interpreter before you post. :) ChrisA From nagle at animats.com Thu Jul 5 13:34:16 2012 From: nagle at animats.com (John Nagle) Date: Thu, 05 Jul 2012 10:34:16 -0700 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: On 7/4/2012 5:29 PM, Vlastimil Brom wrote: > Hi all, > I'd like to ask about the possibilities to do some basic manipulation > on timestamps - such as incrementing a given time (hour.minute - > string) by some minutes. > Very basic notion of "time" is assumed, i.e. dateless, > timezone-unaware, DST-less etc. > I first thought, it would be possible to just add a timedelta to a > time object, but, it doesn't seem to be the case. That's correct. A datetime.time object is a time within a day. A datetime.date object is a date without a time. A datetime.datetime object contains both. You can add a datetime.timedelta object to a datetime.datetime object, which will yield a datetime.datetime object. You can also call time.time(), and get the number of seconds since the epoch (usually 1970-01-01 00:00:00 UTC). That's just a number, and you can do arithmetic on that. Adding a datetime.time to a datetime.timedelta isn't that useful. It would have to return a value error if the result crossed a day boundary. John Nagle From dieter at handshake.de Thu Jul 5 13:47:53 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 05 Jul 2012 19:47:53 +0200 Subject: Question about weakref References: <87hatmr3xf.fsf@handshake.de> Message-ID: <87a9ze85h2.fsf@handshake.de> Frank Millman writes: > On 05/07/2012 10:46, Dieter Maurer wrote: >> Instead of the low level "weakref", you might use a "WeakKeyDictionary". >> > > Thanks, Dieter. I could do that. > > In fact, a WeakSet suits my purposes better. I tested it with my > original example, and it works correctly. It also saves me the step of > deleting the weak reference once the original object is deleted, as it > seems to do that automatically. > > I just need to double-check that I would never have the same > listener-object try to register itself with the publisher twice, as > that would obviously fail with a Set, as it would with a Dict. No need to verify. A secondary subscription would be effectively a no-operation -- with both a "set" and a "dict". > I would still like to know why weakref.proxy raised an exception. I > have re-read the manual several times, and googled for similar > problems, but am none the wiser. In fact, it is documented. Accessing a proxy will raise an exception when the proxied object no longer exists. What you can ask is why your proxy has been accessed after the object was deleted. The documentation is specific: during the callback, the object should still exist. Thus, apparently, one of your proxies outlived an event that should have deleted it (probably a hole in your logic). From demianbrecht at gmail.com Thu Jul 5 13:48:34 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Thu, 5 Jul 2012 10:48:34 -0700 (PDT) Subject: OAuth 2.0 implementation In-Reply-To: References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> Message-ID: <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> On Thursday, 5 July 2012 08:19:41 UTC-7, Alec Taylor wrote: > On Fri, Jul 6, 2012 at 12:06 AM, Demian Brecht wrote: > > FWIW, this package has undergone a major overhaul (474 LOC down to much happier 66) and is available at https://github.com/demianbrecht/sanction. Also available from PyPI. > > Thanks for this, I've now shared it on my favourite web-framework > (which unfortunately recommends Janrain) as an alternative: > https://groups.google.com/forum/#!topic/web2py/XjUEewfP5Xg No worries, thanks for the interest :) From demianbrecht at gmail.com Thu Jul 5 13:48:34 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Thu, 5 Jul 2012 10:48:34 -0700 (PDT) Subject: OAuth 2.0 implementation In-Reply-To: References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> Message-ID: <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> On Thursday, 5 July 2012 08:19:41 UTC-7, Alec Taylor wrote: > On Fri, Jul 6, 2012 at 12:06 AM, Demian Brecht wrote: > > FWIW, this package has undergone a major overhaul (474 LOC down to much happier 66) and is available at https://github.com/demianbrecht/sanction. Also available from PyPI. > > Thanks for this, I've now shared it on my favourite web-framework > (which unfortunately recommends Janrain) as an alternative: > https://groups.google.com/forum/#!topic/web2py/XjUEewfP5Xg No worries, thanks for the interest :) From rurpy at yahoo.com Thu Jul 5 14:15:04 2012 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 5 Jul 2012 11:15:04 -0700 (PDT) Subject: simpler increment of time values? In-Reply-To: References: Message-ID: <10c08425-e66d-4abc-958e-d36ccd216847@googlegroups.com> On Thursday, July 5, 2012 11:34:16 AM UTC-6, John Nagle wrote: >[...] > You can also call time.time(), and get the number of seconds > since the epoch (usually 1970-01-01 00:00:00 UTC). That's just > a number, and you can do arithmetic on that. > > Adding a datetime.time to a datetime.timedelta isn't that > useful. It certainly is useful and I gave an obvious and real- world example in my previous post. > It would have to return a value error if the result > crossed a day boundary. Why? When I turn the adjustment knob on my analog clock it crosses the day boundary from 23:59 to 0:00 with no problem whatsoever. Why is Python unable to do what billions of clocks do? Instead I have to convert everything to seconds and do the same math I would have done in fortran in 1980. Phew. Another example of Pythonic "purity beats practicality" From hansmu at xs4all.nl Thu Jul 5 14:40:54 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 05 Jul 2012 20:40:54 +0200 Subject: 2 + 2 = 5 In-Reply-To: <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4ff5dfb7$0$6880$e4fe514c@news2.news.xs4all.nl> On 5/07/12 19:03:57, Alexander Blinne wrote: > On 05.07.2012 16:34, Laszlo Nagy wrote: >>>>> five.contents[five.contents[:].index(5)] = 4 >>>>> 5 >> 4 >>>>> 5 is 4 >> True > That's surprising, because even after changing 5 to 4 both objects still > have different id()s (tested on Py2.7), so 5 is 4 /should/ still be > False (But isn't on my 2.7). But that's some implementation detail we > are not supposed to play with ;) On my 2.7, id(5) gives the same value as id(4) == id(2+2), but id(2+3) has a different value. The 'is' operator is consistent with 'id': >>> 4 is 5 True >>> 2+2 is 2+3 False This is when using the interactive interpreter; it may be different in Idle. -- HansM From tjreedy at udel.edu Thu Jul 5 17:20:20 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 05 Jul 2012 17:20:20 -0400 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <4FF55A85.2040002@jollybox.de> References: <4FF541A9.1090806@gmail.com> <4FF55A85.2040002@jollybox.de> Message-ID: On 7/5/2012 5:12 AM, Thomas Jollans wrote: > On 07/05/2012 09:26 AM, Karim wrote: >> Look at PyUNO from OpenOffice very large API: >> http://www.openoffice.org/api/docs >> >> I use to create all my documention (Excell, Writer, etc...) on this API. > > Note that this API is for OpenOffice, not Microsoft Excel. However, as > you probably know, you can open most Excel files in OpenOffice's Calc. > > I urge you to consider LibreOffice, a fork of OpenOffice that is now > broadly considered its successor. Its API can also be used in Python > http://api.libreoffice.org/ Can you explain or point to a document that explains how to actually do that? (use the LibreOffice api from Python?) The only mention of Python on that page is under examples. (and there is no mention of python in the installation guide, even as an option, nor in the development tools doc, ). On the example page, there is only one example and unlike all the other sections, no 'Additional information' linking to a 'Python Language binding'. In toolpanel.py of the example, there is import uno import unohelper from com.sun.star.ui import XUIElementFactory from com.sun.star.ui import XUIElement from com.sun.star.ui.UIElementType import TOOLPANEL as unoTOOLPANEL from com.sun.star.ui import XToolPanel but where are the python-importable modules and com package and their docs and how does one get them? There are not in the example directory. The IDL reference only covers the com.sun.star stuff. --- Looking with Google, I see that some linux distros include LibreOffice-PyUno in thier package managers. Not helpful for Windows. The LibreOffice installation includes a python2.6.1 installation under LO.../program/ with pyuno pre-installed. No doc that I could see. However, when running it >>> import com.sun.star.ui Traceback (most recent call last): File "", line 1, in ImportError: No module named com.sun.star.ui Oh, there is a trick to it >>> import uno >>> import unohelper >>> import com.sun.star.ui Traceback (most recent call last): File "", line 1, in File "uno.py", line 263, in _uno_import return _g_delegatee( name, *optargs, **kwargs ) ImportError: No module named com.sun.star.ui >>> from com.sun.star.ui import XToolPanel So import uno and unohelper and one can import objects from the non-existent com.sun.star.ui module. Still, a lot more is needed to understand even the example. -- Terry Jan Reedy From driscoll at cs.wisc.edu Thu Jul 5 17:46:48 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Thu, 05 Jul 2012 16:46:48 -0500 Subject: 2 + 2 = 5 In-Reply-To: <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4FF60B48.7000607@cs.wisc.edu> On 01/-10/-28163 01:59 PM, Alexander Blinne wrote: > 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4. > 5+1 is actually 4+1, which is 5, but 5 is again 4. > 5+2 is 4+2 which is 6. Now all I can think is "Hoory for new math, new-hoo-hoo math" :-) Evan From rhodri at wildebst.demon.co.uk Thu Jul 5 18:23:08 2012 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 05 Jul 2012 23:23:08 +0100 Subject: 2 + 2 = 5 References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 04 Jul 2012 20:37:25 +0100, Paul Rubin wrote: > I just came across this (https://gist.github.com/1208215): > > import sys > import ctypes > pyint_p = ctypes.POINTER(ctypes.c_byte*sys.getsizeof(5)) > five = ctypes.cast(id(5), pyint_p) > print(2 + 2 == 5) # False > five.contents[five.contents[:].index(5)] = 4 > print(2 + 2 == 5) # True (must be sufficiently large values of 2 > there...) > > Heh. The author is apparently anonymous, I guess for good reason. Someone's been writing FORTRAN again :-) -- Rhodri James *-* Wildebeest Herder to the Masses From amc96 at cam.ac.uk Thu Jul 5 18:39:58 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Thu, 05 Jul 2012 23:39:58 +0100 Subject: 2 + 2 = 5 In-Reply-To: References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <%IoJr.487993$ra1.293468@fx05.am4> On 05/07/2012 22:46, Evan Driscoll wrote: > On 01/-10/-28163 01:59 PM, Alexander Blinne wrote: >> 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4. >> 5+1 is actually 4+1, which is 5, but 5 is again 4. >> 5+2 is 4+2 which is 6. > > Now all I can think is "Hoory for new math, new-hoo-hoo math" :-) > > Evan It wont do you a bit of good to read new math! (My mind was on exactly the same track) ~Andrew From gdamjan at gmail.com Thu Jul 5 18:55:48 2012 From: gdamjan at gmail.com (Damjan) Date: Fri, 06 Jul 2012 00:55:48 +0200 Subject: Confusing datetime.datetime In-Reply-To: References: Message-ID: On 05.07.2012 16:10, Damjan wrote: > I've been struggling with an app that uses > Postgresql/Psycopg2/SQLAlchemy and I've come to this confusing > behaviour of datetime.datetime. Also this: #! /usr/bin/python2 # retardations in python's datetime import pytz TZ = pytz.timezone('Europe/Skopje') from datetime import datetime x1 = datetime.now(tz=TZ) x2 = datetime(x1.year, x1.month, x1.day, tzinfo=TZ) assert x1.tzinfo == x2.tzinfo WHY does the assert throw an error??? From steve+comp.lang.python at pearwood.info Thu Jul 5 21:28:56 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Jul 2012 01:28:56 GMT Subject: Confusing datetime.datetime References: Message-ID: <4ff63f58$0$29988$c3e8da3$5496439d@news.astraweb.com> On Fri, 06 Jul 2012 00:55:48 +0200, Damjan wrote: > Also this: > > #! /usr/bin/python2 > # retardations in python's datetime > > import pytz > TZ = pytz.timezone('Europe/Skopje') > > from datetime import datetime > > x1 = datetime.now(tz=TZ) > x2 = datetime(x1.year, x1.month, x1.day, tzinfo=TZ) > > assert x1.tzinfo == x2.tzinfo > > > WHY does the assert throw an error??? I don't have pytz, so I can't test your exact code. But using my own time zone class, it seems to work fine in Python 2.5, 2.6 and 2.7: from datetime import datetime, timedelta, tzinfo ZERO = timedelta(0) HOUR = timedelta(hours=1) class UTC(tzinfo): def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO utc = UTC() t1 = datetime.now(tz=utc) t2 = datetime(t1.year, t1.month, t1.day, tzinfo=utc) assert t1.tzinfo == t2.tzinfo No assertion error at all. This makes me think that the "retardation" as you put it is not in Python's datetime module at all, but in pytz. What does TZ == TZ give? If it returns False, I recommend you report it as a bug against the pytz module. -- Steven From steve+comp.lang.python at pearwood.info Thu Jul 5 21:29:42 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Jul 2012 01:29:42 GMT Subject: 2 + 2 = 5 References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4ff63f85$0$29988$c3e8da3$5496439d@news.astraweb.com> On Thu, 05 Jul 2012 16:46:48 -0500, Evan Driscoll wrote: > On 01/-10/-28163 01:59 PM, Alexander Blinne wrote: >> 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4. 5+1 is actually >> 4+1, which is 5, but 5 is again 4. 5+2 is 4+2 which is 6. > > Now all I can think is "Hoory for new math, new-hoo-hoo math" :-) +1 QOTW -- Steven From gdamjan at gmail.com Thu Jul 5 22:05:38 2012 From: gdamjan at gmail.com (Damjan) Date: Fri, 06 Jul 2012 04:05:38 +0200 Subject: Confusing datetime.datetime In-Reply-To: <4ff63f58$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <4ff63f58$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: > from datetime import datetime, timedelta, tzinfo > ZERO = timedelta(0) > HOUR = timedelta(hours=1) > > class UTC(tzinfo): > def utcoffset(self, dt): > return ZERO > def tzname(self, dt): > return "UTC" > def dst(self, dt): > return ZERO > > utc = UTC() > t1 = datetime.now(tz=utc) > t2 = datetime(t1.year, t1.month, t1.day, tzinfo=utc) > assert t1.tzinfo == t2.tzinfo > > > No assertion error at all. > > This makes me think that the "retardation" as you put it is not in > Python's datetime module at all, but in pytz. > > What does TZ == TZ give? If it returns False, I recommend you report it > as a bug against the pytz module. It returns True, so it seems to be changed in the datetime object?? I tried both 2.7 and 3.2 -- damjan From research at johnohagan.com Thu Jul 5 22:06:35 2012 From: research at johnohagan.com (John O'Hagan) Date: Fri, 6 Jul 2012 12:06:35 +1000 Subject: Apology for OT posts (was: code review) In-Reply-To: <4FF3D708.6090405@tysdomain.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> <4FF3D708.6090405@tysdomain.com> Message-ID: <20120706120635.7d2f27547d8056a066dc9342@johnohagan.com> On Tue, 03 Jul 2012 23:39:20 -0600 "Littlefield, Tyler" wrote: > On 7/3/2012 10:55 PM, Simon Cropper wrote: > > Some questions to Tyler Littlefield, who started this thread. > > > > Q1 -- Did you get any constructive feedback on your code? > > I did get some, which I appreciated. someone mentioned using PyLint. > From reading, I found it was really really pedantic, so I used PyFlakes > instead. > > > > Q2 -- Did you feel that the process of submitting your code for review > > met your expectation? > > There wasn't much more to review, so yes. The info I got was helpful and > farther than it was before I started. > > > Q3 -- Would you recommend others doing this either on this forum or > > other fora? > > > > It appears to me - third party watching the ongoing dialog - that the > > tread has gone right off topic (some time ago) and someone should > > really start a new thread under a new title/subject. Most of what I > > have read does not appear to be discussing your code or how you could > > improve your code. > > > I basically just stopped after a while. It got into a my language is > better than your language, so I didn't see much constructive info. I've > started reading from the bottom though, where it looks like it's back, > and I do appreciate the rest of the info given, as well. Thanks again > for the feedback. > As one of the perpetrators, I did apologise for being OT within the body of my replies to OT posts, but I see the irony. I guess I just thought somebody else would do it eventually. I hereby apologise for not taking the correct action, and vow to do so in future: to change the subject line regardless of who initially went OT, starting now. Regards, -- John From kliateni at gmail.com Thu Jul 5 22:30:48 2012 From: kliateni at gmail.com (Karim) Date: Fri, 06 Jul 2012 04:30:48 +0200 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: References: <4FF541A9.1090806@gmail.com> <4FF55A85.2040002@jollybox.de> Message-ID: <4FF64DD8.8030007@gmail.com> Le 05/07/2012 23:20, Terry Reedy a ?crit : > On 7/5/2012 5:12 AM, Thomas Jollans wrote: >> On 07/05/2012 09:26 AM, Karim wrote: >>> Look at PyUNO from OpenOffice very large API: >>> http://www.openoffice.org/api/docs >>> >>> I use to create all my documention (Excell, Writer, etc...) on this >>> API. >> >> Note that this API is for OpenOffice, not Microsoft Excel. However, as >> you probably know, you can open most Excel files in OpenOffice's Calc. >> >> I urge you to consider LibreOffice, a fork of OpenOffice that is now >> broadly considered its successor. Its API can also be used in Python >> http://api.libreoffice.org/ > > Can you explain or point to a document that explains how to actually > do that? (use the LibreOffice api from Python?) > > The only mention of Python on that page is under examples. (and there > is no mention of python in the installation guide, even as an option, > nor in the development tools doc, ). > > On the example page, there is only one example and unlike all the > other sections, no 'Additional information' linking to a 'Python > Language binding'. > > In toolpanel.py of the example, there is > > import uno > import unohelper > > from com.sun.star.ui import XUIElementFactory > from com.sun.star.ui import XUIElement > from com.sun.star.ui.UIElementType import TOOLPANEL as unoTOOLPANEL > from com.sun.star.ui import XToolPanel > > but where are the python-importable modules and com package and their > docs and how does one get them? There are not in the example directory. > > The IDL reference only covers the com.sun.star stuff. > > --- > Looking with Google, I see that some linux distros include > LibreOffice-PyUno in thier package managers. Not helpful for Windows. > > The LibreOffice installation includes a python2.6.1 installation under > LO.../program/ with pyuno pre-installed. No doc that I could see. > However, when running it > > >>> import com.sun.star.ui > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named com.sun.star.ui > > Oh, there is a trick to it > >>> import uno > >>> import unohelper > >>> import com.sun.star.ui > Traceback (most recent call last): > File "", line 1, in > File "uno.py", line 263, in _uno_import > return _g_delegatee( name, *optargs, **kwargs ) > ImportError: No module named com.sun.star.ui > >>> from com.sun.star.ui import XToolPanel > > So import uno and unohelper and one can import objects from the > non-existent com.sun.star.ui module. Still, a lot more is needed to > understand even the example. > Hi Terry, You are right it was the warrior path at the beginning to be able to produce some code but it is working pretty well. I add to gather many pieces and examples. In fact, you should take the OOo Basic langage example (API) and convert it (sometimes for python some cases have been changed but mainly you have to use ones from original API namely OOo Basic language). They only did python wrapper around the native API. An excellent link to derived all code example to python: http://www.pitonyak.org/AndrewMacro.sxw. On latest ubuntu you get no error if you are importing: import uno import unohelper BUT IN OTHER ENVIRONMENT if the version of python is different from the one embedded inside OpenOffice (LibreOffice) namely 2.6.X You are obliged to recompile a OOo version with you python version. BUT there is a way to hack this. I did it, just do the following: LD_LIBRARY_PATH=:/usr/lib/openoffice.org/ure/lib:/usr/lib/openoffice.org/basis3.3/program PYTHONPATH=:/usr/lib/openoffice.org3/basis-link/program/ UNO_PATH=/usr/lib/openoffice.org/basis3.3/program URE_BOOTSTRAP=vnd.sun.star.pathname:/usr/lib/openoffice.org/basis3.3/program/fundamentalbasisrc Jut set these env variables according to your OOo installation and you will get no error by importing uno and unohelper. One article to begin with: http://www.linuxjournal.com/content/starting-stopping-and-connecting-openoffice-python And to finish basic code to get started and some functions I adapted from Andrew 's Macro book in python to search string and update a table inside writer document (work or MSW ord or SW format): Start up code ------------------------------------------------------------------------------------------------------- import uno import unohelper # 1. Get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # 2. Create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext ) # 3. Get the central desktop object smgr = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" ) # 4. Declare the ServiceManager remoteContext = smgr.getPropertyValue( "DefaultContext" ) # 5. Get the central desktop object desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext) """ !!! Document text creation !!! """ # open a writer document #doc = desktop.loadComponentFromURL('private:factory/swriter','_blank', 0, ()) #document = desktop.loadComponentFromURL("file:///c:"+filepath+".doc" ,"_blank", 0, (prop,)) prop = PropertyValue() prop.Name='Hidden' #prop.Value=True prop.Value=False #inProps = PropertyValue( "Hidden" , 0 , True, 0 ) doc = desktop.loadComponentFromURL('private:factory/swriter','_blank', 0, (prop,)) #doc = desktop.loadComponentFromURL('private:factory/swriter','_blank', 0, ()) text = doc.Text cursor = text.createTextCursor() text.insertString(cursor, 'The first line in the newly created text document.\n', 0) text.insertString(cursor, 'Now we are in the second line\n' , 0) ------------------------------------------------------------------------------- Functions example: def search_text(component=None, text=None): """ Generator function to seek for some text in a document. @param component the component where the text is seeked. @param text the text to be searched. @return the found occurence one at a time per generator call. """ # Creation of a descriptor from a document w/ search capabilities. descriptor = component.createSearchDescriptor() descriptor.SearchString = text descriptor.SearchWords = True descriptor.SearchCaseSensitive = False # Get the first match. found = component.findFirst(descriptor) while found: yield found found = component.findNext(found.End, descriptor) def search_replace_text(component=None, search=None, replace=None): """ Seek and replace text occurrence in a text component. @param component the component where the text is seeked. @param search the text to be searched. @param replace the text to be replaced. """ for found in search_text(component=doc, text=search): found.setString(replace) def insert_table_rows(table=None, rows=None, index=1): """ Insert multiple rows in a table object at . @param table the component where the text is seeked. @param rows the data array (tuples of tuples) . @param index the index position of the insertion. """" try: table.RepeatHeadline = True table.HeaderRowCount = 1 # Get the DataArray. data = list(table.DataArray) # Add to it the data rows. for element, i in enumerate(rows, index): data.insert(element, i) # Resize the table to prepare data adding. table_rows = table.Rows # Add #rows starting at the NumRows given by index position. table_rows.insertByIndex(table_rows.Count, len(rows)) Cheers Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Jul 5 22:34:25 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Jul 2012 02:34:25 GMT Subject: simpler increment of time values? References: <10c08425-e66d-4abc-958e-d36ccd216847@googlegroups.com> Message-ID: <4ff64eb1$0$29988$c3e8da3$5496439d@news.astraweb.com> On Thu, 05 Jul 2012 11:15:04 -0700, rurpy wrote: > On Thursday, July 5, 2012 11:34:16 AM UTC-6, John Nagle wrote: >>[...] >> You can also call time.time(), and get the number of seconds >> since the epoch (usually 1970-01-01 00:00:00 UTC). That's just a >> number, and you can do arithmetic on that. >> >> Adding a datetime.time to a datetime.timedelta isn't that >> useful. > > It certainly is useful and I gave an obvious and real- world example in > my previous post. Agreed. A timedelta of less than one day magnitude should be usable with time objects, and wrap around at midnight. That's a clear and useful extension to the current functionality. I can't see a feature request (rejected or otherwise) on the bug tracker. Perhaps you should raise one for Python 3.4. It will have a better chance of being accepted if you include a patch, or at least tests. http://bugs.python.org/ -- Steven From maillist.tom at gmail.com Thu Jul 5 22:50:56 2012 From: maillist.tom at gmail.com (tom z) Date: Fri, 6 Jul 2012 10:50:56 +0800 Subject: Help: PYMALLOC_DBUG and PIL Message-ID: Thanks Roman. of course, i use PYMALLOC_DEBUG with PYMALLOC. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Jul 6 01:09:19 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Jul 2012 01:09:19 -0400 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <4FF64DD8.8030007@gmail.com> References: <4FF541A9.1090806@gmail.com> <4FF55A85.2040002@jollybox.de> <4FF64DD8.8030007@gmail.com> Message-ID: <4FF672FF.5080101@udel.edu> On 7/5/2012 10:30 PM, Karim wrote: > An excellent link to derived all code example to python: > http://www.pitonyak.org/AndrewMacro.sxw. Even though he only writes in OOBasic, you are right that he explains the basic concepts needed for accessing the api from any language. He is also honest. Writing non-api code is relatively easy; accessing the OO/LO api is harder. I made a start. When I get further, I will look at the examples that are close to some things I want to do. I will also study your Python examples. Thanks for the help. Terry From brandon.harris at reelfx.com Fri Jul 6 01:22:44 2012 From: brandon.harris at reelfx.com (brandon harris) Date: Fri, 6 Jul 2012 05:22:44 +0000 Subject: tkFileDialogs Message-ID: <3CBB23A36B2BB04B9672F551A7EC1492197FDB1E@Exchange3.reelfx.com> I'm wanting to allow users to select hidden directories in windows and it seems that using the tkFileDialog.askdirectory() won't allow for that. It's using the tkFileDialog.Directory class which calls an internal command 'tk_chooseDirectory' . However the file selector dialogs (askopenfilename, asksaveasfilename, etc) has the common windows dialog which supports showing hidden folders. It's using the tkFileDialog.Open class which is calling an internal command of 'tk_getOpenFile'. Can anyone shed light on why these two dialogs are so very different and possibly give me a solution to this hidden directory issue. I have found that you can't really use the Open class because it's going to require a file be selected, not a directory and the Directory class won't navigate to or have an initialdir that is hidden (on windows the %APPDAT% folder is hidden by default) Windows Example Code. import tkFileDialog # Won't start in or allow navigation to APPDATA test = tkFileDialog.askdirectory(initialdir='%APPDATA%') # Will start in and navigate to APPDATA test = tkFileDialog.askopenfile(initialdir='%APPDATA%') Thanks in advance for any help given! Brandon L. Harris From simoncropper at fossworkflowguides.com Fri Jul 6 01:30:55 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 06 Jul 2012 15:30:55 +1000 Subject: Apology for OT posts In-Reply-To: <20120706120635.7d2f27547d8056a066dc9342@johnohagan.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> <4FF3D708.6090405@tysdomain.com> <20120706120635.7d2f27547d8056a066dc9342@johnohagan.com> Message-ID: <4FF6780F.5070100@fossworkflowguides.com> On 06/07/12 12:06, John O'Hagan wrote: > On Tue, 03 Jul 2012 23:39:20 -0600 > "Littlefield, Tyler" wrote: > >> On 7/3/2012 10:55 PM, Simon Cropper wrote: >>> Some questions to Tyler Littlefield, who started this thread. >>> >>> Q1 -- Did you get any constructive feedback on your code? >> >> I did get some, which I appreciated. someone mentioned using PyLint. >> From reading, I found it was really really pedantic, so I used PyFlakes >> instead. >>> >>> Q2 -- Did you feel that the process of submitting your code for review >>> met your expectation? >> >> There wasn't much more to review, so yes. The info I got was helpful and >> farther than it was before I started. >> >>> Q3 -- Would you recommend others doing this either on this forum or >>> other fora? >>> >>> It appears to me - third party watching the ongoing dialog - that the >>> tread has gone right off topic (some time ago) and someone should >>> really start a new thread under a new title/subject. Most of what I >>> have read does not appear to be discussing your code or how you could >>> improve your code. >>> >> I basically just stopped after a while. It got into a my language is >> better than your language, so I didn't see much constructive info. I've >> started reading from the bottom though, where it looks like it's back, >> and I do appreciate the rest of the info given, as well. Thanks again >> for the feedback. >> > > As one of the perpetrators, I did apologise for being OT within the body of my > replies to OT posts, but I see the irony. I guess I just thought somebody else > would do it eventually. I hereby apologise for not taking the correct action, > and vow to do so in future: to change the subject line regardless of who > initially went OT, starting now. > > Regards, > -- > John > thanks :) bet this kills the conservation though... Simon From kliateni at gmail.com Fri Jul 6 01:33:17 2012 From: kliateni at gmail.com (Karim) Date: Fri, 06 Jul 2012 07:33:17 +0200 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <4FF672FF.5080101@udel.edu> References: <4FF541A9.1090806@gmail.com> <4FF55A85.2040002@jollybox.de> <4FF64DD8.8030007@gmail.com> <4FF672FF.5080101@udel.edu> Message-ID: <4FF6789D.2040108@gmail.com> Le 06/07/2012 07:09, Terry Reedy a ?crit : > > On 7/5/2012 10:30 PM, Karim wrote: > >> An excellent link to derived all code example to python: >> http://www.pitonyak.org/AndrewMacro.sxw. > > Even though he only writes in OOBasic, you are right that he explains > the basic concepts needed for accessing the api from any language. He > is also honest. Writing non-api code is relatively easy; accessing the > OO/LO api is harder. I made a start. When I get further, I will look > at the examples that are close to some things I want to do. I will > also study your Python examples. Thanks for the help. > > Terry > > NP you are welcome to ask me any question. Cheers Karim From frank at chagford.com Fri Jul 6 03:00:49 2012 From: frank at chagford.com (Frank Millman) Date: Fri, 06 Jul 2012 09:00:49 +0200 Subject: Question about weakref In-Reply-To: <87a9ze85h2.fsf@handshake.de> References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> Message-ID: On 05/07/2012 19:47, Dieter Maurer wrote: > Frank Millman writes: > >> I would still like to know why weakref.proxy raised an exception. I >> have re-read the manual several times, and googled for similar >> problems, but am none the wiser. > > In fact, it is documented. Accessing a proxy will raise an exception > when the proxied object no longer exists. > > What you can ask is why your proxy has been accessed after the > object was deleted. The documentation is specific: during the callback, > the object should still exist. Thus, apparently, one of your proxies > outlived an event that should have deleted it (probably a hole in > your logic). > I have investigated a bit further, and now I have a clue as to what is happening, though not a full understanding. If you use 'b = weakref.ref(obj)', 'b' refers to the weak reference, and 'b()' refers to the referenced object. If you use 'b = weakref.proxy(obj)', 'b' refers to the referenced object. I don't know how to refer to the weak reference itself. In a way that is the whole point of using 'proxy', but the difficulty comes when you want to remove the weak reference when the referenced object is deleted. This is from the manual section on weakref.ref - "If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available." My callback method looks like this - del del_b(b): self.array.remove(b) It successfully removes the weak reference from self.array. This is from the manual section on weakref.proxy - "callback is the same as the parameter of the same name to the ref() function." My callback method looks the same. However, although 'b' is the weak reference, when I refer to 'b' it refers to the original object, which at this stage no longer exists. So my revised question is - How can you remove the weak reference if you use proxy? The full story is more complicated than that - why does my example work when I delete x, then y, then z, but not if I reverse the order? However, I think that I have isolated the fundamental reason. So any comments on my latest findings will be appreciated. Frank From __peter__ at web.de Fri Jul 6 03:35:16 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Jul 2012 09:35:16 +0200 Subject: Discussion on some Code Issues References: <34484d3d-d4c2-463b-8f83-dba57ce0511d@googlegroups.com> <996c1d6a-f297-401e-94a4-99be159a0801@googlegroups.com> Message-ID: subhabangalore at gmail.com wrote: [Please don't top-post] >> start = 0 >> for match in re.finditer(r"\$", data): >> end = match.start() >> print(start, end) >> print(data[start:end]) >> start = match.end() > That is a nice one. I am thinking if I can write "for lines in f" sort of > code that is easy but then how to find out the slices then, You have to keep track both of the offset of the line and the offset within the line: def offsets(lines, pos=0): for line in lines: yield pos, line pos += len(line) start = 0 for line_start, line in offsets(lines): for pos, part in offsets(re.split(r"(\$)", line), line_start): if part == "$": print(start, pos) start = pos + 1 (untested code, I'm assuming that the file ends with a $) > btw do you > know in any case may I convert the index position of file to the list > position provided I am writing the list for the same file we are reading. Use a lookup list with the end positions of the texts and then find the relevant text with bisect. >>> ends = [10, 20, 50] >>> filepos = 15 >>> bisect.bisect(ends, filepos) 1 # position 15 belongs to the second text From rosuav at gmail.com Fri Jul 6 03:45:39 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 6 Jul 2012 17:45:39 +1000 Subject: Apology for OT posts In-Reply-To: <4FF6780F.5070100@fossworkflowguides.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> <4FF3D708.6090405@tysdomain.com> <20120706120635.7d2f27547d8056a066dc9342@johnohagan.com> <4FF6780F.5070100@fossworkflowguides.com> Message-ID: On Fri, Jul 6, 2012 at 3:30 PM, Simon Cropper wrote: > bet this kills the conservation though... Probably. Until someone trolls the list again and sets us all going... I'm another of the worst perps, so in the words of Pooh-Bah, "I desire to associate myself with that expression of regret". It was a pretty good discussion actually. The only real problem was the subject line. ChrisA From mspadaccino at gmail.com Fri Jul 6 04:31:29 2012 From: mspadaccino at gmail.com (Maurizio Spadaccino) Date: Fri, 6 Jul 2012 10:31:29 +0200 Subject: Which way is best to execute a Python script in Excel? Message-ID: <2FC1C76A-131B-47C5-843C-71346336EA97@gmail.com> Hi Emile Thanks for the reply. Could you provide me a more detailed 'how-to' tutorial on implementing a VBA macro that calls a script or a function from python, or tell me where on the web I can find it? The OReilly chapter seems a bit hard for me at this stage? I dont know, for example, where i should tell the macro where to locate the script... Maurizio From breamoreboy at yahoo.co.uk Fri Jul 6 05:37:26 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 06 Jul 2012 10:37:26 +0100 Subject: Apology for OT posts In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <16ab546d-79e8-4d9a-9f8b-a28494d885f7@email.android.com> <4FF3CCCD.8070309@fossworkflowguides.com> <4FF3D708.6090405@tysdomain.com> <20120706120635.7d2f27547d8056a066dc9342@johnohagan.com> <4FF6780F.5070100@fossworkflowguides.com> Message-ID: On 06/07/2012 08:45, Chris Angelico wrote: > On Fri, Jul 6, 2012 at 3:30 PM, Simon Cropper > wrote: >> bet this kills the conservation though... > > Probably. Until someone trolls the list again and sets us all going... > > I'm another of the worst perps, so in the words of Pooh-Bah, "I desire > to associate myself with that expression of regret". > > It was a pretty good discussion actually. The only real problem was > the subject line. > > ChrisA > As far as I'm concerned nothing is OT here unless it is blatant trolling or spamming. It makes for a far more interesting read than the groups that have a policy of "if it's not in the standard, we won't discuss it". The set of languages that start with the third letter of the English language springs instantly to my mind. Agreed that the subject line should be changed. -- Cheers. Mark Lawrence. From lars at rational-it.com Fri Jul 6 07:22:18 2012 From: lars at rational-it.com (lars van gemerden) Date: Fri, 6 Jul 2012 04:22:18 -0700 (PDT) Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <3a9d4b46-2e99-4c30-882b-8ee68cb809da@googlegroups.com> On Sunday, July 1, 2012 5:48:40 PM UTC+2, Evan Driscoll wrote: > On 7/1/2012 4:54, Alister wrote: > > On Sat, 30 Jun 2012 23:45:25 -0500, Evan Driscoll wrote: > >> If I had seen that in a program, I'd have assumed it was a bug. > > > > You would? > > I have only been using python for 6 - 12 months but in my past I > > programmed microcontrollers in assembly. > > > > as soon as i saw it i understood it & thought great, like a light bulb > > going on. > > It's not a matter of "I wouldn't have understood what the author was > trying to do" (with a small caveat), it's a matter of "I'd have assumed > that the author didn't understand the language semantics." > > I'm pretty sure it goes contrary to *every other programming language > I've ever used* (and a couple that I haven't). > > I understand why Python does it, and it certainly is nice in that it > matches typical mathematical notation, but the surprise quotient is > *very* high in the PL world IMO. > > Evan Avoiding suprises would mean we cannot improve languages, just reshuffle features? Cheers, Lars From lars at rational-it.com Fri Jul 6 07:22:18 2012 From: lars at rational-it.com (lars van gemerden) Date: Fri, 6 Jul 2012 04:22:18 -0700 (PDT) Subject: code review In-Reply-To: References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> Message-ID: <3a9d4b46-2e99-4c30-882b-8ee68cb809da@googlegroups.com> On Sunday, July 1, 2012 5:48:40 PM UTC+2, Evan Driscoll wrote: > On 7/1/2012 4:54, Alister wrote: > > On Sat, 30 Jun 2012 23:45:25 -0500, Evan Driscoll wrote: > >> If I had seen that in a program, I'd have assumed it was a bug. > > > > You would? > > I have only been using python for 6 - 12 months but in my past I > > programmed microcontrollers in assembly. > > > > as soon as i saw it i understood it & thought great, like a light bulb > > going on. > > It's not a matter of "I wouldn't have understood what the author was > trying to do" (with a small caveat), it's a matter of "I'd have assumed > that the author didn't understand the language semantics." > > I'm pretty sure it goes contrary to *every other programming language > I've ever used* (and a couple that I haven't). > > I understand why Python does it, and it certainly is nice in that it > matches typical mathematical notation, but the surprise quotient is > *very* high in the PL world IMO. > > Evan Avoiding suprises would mean we cannot improve languages, just reshuffle features? Cheers, Lars From chirag.b.93 at gmail.com Fri Jul 6 07:53:11 2012 From: chirag.b.93 at gmail.com (Chirag B) Date: Fri, 6 Jul 2012 04:53:11 -0700 (PDT) Subject: stuck in files!! Message-ID: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> i want to kno how to link two applications using python for eg:notepad txt file and some docx file. like i wat to kno how to take path of those to files and run them simultaneously.like if i type something in notepad it has to come in wordpad whenever i run that code. From brandon.harris at reelfx.com Fri Jul 6 09:22:19 2012 From: brandon.harris at reelfx.com (brandon harris) Date: Fri, 6 Jul 2012 13:22:19 +0000 Subject: tkFileDialogs In-Reply-To: <4FF67AD7.1030505@gmail.com> References: <3CBB23A36B2BB04B9672F551A7EC1492197FDB1E@Exchange3.reelfx.com>, <4FF67AD7.1030505@gmail.com> Message-ID: <3CBB23A36B2BB04B9672F551A7EC1492197FDC34@Exchange3.reelfx.com> It doesn't matter whether I pass the actual path in or the global variable name. The result is the same. Brandon L. Harris ________________________________________ From: Karim [kliateni at gmail.com] Sent: Friday, July 06, 2012 12:42 AM To: brandon harris Subject: Re: tkFileDialogs Le 06/07/2012 07:22, brandon harris a ?crit : > I'm wanting to allow users to select hidden directories in windows and it seems that using the tkFileDialog.askdirectory() won't allow for that. It's using the tkFileDialog.Directory class which calls an internal command 'tk_chooseDirectory' . However the file selector dialogs (askopenfilename, asksaveasfilename, etc) has the common windows dialog which supports showing hidden folders. It's using the tkFileDialog.Open class which is calling an internal command of 'tk_getOpenFile'. > > Can anyone shed light on why these two dialogs are so very different and possibly give me a solution to this hidden directory issue. I have found that you can't really use the Open class because it's going to require a file be selected, not a directory and the Directory class won't navigate to or have an initialdir that is hidden (on windows the %APPDAT% folder is hidden by default) > > Windows Example Code. > > import tkFileDialog > # Won't start in or allow navigation to APPDATA > test = tkFileDialog.askdirectory(initialdir='%APPDATA%') > # Will start in and navigate to APPDATA > test = tkFileDialog.askopenfile(initialdir='%APPDATA%') > > Thanks in advance for any help given! > > > Brandon L. Harris Heuuuuuu. Don't you use os.environ['APPDATA'] if this is an environment variable? Cheers karim From emile at fenx.com Fri Jul 6 09:28:36 2012 From: emile at fenx.com (Emile van Sebille) Date: Fri, 06 Jul 2012 06:28:36 -0700 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <2FC1C76A-131B-47C5-843C-71346336EA97@gmail.com> References: <2FC1C76A-131B-47C5-843C-71346336EA97@gmail.com> Message-ID: On 7/6/2012 1:31 AM Maurizio Spadaccino said... > Could you provide me a more detailed 'how-to' tutorial on implementing a VBA macro that calls a script or a function from python, or tell me where on the web I can find it? The OReilly chapter seems a bit hard for me at this stage? I'm not going to write a how-to, but the relevant bits from the VBA code look like this: Set fpiUtils = CreateObject("fenxDCom.Util") response = fpiUtils.FirstPartInsp(nomDiam, numFlutes, nomOAL, nomLOC) > I dont know, for example, where i should tell the macro where to locate the script... Registering the com server does that for you (the __name__ == __main__ part of the python script) Again, get one of the examples working and move out from there. Emile From steve+comp.lang.python at pearwood.info Fri Jul 6 09:58:10 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Jul 2012 13:58:10 GMT Subject: code review References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <3a9d4b46-2e99-4c30-882b-8ee68cb809da@googlegroups.com> Message-ID: <4ff6eef2$0$29988$c3e8da3$5496439d@news.astraweb.com> On Fri, 06 Jul 2012 04:22:18 -0700, lars van gemerden wrote: > Avoiding suprises would mean we cannot improve languages, just reshuffle > features? No, of course not. But there have been hundreds of programming languages, including many different programming paradigms (procedural, imperative, object oriented, stack-based, functional, logic, aspect, event-driven, natural language, and many others), and tens of millions of person-days worth of experience in programming. It's not 1960 any more, in general terms we mostly have a good idea of what works and what doesn't. (Sadly, when I say "we" I mean collectively. Many language designers, and programmers, don't have the foggiest clue as to what makes a good clean design. Hence C++ and PHP.) The days when you could expect a brilliant new programming paradigm to lead to a massive improvement in programmer productivity, like going from assembly code to Fortran, are long gone. Now we look for incremental improvements. (Although of course there is always a chance that some yet unthought of new paradigm will revolutionise computer programming -- but I wouldn't bet on it.) When you're dealing with a well-designed, mature language like Python, you are even more limited. There's only so many changes you can make without turning it into a completely different language. And if you care about backward compatibility and wish to avoid breaking existing programs, there are even fewer changes that can be considered. Many good programming features must be avoided, not because they are bad, but because they don't match the rest of the language. Even though Python copies features from many different paradigms and languages, there is a mostly unified style of good Python code and any feature that doesn't match that style should be left out. There's few things worse than a language with random features just bolted on. -- Steven From diolu at bigfoot.com Fri Jul 6 10:01:24 2012 From: diolu at bigfoot.com (Olive) Date: Fri, 6 Jul 2012 16:01:24 +0200 Subject: Creating an instance when the argument is already an instance. References: <20120705122924.481a546b@bigfoot.com> <4ff580b4$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20120706160124.1fa7f5e0@bigfoot.com> On 05 Jul 2012 11:55:33 GMT Steven D'Aprano wrote: > On Thu, 05 Jul 2012 12:29:24 +0200, Olive wrote: > > > I am learning python -:) > > > > I am creating a new class: package (to analyse the packages > > database in some linux distros). I have created a class package > > such that package("string") give me an instance of package if > > string is a correct representation of a package. I would like that > > if pack is already an instance of package then package(pack) just > > return pack. > > The built-in types only do this for immutable objects, those which > cannot be modified. > > py> a = float('42.5') > py> b = float(a) > py> a is b > True > > > But note carefully that this is not a guarantee of the language. > Other versions of Python may not do this. > > Also note carefully that it is only immutable objects which do this. > Mutable objects do not behave this way: > > py> a = ['a', 1, None] > py> b = list(a) > py> a is b > False > > > By default, most custom-made classes are mutable, and so re-using > instances is the wrong thing to do. Unfortunately, it is moderately > tricky to make mutable classes in Python. One way is described here: > > http://northernplanets.blogspot.com.au/2007/01/immutable-instances-in-python.html > > You can also look at the source code for Decimal (warning: it's BIG) > or Fraction: > > http://hg.python.org/cpython/file/2.7/Lib/decimal.py > http://hg.python.org/cpython/file/2.7/Lib/fractions.py > > > But suppose you make your class immutable. Then it's quite safe, and > easy, to get the behaviour you want: > > > class Package(object): > def __new__(cls, argument): > if isinstance(argument, Package): > return argument > return object.__new__(cls, argument) > > > or similar, I haven't actually tested the above. But the important > trick is to use __new__, the constructor, rather than __init__, which > runs after the instance is already created, and to use an isinstance > test to detect when you already have an instance. > Yes the trick with the __new__ works. We have to test afterwards i the __init__ if the instance is already initialised and otherwise do nothing. Thanks! I am learning and I didn't know the __new__ feature. Olive From t at jollybox.de Fri Jul 6 10:56:41 2012 From: t at jollybox.de (Thomas Jollans) Date: Fri, 06 Jul 2012 16:56:41 +0200 Subject: stuck in files!! In-Reply-To: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> References: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> Message-ID: <4FF6FCA9.70401@jollybox.de> On 07/06/2012 01:53 PM, Chirag B wrote: > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. > Not possible. (okay, within certain restrictions it might not be completely impossible) What are you trying to achieve? From demianbrecht at gmail.com Fri Jul 6 11:38:54 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Fri, 6 Jul 2012 08:38:54 -0700 (PDT) Subject: OAuth 2.0 implementation In-Reply-To: <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> Message-ID: <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> Supported provider list (with example code) is now: * Facebook * Google * Foursquare * bitly * GitHub * StackExchange * Instagram Other providers may also be supported out of the box, but have been untested thus far. From demianbrecht at gmail.com Fri Jul 6 11:38:54 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Fri, 6 Jul 2012 08:38:54 -0700 (PDT) Subject: OAuth 2.0 implementation In-Reply-To: <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> Message-ID: <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> Supported provider list (with example code) is now: * Facebook * Google * Foursquare * bitly * GitHub * StackExchange * Instagram Other providers may also be supported out of the box, but have been untested thus far. From rantingrickjohnson at gmail.com Fri Jul 6 12:17:06 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Fri, 6 Jul 2012 09:17:06 -0700 (PDT) Subject: tkFileDialogs References: Message-ID: <9177eeb0-da29-4c83-b370-e810a1cb085b@w6g2000yqg.googlegroups.com> On Jul 6, 12:22?am, brandon harris wrote: > [...] > import tkFileDialog > # Won't start in or allow navigation to APPDATA > test = tkFileDialog.askdirectory(initialdir='%APPDATA%') > # Will start in and navigate to APPDATA > test = tkFileDialog.askopenfile(initialdir='%APPDATA%') Don't you just love inconsistencies! I get weird results using your "string". Why not use expanduser? py> path = os.path.expanduser('~\\AppData') Of course that will not solve your main problem though. Probably since showing hidden files is a function of the OS setting, which explorer follows blindly. I tried your code AFTER changing "show hidden_files_and_folders=True" and both dialogs open into the correct directory, as expected. You could modify the setting, then show the dialog, then revert the setting back. Ah. The joys of Win32 scripting... *chokes* From rantingrickjohnson at gmail.com Fri Jul 6 12:40:15 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Fri, 6 Jul 2012 09:40:15 -0700 (PDT) Subject: simpler increment of time values? References: Message-ID: On Jul 5, 12:16?pm, Chris Angelico wrote: > > So it's even easier than I said. And bonus lesson for the day: Try > things in the interactive interpreter before you post. :) but first: be sure to familiarize yourself with the many built-in "python classes"(sic). Re-inventing the wheel is breaking the lazy programmers' creed. It should only be broken if you wish to understand how things work "under the hood". From hansmu at xs4all.nl Fri Jul 6 12:41:58 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 06 Jul 2012 18:41:58 +0200 Subject: Confusing datetime.datetime In-Reply-To: References: Message-ID: <4ff71557$0$6974$e4fe514c@news2.news.xs4all.nl> On 6/07/12 00:55:48, Damjan wrote: > On 05.07.2012 16:10, Damjan wrote: >> I've been struggling with an app that uses >> Postgresql/Psycopg2/SQLAlchemy and I've come to this confusing >> behaviour of datetime.datetime. > > > Also this: > > #! /usr/bin/python2 > # retardations in python's datetime > > import pytz > TZ = pytz.timezone('Europe/Skopje') > > from datetime import datetime > > x1 = datetime.now(tz=TZ) > x2 = datetime(x1.year, x1.month, x1.day, tzinfo=TZ) > > assert x1.tzinfo == x2.tzinfo > > WHY does the assert throw an error??? Because x1 and x2 have different time zones. The tzinfo field in x2 is equal to TZ and has a UTC offset of 1 hour. The tzinfo field in x1 contains the DST version of that timezone, with a UTC offset of 2 hours, because Skopje is currently on DST. I think you want: x2 = TZ.localize(datetime(x1.year, x1.month, x1.day)) That produces a datetime with the year, month and day set as indicated and tzinfo set to the correct UTC offset for that date, at 00:00 hours. Or maybe you need: x2 = TZ.localize(datetime(x1.year, x1.month, x1.day, 12)) x2 = x2.replace(hour=0) That determines whether DST should be on at noon, and then resets the hour field to zero. This produces the same outcome as the one liner, except on days when DST is switched on or off. Hope this helps, -- HansM From andrea.crotti.0 at gmail.com Fri Jul 6 12:46:35 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Fri, 6 Jul 2012 17:46:35 +0100 Subject: stuck in files!! In-Reply-To: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> References: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> Message-ID: 2012/7/6 Chirag B : > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. > -- > http://mail.python.org/mailman/listinfo/python-list I don't think that "I want to know" ever lead to some useful answers, it would be not polite even if people were actually paid to answer ;) Anyway it's quite an application-os specific question, probably not very easy either.. From zahlman at gmail.com Fri Jul 6 12:55:31 2012 From: zahlman at gmail.com (Karl Knechtel) Date: Fri, 6 Jul 2012 12:55:31 -0400 Subject: Issues with `codecs.register` and `codecs.CodecInfo` objects Message-ID: Hello all, While attempting to make a wrapper for opening multiple types of UTF-encoded files (more on that later, in a separate post, I guess), I ran into some oddities with the `codecs` module, specifically to do with `.register` ing `CodecInfo` objects. I'd like to report a bug or something, but there are several intertangled issues here and I'm not really sure how to report it so I thought I'd open the discussion. Apologies in advance if I get a bit rant-y, and a warning that this is fairly long. Observe what happens when you `register` the wrong function: >>> import codecs >>> def ham(name): ... # Very obviously wrong, just for demonstration purposes ... if name == 'spam': return 'eggs' ... >>> codecs.register(ham) Already there is a problem in that there is no error... there is no realistic way to catch this, of course, but IMHO it points to an issue with the interface. I don't want to register a codec lookup function; I want to register *a codec*. The built-in lookup process would be just fine if I could just somehow tell it about this one new codec I have... I really don't see the use case for the added flexibility of the current interface, and it means that every time I have a new codec, I need to either create a new lookup function as well (to register it), or hook into an existing one that's still of my own creation. Anyway, moving on, let's see what happens when we try to use the faulty codec: >>> codecs.getencoder('spam') Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\codecs.py", line 939, in getencoder return lookup(encoding).encode TypeError: codec search functions must return 4-tuples Ehh?! That's odd. I thought I was supposed to return a `CodecInfo` object, not a 4-tuple! Although as an aside, AFAICT the documentation *doesn't actually document the CodecInfo class*, it just says what attributes CodecInfo objects are supposed to have. A bit of digging around with Google and existing old bugs on the tracker suggests that this comes about due to backwards-compatibility: in 2.4 and below, they *were* 4-tuples. But now CodecInfo objects are expected to provide 6 functions (and a name), not 4. Clearly that won't fit in a 4-tuple, and anyway I thought we had gotten rid of all this deprecated stuff. Regardless, let's see what happens if we do try to register a 4-tuple-lookup-er: >>> def spam(name): ... # As long as we return a 4-tuple, it doesn't really matter what the functions are; ... # errors shouldn't happen until we actually attempt to encode/decode. Right? ... if name == 'spam': return (spam, spam, spam, spam) Oops, we need to restart the interpreter, or otherwise reset global state somehow, because the old lookup function has priority over this one, and *there is no way to unregister it*. But once that's fixed: >>> codecs.getencoder('spam') Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\codecs.py", line 939, in getencoder return lookup(encoding).encode AttributeError: 'tuple' object has no attribute 'encode' That's quite odd indeed. We can't actually trust the error message we got before! 4-tuples don't work any more like they used to, so our backwards-compatibility concession doesn't even work. Meanwhile, we're left wondering how CodecInfo objects work at all. Is the error message wrong? Nope, well, not really. Let's grab an known good CodecInfo object and see what we can find out... >>> utf8 = codecs.lookup('utf-8') >>> utf8.__class__.__bases__ (,) >>> # not collections.namedtuple, which is understandable, since that wasn't available until 2.6... >>> len(utf8) 4 >>> # OK, apparently it magically actually is a tuple of length 4 despite needing 7 attributes. I wonder which ones are included: >>> tuple(utf8) (, , , ) >>> # Unsurprising: the ones mandated by the original PEP (100! That long ago...) ... and if we try `help` (or look at examples in the standard library or find them with Google - but I sure don't see any in the webpage docs), we can at least find out how to construct a CodecInfo object properly - although, curiously, it's implemented using `__new__` rather than `__init__`. You *can* hack around with `collections.namedtuple` and create something that basically works: # restarting again... >>> import codecs, collections >>> my_codecinfo = collections.namedtuple('my_codecinfo', 'encode decode streamreader streamwriter') >>> def spam(name): ... if name == 'spam': return my_codecinfo(spam, spam, spam, spam) And now the error correctly doesn't occur until we actually attempt to encode or decode something. Except we still don't have an incremental decoder/encoder, and in fact those are missing attributes rather than `None` as they're defaulted to by the `CodecInfo` class. (Of course, we can subclass `collections.namedtuple` to fix this, but then we're basically reverse-engineering the `codecs.CodecInfo` class wholesale...) Speaking of which, one last thing: >>> # Another restart, of course >>> import codecs >>> def spam(name): ... if name == 'spam': return codecs.CodecInfo(spam, spam) ... >>> codecs.register(spam) >>> codecs.getincrementaldecoder('spam') Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\codecs.py", line 976, in getincrementaldecoder raise LookupError(encoding) LookupError: spam That seems wrong to me too: the codec is certainly *there*, it just doesn't support incremental decoding. I would expect the error message to be more specific. -- ~Zahlman {:> From ian.g.kelly at gmail.com Fri Jul 6 13:04:06 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 6 Jul 2012 11:04:06 -0600 Subject: Question about weakref In-Reply-To: References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> Message-ID: On Fri, Jul 6, 2012 at 1:00 AM, Frank Millman wrote: > I have investigated a bit further, and now I have a clue as to what is > happening, though not a full understanding. > > If you use 'b = weakref.ref(obj)', 'b' refers to the weak reference, and > 'b()' refers to the referenced object. > > If you use 'b = weakref.proxy(obj)', 'b' refers to the referenced object. I > don't know how to refer to the weak reference itself. In a way that is the > whole point of using 'proxy', but the difficulty comes when you want to > remove the weak reference when the referenced object is deleted. Not quite. 'b' refers to the proxy, which uses magic methods to mimic the referenced object. It is still a separate object, however. In fact, I actually think it's not directly possible to refer to the *referenced object* via a proxy, although there are round-about ways to accomplish it. >>> import weakref >>> class Foo(object): pass >>> a = Foo() >>> id(a) 11253072 >>> b = weakref.proxy(a) >>> id(b) 11258400 >>> a is a True >>> a is b False > The full story is more complicated than that - why does my example work when > I delete x, then y, then z, but not if I reverse the order? On that, I'm really not sure. I tried to reproduce the problem locally and wasn't able to. What build of Python are you using, and on what platform? I have one suggestion, though: you might try removing the __del__ method from the listener class, as the presence of that method can interfere with garbage collection in some cases, and it is generally contra-recommended. I'm not sure why that would affect the code you posted, but it can't hurt to try it. Cheers, Ian From ian.g.kelly at gmail.com Fri Jul 6 13:48:36 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 6 Jul 2012 11:48:36 -0600 Subject: Question about weakref In-Reply-To: References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> Message-ID: On Fri, Jul 6, 2012 at 11:04 AM, Ian Kelly wrote: > On that, I'm really not sure. I tried to reproduce the problem > locally and wasn't able to. What build of Python are you using, and > on what platform? I spoke too soon, I am able to reproduce it. I think what's going on here is that when you try to remove the proxy from the list, the list.remove() call searches for the object by *equality*, not by identity. The problem is that at the time of the callback, the referent is no longer available to implement the equality test, as noted in the weakref.ref() documentation. As long as the proxy happens to be the first element of the list, this is not a problem, because the proxy evidently short-circuits self == self to return True. If it's not the first element of the list, though, then the first comparison compares the proxy to some other object, and the proxy raises an exception, because without the referent it no longer knows how to compare. If you change your del_b() method to the following, though, it works: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] This works because it carefully only handles the proxy object itself and no longer relies on any aspect of the referent for deletion. It's not a problem for weakref.ref, because ref objects require an explicit dereferencing step to access the referent. Cheers, Ian From ian.g.kelly at gmail.com Fri Jul 6 13:51:32 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 6 Jul 2012 11:51:32 -0600 Subject: Question about weakref In-Reply-To: References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> Message-ID: On Fri, Jul 6, 2012 at 11:48 AM, Ian Kelly wrote: > def del_b(self, b): > for i, x in enumerate(self.array): > if b is x: > del self.array[i] That should probably have an explicit break on the end: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] break From ethan at stoneleaf.us Fri Jul 6 14:12:51 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Jul 2012 11:12:51 -0700 Subject: Question about weakref In-Reply-To: References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> Message-ID: <4FF72AA3.3070808@stoneleaf.us> Ian Kelly wrote: > def del_b(self, b): > for i, x in enumerate(self.array): > if b is x: > del self.array[i] > break Nice work, Ian. From foo at email.invalid Fri Jul 6 14:21:07 2012 From: foo at email.invalid (Alex) Date: Fri, 6 Jul 2012 18:21:07 +0000 (UTC) Subject: stuck in files!! References: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> Message-ID: Chirag B wrote: > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. Text and docx files are not "applications"; you don't "run" them. You can "open" them with applications like Notepad or Microsoft Word, and you can open two files simultaneously in two different applications (or in two windows within the same application). Other than that, I don't understand what you mean by "link" them or what it means for something typed in Notepad to "come in wordpad." From pavan.kumar at intsystech.com Fri Jul 6 14:39:10 2012 From: pavan.kumar at intsystech.com (pavan) Date: Fri, 6 Jul 2012 14:39:10 -0400 Subject: Immediate Hiring a Python /Django in NJ. Main skills should be Python . knowledge of java / c++. More technologies are a plus. Message-ID: <073301cd5ba6$a4519080$ecf4b180$@kumar@intsystech.com> Dear Candidate. Hope you are having a great day! We have an opportunity for you . We trust that your knowledge, skills and experience will be among our most valuable assets .Please let us know would you be interested for this job opening. If you are interested in pursuing this opportunity, please reply with an updated copy of your resume in word format, with details to pavan.kumar at intsystech.com We apologize, if any inconvenience is caused or this job opening is irrelevant / not of interest to you and request you to ignore this mail. **************************************************************************** Title:Python Script Developers/Django Developer Duration:Long Term Location - NJ Suitable Profile :(knowledge in Java with Pythonscripts , C# Exp) Client Needs solid Python scripts developers and good knowledge of java / c++. Nice to have C#as well. We apologize, if any inconvenience is caused or this job opening is irrelevant / not of interest to you and request you to ignore this mail. I appreciate if you can forward this opportunity with your friends/Colleagues who is despirately looking for project as it is a almost closing position or kindly provide their details to my email id. I appreciate your time and look forward to hearing from you soon. Thanks & Regards, ________________________________________________ Pavan | International Systems Technologies Inc. | 15 Corporate place south.| Suite 135 Piscataway, NJ 08854 Direct -908-333-5697 Tel: 908-315-0700 x 601| Fax: 732-348-9533| pavan.kumar at intsystech.com www.intsystech.com cid:image002.jpg at 01CC7CEF.ABDD8070pavanrek spavanintsystech IST exists to help Note: This e-mail transmission may contain information that is proprietary, privileged and/or confidential and is intended exclusively for the person(s) to whom it is addressed. Any use, copying, retention or disclosure by any person other than the intended recipient or the intended recipient's designees is strictly prohibited. If you are not the intended recipient or their designee, please notify the sender immediately by return e-mail and delete all copies. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image005.jpg Type: image/jpeg Size: 941 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image006.jpg Type: image/jpeg Size: 839 bytes Desc: not available URL: From alec.taylor6 at gmail.com Fri Jul 6 14:41:40 2012 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 7 Jul 2012 04:41:40 +1000 Subject: OAuth 2.0 implementation In-Reply-To: <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> Message-ID: On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht wrote: > Supported provider list (with example code) is now: > * Facebook > * Google > * Foursquare > * bitly > * GitHub > * StackExchange > * Instagram > > Other providers may also be supported out of the box, but have been untested thus far. Looking good. Keep adding more to the list! I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn auths added to the list. Also I'll be extending it a little more at some point to make it "friendlier" :P Thanks for merging my last pull-request, Alec Taylor From demianbrecht at gmail.com Fri Jul 6 14:49:55 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Fri, 6 Jul 2012 11:49:55 -0700 Subject: OAuth 2.0 implementation In-Reply-To: References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> Message-ID: <026401cd5ba8$240fc8e0$6c2f5aa0$@gmail.com> No worries, thanks for the request. Unfortunately AFAIK (according to the OAuth provider list on Wikipedia), both Twitter and LinkedIn still use OAuth 1.0a, so until they hop on the OAuth 2.0 bandwagon, they won't be added. -----Original Message----- From: Alec Taylor [mailto:alec.taylor6 at gmail.com] Sent: Friday, July 06, 2012 11:42 AM To: Demian Brecht Cc: comp.lang.python at googlegroups.com; python-list at python.org Subject: Re: OAuth 2.0 implementation On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht wrote: > Supported provider list (with example code) is now: > * Facebook > * Google > * Foursquare > * bitly > * GitHub > * StackExchange > * Instagram > > Other providers may also be supported out of the box, but have been untested thus far. Looking good. Keep adding more to the list! I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn auths added to the list. Also I'll be extending it a little more at some point to make it "friendlier" :P Thanks for merging my last pull-request, Alec Taylor From alec.taylor6 at gmail.com Fri Jul 6 14:58:35 2012 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 7 Jul 2012 04:58:35 +1000 Subject: OAuth 2.0 implementation In-Reply-To: <026401cd5ba8$240fc8e0$6c2f5aa0$@gmail.com> References: <1973354.3.1332816158529.JavaMail.geo-discussion-forums@pbae2> <3e023dd6-eb7d-4a7a-b868-bd41d7c69c8b@googlegroups.com> <7f8f94b6-ed63-41ce-8180-83ca96d88ea3@googlegroups.com> <5b061fbe-71eb-43c3-b8e9-ce5b02a9cce7@googlegroups.com> <026401cd5ba8$240fc8e0$6c2f5aa0$@gmail.com> Message-ID: Yeah, seems Twitter is still stuck on 1.0a... But LinkedIn seems to support 1.0a for REST and 2 for JS: https://developer.linkedin.com/apis So that could be a definite contender for Sanction support On Sat, Jul 7, 2012 at 4:49 AM, Demian Brecht wrote: > No worries, thanks for the request. > > Unfortunately AFAIK (according to the OAuth provider list on Wikipedia), > both Twitter and LinkedIn still use OAuth 1.0a, so until they hop on the > OAuth 2.0 bandwagon, they won't be added. > > -----Original Message----- > From: Alec Taylor [mailto:alec.taylor6 at gmail.com] > Sent: Friday, July 06, 2012 11:42 AM > To: Demian Brecht > Cc: comp.lang.python at googlegroups.com; python-list at python.org > Subject: Re: OAuth 2.0 implementation > > On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht > wrote: >> Supported provider list (with example code) is now: >> * Facebook >> * Google >> * Foursquare >> * bitly >> * GitHub >> * StackExchange >> * Instagram >> >> Other providers may also be supported out of the box, but have been > untested thus far. > > Looking good. Keep adding more to the list! > > I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn > auths added to the list. > > Also I'll be extending it a little more at some point to make it > "friendlier" :P > > Thanks for merging my last pull-request, > > Alec Taylor > From cjw at ncf.ca Fri Jul 6 15:11:21 2012 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 06 Jul 2012 15:11:21 -0400 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: References: <4FF541A9.1090806@gmail.com> <4FF55A85.2040002@jollybox.de> <4FF64DD8.8030007@gmail.com> Message-ID: On 06/07/2012 1:09 AM, Terry Reedy wrote: > > On 7/5/2012 10:30 PM, Karim wrote: > >> An excellent link to derived all code example to python: >> http://www.pitonyak.org/AndrewMacro.sxw. > > Even though he only writes in OOBasic, you are right that he explains > the basic concepts needed for accessing the api from any language. He is > also honest. Writing non-api code is relatively easy; accessing the > OO/LO api is harder. I made a start. When I get further, I will look at > the examples that are close to some things I want to do. I will also > study your Python examples. Thanks for the help. > > Terry > > You might be interested in pyspread (http://manns.github.com/pyspread/). It is no longer maintained for Windows. Colin W. From ethan at stoneleaf.us Fri Jul 6 17:34:02 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Jul 2012 14:34:02 -0700 Subject: API design question for dbf.py Message-ID: <4FF759CA.9060803@stoneleaf.us> I'm looking for some free advice. ;) My dbf module has three basic containers, all of which support list-like access: Table, List, and Index, each of which is filled with _DbfRecords. The fun part is that a _DbfRecord can compare equal to another _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the same locations, or a dict with the same keys/fields and values. The really fun part is __contains__: should the __contains__ method return True when a _DbfRecordTemplate, tuple, or dict is looked up in the Table, List, or Index and there is a matching record? ~Ethan~ From salmanmk at live.com Fri Jul 6 17:40:08 2012 From: salmanmk at live.com (Salman Malik) Date: Fri, 6 Jul 2012 16:40:08 -0500 Subject: PyEval_SetProfile usage ? Message-ID: Hi All, I have used the Python's C-API to call some Python code in my c code and now I want to know how much time does my Python part of the program takes. I came across the PyEval_SetProfile API and am not sure how to use it. Do I need to write my own profiling function? Any pointer to examples or how to's will be much appreciated. Thanks, Salman -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Fri Jul 6 17:48:22 2012 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 6 Jul 2012 23:48:22 +0200 Subject: simpler increment of time values? In-Reply-To: References: Message-ID: Thanks to all for further comments! Just for completeness and in case somebody would like to provide some suggestions or corrections; the following trivial class should be able to deal with the initial requirement of adding or subtracting dateless time values (hour:minute). regards, vbr # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import re class TrivialTime(object): """ Trivial, dateless, DST-less, TZN-less time in 24-hours cycle only supporting hours and minutes; allows addition and subtraction. """ def __init__(self, hours=0, minutes=0): self.total_minutes = (int(hours) * 60 + int(minutes)) % (60 * 24) self.hours, self.minutes = divmod(self.total_minutes, 60) def __add__(self, other): return TrivialTime(minutes=self.total_minutes + other.total_minutes) def __sub__(self, other): return TrivialTime(minutes=self.total_minutes - other.total_minutes) def __repr__(self): return "TrivialTime({}, {})".format(self.hours, self.minutes) def __str__(self): return "{}.{:0>2}".format(self.hours, self.minutes) @staticmethod def fromstring(time_string, format_re=r"^([0-2]?\d?)[.:,-]\s*([0-5]\d)$"): """ Returns a TrivialTime instance according to the data from the given string with respect to the regex time format (two parethesised groups for minutes and seconds respectively). """ time_string_match = re.match(format_re, time_string) if not time_string_match: raise ValueError("Time data cannot be obtained from the given string and the format regex.") return TrivialTime(hours=int(time_string_match.group(1)), minutes=int(time_string_match.group(2))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # From rosuav at gmail.com Fri Jul 6 18:13:51 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 7 Jul 2012 08:13:51 +1000 Subject: stuck in files!! In-Reply-To: References: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> Message-ID: On Sat, Jul 7, 2012 at 4:21 AM, Alex wrote: > Chirag B wrote: > >> i want to kno how to link two applications using python for eg:notepad >> txt file and some docx file. like i wat to kno how to take path of >> those to files and run them simultaneously.like if i type something in >> notepad it has to come in wordpad whenever i run that code. > > Text and docx files are not "applications"; you don't "run" them. You > can "open" them with applications like Notepad or Microsoft Word, and > you can open two files simultaneously in two different applications (or > in two windows within the same application). > > Other than that, I don't understand what you mean by "link" them or > what it means for something typed in Notepad to "come in wordpad." The nearest I can think of has nothing to do with Python, but all to do with the applications concerned: DDE. Back in the early 90s it was a much-touted technology on OS/2 - you could fire up Mesa (spreadsheet), hotlink a particular group of cells to a table in DeScribe, edit one and see the other change instantly. It was pretty cool for its day. How you'd go about implementing it today I don't know, but there's a few options available. Really depends on what the OP actually wants to achieve: Duplicate typing, shared text, simultaneous editing? ChrisA From python at mrabarnett.plus.com Fri Jul 6 18:26:09 2012 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 06 Jul 2012 23:26:09 +0100 Subject: API design question for dbf.py In-Reply-To: <4FF759CA.9060803@stoneleaf.us> References: <4FF759CA.9060803@stoneleaf.us> Message-ID: <4FF76601.3090806@mrabarnett.plus.com> On 06/07/2012 22:34, Ethan Furman wrote: > I'm looking for some free advice. ;) > > My dbf module has three basic containers, all of which support list-like > access: Table, List, and Index, each of which is filled with _DbfRecords. > > The fun part is that a _DbfRecord can compare equal to another > _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the > same locations, or a dict with the same keys/fields and values. > > The really fun part is __contains__: should the __contains__ method > return True when a _DbfRecordTemplate, tuple, or dict is looked up in > the Table, List, or Index and there is a matching record? > Well, if x is in c and x == y, then y is in c. Does that help? ;-) From pengyu.ut at gmail.com Fri Jul 6 18:38:38 2012 From: pengyu.ut at gmail.com (Peng Yu) Date: Fri, 6 Jul 2012 15:38:38 -0700 (PDT) Subject: How to print a number as if in the python interpreter? Message-ID: <10e16ff7-b5cf-4c77-8b7d-f58c035f748a@j25g2000yqn.googlegroups.com> Hi, In [2]: sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) Out[2]: 0.9999999999999999 In ipython, I got the above output. But I got a different output from "print". Is there a way to print exact what I saw in ipython? ~/linux/test/python/man/library/math/fsum$ cat main.py #!/usr/bin/env python print sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) ~/linux/test/python/man/library/math/fsum$ ./main.py 1.0 Regards, Peng From ethan at stoneleaf.us Fri Jul 6 18:46:42 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Jul 2012 15:46:42 -0700 Subject: API design question for dbf.py In-Reply-To: <4FF76601.3090806@mrabarnett.plus.com> References: <4FF759CA.9060803@stoneleaf.us> <4FF76601.3090806@mrabarnett.plus.com> Message-ID: <4FF76AD2.2040706@stoneleaf.us> MRAB wrote: > On 06/07/2012 22:34, Ethan Furman wrote: >> I'm looking for some free advice. ;) >> >> My dbf module has three basic containers, all of which support list-like >> access: Table, List, and Index, each of which is filled with >> _DbfRecords. >> >> The fun part is that a _DbfRecord can compare equal to another >> _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the >> same locations, or a dict with the same keys/fields and values. >> >> The really fun part is __contains__: should the __contains__ method >> return True when a _DbfRecordTemplate, tuple, or dict is looked up in >> the Table, List, or Index and there is a matching record? >> > Well, if x is in c and x == y, then y is in c. Does that help? ;-) Heh, that's pretty much the conclusion I was coming to. As a more concrete example: --> x = 4.0 --> x in [1, 4, 7, 4, 9, 3, 4] True It's checking for equality, not identity. Thinks for helping me think that through. ~Ethan~ From clp2 at rebertia.com Fri Jul 6 18:59:28 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 6 Jul 2012 15:59:28 -0700 Subject: How to print a number as if in the python interpreter? In-Reply-To: <10e16ff7-b5cf-4c77-8b7d-f58c035f748a@j25g2000yqn.googlegroups.com> References: <10e16ff7-b5cf-4c77-8b7d-f58c035f748a@j25g2000yqn.googlegroups.com> Message-ID: On Fri, Jul 6, 2012 at 3:38 PM, Peng Yu wrote: > Hi, > > In [2]: sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) > Out[2]: 0.9999999999999999 > > In ipython, I got the above output. But I got a different output from > "print". Is there a way to print exact what I saw in ipython? > > ~/linux/test/python/man/library/math/fsum$ cat main.py > #!/usr/bin/env python > print sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) > ~/linux/test/python/man/library/math/fsum$ ./main.py > 1.0 chris at mbp ~ $ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = sum(0.1 for i in range(10)) >>> x # the interpreter implicitly repr()s the result of an expression 0.9999999999999999 >>> print x # whereas `print` str()s its operands 1.0 >>> (str(x), repr(x)) # as proof and for clarity ('1.0', '0.9999999999999999') Beware the subtleties of floating-point arithmetic! http://docs.python.org/tutorial/floatingpoint.html Cheers, Chris From jeanpierreda at gmail.com Fri Jul 6 19:01:05 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 6 Jul 2012 19:01:05 -0400 Subject: API design question for dbf.py In-Reply-To: <4FF76AD2.2040706@stoneleaf.us> References: <4FF759CA.9060803@stoneleaf.us> <4FF76601.3090806@mrabarnett.plus.com> <4FF76AD2.2040706@stoneleaf.us> Message-ID: On Fri, Jul 6, 2012 at 6:46 PM, Ethan Furman wrote: > It's checking for equality, not identity. >>> x = float('nan') >>> x in [x] True It's checking for equality OR identity. -- Devin From ethan at stoneleaf.us Fri Jul 6 19:22:26 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 06 Jul 2012 16:22:26 -0700 Subject: API design question for dbf.py In-Reply-To: References: <4FF759CA.9060803@stoneleaf.us> <4FF76601.3090806@mrabarnett.plus.com> <4FF76AD2.2040706@stoneleaf.us> Message-ID: <4FF77332.3010809@stoneleaf.us> Devin Jeanpierre wrote: > On Fri, Jul 6, 2012 at 6:46 PM, Ethan Furman wrote: >> It's checking for equality, not identity. > > >>> x = float('nan') > >>> x in [x] > True > > It's checking for equality OR identity. Good point. In my case, checking for equality will cover both cases. ~Ethan~ From steve+comp.lang.python at pearwood.info Fri Jul 6 22:56:13 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 07 Jul 2012 02:56:13 GMT Subject: Issues with `codecs.register` and `codecs.CodecInfo` objects References: Message-ID: <4ff7a54c$0$29988$c3e8da3$5496439d@news.astraweb.com> On Fri, 06 Jul 2012 12:55:31 -0400, Karl Knechtel wrote: > Hello all, > > While attempting to make a wrapper for opening multiple types of > UTF-encoded files (more on that later, in a separate post, I guess), I > ran into some oddities with the `codecs` module, specifically to do with > `.register` ing `CodecInfo` objects. I'd like to report a bug or > something, but there are several intertangled issues here and I'm not > really sure how to report it so I thought I'd open the discussion. > Apologies in advance if I get a bit rant-y, and a warning that this is > fairly long. [...] Yes, it's a strangely indirect API, and yes it looks like you have identified a whole bucket full of problems with it. And no, I don't know why that API was chosen. Changing to a cleaner, more direct (sensible?) API would be a fairly big step. If you want to pursue this, the steps I recommend you take are: 1) understanding the reason for the old API (search the Internet and particularly the python-dev at python.org archives); 2) have a plan for how to avoid breaking code that relies on the existing API; 3) raise the issue on python-ideas at python.org to gather feedback and see how much opposition or support it is likely to get; they'll suggest whether a bug report is sufficient or if you'll need a PEP; http://www.python.org/dev/peps/ If you can provide a patch and a test suite, you will have a much better chance of pushing it through. If not, you are reliant on somebody else who can being interested enough to do the work. And one last thing: any new functionality will simply *not* be considered for Python 2.x. Aim for Python 3.4, since the 2.x series is now in bug- fix only maintenance mode and the 3.3 beta is no longer accepting new functionality, only bug fixes. -- Steven From shilparani9030 at gmail.com Fri Jul 6 23:19:27 2012 From: shilparani9030 at gmail.com (SHILPA) Date: Fri, 6 Jul 2012 20:19:27 -0700 (PDT) Subject: UNSEENED RARE HOT PHOTOS AND VIDEOS Message-ID: ALL INTERVIEW QUESTIONS& STUDY MATERIAL http://newdotnetinterviewquestions.blogspot.in/ TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING http://datingsitesdatingtips.blogspot.in/ FOR LATEST MOVIE UPDATED LINKS ADE PREMA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/ade-prema-stills.html HANSIKA MOTWANI LATEST HOT PICS http://actressgallery-kalyani.blogspot.in/2012/07/hansika-motwani-actress.html HOT NEETHU CHANDRA LATEST PICS http://actressgallery-kalyani.blogspot.in/2012/07/neetu-chandra-actress.html ACTRESS AMRUTHA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/amrutha-actress.html SELATHUPONNU MOVIE HOT PHOTOS http://actressgallery-kalyani.blogspot.in/2012/07/selathuponnu-movie-stills.html SULAGNA PANIGRAHI HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/06/sulagna-panigrahi-actress.html RUBY PARIHAR HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.com/2012/06/actress-ruby-parihar.html ACTRESS YAMI GOUTHAM LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/06/yami-gautam-actress.html ACTRESS HOT STILLS IN SIIMA AWARDS 2012 http://actressgallery-kalyani.blogspot.in/2012/06/actress-siima-awards-2012-stills.html EM BABU LADDU KAVALA MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/06/em-babu-laddu-kavala-movie-stills.html SRMANARAYANA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/06/srimannarayana-movie-stills.html KAJAL AGARWAL LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/06/kajal-agarwal-latest-stills.html SANA KHAN LATEST HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/sana-khan-latest-stills.html COOL BOYS HOT GIRLS MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/06/cool-boys-hot-girls-movie-stills.html MITAAYI MOVIE LATEST GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/mitaayi-movie-stills.html NAGARJUNA DAMARUKAM MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/damarukam-movie-stills.html ALLU ARJUN JULAYI MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/julayi-movie-stills.html SUDIGADU MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/sudigadu-movie-stills.html MR 7 MOVIE FILM GALLERY http://actressgallery-kalyani.blogspot.in/2012/05/mr7-movie-stills.html ALL THE BEST MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/all-best-movie-stills.html Midatha Telugu movie Hot Namitha Stills http://actressgallery-kalyani.blogspot.com/2012/05/midatha-movie-stills.html OKA COLLEGE LOVE STORY MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/oka-college-love-story-movie-stills.html KATRINA KAIF LATEST UNSEENED PHOTOS http://actressgallery-kalyani.blogspot.com/2012/05/katrina-kaif-latest-pics.html TAMIL ACTRESS ARUNDHATI HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/05/arundhati-tamil-actress.html THANDHAVAM MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/05/thandavam-movie-stills.html EEGA MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.com/2012/04/eega-movie-stills.html Mem Vayasuku Vacham Latest Hot Stills http://actressgallery-kalyani.blogspot.com/2012/04/mem-vayasuku-vacham-stills.html ILEANA LATEST HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/01/ileana-latest-stills.html ACTREESS SUPRIYA SHAILJA LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/02/supriya-shailja-stills.html SHEELA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/01/sheela-latest-stills.html KATRINA KAIF ITEM SONG STILLS http://actressgallery-kalyani.blogspot.com/2012/01/katrina-kaif-item-song-stills.html RITU KAUR LATEST PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2012/01/ritu-kaur-stills.html SHRUTI HASSAN HOT IN 3 MOVIE http://actressgallery-kalyani.blogspot.com/2011/11/shruti-hassan-in-3-movie.html HOT LINKS FOR YOUTH ONLY PRANEETHA HOT SPICY IMAGES http://actressimages-9.blogspot.in/2012/06/praneetha-latest-stills.html SHRUTHI HASSAN HALF SAREE STILLS http://actressimages-9.blogspot.in/2012/05/shruti-hassan-half-saree-stills.html TAMANNA HOT NAVEL PHOTOS http://actressimages-9.blogspot.in/2012/05/tamanna-navel-photos.html TRISHA LATEST HOT STILLS http://actressgallery9.blogspot.in/2012/05/trisha.html MONIKA LATEST HOT HD STLLS http://actressgallery9.blogspot.in/2012/05/monika-stills.html MALLIKA KAPOOR HOT SIZZLING STILLS http://actressimages-9.blogspot.in/2012/05/mallika-kapoor.html Richa Panai Stills http://actressimages-9.blogspot.com/2012/04/richa-panai-stills.html MADHAVI LATHA LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/04/madhavi-latha-stills.html KRITI KHARBANDA HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/kriti-kharbanda.html NEELAM UPADHYAY HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/neelam-upadhyay.html SAMANTHA LATEST HOT ROMANTIC STILLS http://actressimages-9.blogspot.in/2012/03/samantha-latest-stills.html NAYANTHARA HOT WALLPAPERS http://actressimages-9.blogspot.in/2012/01/nayanthara.html ANU SMRUTHI LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/02/anu-smirthi-stills.html AISHWARYA RAI LATEST HOT PICS http://actressimages-9.blogspot.in/2012/01/aishwarya-rai.html From redstone-cold at 163.com Sat Jul 7 00:56:35 2012 From: redstone-cold at 163.com (iMath) Date: Fri, 6 Jul 2012 21:56:35 -0700 (PDT) Subject: =?windows-1252?Q?What=92s_the_differences_between_these_two__pieces_o?= =?windows-1252?Q?f_code_=3F?= Message-ID: <48fbfc85-c495-4131-a18a-1ebb94e7ce20@googlegroups.com> What?s the differences between these two pieces of code ? (1) for i in range(1, 7): print(2 * i, end=' ') (2) for i in range(1, 7): print(2 * i, end=' ') print() when executed both respectively in Python shell ,I get the same effect . Who can tell me why ? From gherron at digipen.edu Sat Jul 7 01:41:04 2012 From: gherron at digipen.edu (Gary Herron) Date: Fri, 06 Jul 2012 22:41:04 -0700 Subject: =?windows-1252?Q?What=92s_the_differences_between_th?= =?windows-1252?Q?ese_two__pieces_of_code_=3F?= In-Reply-To: <48fbfc85-c495-4131-a18a-1ebb94e7ce20@googlegroups.com> References: <48fbfc85-c495-4131-a18a-1ebb94e7ce20@googlegroups.com> Message-ID: <4FF7CBF0.3030804@digipen.edu> On 07/06/2012 09:56 PM, iMath wrote: > What?s the differences between these two pieces of code ? > (1) > for i in range(1, 7): > print(2 * i, end=' ') > > > (2) > for i in range(1, 7): > print(2 * i, end=' ') > print() > > > when executed both respectively in Python shell ,I get the same effect . Who can tell me why ? What "effect" are you referring to? What did you expect? What did you get? What version of Python? (3 I'd guess). As for me, the first one fails because of a syntax (indentation) error and the second prints the even numbers 2 through 12. What are we supposed to be comparing? Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From frank at chagford.com Sat Jul 7 01:41:26 2012 From: frank at chagford.com (Frank Millman) Date: Sat, 07 Jul 2012 07:41:26 +0200 Subject: Question about weakref In-Reply-To: <4FF72AA3.3070808@stoneleaf.us> References: <87hatmr3xf.fsf@handshake.de> <87a9ze85h2.fsf@handshake.de> <4FF72AA3.3070808@stoneleaf.us> Message-ID: On 06/07/2012 20:12, Ethan Furman wrote: > Ian Kelly wrote: >> def del_b(self, b): >> for i, x in enumerate(self.array): >> if b is x: >> del self.array[i] >> break > > Nice work, Ian. I second that. Thanks very much, Ian. Frank From sdavis.webb at gmail.com Sat Jul 7 01:47:56 2012 From: sdavis.webb at gmail.com (Stephen Webb) Date: Fri, 6 Jul 2012 23:47:56 -0600 Subject: git_revision issues with scipy/numpy/matplotlib Message-ID: I installed py27-numpy / scipy / matplotlib using macports, and it ran without failing. When I run Python I get the following error: $>> which python /Library/Frameworks/Python.framework/Versions/2.7/bin/python $>> python Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/__init__.py", line 128, in from version import git_revision as __git_revision__ ImportError: cannot import name git_revision I get the same error for all three packages. Is this a MacPorts issue or a different issue? I am running OS X 10.6 with the Intel Core i5 architecture. At one point I thought this was a 64-bit versus 32-bit issue, viz.: >>> import platform >>> platform.architecture() ('64bit', '') but I would have thought the MacPorts install would have resolved that. Any help would be appreciated. Thanks! -s From howmuchistoday at gmail.com Sat Jul 7 03:09:32 2012 From: howmuchistoday at gmail.com (self.python) Date: Sat, 7 Jul 2012 00:09:32 -0700 (PDT) Subject: why greenlet, gevent or the stackless are needed? Message-ID: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> (I'm very new to this coroutine part so It's not supposed to attack these modules, just I don't know the differences) atfer version 2.5, python officially support coroutine with yield. and then, why greenlet, gevent, Stackless python are still useful? it there somthing that "yield" can't do or just it is easier or powerful? From steve+comp.lang.python at pearwood.info Sat Jul 7 03:21:41 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 07 Jul 2012 07:21:41 GMT Subject: =?iso-8859-7?q?What=A2s?= the differences between these two pieces of code ? References: <48fbfc85-c495-4131-a18a-1ebb94e7ce20@googlegroups.com> Message-ID: <4ff7e384$0$29988$c3e8da3$5496439d@news.astraweb.com> On Fri, 06 Jul 2012 21:56:35 -0700, iMath wrote: > What?s the differences between these two pieces of code ? Have you tried it? What do you see? Obviously the difference is that the second piece calls print() at the end, and the first does not. Since the for-loops are identical, we can ignore them. The difference between the two pieces of code is the same as between (1) (do nothing at all) and (2) call print() which should be obvious: doing nothing does nothing. Calling print() prints a blank line. More details below. > (1) > for i in range(1, 7): > print(2 * i, end=' ') > > > (2) > for i in range(1, 7): > print(2 * i, end=' ') > print() > > > when executed both respectively in Python shell ,I get the same > effect . Who can tell me why ? No you don't get the same effect. At least not with the code as given. The first gives a SyntaxError, as the indentation is missing. If you fix that problem by inserting the appropriate indentation, it prints the even numbers from 2 to 12, ending each number with a triple space ' ' instead of a newline so they all appear on the same line. Because no newline gets printed, the prompt appears on the same line: py> for i in range(1, 7): ... print(2 * i, end=' ') ... 2 4 6 8 10 12 py> (Notice that I use "py>" as my prompt instead of ">>>".) The second one as given also gives a SyntaxError, due to a limitation of the Python interactive interpreter. (When you outdent a level, you need to leave a blank line. The non-interactive interpreter does not have this limitation.) Fixing that problem by inserting a blank line, you get exactly the same numbers printed (of course! the for loops are identical), except at the end, after the for-loop has finished, you also call print(), which gives you this output: py> for i in range(1, 7): ... print(2 * i, end=' ') ... 2 4 6 8 10 12 py> print() py> Notice the blank line printed? -- Steven From jeanpierreda at gmail.com Sat Jul 7 03:33:26 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 7 Jul 2012 03:33:26 -0400 Subject: why greenlet, gevent or the stackless are needed? In-Reply-To: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> References: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> Message-ID: On Sat, Jul 7, 2012 at 3:09 AM, self.python wrote: > it there somthing that "yield" can't do > or just it is easier or powerful? couroutine-like generators can't give up control flow unless they are the top level function handled by the coroutine controller thing. For example, we can do this: def foo(): while True: next_value = (yield) print next_value But we can't do this: def yap(): next_value = (yield) print next_value def foo(): while True: yap() If we explicitly say that "yap" can control us, via "yield from" (new in Python 3.3), then we can do something like the above, but this still requires explicit markup. In all other releases of Python, this is impossible. On the other hand, coroutines in greenlet et al can do a coroutine context switch at any point. The upside is that this is more flexible (and does something generators pre-3.3 cannot). The downside is that you now need locking structures to guarantee atomic interactions with a shared resource, whereas with generators you know that you always are the sole thing running, until you do a yield (and unless real threads or greenlet or whatever are involved, of course.) -- Devin From howmuchistoday at gmail.com Sat Jul 7 04:29:11 2012 From: howmuchistoday at gmail.com (self.python) Date: Sat, 7 Jul 2012 01:29:11 -0700 (PDT) Subject: why greenlet, gevent or the stackless are needed? In-Reply-To: References: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> Message-ID: r 2012? 7? 7? ??? ?? 4? 33? 26? UTC+9, Devin Jeanpierre ?? ?: > On Sat, Jul 7, 2012 at 3:09 AM, self.python wrote: > > it there somthing that "yield" can't do > > or just it is easier or powerful? > > couroutine-like generators can't give up control flow unless they are > the top level function handled by the coroutine controller thing. For > example, we can do this: > > def foo(): > while True: > next_value = (yield) > print next_value > > But we can't do this: > > def yap(): > next_value = (yield) > print next_value > > def foo(): > while True: > yap() > > If we explicitly say that "yap" can control us, via "yield from" (new > in Python 3.3), then we can do something like the above, but this > still requires explicit markup. In all other releases of Python, this > is impossible. > > On the other hand, coroutines in greenlet et al can do a coroutine > context switch at any point. The upside is that this is more flexible > (and does something generators pre-3.3 cannot). The downside is that > you now need locking structures to guarantee atomic interactions with > a shared resource, whereas with generators you know that you always > are the sole thing running, until you do a yield (and unless real > threads or greenlet or whatever are involved, of course.) > > -- Devin first, thanks for good answer:) but I don't understand why the code def yap(): next_value = (yield) print next_value def foo(): while True: yap() really do. what is the purpose of that code? From howmuchistoday at gmail.com Sat Jul 7 04:29:11 2012 From: howmuchistoday at gmail.com (self.python) Date: Sat, 7 Jul 2012 01:29:11 -0700 (PDT) Subject: why greenlet, gevent or the stackless are needed? In-Reply-To: References: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> Message-ID: r 2012? 7? 7? ??? ?? 4? 33? 26? UTC+9, Devin Jeanpierre ?? ?: > On Sat, Jul 7, 2012 at 3:09 AM, self.python wrote: > > it there somthing that "yield" can't do > > or just it is easier or powerful? > > couroutine-like generators can't give up control flow unless they are > the top level function handled by the coroutine controller thing. For > example, we can do this: > > def foo(): > while True: > next_value = (yield) > print next_value > > But we can't do this: > > def yap(): > next_value = (yield) > print next_value > > def foo(): > while True: > yap() > > If we explicitly say that "yap" can control us, via "yield from" (new > in Python 3.3), then we can do something like the above, but this > still requires explicit markup. In all other releases of Python, this > is impossible. > > On the other hand, coroutines in greenlet et al can do a coroutine > context switch at any point. The upside is that this is more flexible > (and does something generators pre-3.3 cannot). The downside is that > you now need locking structures to guarantee atomic interactions with > a shared resource, whereas with generators you know that you always > are the sole thing running, until you do a yield (and unless real > threads or greenlet or whatever are involved, of course.) > > -- Devin first, thanks for good answer:) but I don't understand why the code def yap(): next_value = (yield) print next_value def foo(): while True: yap() really do. what is the purpose of that code? From mspadaccino at gmail.com Sat Jul 7 05:05:08 2012 From: mspadaccino at gmail.com (Maurizio Spadaccino) Date: Sat, 7 Jul 2012 11:05:08 +0200 Subject: Which way is best to execute a Python script in Excel? Message-ID: <24250F59-4B83-45AC-BF85-BFC6476A18C3@gmail.com> Thanks again Emile, I'll try out some examples. I found this one: http://showmedo.com/videotutorials/video?name=2190050&fromSeriesID=219 quite enlightning. One last doubt is: say the python code gets used by more Excel Users (different pc), can I include in some way a dinamic generation of the id in order to allow each pc to register is own COM server or do I have to hard code the id on each machine specifically? From t at jollybox.de Sat Jul 7 05:38:10 2012 From: t at jollybox.de (Thomas Jollans) Date: Sat, 07 Jul 2012 11:38:10 +0200 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <24250F59-4B83-45AC-BF85-BFC6476A18C3@gmail.com> References: <24250F59-4B83-45AC-BF85-BFC6476A18C3@gmail.com> Message-ID: <4FF80382.8060504@jollybox.de> On 07/07/2012 11:05 AM, Maurizio Spadaccino wrote: > Thanks again Emile, I'll try out some examples. I found this one: http://showmedo.com/videotutorials/video?name=2190050&fromSeriesID=219 > quite enlightning. > One last doubt is: say the python code gets used by more Excel Users (different pc), can I include in some way a dinamic generation of the id in order to allow each pc to register is own COM server or do I have to hard code the id on each machine specifically? > It sounds like you're misunderstanding what's going on: COM is not network transparent by nature. Separate PCs are completely separate unless you explicitly create a connection. Apart from that, it looks like this is a UUID. See http://docs.python.org/library/uuid.html From dmitrey15 at gmail.com Sat Jul 7 05:44:06 2012 From: dmitrey15 at gmail.com (dmitrey) Date: Sat, 7 Jul 2012 02:44:06 -0700 (PDT) Subject: Stochastic programming and optimization addon for FuncDesigner Message-ID: hi all, you may be interested in stochastic programming and optimization with free Python module FuncDesigner ( http://openopt.org/FuncDesigner ). We have wrote Stochastic addon for FuncDesigner ( http://openopt.org/StochasticProgramming ), but (at least for several years) it will be commercional (currently it's free for some small-scaled problems only and for noncommercial research / educational purposes only). However, we will try to keep our prices several times less than our competitors have. Also, we will provide some discounts, including region-based ones, and first 15 customers will also got a discount. For further information, documentation and some examples etc read more at http://openopt.org/StochasticProgramming ---------------------------- Regards, D. http://openopt.org/Dmitrey From t at jollybox.de Sat Jul 7 05:50:05 2012 From: t at jollybox.de (Thomas Jollans) Date: Sat, 07 Jul 2012 11:50:05 +0200 Subject: PyEval_SetProfile usage ? In-Reply-To: References: Message-ID: <4FF8064D.4000508@jollybox.de> On 07/06/2012 11:40 PM, Salman Malik wrote: > Hi All, > > I have used the Python's C-API to call some Python code in my c code and > now I want to know how much time does my Python part of the program > takes. I came across the PyEval_SetProfile API and am not sure how to > use it. Do I need to write my own profiling function? You could have a look at the source code of the cProfile extension module. I assume it uses the feature. In your case, what's wrong with simply measuring the time? /* variables. */ unsigned long delta_usec; struct timeval t1, t2; /* get start time */ gettimeofday (&t1, NULL); /* DO PYTHON STUFF */ /* get end time */ gettimeofday (&t2, NULL); /* delta? */ delta_usec = (t2.tv_sec - t1.tv_sec) * 1000 + (signed)(t2.tv_usec - t1.tv_usec); /* if your Python code is called multiple times, do this for each one, and (if you like) sum up the result. It's simpe enough, and you don't have to mess with profiling function. Alternatively, you could use a C profiler like Valgrind */ From darragh.ssa at gmail.com Sat Jul 7 05:58:44 2012 From: darragh.ssa at gmail.com (Kruptein) Date: Sat, 7 Jul 2012 02:58:44 -0700 (PDT) Subject: Deditor 0.4.0 Message-ID: Hey I released a new version of my python-focused text-editor. you can download it at http://launchpad.net/deditor What is it? Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. I focus on making it a python specific editor but you can use it to edit other files as well. It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. I hope some of you like it and if you don't try to give some constructive criticism :) Most changes in regard to previous release are under the hood. so existing users might not notice a lot. Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p From hansmu at xs4all.nl Sat Jul 7 06:18:45 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Sat, 07 Jul 2012 12:18:45 +0200 Subject: git_revision issues with scipy/numpy/matplotlib In-Reply-To: References: Message-ID: <4ff80d06$0$6909$e4fe514c@news2.news.xs4all.nl> On 7/07/12 07:47:56, Stephen Webb wrote: > I installed py27-numpy / scipy / matplotlib using macports, and it ran without failing. > > When I run Python I get the following error: > > $>> which python > > /Library/Frameworks/Python.framework/Versions/2.7/bin/python That's a python from python.org, not from MacPorts. > $>> python > > Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import numpy > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/__init__.py", line 128, in > from version import git_revision as __git_revision__ > ImportError: cannot import name git_revision > > I get the same error for all three packages. Is this a MacPorts issue or a different issue? You have (at least) three pythons on your Mac: one from Apple in /usr/bin, one from python.org (the one you found) and one from MacPorts in /opt/local/bin/python You may want to add /opt/local/bin to the front of your PATH; that will also pick up the MacPorts version of other software you've installed from MacPorts. Or you can explicitly type the full path of the python you want. Or you can define aliases, for example: alias apple_python=/usr/bin/python alias macport_python=/opt/local/bin/python lfpv=/Library/Frameworks/Python.framework/Versions alias python_org_python=$lfpv/2.7/bin/python Hope this helps, -- HansM From kwame.asamoah.tekyi at gmail.com Sat Jul 7 07:30:50 2012 From: kwame.asamoah.tekyi at gmail.com (kwame.asamoah.tekyi at gmail.com) Date: Sat, 7 Jul 2012 04:30:50 -0700 (PDT) Subject: IDLE won't wrap lines of text In-Reply-To: References: Message-ID: i think i understand the question... see when u doing django and u have use the views.py to respond to request in html form,,, its hard to wrap the html codes in idle.. On Sunday, February 20, 2011 11:54:36 PM UTC, Terry Reedy wrote: > On 2/19/2011 6:56 PM, Richard D. Moores wrote: > > Vista > > Python 3.1.3 > > > > I can't figure out how to get IDLE to wrap text pasted in from, say, a > > newspaper article. Usually, a each paragraph will appear as one long > > unwrapped line, with no way to read the whole line, because no > > horizontal bar is created. I haven't found anything about this in > > either the options or the help. > > The IDLE editor was designed for writing Python code, not general text. > It is expected that you will limit line lengths to what can be seen on > your screen. > > -- > Terry Jan Reedy From kwame.asamoah.tekyi at gmail.com Sat Jul 7 07:30:50 2012 From: kwame.asamoah.tekyi at gmail.com (kwame.asamoah.tekyi at gmail.com) Date: Sat, 7 Jul 2012 04:30:50 -0700 (PDT) Subject: IDLE won't wrap lines of text In-Reply-To: References: Message-ID: i think i understand the question... see when u doing django and u have use the views.py to respond to request in html form,,, its hard to wrap the html codes in idle.. On Sunday, February 20, 2011 11:54:36 PM UTC, Terry Reedy wrote: > On 2/19/2011 6:56 PM, Richard D. Moores wrote: > > Vista > > Python 3.1.3 > > > > I can't figure out how to get IDLE to wrap text pasted in from, say, a > > newspaper article. Usually, a each paragraph will appear as one long > > unwrapped line, with no way to read the whole line, because no > > horizontal bar is created. I haven't found anything about this in > > either the options or the help. > > The IDLE editor was designed for writing Python code, not general text. > It is expected that you will limit line lengths to what can be seen on > your screen. > > -- > Terry Jan Reedy From johnpote at jptechnical.co.uk Sat Jul 7 08:03:27 2012 From: johnpote at jptechnical.co.uk (John Pote) Date: Sat, 07 Jul 2012 13:03:27 +0100 Subject: select module missing/corrupt Message-ID: We are using a virtual web server running some version of Unix. It has Python versions 2.4,2.6 and 3.1 pre-installed. (BTW the intention is to use Python for a CGI script.) When my script imports subprocess I get the traceback File "/usr/lib/python2.6/subprocess.py", line 427, in import select ImportError: No module named select On searching the Python installation I found what I presume is the select module library file /usr/lib/python2.6/lib-dynload/select_failed.so whereas in the 2.4 installation the file is /usr/lib/python2.4/lib-dynload/select.so and subprocess imports OK. Anyone know why the version 2.6 select .so file should be renamed select_failed.so and so not able to be imported? Of interest the 3.1 installation also has the select module file re-named select_failed.so. Any help appreciated, Regards, John Pote --- Posted via news://freenews.netfront.net/ - Complaints to news at netfront.net --- From ousmane at wilane.org Sat Jul 7 08:09:56 2012 From: ousmane at wilane.org (Ousmane Wilane) Date: Sat, 07 Jul 2012 14:09:56 +0200 Subject: git_revision issues with scipy/numpy/matplotlib In-Reply-To: <4ff80d06$0$6909$e4fe514c@news2.news.xs4all.nl> References: <4ff80d06$0$6909$e4fe514c@news2.news.xs4all.nl> Message-ID: <87zk7bg4bv.wl%ousmane@wilane.org> >>>>> "H" == Hans Mulder writes: H> Or you can explicitly type the full path of the python you want. H> Or you can define aliases, for example: H> alias apple_python=/usr/bin/python alias H> macport_python=/opt/local/bin/python H> lfpv=/Library/Frameworks/Python.framework/Versions alias H> python_org_python=$lfpv/2.7/bin/python Or alternatively use `port select --set' to make one of the MacPort version the default: imac:~ wilane$ port select --list python Available versions for python: none python25-apple python26 python26-apple python27 (active) python27-apple python32 Cheers -- Ousmane From emile at fenx.com Sat Jul 7 10:31:07 2012 From: emile at fenx.com (Emile van Sebille) Date: Sat, 07 Jul 2012 07:31:07 -0700 Subject: Which way is best to execute a Python script in Excel? In-Reply-To: <24250F59-4B83-45AC-BF85-BFC6476A18C3@gmail.com> References: <24250F59-4B83-45AC-BF85-BFC6476A18C3@gmail.com> Message-ID: On 7/7/2012 2:05 AM Maurizio Spadaccino said... > Thanks again Emile, I'll try out some examples. I found this one: http://showmedo.com/videotutorials/video?name=2190050&fromSeriesID=219 > quite enlightning. > One last doubt is: say the python code gets used by more Excel Users (different pc), can I include in some way a dinamic generation of the id in order to allow each pc to register is own COM server or do I have to hard code the id on each machine specifically? > Here's how to generate an ID, but it's likely not to occur on other machines. >>> import pythoncom; print pythoncom.CreateGuid() {CE571F2A-6BD8-4A8D-9482-4EC02FAC171E} There's an interesting perspective on uniqueness of guid's at http://betterexplained.com/articles/the-quick-guide-to-guids/ So, create it once and hardcode it in. If you provide new features in a subsequent version you may want to issue a new guid, particularly to develop a new version while still running the old on the same machine. Each user will then need to have python and pythonwin installed, then run your com server to execute the com server registration piece in the "if __name__ == '__main__'" part of things. Emile From hansmu at xs4all.nl Sat Jul 7 10:40:59 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Sat, 07 Jul 2012 16:40:59 +0200 Subject: git_revision issues with scipy/numpy/matplotlib In-Reply-To: <87zk7bg4bv.wl%ousmane@wilane.org> References: <4ff80d06$0$6909$e4fe514c@news2.news.xs4all.nl> <87zk7bg4bv.wl%ousmane@wilane.org> Message-ID: <4ff84a7c$0$6878$e4fe514c@news2.news.xs4all.nl> On 7/07/12 14:09:56, Ousmane Wilane wrote: >>>>>> "H" == Hans Mulder writes: > > H> Or you can explicitly type the full path of the python you want. > > H> Or you can define aliases, for example: > > H> alias apple_python=/usr/bin/python alias > H> macport_python=/opt/local/bin/python > > H> lfpv=/Library/Frameworks/Python.framework/Versions alias > H> python_org_python=$lfpv/2.7/bin/python > > > Or alternatively use `port select --set' to make one of the MacPort version the > default: > > imac:~ wilane$ port select --list python > Available versions for python: > none > python25-apple > python26 > python26-apple > python27 (active) > python27-apple > python32 That would work if the OP had /opt/local/bin early in his searcht path. However, the OP has installed Python27 from python.org, and that has prepended /Library/Frameworks/Python.framework/Versions/2.7/bin to his PATH, overriding anything he does with "port select". He could, of course, change his PATH and move /opt/local/bin to the front and then use "port select". -- HansM From emile at fenx.com Sat Jul 7 10:45:15 2012 From: emile at fenx.com (Emile van Sebille) Date: Sat, 07 Jul 2012 07:45:15 -0700 Subject: select module missing/corrupt In-Reply-To: References: Message-ID: On 7/7/2012 5:03 AM John Pote said... > We are using a virtual web server running some version of Unix. It has > Python versions 2.4,2.6 and 3.1 pre-installed. > > (BTW the intention is to use Python for a CGI script.) > > When my script imports subprocess I get the traceback > File "/usr/lib/python2.6/subprocess.py", line 427, in > import select > ImportError: No module named select > > On searching the Python installation I found what I presume is the > select module library file > > /usr/lib/python2.6/lib-dynload/select_failed.so > > whereas in the 2.4 installation the file is > /usr/lib/python2.4/lib-dynload/select.so > and subprocess imports OK. > > Anyone know why the version 2.6 select .so file should be renamed > select_failed.so and so not able to be imported? When python builds, modules that don't build cleanly get renamed [module]_failed. See http://mail.python.org/pipermail/python-dev/2002-March/020568.html for more info. Emile > > Of interest the 3.1 installation also has the select module file > re-named select_failed.so. > > Any help appreciated, > > Regards, > John Pote > > > --- Posted via news://freenews.netfront.net/ - Complaints to > news at netfront.net --- From k.sahithi2862 at gmail.com Sat Jul 7 10:58:09 2012 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Sat, 7 Jul 2012 07:58:09 -0700 (PDT) Subject: BEST HOT PHOTOS & VIDEOS & iINTERVIEW QUESTIONS Message-ID: <3263dd15-114e-4ad5-9415-f6d51e395ad1@l6g2000pbi.googlegroups.com> ALL INTERVIEW QUESTIONS& STUDY MATERIAL http://newdotnetinterviewquestions.blogspot.in/ TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING http://datingsitesdatingtips.blogspot.in/ FOR LATEST MOVIE UPDATED LINKS ADE PREMA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/ade-prema-stills.html HANSIKA MOTWANI LATEST HOT PICS http://actressgallery-kalyani.blogspot.in/2012/07/hansika-motwani-actress.html HOT NEETHU CHANDRA LATEST PICS http://actressgallery-kalyani.blogspot.in/2012/07/neetu-chandra-actress.html ACTRESS AMRUTHA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/amrutha-actress.html SELATHUPONNU MOVIE HOT PHOTOS http://actressgallery-kalyani.blogspot.in/2012/07/selathuponnu-movie-stills.html SULAGNA PANIGRAHI HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/06/sulagna-panigrahi-actress.html RUBY PARIHAR HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.com/2012/06/actress-ruby-parihar.html ACTRESS YAMI GOUTHAM LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/06/yami-gautam-actress.html ACTRESS HOT STILLS IN SIIMA AWARDS 2012 http://actressgallery-kalyani.blogspot.in/2012/06/actress-siima-awards-2012-stills.html EM BABU LADDU KAVALA MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/06/em-babu-laddu-kavala-movie-stills.html SRMANARAYANA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/06/srimannarayana-movie-stills.html KAJAL AGARWAL LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/06/kajal-agarwal-latest-stills.html SANA KHAN LATEST HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/sana-khan-latest-stills.html COOL BOYS HOT GIRLS MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/06/cool-boys-hot-girls-movie-stills.html MITAAYI MOVIE LATEST GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/mitaayi-movie-stills.html NAGARJUNA DAMARUKAM MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/damarukam-movie-stills.html ALLU ARJUN JULAYI MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/julayi-movie-stills.html SUDIGADU MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/sudigadu-movie-stills.html MR 7 MOVIE FILM GALLERY http://actressgallery-kalyani.blogspot.in/2012/05/mr7-movie-stills.html ALL THE BEST MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/all-best-movie-stills.html Midatha Telugu movie Hot Namitha Stills http://actressgallery-kalyani.blogspot.com/2012/05/midatha-movie-stills.html OKA COLLEGE LOVE STORY MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/oka-college-love-story-movie-stills.html KATRINA KAIF LATEST UNSEENED PHOTOS http://actressgallery-kalyani.blogspot.com/2012/05/katrina-kaif-latest-pics.html TAMIL ACTRESS ARUNDHATI HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/05/arundhati-tamil-actress.html THANDHAVAM MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/05/thandavam-movie-stills.html EEGA MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.com/2012/04/eega-movie-stills.html Mem Vayasuku Vacham Latest Hot Stills http://actressgallery-kalyani.blogspot.com/2012/04/mem-vayasuku-vacham-stills.html ILEANA LATEST HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/01/ileana-latest-stills.html ACTREESS SUPRIYA SHAILJA LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/02/supriya-shailja-stills.html SHEELA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/01/sheela-latest-stills.html KATRINA KAIF ITEM SONG STILLS http://actressgallery-kalyani.blogspot.com/2012/01/katrina-kaif-item-song-stills.html RITU KAUR LATEST PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2012/01/ritu-kaur-stills.html SHRUTI HASSAN HOT IN 3 MOVIE http://actressgallery-kalyani.blogspot.com/2011/11/shruti-hassan-in-3-movie.html HOT LINKS FOR YOUTH ONLY PRANEETHA HOT SPICY IMAGES http://actressimages-9.blogspot.in/2012/06/praneetha-latest-stills.html SHRUTHI HASSAN HALF SAREE STILLS http://actressimages-9.blogspot.in/2012/05/shruti-hassan-half-saree-stills.html TAMANNA HOT NAVEL PHOTOS http://actressimages-9.blogspot.in/2012/05/tamanna-navel-photos.html TRISHA LATEST HOT STILLS http://actressgallery9.blogspot.in/2012/05/trisha.html MONIKA LATEST HOT HD STLLS http://actressgallery9.blogspot.in/2012/05/monika-stills.html MALLIKA KAPOOR HOT SIZZLING STILLS http://actressimages-9.blogspot.in/2012/05/mallika-kapoor.html Richa Panai Stills http://actressimages-9.blogspot.com/2012/04/richa-panai-stills.html MADHAVI LATHA LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/04/madhavi-latha-stills.html KRITI KHARBANDA HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/kriti-kharbanda.html NEELAM UPADHYAY HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/neelam-upadhyay.html SAMANTHA LATEST HOT ROMANTIC STILLS http://actressimages-9.blogspot.in/2012/03/samantha-latest-stills.html NAYANTHARA HOT WALLPAPERS http://actressimages-9.blogspot.in/2012/01/nayanthara.html ANU SMRUTHI LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/02/anu-smirthi-stills.html AISHWARYA RAI LATEST HOT PICS http://actressimages-9.blogspot.in/2012/01/aishwarya-rai.html From gdamjan at gmail.com Sat Jul 7 11:38:53 2012 From: gdamjan at gmail.com (Damjan) Date: Sat, 07 Jul 2012 17:38:53 +0200 Subject: why greenlet, gevent or the stackless are needed? In-Reply-To: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> References: <456501fb-af2d-4741-9b73-33c65d7f0aa8@t1g2000pbl.googlegroups.com> Message-ID: On 07.07.2012 09:09, self.python wrote: > (I'm very new to this coroutine part > so It's not supposed to attack these modules, > just I don't know the differences) > > atfer version 2.5, python officially support coroutine with yield. > and then, why greenlet, gevent, Stackless python are still useful? > > it there somthing that "yield" can't do > or just it is easier or powerful? The greenlet site has some very simple examples what it can provide. For example jumping from one function in another, and back http://greenlet.readthedocs.org/en/latest/index.html Gevent then uses greenlet to do lightweight "processes" (greenlets) that are I/O scheduled. This allows for a simple model of programming that scales to a large number of concurrent connections. You could do that with threads but you can't start as many threads as greenlets, since they have a much larger memory address space footprint. There's one function, called the gevent hub, that waits for any I/O event and then switches to the function that "blocked" on that I/O. -- damjan From sdavis.webb at gmail.com Sat Jul 7 11:57:10 2012 From: sdavis.webb at gmail.com (Stephen Webb) Date: Sat, 7 Jul 2012 09:57:10 -0600 Subject: git_revision issues with scipy/numpy/matplotlib In-Reply-To: <4ff84a7c$0$6878$e4fe514c@news2.news.xs4all.nl> References: <4ff80d06$0$6909$e4fe514c@news2.news.xs4all.nl> <87zk7bg4bv.wl%ousmane@wilane.org> <4ff84a7c$0$6878$e4fe514c@news2.news.xs4all.nl> Message-ID: I think the easiest thing to do would be to remove the python.org Python entirely, kill it from the path (which I've already done), and install directly a MacPorts version of Python. Any caveats or warnings about getting rid of the /Library/Frameworks/Python.... directory? On Jul 7, 2012, at Jul 7 8:40 AM, Hans Mulder wrote: > On 7/07/12 14:09:56, Ousmane Wilane wrote: >>>>>>> "H" == Hans Mulder writes: >> >> H> Or you can explicitly type the full path of the python you want. >> >> H> Or you can define aliases, for example: >> >> H> alias apple_python=/usr/bin/python alias >> H> macport_python=/opt/local/bin/python >> >> H> lfpv=/Library/Frameworks/Python.framework/Versions alias >> H> python_org_python=$lfpv/2.7/bin/python >> >> >> Or alternatively use `port select --set' to make one of the MacPort version the >> default: >> >> imac:~ wilane$ port select --list python >> Available versions for python: >> none >> python25-apple >> python26 >> python26-apple >> python27 (active) >> python27-apple >> python32 > > That would work if the OP had /opt/local/bin early in his searcht path. > However, the OP has installed Python27 from python.org, and that has > prepended /Library/Frameworks/Python.framework/Versions/2.7/bin to > his PATH, overriding anything he does with "port select". > > He could, of course, change his PATH and move /opt/local/bin to the > front and then use "port select". > > -- HansM > -- > http://mail.python.org/mailman/listinfo/python-list From t at jollybox.de Sat Jul 7 12:12:54 2012 From: t at jollybox.de (Thomas Jollans) Date: Sat, 07 Jul 2012 18:12:54 +0200 Subject: Socket code not executing properly in a thread (Windows) In-Reply-To: References: Message-ID: <4FF86006.4020607@jollybox.de> On 07/08/2012 12:55 PM, Andrew D'Angelo wrote: Please set your clock to the correct date and time. > (If it would help, the > full code can be seen here: http://lickitung.it.cx/exe/bot/bot.py): No, it can't. > def sendPrivateMessage(channel, message):#private message send function > > global mute > > if mute == 0: > > IRC.send("PRIVMSG " + channel + " :" + message + "\r\n") #IRC being > the socket Do you have an error message or something? Without knowing more about the IRC library you're using, it's hard to say what the reason behind the platform-dependent behaviour is. However, it's clear that you should be calling IRC.send from the main thread. That shouldn't be too hard to achieve, save the message to some sort of event or outgoing message queue that the main thread processes in sequence. (This sounds to me like an application better implemented thread-less, using select() or some method of asynchronous I/O. Just a shame that Python makes neither at all pleasant and leaves threads as the nicest option) Thomas From excel at pharcyde.org Sat Jul 7 12:33:29 2012 From: excel at pharcyde.org (Andrew D'Angelo) Date: Sat, 7 Jul 2012 11:33:29 -0500 Subject: Socket code not executing properly in a thread (Windows) References: Message-ID: "Thomas Jollans" wrote in message news:mailman.1895.1341677582.4697.python-list at python.org... > On 07/08/2012 12:55 PM, Andrew D'Angelo wrote: > > Please set your clock to the correct date and time. My BIOS battery has died and I haven't gotten a chance to replace it. Made a mistake when setting the date on boot-up. :-\ > Do you have an error message or something? No, it simply does not send the message. > Without knowing more about the IRC library you're using I am sending plain text to the socket, without a library. > However, > it's clear that you should be calling IRC.send from the main thread. > That shouldn't be too hard to achieve, save the message to some sort of > event or outgoing message queue that the main thread processes in > sequence. Good idea, thanks. From levinie001 at gmail.com Sat Jul 7 13:23:12 2012 From: levinie001 at gmail.com (levi nie) Date: Sun, 8 Jul 2012 01:23:12 +0800 Subject: something go wrongly Message-ID: my code: aList=[1,2,3,4,5,6,7,8,9,10] xList=[1,2,3] print "now aList is",aList.extend(xList) output: now aList is None what i want is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3] -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Jul 7 13:35:49 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 7 Jul 2012 10:35:49 -0700 Subject: something go wrongly In-Reply-To: References: Message-ID: On Sat, Jul 7, 2012 at 10:23 AM, levi nie wrote: > my code: > > aList=[1,2,3,4,5,6,7,8,9,10] > xList=[1,2,3] > print "now aList is",aList.extend(xList) > > output: > now aList is None > > what i want is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3] See http://stackoverflow.com/a/1682601 list.extend(), list.append(), etc. operate in-place, mutating the existing list object. Such methods return None to emphasize that they do not create new lists. Regards, Chris From levinie001 at gmail.com Sat Jul 7 13:51:38 2012 From: levinie001 at gmail.com (levi nie) Date: Sun, 8 Jul 2012 01:51:38 +0800 Subject: something go wrongly In-Reply-To: References: Message-ID: Thanks, Such methods return None to emphasize that they do not create new lists. i got it. 2012/7/8 Chris Rebert > On Sat, Jul 7, 2012 at 10:23 AM, levi nie wrote: > > my code: > > > > aList=[1,2,3,4,5,6,7,8,9,10] > > xList=[1,2,3] > > print "now aList is",aList.extend(xList) > > > > output: > > now aList is None > > > > what i want is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3] > > See http://stackoverflow.com/a/1682601 > list.extend(), list.append(), etc. operate in-place, mutating the > existing list object. Such methods return None to emphasize that they > do not create new lists. > > Regards, > Chris > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ask at celeryproject.org Sat Jul 7 14:26:08 2012 From: ask at celeryproject.org (Ask Solem) Date: Sat, 7 Jul 2012 19:26:08 +0100 Subject: ANN: Celery 3.0 (chiastic slide) released! Message-ID: <1FE2BDEA-E4F2-45E9-9D18-2A78B43D57B6@celeryproject.org> =========================================== Celery 3.0 (Chiastic Slide) Released! =========================================== Celery is a simple, flexible and reliable distributed system to process vast amounts of messages, while providing operations with the tools required to maintain such a system. It's a task queue with focus on real-time processing, while also supporting task scheduling. Celery has a large and diverse community of users and contributors, you should come join us on IRC (freenode.net: #celery) or our mailing-list (http://groups.google.com/group/celery-users). To read more about Celery you should go read the introduction: - http://docs.celeryproject.org/en/latest/getting-started/introduction.html If you use Celery in combination with Django you must also read the django-celery changelog and upgrade to django-celery 3.0 - http://github.com/celery/django-celery/tree/master/Changelog This version is officially supported on CPython 2.5, 2.6, 2.7, 3.2 and 3.3, as well as PyPy and Jython. /* You should read the full changelog which contains important notes at: - http://docs.celeryproject.org/en/latest/whatsnew-3.0.html */ Highlights ========== - A new and improved API, that is both simpler and more powerful. Everyone must read the new "first-steps" tutorial, and the new "next-steps" tutorial - http://bit.ly/celery-first-steps - http://bit.ly/celery-next-steps Oh, and why not reread the user guide while you're at it :) There are no current plans to deprecate the old API, so you don't have to be in a hurry to port your applications. - The worker is now thread-less, giving great performance improvements. - The new "Canvas" makes it easy to define complex workflows. Ever wanted to chain tasks together? This is possible, but not just that, now you can even chain together groups and chords, or even combine multiple chains. Read more in the Canvas user guide: - http://docs.celeryproject.org/en/latest/userguide/canvas.html - All of Celery's command line programs are now available from a single umbrella command: ``celery``. - This is the last version to support Python 2.5. Starting with Celery 3.1, Python 2.6 or later is required. - Support for the new librabbitmq C client. Celery will automatically use the librabbitmq module if installed, which is a very fast and memory-optimized replacement for the amqplib module. - Redis support is more reliable with improved ack emulation. - Celery now always uses UTC - Over 600 commits, 30k additions/36k deletions. In comparison 1.0 to 2.0 had 18k additions/8k deletions. Thank you to all users and contributors! - http://celeryproject.org/ -- Ask Solem twitter.com/asksol | +44 (0)7713357179 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 495 bytes Desc: Message signed with OpenPGP using GPGMail URL: From salmanmk at live.com Sat Jul 7 15:09:29 2012 From: salmanmk at live.com (Salman Malik) Date: Sat, 7 Jul 2012 14:09:29 -0500 Subject: PyEval_SetProfile usage ? In-Reply-To: <4FF8064D.4000508@jollybox.de> References: , <4FF8064D.4000508@jollybox.de> Message-ID: Thanks Thomas! I will try the timer code that you provided. I have tried profiling with just wrapping the python code with cprofiler's runctx but the problem is that my python code is sort of a packet parser and is called for each packet, but when I see the profiled results it appears that the profile gets rewritten for each packet and I can't see the aggregate result: I see 1-2 calls per function and each call is shown to have taken 0.00 time. I have also tried valgrind's callgrind in conjunction with kcachegrind but it doesn't seem to show time measurement and by some reading I learned that it gives the CPU cycle's per function and not time. Any suggestions in this regard will also be very helpful.. Thanks! Salman > Date: Sat, 7 Jul 2012 11:50:05 +0200 > From: t at jollybox.de > To: python-list at python.org > Subject: Re: PyEval_SetProfile usage ? > > On 07/06/2012 11:40 PM, Salman Malik wrote: > > Hi All, > > > > I have used the Python's C-API to call some Python code in my c code and > > now I want to know how much time does my Python part of the program > > takes. I came across the PyEval_SetProfile API and am not sure how to > > use it. Do I need to write my own profiling function? > > You could have a look at the source code of the cProfile extension > module. I assume it uses the feature. > > In your case, what's wrong with simply measuring the time? > > > /* variables. */ > unsigned long delta_usec; > struct timeval t1, t2; > > /* get start time */ > gettimeofday (&t1, NULL); > > /* DO PYTHON STUFF */ > > /* get end time */ > gettimeofday (&t2, NULL); > > /* delta? */ > delta_usec = (t2.tv_sec - t1.tv_sec) * 1000 > + (signed)(t2.tv_usec - t1.tv_usec); > > /* if your Python code is called multiple times, do this for each one, > and (if you like) sum up the result. It's simpe enough, and you > don't have to mess with profiling function. > Alternatively, you could use a C profiler like Valgrind > */ > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sat Jul 7 15:17:00 2012 From: nagle at animats.com (John Nagle) Date: Sat, 07 Jul 2012 12:17:00 -0700 Subject: Socket code not executing properly in a thread (Windows) In-Reply-To: References: Message-ID: On 7/8/2012 3:55 AM, Andrew D'Angelo wrote: > Hi, I've been writing an IRC chatbot that an relay messages it receives as > an SMS. We have no idea what IRC module you're using. > As it stands, I can retrieve and parse SMSs from Google Voice perfectly The Google Voice code you have probably won't work once you have enough messages stored that Google Voice returns them on multiple pages. You have to read all the pages. If there's any significant amount of traffic, the completed messages have to be moved or deleted, or each polling cycle returns more data than the last one. Google Voice isn't a very good SMS gateway. I used to use it, but switched to Twilio (which costs, but works) two years ago. John Nagle From subhabangalore at gmail.com Sat Jul 7 15:54:16 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sat, 7 Jul 2012 12:54:16 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: Message-ID: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> On Thursday, July 5, 2012 4:51:46 AM UTC+5:30, (unknown) wrote: > Dear Group, > > I am Sri Subhabrata Banerjee trying to write from Gurgaon, India to discuss some coding issues. If any one of this learned room can shower some light I would be helpful enough. > > I got to code a bunch of documents which are combined together. > Like, > > 1)A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing. > 2) The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. > 3) A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > The task is to separate the documents on the fly and to parse each of the documents with a definite set of rules. > > Now, the way I am processing is: > I am clubbing all the documents together, as, > > A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection. A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > But they are separated by a tag set, like, > A Mumbai-bound aircraft with 99 passengers on board was struck by lightning on Tuesday evening that led to complete communication failure in mid-air and forced the pilot to make an emergency landing.$ > The discovery of a new sub-atomic particle that is key to understanding how the universe is built has an intrinsic Indian connection.$ > A bomb explosion outside a shopping mall here on Tuesday left no one injured, but Nigerian authorities put security agencies on high alert fearing more such attacks in the city. > > To detect the document boundaries, I am splitting them into a bag of words and using a simple for loop as, > for i in range(len(bag_words)): > if bag_words[i]=="$": > print (bag_words[i],i) > > There is no issue. I am segmenting it nicely. I am using annotated corpus so applying parse rules. > > The confusion comes next, > > As per my problem statement the size of the file (of documents combined together) won?t increase on the fly. So, just to support all kinds of combinations I am appending in a list the ?I? values, taking its length, and using slice. Works perfect. Question is, is there a smarter way to achieve this, and a curious question if the documents are on the fly with no preprocessed tag set like ?$? how may I do it? From a bunch without EOF isn?t it a classification problem? > > There is no question on parsing it seems I am achieving it independent of length of the document. > > If any one in the group can suggest how I am dealing with the problem and which portions should be improved and how? > > Thanking You in Advance, > > Best Regards, > Subhabrata Banerjee. Thanks Peter but I feel your earlier one was better, I got an interesting one: [i - 1 for i in range(len(f1)) if f1.startswith('$', i - 1)] But I am bit intrigued with another question, suppose I say: file_open=open("/python32/doc1.txt","r") file=a1.read().lower() for line in file: line_word=line.split() This works fine. But if I print it would be printed continuously. I like to store in some variable,so that I may print line of my choice and manipulate them at my choice. Is there any way out to this problem? Regards, Subhabrata Banerjee From sg552 at hotmail.co.uk Sat Jul 7 16:00:55 2012 From: sg552 at hotmail.co.uk (Rotwang) Date: Sat, 07 Jul 2012 21:00:55 +0100 Subject: ANN: Celery 3.0 (chiastic slide) released! In-Reply-To: References: Message-ID: On 07/07/2012 19:26, Ask Solem wrote: > =========================================== > Celery 3.0 (Chiastic Slide) Released! > =========================================== Does this have anything to do with the Autechre album? -- I have made a thing that superficially resembles music: http://soundcloud.com/eroneity/we-berated-our-own-crapiness From contropinion at gmail.com Sun Jul 8 00:47:08 2012 From: contropinion at gmail.com (contro opinion) Date: Sun, 8 Jul 2012 00:47:08 -0400 Subject: how to compile pygtk in python2.7? Message-ID: 1.download pygtk 2.cd /home/tiger/pygtk-2.24.0 3.PYTHON=/usr/bin/python2.7 ./configure --prefix=/usr 4. make 5. make install *tiger at ocean:~$ python2.7 Python 2.7.3 (default, Jul 1 2012, 14:13:18) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gtk Traceback (most recent call last): File "", line 1, in ImportError: No module named gtk >>> * i can't compile pygtk in python2.7,how to compile it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun Jul 8 01:10:32 2012 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 7 Jul 2012 22:10:32 -0700 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: On Sat, Jul 7, 2012 at 9:47 PM, contro opinion wrote: > 1.download pygtk > > 2.cd /home/tiger/pygtk-2.24.0 > > 3.PYTHON=/usr/bin/python2.7 ./configure --prefix=/usr > 4. make > 5. make install > > tiger at ocean:~$ python2.7 > Python 2.7.3 (default, Jul 1 2012, 14:13:18) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import gtk > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named gtk >>>> > > i can't compile pygtk in python2.7,how to compile it? > > -- What is the output of make and make install? Does it compile successfully, or is there an error? Does the current user have permission to write to /usr? You haven't given us enough information to figure out what's going on? From subhabangalore at gmail.com Sun Jul 8 01:42:13 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sat, 7 Jul 2012 22:42:13 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> Message-ID: <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> On Sunday, July 8, 2012 2:21:14 AM UTC+5:30, Dennis Lee Bieber wrote: > On Sat, 7 Jul 2012 12:54:16 -0700 (PDT), subhabangalore at gmail.com > declaimed the following in gmane.comp.python.general: > > > But I am bit intrigued with another question, > > > > suppose I say: > > file_open=open("/python32/doc1.txt","r") > > file=a1.read().lower() > > for line in file: > > line_word=line.split() > > > > This works fine. But if I print it would be printed continuously. > > "This works fine" -- Really? > > 1) Why are you storing data files in the install directory of your > Python interpreter? > > 2) "a1" is undefined -- you should get an exception on that line which > makes the following irrelevant; replacing "a1" with "file_open" leads > to... > > 3) "file" is a) a predefined function in Python, which you have just > shadowed and b) a poor name for a string containing the contents of a > file > > 4) "for line in file", since "file" is a string, will iterate over EACH > CHARACTER, meaning (since there is nothing to split) that "line_word" is > also just a single character. > > for line in file.split("\n"): > > will split the STRING into logical lines (assuming a new-line character > splits the lines) and permit the subsequent split to pull out wordS > ("line_word" is misleading, as to will contain a LIST of words from the > line). > > > I like to store in some variable,so that I may print line of my choice and manipulate them at my choice. > > Is there any way out to this problem? > > > > > > Regards, > > Subhabrata Banerjee > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ Thanks for pointing out the mistakes. Your points are right. So I am trying to revise it, file_open=open("/python32/doc1.txt","r") for line in file_open: line_word=line.split() print (line_word) To store them the best way is to assign a blank list and append but is there any alternate method for huge data it becomes tough as the list becomes huge if any way variables may be assigned. Regards, Subhabrata Banerjee. From subhabangalore at gmail.com Sun Jul 8 01:42:13 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sat, 7 Jul 2012 22:42:13 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> Message-ID: <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> On Sunday, July 8, 2012 2:21:14 AM UTC+5:30, Dennis Lee Bieber wrote: > On Sat, 7 Jul 2012 12:54:16 -0700 (PDT), subhabangalore at gmail.com > declaimed the following in gmane.comp.python.general: > > > But I am bit intrigued with another question, > > > > suppose I say: > > file_open=open("/python32/doc1.txt","r") > > file=a1.read().lower() > > for line in file: > > line_word=line.split() > > > > This works fine. But if I print it would be printed continuously. > > "This works fine" -- Really? > > 1) Why are you storing data files in the install directory of your > Python interpreter? > > 2) "a1" is undefined -- you should get an exception on that line which > makes the following irrelevant; replacing "a1" with "file_open" leads > to... > > 3) "file" is a) a predefined function in Python, which you have just > shadowed and b) a poor name for a string containing the contents of a > file > > 4) "for line in file", since "file" is a string, will iterate over EACH > CHARACTER, meaning (since there is nothing to split) that "line_word" is > also just a single character. > > for line in file.split("\n"): > > will split the STRING into logical lines (assuming a new-line character > splits the lines) and permit the subsequent split to pull out wordS > ("line_word" is misleading, as to will contain a LIST of words from the > line). > > > I like to store in some variable,so that I may print line of my choice and manipulate them at my choice. > > Is there any way out to this problem? > > > > > > Regards, > > Subhabrata Banerjee > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ Thanks for pointing out the mistakes. Your points are right. So I am trying to revise it, file_open=open("/python32/doc1.txt","r") for line in file_open: line_word=line.split() print (line_word) To store them the best way is to assign a blank list and append but is there any alternate method for huge data it becomes tough as the list becomes huge if any way variables may be assigned. Regards, Subhabrata Banerjee. From rosuav at gmail.com Sun Jul 8 01:44:56 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 8 Jul 2012 15:44:56 +1000 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: On Sun, Jul 8, 2012 at 2:47 PM, contro opinion wrote: > 3.PYTHON=/usr/bin/python2.7 ./configure --prefix=/usr > 4. make > 5. make install What happened when you typed these commands? Were there failure messages? As Benjamine suggested, do you need to become root to install? ChrisA From rosuav at gmail.com Sun Jul 8 04:03:25 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 8 Jul 2012 18:03:25 +1000 Subject: Discussion on some Code Issues In-Reply-To: <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> Message-ID: On Sun, Jul 8, 2012 at 3:42 PM, wrote: > Thanks for pointing out the mistakes. Your points are right. So I am trying to revise it, > > file_open=open("/python32/doc1.txt","r") > for line in file_open: > line_word=line.split() > print (line_word) Yep. I'd be inclined to rename file_open to something that says what the file _is_, and you may want to look into the 'with' statement to guarantee timely closure of the file, but that's a way to do it. Also, as has already been mentioned: keeping your data files in the Python binaries directory isn't usually a good idea. More common to keep them in the same directory as your script, which would mean that you don't need a path on it at all. ChrisA From contropinion at gmail.com Sun Jul 8 04:26:14 2012 From: contropinion at gmail.com (contro opinion) Date: Sun, 8 Jul 2012 04:26:14 -0400 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: it's so strange when i input hisroty 506 cd /home/tiger/pygtk-2.24.0 507 PYTHON=/usr/local/bin/python2.7 ./configure --prefix=/usr 508 echo $? #i get 0 ,it means success?? 509 make 510 echo $? #i get 0 ,it means success?? 511 make install 512 echo $? #i get 0 ,it means success?? no wrong output can see . root at ocean:~# python2.7 Python 2.7.3 (default, Jul 1 2012, 14:13:18) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gtk Traceback (most recent call last): File "", line 1, in ImportError: No module named gtk >>> 2012/7/8 Chris Angelico > On Sun, Jul 8, 2012 at 2:47 PM, contro opinion > wrote: > > 3.PYTHON=/usr/bin/python2.7 ./configure --prefix=/usr > > 4. make > > 5. make install > > What happened when you typed these commands? Were there failure > messages? As Benjamine suggested, do you need to become root to > install? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Jul 8 04:28:58 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 8 Jul 2012 18:28:58 +1000 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: On Sun, Jul 8, 2012 at 6:26 PM, contro opinion wrote: > it's so strange > when i input > hisroty > > 506 cd /home/tiger/pygtk-2.24.0 > 507 PYTHON=/usr/local/bin/python2.7 ./configure --prefix=/usr > 508 echo $? #i get 0 ,it means success?? > 509 make > 510 echo $? #i get 0 ,it means success?? > 511 make install > 512 echo $? #i get 0 ,it means success?? > > no wrong output can see . Any output at all? Normally configure and make will produce long screeds. If they didn't, that's wrong output. ChrisA From excel at pharcyde.org Sun Jul 8 05:03:40 2012 From: excel at pharcyde.org (Andrew D'Angelo) Date: Sun, 8 Jul 2012 04:03:40 -0500 Subject: Socket code not executing properly in a thread (Windows) References: Message-ID: "John Nagle" wrote in message news:jta1v7$v0b$1 at dont-email.me... > We have no idea what IRC module you're using. I am sending plain text to the socket, sorry for not mentioning it before. At the simplest level, it appears that when the code runs in Windows, data is not sent to a socket when inside a thread, while on OS X it is. Also, running the sned to socket code inside the main loop would not work, as the main loop pauses until it recieves data from the socket (an IRC message), which is why I didn't put the SMS code in the main loop in the first place. > The Google Voice code you have probably won't work once you have > enough messages stored that Google Voice returns them on multiple > pages. I know that this is not the problem because the code works fine on OS X, but not Windows, where I actually need it to run. In addition, each message is deleted as it is parsed and no other SMSs are sent to the number, so fill-up should not be a problem. From contropinion at gmail.com Sun Jul 8 06:52:50 2012 From: contropinion at gmail.com (contro opinion) Date: Sun, 8 Jul 2012 06:52:50 -0400 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: 1.PYTHON=/usr/local/bin/python2.7 ./configure --prefix=/usr the output is : checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes checking for style of include used by make... GNU checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking dependency style of gcc... gcc3 checking for bind_textdomain_codeset... yes checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking for some Win32 platform... no checking for native Win32... no checking for a sed that does not truncate output... /bin/sed checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 1572864 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking for /usr/bin/ld option to reload object files... -r checking for objdump... objdump checking how to recognize dependent libraries... pass_all checking for ar... ar checking for strip... strip checking for ranlib... ranlib checking command to parse /usr/bin/nm -B output from gcc object... ok checking how to run the C preprocessor... gcc -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking for dlfcn.h... yes checking for objdir... .libs checking if gcc supports -fno-rtti -fno-exceptions... no checking for gcc option to produce PIC... -fPIC -DPIC checking if gcc PIC flag -fPIC -DPIC works... yes checking if gcc static flag -static works... yes checking if gcc supports -c -o file.o... yes checking if gcc supports -c -o file.o... (cached) yes checking whether the gcc linker (/usr/bin/ld) supports shared libraries... yes checking whether -lc should be explicitly linked in... no checking dynamic linker characteristics... GNU/Linux ld.so checking how to hardcode library paths into programs... immediate checking whether stripping libraries is possible... yes checking if libtool supports shared libraries... yes checking whether to build shared libraries... yes checking whether to build static libraries... no configure: creating ./config.lt config.lt: creating libtool checking whether /usr/local/bin/python2.7 version >= 2.3.5... yes checking for /usr/local/bin/python2.7 version... 2.7 checking for /usr/local/bin/python2.7 platform... linux2 checking for /usr/local/bin/python2.7 script directory... ${prefix}/lib/python2.7/site-packages checking for /usr/local/bin/python2.7 extension module directory... ${exec_prefix}/lib/python2.7/site-packages checking for headers required to compile python extensions... found checking for PySignal_SetWakeupFd in Python.h... yes checking for python module thread... yes checking whether to enable threading in pygtk... yes checking for pkg-config... /usr/bin/pkg-config checking pkg-config is at least version 0.16... yes checking for GLIB - version >= 2.8.0... yes (version 2.24.2) checking for PYGOBJECT... yes checking for gio-types.defs... /usr/share/pygobject/2.0/defs/gio-types.defs checking for ATK... yes checking for PANGO... yes checking for codegen... /usr/share/pygobject/2.0/codegen checking for PYCAIRO... yes checking for PANGOCAIRO... yes checking for GTK... yes checking for GTK210... yes checking for GTK212... yes checking for GTK214... yes checking for GTK216... yes checking for GTK218... yes checking for GTK220... yes checking for GTK222... no no checking for GTK224... no no checking for LIBGLADE... yes checking for GTKUNIXPRINT... yes checking for GDK target... x11 checking for numpy/arrayobject.h... yes checking whether gcc understands -Wall... yes checking whether gcc understands -fno-strict-aliasing... yes checking whether gcc understands -std=c9x... yes configure: creating ./config.status config.status: creating Makefile config.status: creating pygtk-2.0.pc config.status: creating pygtk-codegen-2.0 config.status: creating gtk/Makefile config.status: creating docs/Makefile config.status: creating docs/reference/entities.docbook config.status: creating examples/Makefile config.status: creating tests/Makefile config.status: creating pygtk.spec config.status: creating PKG-INFO config.status: creating config.h config.status: config.h is unchanged config.status: executing depfiles commands config.status: executing libtool commands The following modules will be built: atk pango pangocairo gtk with 2.20 API gtk.glade gtk.unixprint Numpy support: yes root at ocean:/home/tiger/pygtk-2.24.0# echo $? 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From contropinion at gmail.com Sun Jul 8 06:54:32 2012 From: contropinion at gmail.com (contro opinion) Date: Sun, 8 Jul 2012 06:54:32 -0400 Subject: how to compile pygtk in python2.7? In-Reply-To: References: Message-ID: 2.make the output is : Could not write method GdkFont.text_width_wc: No ArgType for const-GdkWChar* Could not write method GdkFont.char_width_wc: No ArgType for GdkWChar Could not write method GdkFont.text_extents_wc: No ArgType for const-GdkWChar* Could not write method GdkFont.string_extents: No ArgType for gint* Could not write method GdkFont.get_xfont: No ArgType for gpointer Could not write method GdkFont.x11_font_get_xdisplay: No ArgType for Display* Could not write method GdkCursor.get_xdisplay: No ArgType for Display* Could not write method GdkCursor.get_xcursor: No ArgType for Cursor Could not write method GdkRegion.spans_intersect_foreach: No ArgType for GdkSpan* Could not write method GdkRegion.rect_equal: No ArgType for const-GdkRectangle* Warning: generating old-style constructor for:gdk_colormap_new Could not write method GdkColormap.alloc_colors: No ArgType for gboolean* Could not write method GdkColormap.get_xdisplay: No ArgType for Display* Could not write method GdkColormap.get_xcolormap: No ArgType for Colormap Warning: generating old-style constructor for:gdk_display_open Could not write method GdkDisplay.add_client_message_filter: No ArgType for GdkFilterFunc Could not write method GdkDisplay.set_pointer_hooks: No ArgType for const-GdkDisplayPointerHooks* Could not write method GdkDisplay.get_xdisplay: No ArgType for Display* Could not write method GdkDisplay.set_cursor_theme: No ArgType for const-gint Could not write method GdkDrawable.set_data: No ArgType for gpointer Could not write method GdkDrawable.get_data: No ArgType for gpointer Could not write method GdkDrawable.draw_text_wc: No ArgType for const-GdkWChar* Could not write method GdkDrawable.get_xdisplay: No ArgType for Display* Could not write method GdkDrawable.get_xid: No ArgType for XID Could not write virtual accessor method GdkDrawable.create_gc: No ArgType for GdkGCValues* Could not write virtual accessor method GdkDrawable.draw_polygon: No ArgType for GdkPoint* Could not write virtual accessor method GdkDrawable.draw_text_wc: No ArgType for const-GdkWChar* Could not write virtual accessor method GdkDrawable.draw_points: No ArgType for GdkPoint* Could not write virtual accessor method GdkDrawable.draw_segments: No ArgType for GdkSegment* Could not write virtual accessor method GdkDrawable.draw_lines: No ArgType for GdkPoint* Could not write virtual accessor method GdkDrawable.get_size: No ArgType for gint* Could not write virtual accessor method GdkDrawable.get_composite_drawable: No ArgType for gint* Could not write virtual accessor method GdkDrawable.draw_trapezoids: No ArgType for GdkTrapezoid* Could not write virtual accessor method GdkDrawable.ref_cairo_surface: No ArgType for cairo_surface_t* Could not write virtual proxy GdkDrawable.create_gc: No ArgType for GdkGCValues* Could not write virtual proxy GdkDrawable.draw_polygon: No ArgType for GdkPoint* Could not write virtual proxy GdkDrawable.draw_text_wc: No ArgType for const-GdkWChar* Could not write virtual proxy GdkDrawable.draw_points: No ArgType for GdkPoint* Could not write virtual proxy GdkDrawable.draw_segments: No ArgType for GdkSegment* Could not write virtual proxy GdkDrawable.draw_lines: No ArgType for GdkPoint* Could not write virtual proxy GdkDrawable.get_size: cannot use int* parameter with direction 'None' Could not write virtual proxy GdkDrawable.get_composite_drawable: cannot use int* parameter with direction 'None' Could not write virtual proxy GdkDrawable.draw_trapezoids: No ArgType for GdkTrapezoid* Could not write virtual proxy GdkDrawable.ref_cairo_surface: No ArgType for cairo_surface_t* Could not write method GdkWindow.selection_property_get: No ArgType for guchar** Could not write method GdkWindow.remove_filter: No ArgType for GdkFilterFunc Could not write method GdkWindow.invalidate_maybe_recurse: No ArgType for gboolean (*child_func)(GdkWindow *, gpointer) Could not write method GdkWindow.get_internal_paint_info: No ArgType for GdkDrawable** Could not write method GdkWindow.get_root_coords: No ArgType for gint* Warning: generating old-style constructor for:gdk_pango_renderer_new Warning: generating old-style constructor for:gdk_pixmap_new Could not write method GdkGC.get_values: No ArgType for GdkGCValues* Could not write method GdkGC.get_xdisplay: No ArgType for Display* Could not write method GdkGC.get_xgc: No ArgType for GC Could not write virtual accessor method GdkGC.get_values: No ArgType for GdkGCValues* Could not write virtual accessor method GdkGC.set_values: No ArgType for GdkGCValues* Could not write virtual accessor method GdkGC.set_dashes: No ArgType for gint8[] Could not write virtual proxy GdkGC.get_values: No ArgType for GdkGCValues* Could not write virtual proxy GdkGC.set_values: No ArgType for GdkGCValues* Could not write virtual proxy GdkGC.set_dashes: No ArgType for gint8[] Warning: generating old-style constructor for:gdk_image_new Could not write method GdkImage.get_xdisplay: No ArgType for Display* Could not write method GdkImage.get_ximage: No ArgType for XImage* Could not write method GdkKeymap.add_virtual_modifiers: No ArgType for GdkModifierType* Could not write method GdkKeymap.map_virtual_modifiers: No ArgType for GdkModifierType* Warning: generating old-style constructor for:gdk_pixbuf_new Could not write method GdkPixbuf.render_pixmap_and_mask_for_colormap: No ArgType for GdkPixmap** Could not write method GdkPixbuf.savev: No ArgType for char** Could not write method GdkPixbuf.save_to_callbackv: No ArgType for GdkPixbufSaveFunc Could not write method GdkPixbuf.save_to_buffer: varargs functions not supported Could not write method GdkPixbuf.save_to_bufferv: No ArgType for gchar** Warning: generating old-style constructor for:gdk_pixbuf_animation_new_from_file Warning: generating old-style constructor for:gdk_pixbuf_simple_anim_new Could not write method GdkScreen.get_xscreen: No ArgType for Screen* Could not write method GdkScreen.lookup_visual: No ArgType for VisualID Could not write method GdkScreen.get_window_stack: No ArgType for GList* Warning: generating old-style constructor for:gdk_visual_get_best_with_both Could not write method GdkVisual.get_xvisual: No ArgType for Visual* Could not write function parse_args: No ArgType for gint* Could not write function init: No ArgType for gint* Could not write function init_check: No ArgType for gint* Could not write function input_add_full: No ArgType for GdkInputFunction Could not write function input_add: No ArgType for GdkInputFunction Could not write function wcstombs: No ArgType for const-GdkWChar* Could not write function mbstowcs: No ArgType for GdkWChar* Could not write function threads_set_lock_functions: No ArgType for GCallback Could not write function colors_alloc: No ArgType for gulong* Could not write function colors_free: No ArgType for gulong* Could not write function drag_get_protocol: No ArgType for GdkDragProtocol* Could not write function drag_get_protocol_for_display: No ArgType for GdkDragProtocol* Could not write function draw_trapezoids: No ArgType for GdkTrapezoid* Could not write function add_client_message_filter: No ArgType for GdkFilterFunc Could not write function setting_get: No ArgType for GValue* Could not write function image_new_bitmap: No ArgType for gpointer Could not write function pango_layout_line_get_clip_region: No ArgType for gint* Could not write function pango_layout_get_clip_region: No ArgType for gint* Could not write function text_property_to_text_list: No ArgType for gchar*** Could not write function text_property_to_utf8_list: No ArgType for gchar*** Could not write function utf8_to_compound_text: No ArgType for GdkAtom* Could not write function string_to_compound_text: No ArgType for GdkAtom* Could not write function text_property_to_text_list_for_display: No ArgType for gchar*** Could not write function text_property_to_utf8_list_for_display: No ArgType for gchar*** Could not write function string_to_compound_text_for_display: No ArgType for GdkAtom* Could not write function utf8_to_compound_text_for_display: No ArgType for GdkAtom* Could not write function free_text_list: No ArgType for gchar** Could not write function rgb_cmap_new: No ArgType for guint32* Could not write function window_constrain_size: No ArgType for GdkGeometry* Could not write function set_pointer_hooks: No ArgType for const-GdkPointerHooks* Could not write function pixbuf_error_quark: No ArgType for GQuark Could not write function region_polygon: No ArgType for GdkPoint* Could not write function x11_get_default_root_xwindow: No ArgType for Window Could not write function x11_get_default_xdisplay: No ArgType for Display* Could not write function gdkx_visual_get: No ArgType for VisualID Could not write function gdkx_colormap_get: No ArgType for Colormap Could not write function xid_table_lookup_for_display: No ArgType for XID Could not write function xid_table_lookup: No ArgType for XID Could not write function x11_lookup_xdisplay: No ArgType for Display* Could not write function x11_atom_to_xatom_for_display: No ArgType for Atom Could not write function x11_xatom_to_atom_for_display: No ArgType for Atom Could not write function x11_get_xatom_by_name_for_display: No ArgType for Atom Could not write function x11_get_xatom_name_for_display: No ArgType for Atom Could not write function x11_atom_to_xatom: No ArgType for Atom Could not write function x11_xatom_to_atom: No ArgType for Atom Could not write function x11_get_xatom_by_name: No ArgType for Atom Could not write function x11_get_xatom_name: No ArgType for Atom Could not write function x11_display_broadcast_startup_message: varargs functions not supported Could not write function threads_add_idle_full: No ArgType for GSourceFunc Could not write function threads_add_idle: No ArgType for GSourceFunc Could not write function threads_add_timeout_full: No ArgType for GSourceFunc Could not write function threads_add_timeout: No ArgType for GSourceFunc Could not write function x11_screen_get_monitor_output: No ArgType for XID Warning: Constructor for GdkColormap needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkDisplay needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkWindow needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPangoRenderer needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPixmap needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkGC needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkImage needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPixbuf needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPixbufAnimation needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPixbufLoader needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkPixbufSimpleAnim needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkScreen needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors Warning: Constructor for GdkVisual needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors ***INFO*** The coverage of global functions is 73.76% (149/202) ***INFO*** The coverage of methods is 90.27% (399/442) ***INFO*** The coverage of virtual proxies is 69.77% (30/43) ***INFO*** The coverage of virtual accessors is 69.77% (30/43) ***INFO*** There are no declared interface proxies. In file included from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1718, from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:15, from ./gdk.override:49: /usr/local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" Warning: Constructor for GladeXML needs to be updated to new API See http://live.gnome.org/PyGTK_2fWhatsNew28#update-constructors ***INFO*** The coverage of global functions is 100.00% (7/7) ***INFO*** The coverage of methods is 100.00% (5/5) ***INFO*** There are no declared virtual proxies. ***INFO*** There are no declared virtual accessors. ***INFO*** There are no declared interface proxies. echo $? # the output is 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From excel at pharcyde.org Sun Jul 8 06:55:03 2012 From: excel at pharcyde.org (Andrew D'Angelo) Date: Sun, 8 Jul 2012 05:55:03 -0500 Subject: Socket code not executing properly in a thread (Windows) Message-ID: Hi, I've been writing an IRC chatbot that an relay messages it recieves as an SMS. As it stands, I can retrieve and parse SMSs from Google Voice perfectly, and print them to the console. The problem lies in actually posting the message to the IRC channel. Since the SMS checker runs in a thread apart from the regular chatbot duties, the socket communication also takes place in the thread. Something even stranger is that the code works on OS X, but not on WIndows, where my server runs. Here is a code snippet (If it would help, the full code can be seen here: http://lickitung.it.cx/exe/bot/bot.py): def checkVoice(): global upHz global CHANNEL global mute while 1: print "Update voice!" voice.sms() msgitems = [] #Extract all conversations by searching for a DIV with an ID at top level. tree = BeautifulSoup(voice.sms.html) conversations = tree.findAll("div",attrs={"id" : True},recursive=False) #parsing code cut for brevity - I know it works, though sendPrivateMessage(CHANNEL,message) #as far as I can tell, this is failing to execute time.sleep(upHz) def sendPrivateMessage(channel, message):#private message send function global mute if mute == 0: IRC.send("PRIVMSG " + channel + " :" + message + "\r\n") #IRC being the socket From t at jollybox.de Sun Jul 8 07:01:18 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 08 Jul 2012 13:01:18 +0200 Subject: Socket code not executing properly in a thread (Windows) In-Reply-To: References: Message-ID: <4FF9687E.3070205@jollybox.de> On 07/08/2012 11:03 AM, Andrew D'Angelo wrote: > Also, running the sned to socket code inside the main loop would not work, > as the main loop pauses until it recieves data from the socket (an IRC > message), which is why I didn't put the SMS code in the main loop in the > first place. http://docs.python.org/library/select.html From richardbp at gmail.com Sun Jul 8 07:29:41 2012 From: richardbp at gmail.com (Richard Baron Penman) Date: Sun, 8 Jul 2012 21:29:41 +1000 Subject: How to safely maintain a status file Message-ID: Hello, I want my script to generate a ~1KB status file several times a second. The script may be terminated at any time but the status file must not be corrupted. When the script is started next time the status file will be read to check what needs to be done. My initial solution was a thread that writes status to a tmp file first and then renames: open(tmp_file, 'w').write(status) os.rename(tmp_file, status_file) This works well on Linux but Windows raises an error when status_file already exists. http://docs.python.org/library/os.html#os.rename I guess I could delete the status file: open(tmp_file, 'w').write(status) if os.path.exists(status_file): os.remove(status_file) os.rename(tmp_file, status_file) and then on startup read from tmp_file if status_file does not exist. But this seems awkward. Is there a better way? Or do I need to use a database? Richard From lists at cheimes.de Sun Jul 8 07:53:05 2012 From: lists at cheimes.de (Christian Heimes) Date: Sun, 08 Jul 2012 13:53:05 +0200 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: Am 08.07.2012 13:29, schrieb Richard Baron Penman: > My initial solution was a thread that writes status to a tmp file > first and then renames: > > open(tmp_file, 'w').write(status) > os.rename(tmp_file, status_file) You algorithm may not write and flush all data to disk. You need to do additional work. You must also store the tmpfile on the same partition (better: same directory) as the status file with open(tmp_file, "w") as f: f.write(status) # flush buffer and write data/metadata to disk f.flush() os.fsync(f.fileno()) # now rename the file os.rename(tmp_file, status_file) # finally flush metadata of directory to disk dirfd = os.open(os.path.dirname(status_file), os.O_RDONLY) try: os.fsync(dirfd) finally: os.close(dirfd) > This works well on Linux but Windows raises an error when status_file > already exists. > http://docs.python.org/library/os.html#os.rename Windows doesn't suppport atomic renames if the right side exists. I suggest that you implement two code paths: if os.name == "posix": rename = os.rename else: def rename(a, b): try: os.rename(a, b) except OSError, e: if e.errno != 183: raise os.unlink(b) os.rename(a, b) Christian From mhrivnak at hrivnak.org Sun Jul 8 12:47:25 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Sun, 8 Jul 2012 12:47:25 -0400 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: What are you keeping in this status file that needs to be saved several times per second? Depending on what type of state you're storing and how persistent it needs to be, there may be a better way to store it. Michael On Sun, Jul 8, 2012 at 7:53 AM, Christian Heimes wrote: > Am 08.07.2012 13:29, schrieb Richard Baron Penman: >> My initial solution was a thread that writes status to a tmp file >> first and then renames: >> >> open(tmp_file, 'w').write(status) >> os.rename(tmp_file, status_file) > > You algorithm may not write and flush all data to disk. You need to do > additional work. You must also store the tmpfile on the same partition > (better: same directory) as the status file > > with open(tmp_file, "w") as f: > f.write(status) > # flush buffer and write data/metadata to disk > f.flush() > os.fsync(f.fileno()) > > # now rename the file > os.rename(tmp_file, status_file) > > # finally flush metadata of directory to disk > dirfd = os.open(os.path.dirname(status_file), os.O_RDONLY) > try: > os.fsync(dirfd) > finally: > os.close(dirfd) > > >> This works well on Linux but Windows raises an error when status_file >> already exists. >> http://docs.python.org/library/os.html#os.rename > > Windows doesn't suppport atomic renames if the right side exists. I > suggest that you implement two code paths: > > if os.name == "posix": > rename = os.rename > else: > def rename(a, b): > try: > os.rename(a, b) > except OSError, e: > if e.errno != 183: > raise > os.unlink(b) > os.rename(a, b) > > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list From subhabangalore at gmail.com Sun Jul 8 13:05:58 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 8 Jul 2012 10:05:58 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> Message-ID: <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: > On Sun, Jul 8, 2012 at 3:42 PM, wrote: > > Thanks for pointing out the mistakes. Your points are right. So I am trying to revise it, > > > > file_open=open("/python32/doc1.txt","r") > > for line in file_open: > > line_word=line.split() > > print (line_word) > > Yep. I'd be inclined to rename file_open to something that says what > the file _is_, and you may want to look into the 'with' statement to > guarantee timely closure of the file, but that's a way to do it. > > Also, as has already been mentioned: keeping your data files in the > Python binaries directory isn't usually a good idea. More common to > keep them in the same directory as your script, which would mean that > you don't need a path on it at all. > > ChrisA Dear Chirs, No file path! Amazing. I do not know I like to know one small example please. Btw, some earlier post said, line.split() to convert line into bag of words can be done with power(), but I did not find it, if any one can help. I do close files do not worry. New style I'd try. Regards, Subha From subhabangalore at gmail.com Sun Jul 8 13:05:58 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 8 Jul 2012 10:05:58 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> Message-ID: <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: > On Sun, Jul 8, 2012 at 3:42 PM, wrote: > > Thanks for pointing out the mistakes. Your points are right. So I am trying to revise it, > > > > file_open=open("/python32/doc1.txt","r") > > for line in file_open: > > line_word=line.split() > > print (line_word) > > Yep. I'd be inclined to rename file_open to something that says what > the file _is_, and you may want to look into the 'with' statement to > guarantee timely closure of the file, but that's a way to do it. > > Also, as has already been mentioned: keeping your data files in the > Python binaries directory isn't usually a good idea. More common to > keep them in the same directory as your script, which would mean that > you don't need a path on it at all. > > ChrisA Dear Chirs, No file path! Amazing. I do not know I like to know one small example please. Btw, some earlier post said, line.split() to convert line into bag of words can be done with power(), but I did not find it, if any one can help. I do close files do not worry. New style I'd try. Regards, Subha From rosuav at gmail.com Sun Jul 8 13:17:00 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 9 Jul 2012 03:17:00 +1000 Subject: Discussion on some Code Issues In-Reply-To: <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: On Mon, Jul 9, 2012 at 3:05 AM, wrote: > On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: >> On Sun, Jul 8, 2012 at 3:42 PM, wrote: >> > file_open=open("/python32/doc1.txt","r") >> Also, as has already been mentioned: keeping your data files in the >> Python binaries directory isn't usually a good idea. More common to >> keep them in the same directory as your script, which would mean that >> you don't need a path on it at all. > No file path! Amazing. I do not know I like to know one small example please. open("doc1.txt","r") Python will look for a file called doc1.txt in the directory you run the script from (which is often going to be the same directory as your .py program). > Btw, some earlier post said, line.split() to convert line into bag of words can be done with power(), but I did not find it, if any one can help. I do close files do not worry. New style I'd try. I don't know what power() function you're talking about, and can't find it in the previous posts; the nearest I can find is a post from Ranting Rick which says a lot of guff that you can ignore. (Rick is a professional troll. Occasionally he says something useful and courteous; more often it's one or the other, or neither.) As to the closing of files: There are a few narrow issues that make it worth using the 'with' statement, such as exceptions; mostly, it's just a good habit to get into. If you ignore it, your file will *usually* be closed fairly soon after you stop referencing it, but there's no guarantee. (Someone else will doubtless correct me if I'm wrong, but I'm pretty sure Python guarantees to properly flush and close on exit, but not necessarily before.) ChrisA From roy at panix.com Sun Jul 8 14:17:41 2012 From: roy at panix.com (Roy Smith) Date: Sun, 08 Jul 2012 14:17:41 -0400 Subject: Discussion on some Code Issues References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: In article , Chris Angelico wrote: > open("doc1.txt","r") > > Python will look for a file called doc1.txt in the directory you run > the script from (which is often going to be the same directory as your > .py program). Well, to pick a nit, the file will be looked for in the current working directory. This may or may not be the directory you ran your script from. Your script could have executed chdir() between the time you started it and you tried to open the file. To pick another nit, it's misleading to say, "Python will look for...". This implies that Python somehow gets involved in pathname resolution, when it doesn't. Python just passes paths to the operating system as opaque strings, and the OS does all the magic of figuring out what that string means. From python at mrabarnett.plus.com Sun Jul 8 14:27:24 2012 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 08 Jul 2012 19:27:24 +0100 Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: <4FF9D10C.8090906@mrabarnett.plus.com> On 08/07/2012 18:17, Chris Angelico wrote: > On Mon, Jul 9, 2012 at 3:05 AM, wrote: >> On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: >>> On Sun, Jul 8, 2012 at 3:42 PM, wrote: >>> > file_open=open("/python32/doc1.txt","r") >>> Also, as has already been mentioned: keeping your data files in the >>> Python binaries directory isn't usually a good idea. More common to >>> keep them in the same directory as your script, which would mean that >>> you don't need a path on it at all. >> No file path! Amazing. I do not know I like to know one small example please. > > open("doc1.txt","r") > > Python will look for a file called doc1.txt in the directory you run > the script from (which is often going to be the same directory as your > .py program). > >> Btw, some earlier post said, line.split() to convert line into bag of words can >> be done with power(), but I did not find it, if any one can help. I do close >> files do not worry. New style I'd try. > > I don't know what power() function you're talking about, and can't > find it in the previous posts; the nearest I can find is a post from > Ranting Rick which says a lot of guff that you can ignore. (Rick is a > professional troll. Occasionally he says something useful and > courteous; more often it's one or the other, or neither.) > I believe the relevant quote is """especially the Python gods have given you *power* over string objects""". If that's the case, he's not referring to a method or a function called "power". He did give the good warning about the problem there could be if the original string contains "$", the character being used as the separator. > As to the closing of files: There are a few narrow issues that make it > worth using the 'with' statement, such as exceptions; mostly, it's > just a good habit to get into. If you ignore it, your file will > *usually* be closed fairly soon after you stop referencing it, but > there's no guarantee. (Someone else will doubtless correct me if I'm > wrong, but I'm pretty sure Python guarantees to properly flush and > close on exit, but not necessarily before.) > From gandalf at shopzeus.com Sun Jul 8 16:57:56 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Sun, 08 Jul 2012 22:57:56 +0200 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: <4FF9F454.40207@shopzeus.com> On Sun, 8 Jul 2012 21:29:41 +1000, Richard Baron Penman declaimed the following in gmane.comp.python.general: >> and then on startup read from tmp_file if status_file does not exist. >> But this seems awkward. >> > It also violates your requirement -- since the "crash" could take > place with a partial "temp file". > > I'd suggest that, rather than deleting the old status file, you > rename IT -- and only delete it IF you successfully rename the temp > file. Yes, this is much better. Almost perfect. Don't forget to consult your system documentation, and check if the rename operation is atomic or not. (Most probably it will only be atomic if the original and the renamed file are on the same physical partition and/or mount point). But even if the rename operation is atomic, there is still a race condition. Your program can be terminated after the original status file has been deleted, and before the temp file was renamed. In this case, you will be missing the status file (although your program already did something just it could not write out the new status). Here is an algorithm that can always write and read a status (but it might not be the latest one). You can keep the last two status files. Writer: * create temp file, write new status info * create lock file if needed * flock it * try: * delete older status file * rename temp file to new status file * finally: unlock the lock file Reader: * flock the lock file * try: * select the newer status file * read status info * finally: unlock the lock file It is guaranteed that you will always have a status to read, and in most cases this will be the last one (because the writer only locks for a short time). However, it is still questionable, because your writer may be waiting for the reader to unlock, so the new status info may not be written immediatelly. It would really help if you could tell us what are you trying to do that needs status. Best, Laszlo From anthra.norell at bluewin.ch Sun Jul 8 17:19:13 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Sun, 08 Jul 2012 23:19:13 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. Message-ID: <1341782353.2041.136.camel@hatchbox-one> Hi widget wizards, The manual describes the "event" attribute "widget" as "The widget which generated this event. This is a valid Tkinter widget instance, not a name. This attribute is set for all events." Ans so it is--has been until on the latest occasion "event.widget" was not the widget, but its name, crashing the handler. # Here I build a list of selectable records having each four fields. # The fields are labels. The selectable line is a frame containing the # labels side by side. The line frames go into self, which is a Frame. for n in range (len (records)): record = records [n] line_frame = Frame (self, name = '-%d-' % n, relief = RAISED, **BUTTON_FRAME_) line_frame.bind ('', self.enter) line_frame.bind ('', self.leave) line_frame.bind ('', self.pick_record) line_frame.bind ('', self.info_profile) line_frame.grid (row = n+2, column = 1) for i in self.range_n_fields: # (0, 1, 2, 3) field = Label (line_frame, text = record [self.INDICES [i]], anchor = W, width = self.COLUMN_WIDTHS [i], **DB_LIST_LABEL_) field.grid (row = 0, column = i, sticky = NW) # Here is the handler: def enter (self, event): w = event.widget print 'hit list.enter (). Event, widget', event, w, w.__class__ # Tracing line w.config (bg = SELECTED_BG_COLOR) # And here is what comes out. The first line is my tracing line. The name is correct in that it # names the entered line_frame, but is wrong because it should be the line_frame, not its name. # The rest is the red exception message: hit list.enter (). Event, widget .main-frame.data-frame.title-hit-list.-10- Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "/home/fr/python/finance/piam/hit_list.py", line 83, in enter w.config (bg = SELECTABLE_BG_COLOR) AttributeError: 'str' object has no attribute 'config' # The same thing happens with . The other handlers I haven't done yet. The same bindings work well in # a Menu class with the difference that the bindings are on the Labels, not a containing Frame. # Dell E6500, Ubuntu 10.04, Python 2.6 Frederic From gdamjan at gmail.com Sun Jul 8 17:49:39 2012 From: gdamjan at gmail.com (Damjan) Date: Sun, 08 Jul 2012 23:49:39 +0200 Subject: Confusing datetime.datetime In-Reply-To: <4ff71557$0$6974$e4fe514c@news2.news.xs4all.nl> References: <4ff71557$0$6974$e4fe514c@news2.news.xs4all.nl> Message-ID: > Because x1 and x2 have different time zones. > > The tzinfo field in x2 is equal to TZ and has a UTC offset of 1 hour. > The tzinfo field in x1 contains the DST version of that timezone, > with a UTC offset of 2 hours, because Skopje is currently on DST. > > I think you want: > > x2 = TZ.localize(datetime(x1.year, x1.month, x1.day)) > > That produces a datetime with the year, month and day set as indicated > and tzinfo set to the correct UTC offset for that date, at 00:00 hours. > > Or maybe you need: > > x2 = TZ.localize(datetime(x1.year, x1.month, x1.day, 12)) > x2 = x2.replace(hour=0) > > That determines whether DST should be on at noon, and then resets the > hour field to zero. This produces the same outcome as the one liner, > except on days when DST is switched on or off. Thanks, I think this will help me. Although these issues seem very much underdocumented in the datetime documentation. Are there any good references of using good times in Python? -- damjan From lists at cheimes.de Sun Jul 8 17:52:40 2012 From: lists at cheimes.de (Christian Heimes) Date: Sun, 08 Jul 2012 23:52:40 +0200 Subject: How to safely maintain a status file In-Reply-To: <4FF9F454.40207@shopzeus.com> References: <4FF9F454.40207@shopzeus.com> Message-ID: Am 08.07.2012 22:57, schrieb Laszlo Nagy: > But even if the rename operation is atomic, there is still a race > condition. Your program can be terminated after the original status file > has been deleted, and before the temp file was renamed. In this case, > you will be missing the status file (although your program already did > something just it could not write out the new status). You are contradicting yourself. Either the OS is providing a fully atomic rename or it doesn't. All POSIX compatible OS provide an atomic rename functionality that renames the file atomically or fails without loosing the target side. On POSIX OS it doesn't matter if the target exists. You don't need locks or any other fancy stuff. You just need to make sure that you flush the data and metadata correctly to the disk and force a re-write of the directory inode, too. It's a standard pattern on POSIX platforms and well documented in e.g. the maildir RFC. You can use the same pattern on Windows but it doesn't work as good and doesn't guaranteed file integrity for two reasons: 1) Windows's rename isn't atomic if the right side exists. 2) Windows locks file when a program opens a file. Other programs can't rename or overwrite the file. (You can get around the issue with some extra work, though.) Christian From rosuav at gmail.com Sun Jul 8 17:54:47 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 9 Jul 2012 07:54:47 +1000 Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: On Mon, Jul 9, 2012 at 4:17 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> open("doc1.txt","r") >> >> Python will look for a file called doc1.txt in the directory you run >> the script from (which is often going to be the same directory as your >> .py program). > > Well, to pick a nit, the file will be looked for in the current working > directory. This may or may not be the directory you ran your script > from. Your script could have executed chdir() between the time you > started it and you tried to open the file. > > To pick another nit, it's misleading to say, "Python will look for...". > This implies that Python somehow gets involved in pathname resolution, > when it doesn't. Python just passes paths to the operating system as > opaque strings, and the OS does all the magic of figuring out what that > string means. Two perfectly accurate nitpicks. And of course, there's a million and one other things that could happen in between, too, including possibilities of the current directory not even existing and so on. I merely oversimplified in the hopes of giving a one-paragraph explanation of what it means to not put a path name in your open() call :) It's like the difference between reminder text on a Magic: The Gathering card and the actual entries in the Comprehensive Rules. Perfect example is the "Madness" ability - the reminder text explains the ability, but uses language that actually is quite incorrect. It's a better explanation, though. Am I overanalyzing this? Yeah, probably... ChrisA From steve+comp.lang.python at pearwood.info Sun Jul 8 20:57:31 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Jul 2012 00:57:31 GMT Subject: Discussion on some Code Issues References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: <4ffa2c7b$0$29988$c3e8da3$5496439d@news.astraweb.com> On Mon, 09 Jul 2012 07:54:47 +1000, Chris Angelico wrote: > It's like > the difference between reminder text on a Magic: The Gathering card and > the actual entries in the Comprehensive Rules. Perfect example is the > "Madness" ability - the reminder text explains the ability, but uses > language that actually is quite incorrect. It's a better explanation, > though. Hang on, you say that an explanation which is "quite incorrect" is *better* than one which is correct? I can see why they call the card "Madness". :-P -- Steven From wuwei23 at gmail.com Sun Jul 8 21:45:00 2012 From: wuwei23 at gmail.com (alex23) Date: Sun, 8 Jul 2012 18:45:00 -0700 (PDT) Subject: stuck in files!! References: <5ddf03db-a5b1-4996-b9ce-6447ad89a3df@nw7g2000pbb.googlegroups.com> Message-ID: <1710b9e3-164f-4e45-827d-cd7b9bb5e868@y3g2000pbc.googlegroups.com> On Jul 6, 9:53?pm, Chirag B wrote: > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. Here's an approach that opens Notepad & Word, then monitors Notepad for any changes, updating the open Word document when they occur. This hasn't been tested in any great depth, and I wouldn't run it anywhere with existing instances of Notepad or Word open without testing what happens first, but it should get you started. For the most part this uses standard library files, although I did go with WinGuiAuto as a quick and dirty wrapper around the win32gui complexity. If you don't want to introduce it as a dependency, you can extract the functionality you need: http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html import os import time from win32com.client import Dispatch from winguiauto import ( findTopWindow, findControl, getEditText, WinGuiAutoError ) # conditional for main loop def window_is_open(hwnd): try: findTopWindow(selectionFunction=lambda ohwnd: hwnd == ohwnd) return True except WinGuiAutoError: return False # start Notepad os.system('start notepad') time.sleep(0.1) # give it time to open or we don't get the handleW npad = findTopWindow(wantedText='Untitled - Notepad') ndoc = findControl(npad, wantedClass='Edit') # edit control for Notepad # start Word word = Dispatch("Word.Application") word.Visible = True wdoc = word.Documents.Add() # edit control (new document) for Word # update Word when Notepad changes MEMORY = None while window_is_open(npad): ntxt = getEditText(ndoc) if ntxt != MEMORY: wdoc.Content.Text = os.linesep.join(ntxt) MEMORY = ntxt time.sleep(1) wdoc.Close() # opens a save dialogue wdoc.Quit() Hope this helps. From matthew.lefavor at nasa.gov Sun Jul 8 21:58:40 2012 From: matthew.lefavor at nasa.gov (Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC]) Date: Sun, 8 Jul 2012 20:58:40 -0500 Subject: something go wrongly In-Reply-To: Message-ID: If you do want an in-place extension, you could try: aList=[1,2,3,4,5,6,7,8,9,10] xList=[1,2,3] print "The concatenated lists are:", aList + bList Though you need to remember that neither aList nor bList is altered in this situation! Matthew Lefavor NASA GSFC [Microtel, LLC] Mail Code 699.0/Org Code 582.0 matthew.lefavor at nasa.gov (301) 614-6818 (Desk) (443) 758-4891 (Cell) From: levi nie To: "python-list at python.org" Subject: Re: something go wrongly Thanks, Such methods return None to emphasize that they do not create new lists. i got it. 2012/7/8 Chris Rebert On Sat, Jul 7, 2012 at 10:23 AM, levi nie wrote: > my code: > > aList=[1,2,3,4,5,6,7,8,9,10] > xList=[1,2,3] > print "now aList is",aList.extend(xList) > > output: > now aList is None > > what i want is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3] See http://stackoverflow.com/a/1682601 list.extend(), list.append(), etc. operate in-place, mutating the existing list object. Such methods return None to emphasize that they do not create new lists. Regards, Chris From howmuchistoday at gmail.com Sun Jul 8 22:02:41 2012 From: howmuchistoday at gmail.com (self.python) Date: Sun, 8 Jul 2012 19:02:41 -0700 (PDT) Subject: how can I make it work? Message-ID: it's a finder using threading to accelerate but it never works.. and I have no idea why it doesn't work:( it doesn't work too after changing threading to multiprocessing.. how can I make it work? or at least I know what's the problem... plz help the poor newbie... import os,threading,multiprocessing def finder(path,q): for x in os.walk(unicode(path)): if x[1]: for dirname in x[1]: if target in dirname.lower(): q.put(os.path.join(x[0],dirname)) if x[2]: for name in x[2]: if target in name.lower(): q.put(os.path.join(x[0],name)) q.put(1) def printer(q): cmd=0 while 1: tmp=q.get() if tmp==1: cmd += 1 continue if cmd ==thnum: break print tmp if __name__ =="__main__": q=multiprocessing.JoinableQueue() ini=os.walk(u"C:\\").next() thnum=len(ini[1]) target=raw_input("what you wanna get\n") p=multiprocessing.Process(target=printer,args=(q,)) p.daemon=1 p.start() for i in xrange(thnum): t=threading.Thread(target=finder,args=(ini[1][i],q,)) t.start() print i," started" q.join() From python at mrabarnett.plus.com Sun Jul 8 22:20:59 2012 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 09 Jul 2012 03:20:59 +0100 Subject: how can I make it work? In-Reply-To: References: Message-ID: <4FFA400B.9040609@mrabarnett.plus.com> On 09/07/2012 03:02, self.python wrote: > it's a finder using threading to accelerate but it never works.. > and I have no idea why it doesn't work:( > it doesn't work too after changing threading to multiprocessing.. > how can I make it work? or at least I know what's the problem... > plz help the poor newbie... > [snip] It would help if you gave more information than just "it doesn't work". In what way doesn't it work? From howmuchistoday at gmail.com Sun Jul 8 22:41:32 2012 From: howmuchistoday at gmail.com (self.python) Date: Sun, 8 Jul 2012 19:41:32 -0700 (PDT) Subject: how can I make it work? In-Reply-To: References: Message-ID: <9ba56ed1-c5fd-4048-8287-f55b16aed50f@googlegroups.com> 2012? 7? 9? ??? ?? 11? 2? 41? UTC+9, self.python ?? ?: > it's a finder using threading to accelerate but it never works.. > and I have no idea why it doesn't work:( > it doesn't work too after changing threading to multiprocessing.. > how can I make it work? or at least I know what's the problem... > plz help the poor newbie... > > > > import os,threading,multiprocessing > > > def finder(path,q): > for x in os.walk(unicode(path)): > if x[1]: > for dirname in x[1]: > if target in dirname.lower(): > q.put(os.path.join(x[0],dirname)) > if x[2]: > for name in x[2]: > if target in name.lower(): > q.put(os.path.join(x[0],name)) > > q.put(1) > > def printer(q): > cmd=0 > while 1: > tmp=q.get() > if tmp==1: > cmd += 1 > continue > if cmd ==thnum: > break > print tmp > > if __name__ =="__main__": > q=multiprocessing.JoinableQueue() > ini=os.walk(u"C:\\").next() > thnum=len(ini[1]) > target=raw_input("what you wanna get\n") > > p=multiprocessing.Process(target=printer,args=(q,)) > p.daemon=1 > p.start() > > for i in xrange(thnum): > t=threading.Thread(target=finder,args=(ini[1][i],q,)) > t.start() > print i," started" > q.join() It shows 0 started 1 started ... 22 started but then it show nothing the cursur blinks continuously but the result never printed(maybe not produces?) From howmuchistoday at gmail.com Sun Jul 8 23:29:51 2012 From: howmuchistoday at gmail.com (self.python) Date: Sun, 8 Jul 2012 20:29:51 -0700 (PDT) Subject: how can I make it work? In-Reply-To: <9ba56ed1-c5fd-4048-8287-f55b16aed50f@googlegroups.com> References: <9ba56ed1-c5fd-4048-8287-f55b16aed50f@googlegroups.com> Message-ID: <0e3be23f-9db9-48f0-840e-058d7f85573f@googlegroups.com> 2012? 7? 9? ??? ?? 11? 41? 32? UTC+9, self.python ?? ?: > 2012? 7? 9? ??? ?? 11? 2? 41? UTC+9, self.python ?? ?: > > it's a finder using threading to accelerate but it never works.. > > and I have no idea why it doesn't work:( > > it doesn't work too after changing threading to multiprocessing.. > > how can I make it work? or at least I know what's the problem... > > plz help the poor newbie... > > > > > > > > import os,threading,multiprocessing > > > > > > def finder(path,q): > > for x in os.walk(unicode(path)): > > if x[1]: > > for dirname in x[1]: > > if target in dirname.lower(): > > q.put(os.path.join(x[0],dirname)) > > if x[2]: > > for name in x[2]: > > if target in name.lower(): > > q.put(os.path.join(x[0],name)) > > > > q.put(1) > > > > def printer(q): > > cmd=0 > > while 1: > > tmp=q.get() > > if tmp==1: > > cmd += 1 > > continue > > if cmd ==thnum: > > break > > print tmp > > > > if __name__ =="__main__": > > q=multiprocessing.JoinableQueue() > > ini=os.walk(u"C:\\").next() > > thnum=len(ini[1]) > > target=raw_input("what you wanna get\n") > > > > p=multiprocessing.Process(target=printer,args=(q,)) > > p.daemon=1 > > p.start() > > > > for i in xrange(thnum): > > t=threading.Thread(target=finder,args=(ini[1][i],q,)) > > t.start() > > print i," started" > > q.join() > > > It shows > 0 started > 1 started > ... > 22 started > but then it show nothing > the cursur blinks continuously > but the result never printed(maybe not produces?) I knew what's the problem on other site. It just because I miss to send the full path to each thread... what an idiot.. but I'm still wondering that there is any good way From richardbp at gmail.com Mon Jul 9 01:50:05 2012 From: richardbp at gmail.com (Plumo) Date: Sun, 8 Jul 2012 22:50:05 -0700 (PDT) Subject: How to safely maintain a status file References: Message-ID: > Windows doesn't suppport atomic renames if the right side exists. ?I > suggest that you implement two code paths: > > if os.name == "posix": > ? ? rename = os.rename > else: > ? ? def rename(a, b): > ? ? ? ? try: > ? ? ? ? ? ? os.rename(a, b) > ? ? ? ? except OSError, e: > ? ? ? ? ? ? if e.errno != 183: > ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? os.unlink(b) > ? ? ? ? ? ? os.rename(a, b) Problem is if the process is stopped between unlink and rename there would no status file. From richardbp at gmail.com Mon Jul 9 01:52:58 2012 From: richardbp at gmail.com (Plumo) Date: Sun, 8 Jul 2012 22:52:58 -0700 (PDT) Subject: How to safely maintain a status file References: Message-ID: > What are you keeping in this status file that needs to be saved > several times per second? ?Depending on what type of state you're > storing and how persistent it needs to be, there may be a better way > to store it. > > Michael This is for a threaded web crawler. I want to cache what URL's are currently in the queue so if terminated the crawler can continue next time from the same point. From richardbp at gmail.com Mon Jul 9 01:58:28 2012 From: richardbp at gmail.com (Plumo) Date: Sun, 8 Jul 2012 22:58:28 -0700 (PDT) Subject: How to safely maintain a status file References: Message-ID: > > and then on startup read from tmp_file if status_file does not exist. > > But this seems awkward. > > ? ? ? ? It also violates your requirement -- since the "crash" could take > place with a partial "temp file". Can you explain why? My thinking was if crash took place when writing the temp file this would not matter because the status file would still exist and be read from. The temp file would only be renamed when fully written. From tjreedy at udel.edu Mon Jul 9 01:58:48 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Jul 2012 01:58:48 -0400 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: <1341782353.2041.136.camel@hatchbox-one> References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: On 7/8/2012 5:19 PM, Frederic Rentsch wrote: > Hi widget wizards, > > The manual describes the "event" attribute "widget" as "The widget > which generated this event. This is a valid Tkinter widget instance, not > a name. This attribute is set for all events." Same in 3.3, with nice example of using it. def turnRed(self, event): event.widget["activeforeground"] = "red" self.button.bind("", self.turnRed) > Ans so it is--has been until on the latest occasion "event.widget" was > not the widget, but its name, crashing the handler. Has event.widget been the widget only in other programs or previously with the same program? > # Here I build a list of selectable records having each four fields. > # The fields are labels. The selectable line is a frame containing the > # labels side by side. The line frames go into self, which is a Frame. > > for n in range (len (records)): for n, record in enumerate(records): > record = records [n] > line_frame = Frame (self, name = '-%d-' % n, relief = RAISED, **BUTTON_FRAME_) > line_frame.bind ('', self.enter) > line_frame.bind ('', self.leave) > line_frame.bind ('', self.pick_record) > line_frame.bind ('', self.info_profile) > line_frame.grid (row = n+2, column = 1) > for i in self.range_n_fields: # (0, 1, 2, 3) > field = Label (line_frame, text = record [self.INDICES [i]], anchor = W, width = self.COLUMN_WIDTHS [i], **DB_LIST_LABEL_) > field.grid (row = 0, column = i, sticky = NW) When posting problem code, you should post a minimal, self-contained example that people can try on other systems and versions. Can you create the problem with one record, which you could give, and one binding? Do you need 4 fields, or would 1 'work'? > # Here is the handler: > > def enter (self, event): > w = event.widget > print 'hit list.enter (). Event, widget', event, w, w.__class__ # Tracing line > w.config (bg = SELECTED_BG_COLOR) > > # And here is what comes out. The first line is my tracing line. The name is correct in that it > # names the entered line_frame, but is wrong because it should be the line_frame, not its name. > # The rest is the red exception message: > > hit list.enter (). Event, widget .main-frame.data-frame.title-hit-list.-10- > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > File "/home/fr/python/finance/piam/hit_list.py", line 83, in enter > w.config (bg = SELECTABLE_BG_COLOR) > AttributeError: 'str' object has no attribute 'config' > > # The same thing happens with . The other handlers I haven't done yet. The same bindings work well in > # a Menu class with the difference that the bindings are on the Labels, not a containing Frame. > > # Dell E6500, Ubuntu 10.04, Python 2.6 You might try a current Python release, and the latest tcl/tk 8.5.11 released last March (comes with 3.3.0 Windows release, don't know how on Ubuntu). There might be (have been?) a bug with events on Frames, or on Frames within Frames treated as widgets. -- Terry Jan Reedy From tjreedy at udel.edu Mon Jul 9 02:05:05 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Jul 2012 02:05:05 -0400 Subject: how can I make it work? In-Reply-To: References: Message-ID: On 7/8/2012 10:02 PM, self.python wrote: > it's a finder using threading to accelerate Threading with Python does not accelerate unless all but one of the treads are i/o bound. You need multiple processes to use multiple cores in parallel. -- Terry Jan Reedy From yeryomin.igor at gmail.com Mon Jul 9 02:39:41 2012 From: yeryomin.igor at gmail.com (yeryomin.igor at gmail.com) Date: Sun, 8 Jul 2012 23:39:41 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> Message-ID: <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: > > I have used Python for a couple of projects last year and > > I found it extremely useful. I could write two middle size > > projects in 2-3 months (part time). Right now I am a bit > > rusty and trying to catch up again with Python. > > > > I am now appearing for Job Interviews these days and I am > > wondering if anybody of you appeared for a Python > > Interview. Can you please share the questions you were > > asked. That will be great help to me. > > While I haven't interviewed precisely for Python, I've been > on the other (interviewing) end and can offer a few of the > sorts of things I ask. I don't expect perfect answers to > all of them, but they show me a range of what the > interviewee knows. I try and give a scattershot of > questions from the following areas to try and narrow down > where they fall in terms of pythonability, and then grill > more deeply around the edges that I find. > > Basic Python: > ============= > - do they know a tuple/list/dict when they see it? > > - when to use list vs. tuple vs. dict. vs. set > > - can they use list comprehensions (and know when not to > abuse them? :) > > - can they use tuple unpacking for assignment? > > - string building...do they use "+=" or do they build a list > and use .join() to recombine them efficiently > > - truth-value testing questions and observations (do they > write "if x == True" or do they just write "if x") > > - basic file-processing (iterating over a file's lines) > > - basic understanding of exception handling > > Broader Basic Python: > ===================== > - questions about the standard library ("do you know if > there's a standard library for doing X?", or "in which > library would you find [common functionality Y]?") Most > of these are related to the more common libraries such as > os/os.path/sys/re/itertools > > - questions about iterators/generators > > - questions about map/reduce/sum/etc family of functions > > - questions about "special" methods (____) > > More Advanced Python: > ===================== > - can they manipulate functions as first-class objects > (Python makes it easy, but do they know how) > > - more detailed questions about the std. libraries (such as > datetime/email/csv/zipfile/networking/optparse/unittest) > > - questions about testing (unittests/doctests) > > - questions about docstrings vs. comments, and the "Why" of > them > > - more detailed questions about regular expressions > > - questions about mutability > > - keyword/list parameters and unpacked kwd args > > - questions about popular 3rd-party toolkits (BeautifulSoup, > pyparsing...mostly if they know about them and when to use > them, not so much about implementation details) > > - questions about monkey-patching > > - questions about PDB > > - questions about properties vs. getters/setters > > - questions about classmethods > > - questions about scope/name-resolution > > - use of lambda > > Python History: > =============== > - decorators added in which version? > > - "batteries included" SQL-capible DB in which version? > > - the difference between "class Foo" and "class Foo(object)" > > - questions from "import this" about pythonic code > > Python Resources: > ================= > - what do they know about various Python web frameworks > (knowing a few names is usually good enough, though > knowledge about the frameworks is a nice plus) such as > Django, TurboGears, Zope, etc. > > - what do they know about various Python GUI frameworks and > the pros/cons of them (tkinter, wx, pykde, etc) > > - where do they go with Python related questions (c.l.p, > google, google-groups, etc) > > Other Process-releated things: > ============================== > - do they use revision control > (RCS/CVS/Subversion/Mercurial/Git...anything but VSS) and > know how to use it well > > - do they write automated tests for their code > > Touchy-feely things: > ==================== > - tabs vs. spaces, and their reasoning > > - reason for choosing Python > > - choice of editor/IDE > > Good luck with your interviewing and hope this helped, > > -tkc From hong.yiwei at gmail.com Mon Jul 9 03:21:10 2012 From: hong.yiwei at gmail.com (cheetah) Date: Mon, 9 Jul 2012 00:21:10 -0700 (PDT) Subject: How can I disable module of tkinter when compiling Python 2.5 on redhat9 ? Message-ID: I don't need it. thanks From lists at cheimes.de Mon Jul 9 04:17:52 2012 From: lists at cheimes.de (Christian Heimes) Date: Mon, 09 Jul 2012 10:17:52 +0200 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: Am 09.07.2012 07:50, schrieb Plumo: >> Windows doesn't suppport atomic renames if the right side exists. I >> suggest that you implement two code paths: > > Problem is if the process is stopped between unlink and rename there > would no status file. Yeah, you have to suffer all of Windows' design flaws. You could add a backup status file or use a completely different approach. From rosuav at gmail.com Mon Jul 9 04:41:28 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 9 Jul 2012 18:41:28 +1000 Subject: Discussion on some Code Issues In-Reply-To: <4ffa2c7b$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> <4ffa2c7b$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 9, 2012 at 10:57 AM, Steven D'Aprano wrote: > On Mon, 09 Jul 2012 07:54:47 +1000, Chris Angelico wrote: > >> It's like >> the difference between reminder text on a Magic: The Gathering card and >> the actual entries in the Comprehensive Rules. Perfect example is the >> "Madness" ability - the reminder text explains the ability, but uses >> language that actually is quite incorrect. It's a better explanation, >> though. > > Hang on, you say that an explanation which is "quite incorrect" is > *better* than one which is correct? > > I can see why they call the card "Madness". > > :-P Agreed about the ability name :) The fact is, though, that when you're explaining something, it's often better to have a one-sentence explanation that's not quite technically accurate than two paragraphs explaining it in multiple steps and are opaque to anyone who doesn't have the rules-lawyer mind. (I happen to have such a mind. It's not always a good thing, but it makes me a better debugger.) Does it really hurt to anthropomorphize and say that "Python looks for modules in the directories in sys.path" instead of "Module lookup consists of iterating over the elements in sys.path [and that's leaving out the worst-case DFS where you explain THAT in detail], calling combine_path [or whatever it is] with the element and the module name, and attempting to stat/open the result"? While your listener's getting bogged down in unnecessary detail, s/he isn't grokking the overall purpose of what you're saying. One option is more accurate. The other is far more helpful. ChrisA From nobody at nowhere.com Mon Jul 9 04:57:15 2012 From: nobody at nowhere.com (Nobody) Date: Mon, 09 Jul 2012 09:57:15 +0100 Subject: How to safely maintain a status file References: Message-ID: On Sun, 08 Jul 2012 22:57:56 +0200, Laszlo Nagy wrote: > Yes, this is much better. Almost perfect. Don't forget to consult your > system documentation, and check if the rename operation is atomic or not. > (Most probably it will only be atomic if the original and the renamed file > are on the same physical partition and/or mount point). On Unix, rename() is always atomic, and requires that source and destination are on the same partition (if you want to "move" a file across partitions, you have to copy it then delete the original). > But even if the rename operation is atomic, there is still a race > condition. Your program can be terminated after the original status file > has been deleted, and before the temp file was renamed. In this case, you > will be missing the status file (although your program already did > something just it could not write out the new status). In the event of abnormal termination, losing some data is to be expected. The idea is to only lose the most recent data while keeping the old copy, rather than losing everything. Writing to a temp file then rename()ing achieves that. From mfmdevine at gmail.com Mon Jul 9 05:37:02 2012 From: mfmdevine at gmail.com (Mark Devine) Date: Mon, 9 Jul 2012 10:37:02 +0100 Subject: migrating from python 2.4 to python 2.6 Message-ID: Hi I have a large code base that was written in python 2.4. I want to migrate to python 2.6. Are there any tools that will aid me in this migration? Thanks A -------------- next part -------------- An HTML attachment was scrubbed... URL: From kelebrinir at gmail.com Mon Jul 9 06:33:52 2012 From: kelebrinir at gmail.com (Putilov Roman) Date: Mon, 09 Jul 2012 16:33:52 +0600 Subject: How can I disable module of tkinter when compiling Python 2.5 on redhat9 ? In-Reply-To: References: Message-ID: <4FFAB390.1060004@gmail.com> 09.07.12 13:21, cheetah ?????: > I don't need it. > > thanks In python's setup.py replace: self.detect_tkinter(inc_dirs, lib_dirs) of def detect_modules(self): This will ignore the compilation of _tkinter.c and tkappinit.c of the python distribution. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Jul 9 07:05:27 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 09 Jul 2012 12:05:27 +0100 Subject: migrating from python 2.4 to python 2.6 In-Reply-To: References: Message-ID: On 09/07/2012 10:37, Mark Devine wrote: > Hi > I have a large code base that was written in python 2.4. I want to migrate > to python 2.6. Are there any tools that will aid me in this migration? > > Thanks > > A > > > Check the what's new for python 2.6. If, and I doubt that there are, any compatabilty issues change your code accordingly. If not your code should run as is. An alternative is simply to run your code and see if it breaks, again I doubt it. -- Cheers. Mark Lawrence. From jeanmichel at sequans.com Mon Jul 9 07:05:58 2012 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 09 Jul 2012 13:05:58 +0200 Subject: Deditor 0.4.0 In-Reply-To: References: Message-ID: <4FFABB16.5020507@sequans.com> Kruptein wrote: > Hey I released a new version of my python-focused text-editor. > you can download it at http://launchpad.net/deditor > > What is it? > Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. > I focus on making it a python specific editor but you can use it to edit other files as well. > It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. > > So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. > > NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. > > I hope some of you like it and if you don't try to give some constructive criticism :) > > > Most changes in regard to previous release are under the hood. so existing users might not notice a lot. > Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p > Good job. I have 2 question: Aren't you reinventing the wheel ? No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') Otherwise, I found this bug : Start the editor, click twice on 'Analyse code', and you'll get a traceback. I looked into the related code: def dUpdate(self, trig, value=None): if trig == "tabclosed": return self.tabClosed(value) def tabClosed(self, tab): """Checks if the tab that is closing is a project""" if tab.parentTab == None: pass Your method interfaces are quite inconsistent, I sense this is quite global to your code: 1/ dUpdate has None as default value for 'value' 2/ tab.parentTab will fail if tab is None 3/ on the traceback you get from the bug above, a bool has been given, bool has no parentTab. Here are 2 advices: 1/ Default values are for the fool/weak/noob/..., your pick. I tend to use them only for backward compatibilty or for interface stability. Otherwise, it's better not to use them. Some people still use them appropriately but in your I think it may help. 2/ In your docstrings, note down the expected type of your parameters (only 1 type ! (except for the None alternative)) and stick to it. Regards, JM From python.list at tim.thechases.com Mon Jul 9 07:07:58 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 06:07:58 -0500 Subject: Python Interview Questions In-Reply-To: <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <4FFABB8E.9050207@tim.thechases.com> On 07/09/12 01:39, yeryomin.igor at gmail.com wrote: > On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: yes, yes I did, almost 5 years ago. :-) You didn't include any questions/comments on my email, so it's a bit hard to respond. >> While I haven't interviewed precisely for Python, I've been >> on the other (interviewing) end and can offer a few of the >> sorts of things I ask. [snip] >> Python History: >> =============== >> - decorators added in which version? >> >> - "batteries included" SQL-capible DB in which version? I've long wanted to update my original post in this department to include things like the "with" statement as well as my reasoning. Some of our deployments were stuck on earlier versions (currently our oldest is a 2.4 deployment that is merrily chugging along, somewhat stuck due to an external binary dependency for which terms changed between versions). At the time I wrote that, we had some 2.2 and 2.3 code in production that couldn't use decorators, and sqlite wasn't officially added until 2.5 (IIRC). Now that everything is at least 2.4, code can now use decorators freely. I'd also likely include questions about integer division and other stuff added in 3.x (such as the default new-class behavior). So my main motivation was to make sure applicants knew that, in some of our environments, certain features might not be available. Not that I wanted to hire a Python historian. >> Other Process-releated things: >> ============================== >> - do they use revision control >> (RCS/CVS/Subversion/Mercurial/Git...anything but VSS) and >> know how to use it well >> >> - do they write automated tests for their code Don't let the importance of these two escape. It's SOOOOOOO easy to grab any of the freely available VCS tools and learn the ropes, or to write some test code. Failure to do so just seems like negligence these days. -tkc From darragh.ssa at gmail.com Mon Jul 9 07:28:49 2012 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 9 Jul 2012 04:28:49 -0700 (PDT) Subject: Deditor 0.4.0 In-Reply-To: References: Message-ID: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> Op maandag 9 juli 2012 13:05:58 UTC+2 schreef Jean-Michel Pichavant het volgende: > Kruptein wrote: > > Hey I released a new version of my python-focused text-editor. > > you can download it at http://launchpad.net/deditor > > > > What is it? > > Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. > > I focus on making it a python specific editor but you can use it to edit other files as well. > > It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. > > > > So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. > > > > NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. > > > > I hope some of you like it and if you don't try to give some constructive criticism :) > > > > > > Most changes in regard to previous release are under the hood. so existing users might not notice a lot. > > Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p > > > Good job. > > I have 2 question: > Aren't you reinventing the wheel ? > No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') > > Otherwise, I found this bug : > Start the editor, click twice on 'Analyse code', and you'll get a traceback. > I looked into the related code: > > def dUpdate(self, trig, value=None): > if trig == "tabclosed": > return self.tabClosed(value) > > def tabClosed(self, tab): > """Checks if the tab that is closing is a project""" > if tab.parentTab == None: > pass > > > Your method interfaces are quite inconsistent, I sense this is quite > global to your code: > > 1/ dUpdate has None as default value for 'value' > 2/ tab.parentTab will fail if tab is None > 3/ on the traceback you get from the bug above, a bool has been given, > bool has no parentTab. > > > Here are 2 advices: > > 1/ Default values are for the fool/weak/noob/..., your pick. I tend to > use them only for backward compatibilty or for interface stability. > Otherwise, it's better not to use them. Some people still use them > appropriately but in your I think it may help. > > 2/ In your docstrings, note down the expected type of your parameters > (only 1 type ! (except for the None alternative)) and stick to it. > > Regards, > > JM To begin with not everything that I want to see is yet implemented. A lot still has to be done for example indentation although I really hate tabs ;D I will give the option in a future release maybe even the next one. I'll check the bug as it probably is indeed a bug. Regarding the default value dUpdate is a method from the plugin system and is called when a trigger is updated. some triggers give an additional value for example a trigger that registers pressed buttons could potentially give which exact key as value. However some triggers don't need this additional value. If a plugin needs both types of triggers the method will need this default value to work. Also the dev version already changed that there always will be sent a value so no need for the default value anymore. Regarding the docstrings: as deditor still is under heavy development not all docstrings are correct or even there. From darragh.ssa at gmail.com Mon Jul 9 07:28:49 2012 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 9 Jul 2012 04:28:49 -0700 (PDT) Subject: Deditor 0.4.0 In-Reply-To: References: Message-ID: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> Op maandag 9 juli 2012 13:05:58 UTC+2 schreef Jean-Michel Pichavant het volgende: > Kruptein wrote: > > Hey I released a new version of my python-focused text-editor. > > you can download it at http://launchpad.net/deditor > > > > What is it? > > Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. > > I focus on making it a python specific editor but you can use it to edit other files as well. > > It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. > > > > So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. > > > > NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. > > > > I hope some of you like it and if you don't try to give some constructive criticism :) > > > > > > Most changes in regard to previous release are under the hood. so existing users might not notice a lot. > > Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p > > > Good job. > > I have 2 question: > Aren't you reinventing the wheel ? > No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') > > Otherwise, I found this bug : > Start the editor, click twice on 'Analyse code', and you'll get a traceback. > I looked into the related code: > > def dUpdate(self, trig, value=None): > if trig == "tabclosed": > return self.tabClosed(value) > > def tabClosed(self, tab): > """Checks if the tab that is closing is a project""" > if tab.parentTab == None: > pass > > > Your method interfaces are quite inconsistent, I sense this is quite > global to your code: > > 1/ dUpdate has None as default value for 'value' > 2/ tab.parentTab will fail if tab is None > 3/ on the traceback you get from the bug above, a bool has been given, > bool has no parentTab. > > > Here are 2 advices: > > 1/ Default values are for the fool/weak/noob/..., your pick. I tend to > use them only for backward compatibilty or for interface stability. > Otherwise, it's better not to use them. Some people still use them > appropriately but in your I think it may help. > > 2/ In your docstrings, note down the expected type of your parameters > (only 1 type ! (except for the None alternative)) and stick to it. > > Regards, > > JM To begin with not everything that I want to see is yet implemented. A lot still has to be done for example indentation although I really hate tabs ;D I will give the option in a future release maybe even the next one. I'll check the bug as it probably is indeed a bug. Regarding the default value dUpdate is a method from the plugin system and is called when a trigger is updated. some triggers give an additional value for example a trigger that registers pressed buttons could potentially give which exact key as value. However some triggers don't need this additional value. If a plugin needs both types of triggers the method will need this default value to work. Also the dev version already changed that there always will be sent a value so no need for the default value anymore. Regarding the docstrings: as deditor still is under heavy development not all docstrings are correct or even there. From rmorgan466 at gmail.com Mon Jul 9 07:37:35 2012 From: rmorgan466 at gmail.com (Rita) Date: Mon, 9 Jul 2012 07:37:35 -0400 Subject: recompiling standard modules Message-ID: I noticed that active state python Tk inter isnt compiled with --enable-threads therefore I would like to recompile the module with a new version of TCL/TK which is compiled with threads. How can I do this? -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Mon Jul 9 08:24:01 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Jul 2012 12:24:01 GMT Subject: Discussion on some Code Issues References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> <4ffa2c7b$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ffacd61$0$29988$c3e8da3$5496439d@news.astraweb.com> On Mon, 09 Jul 2012 18:41:28 +1000, Chris Angelico wrote: > Does it really hurt to anthropomorphize Don't anthropomorphise computers. They don't like it when you do. > and say that "Python looks for > modules in the directories in sys.path" instead of "Module lookup > consists of iterating blah blah blah yadda watermelon yadda blah". I don't think so, I often talk about Python looking for files myself. The intentional stance is an incredibly powerful technique for understanding behaviour of all sorts of entities, sentient or not, from DNA to computers to corporations, and even people. But it does depend on context. Sometimes you need more detail than just "Python looks". You need to know precisely *how* Python looks, and how it decides whether it has found or not. And note that I'm still using the intentional stance. -- Steven From contropinion at gmail.com Mon Jul 9 08:41:17 2012 From: contropinion at gmail.com (contro opinion) Date: Mon, 9 Jul 2012 08:41:17 -0400 Subject: how to write configure Message-ID: PyGObject uses the standard autotools for the build infrastructure. To build, it should be as simple as running: $ ./configure --prefix= my python2.7 is in /usr/lib/python2.7 will i write : ./configure --prefix=/usr/lib/python2.7 or ./configure --prefix=/usr/lib -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Mon Jul 9 08:54:03 2012 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 09 Jul 2012 14:54:03 +0200 Subject: Deditor 0.4.0 In-Reply-To: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> References: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> Message-ID: <4FFAD46B.6080900@sequans.com> Kruptein wrote: > Op maandag 9 juli 2012 13:05:58 UTC+2 schreef Jean-Michel Pichavant het volgende: > >> Kruptein wrote: >> >>> Hey I released a new version of my python-focused text-editor. >>> you can download it at http://launchpad.net/deditor >>> >>> What is it? >>> Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. >>> I focus on making it a python specific editor but you can use it to edit other files as well. >>> It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. >>> >>> So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. >>> >>> NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. >>> >>> I hope some of you like it and if you don't try to give some constructive criticism :) >>> >>> >>> Most changes in regard to previous release are under the hood. so existing users might not notice a lot. >>> Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p >>> >>> >> Good job. >> >> I have 2 question: >> Aren't you reinventing the wheel ? >> No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') >> >> Otherwise, I found this bug : >> Start the editor, click twice on 'Analyse code', and you'll get a traceback. >> I looked into the related code: >> >> def dUpdate(self, trig, value=None): >> if trig == "tabclosed": >> return self.tabClosed(value) >> >> def tabClosed(self, tab): >> """Checks if the tab that is closing is a project""" >> if tab.parentTab == None: >> pass >> >> >> Your method interfaces are quite inconsistent, I sense this is quite >> global to your code: >> >> 1/ dUpdate has None as default value for 'value' >> 2/ tab.parentTab will fail if tab is None >> 3/ on the traceback you get from the bug above, a bool has been given, >> bool has no parentTab. >> >> >> Here are 2 advices: >> >> 1/ Default values are for the fool/weak/noob/..., your pick. I tend to >> use them only for backward compatibilty or for interface stability. >> Otherwise, it's better not to use them. Some people still use them >> appropriately but in your I think it may help. >> >> 2/ In your docstrings, note down the expected type of your parameters >> (only 1 type ! (except for the None alternative)) and stick to it. >> >> Regards, >> >> JM >> > > To begin with not everything that I want to see is yet implemented. A lot still has to be done for example indentation although I really hate tabs ;D I will give the option in a future release maybe even the next one. > > I'll check the bug as it probably is indeed a bug. > > Regarding the default value dUpdate is a method from the plugin system and is called when a trigger is updated. some triggers give an additional value for example a trigger that registers pressed buttons could potentially give which exact key as value. However some triggers don't need this additional value. If a plugin needs both types of triggers the method will need this default value to work. Also the dev version already changed that there always will be sent a value so no need for the default value anymore. > > If you can, use the **kwargs syntax. def foo(tabs, **kwargs): # optional arg if kwargs.get('saveFile', False): self.saveFile(tab.file) # required arg if kwargs['saveFile']: self.saveFile() The type of kwargs will be consistent, it will be always a dictionnary, possibly an empty one, but still a dictionnary, and best part of it, if you change the number of argument in the call, you don't break your interface. > Regarding the docstrings: as deditor still is under heavy development not all docstrings are correct or even there. > > Yep, but writing the expected type of your parameters always help, in particular during the dev phase. you can save the verbose part of the documentation for later. Cheers, JM From roy at panix.com Mon Jul 9 09:25:44 2012 From: roy at panix.com (Roy Smith) Date: Mon, 09 Jul 2012 09:25:44 -0400 Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: In article <3e0ef383-9615-4b4d-89c1-e5519971189f at googlegroups.com>, yeryomin.igor at gmail.com wrote: > On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: > > - more detailed questions about the std. libraries (such as > > datetime/email/csv/zipfile/networking/optparse/unittest) You need to be careful when you ask questions like this. I would expect somebody to be aware of those and have a high-level understanding of what they do, but certainly not remember the details of the exact syntax and argument order. Even with stuff I use everyday (like unittest and datetime), I have a browser open to the reference manual most of the time. > > - questions about PDB Heh. I would answer that with, "Python Debugger? I've never used it". > > Python History: > > =============== > > - decorators added in which version? > > > > - "batteries included" SQL-capible DB in which version? > > > > - the difference between "class Foo" and "class Foo(object)" > > > > - questions from "import this" about pythonic code With the exception of the question about new-style classes, these are silly questions. I was around when both decorators and sqlite3 were added. I couldn't possible tell you when to any precision better than "2 dot something". As for the zen of python, it's cute, and a piece of python folklore, but hardly an essential part of being a good python p From darragh.ssa at gmail.com Mon Jul 9 09:33:31 2012 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 9 Jul 2012 06:33:31 -0700 (PDT) Subject: Deditor 0.4.0 In-Reply-To: References: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> Message-ID: <633b49a2-3057-4186-9fb1-66a460a406e9@googlegroups.com> Op maandag 9 juli 2012 14:54:03 UTC+2 schreef Jean-Michel Pichavant het volgende: > Kruptein wrote: > > Op maandag 9 juli 2012 13:05:58 UTC+2 schreef Jean-Michel Pichavant het volgende: > > > >> Kruptein wrote: > >> > >>> Hey I released a new version of my python-focused text-editor. > >>> you can download it at http://launchpad.net/deditor > >>> > >>> What is it? > >>> Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. > >>> I focus on making it a python specific editor but you can use it to edit other files as well. > >>> It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. > >>> > >>> So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. > >>> > >>> NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. > >>> > >>> I hope some of you like it and if you don't try to give some constructive criticism :) > >>> > >>> > >>> Most changes in regard to previous release are under the hood. so existing users might not notice a lot. > >>> Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p > >>> > >>> > >> Good job. > >> > >> I have 2 question: > >> Aren't you reinventing the wheel ? > >> No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') > >> > >> Otherwise, I found this bug : > >> Start the editor, click twice on 'Analyse code', and you'll get a traceback. > >> I looked into the related code: > >> > >> def dUpdate(self, trig, value=None): > >> if trig == "tabclosed": > >> return self.tabClosed(value) > >> > >> def tabClosed(self, tab): > >> """Checks if the tab that is closing is a project""" > >> if tab.parentTab == None: > >> pass > >> > >> > >> Your method interfaces are quite inconsistent, I sense this is quite > >> global to your code: > >> > >> 1/ dUpdate has None as default value for 'value' > >> 2/ tab.parentTab will fail if tab is None > >> 3/ on the traceback you get from the bug above, a bool has been given, > >> bool has no parentTab. > >> > >> > >> Here are 2 advices: > >> > >> 1/ Default values are for the fool/weak/noob/..., your pick. I tend to > >> use them only for backward compatibilty or for interface stability. > >> Otherwise, it's better not to use them. Some people still use them > >> appropriately but in your I think it may help. > >> > >> 2/ In your docstrings, note down the expected type of your parameters > >> (only 1 type ! (except for the None alternative)) and stick to it. > >> > >> Regards, > >> > >> JM > >> > > > > To begin with not everything that I want to see is yet implemented. A lot still has to be done for example indentation although I really hate tabs ;D I will give the option in a future release maybe even the next one. > > > > I'll check the bug as it probably is indeed a bug. > > > > Regarding the default value dUpdate is a method from the plugin system and is called when a trigger is updated. some triggers give an additional value for example a trigger that registers pressed buttons could potentially give which exact key as value. However some triggers don't need this additional value. If a plugin needs both types of triggers the method will need this default value to work. Also the dev version already changed that there always will be sent a value so no need for the default value anymore. > > > > > If you can, use the **kwargs syntax. > def foo(tabs, **kwargs): > # optional arg > if kwargs.get('saveFile', False): > self.saveFile(tab.file) > # required arg > if kwargs['saveFile']: > self.saveFile() > > > The type of kwargs will be consistent, it will be always a dictionnary, > possibly an empty one, but still a dictionnary, and best part of it, if > you change the number of argument in the call, you don't break your > interface. > > > Regarding the docstrings: as deditor still is under heavy development not all docstrings are correct or even there. > > > > > Yep, but writing the expected type of your parameters always help, in > particular during the dev phase. you can save the verbose part of the > documentation for later. > > Cheers, > > JM Yeah I started to use kwargs in some methods but it's only usefull in some cases imo. I'm a pretty decent python dev imo but I know that there is still a lot that I've to learn so often if I get to know something knew I tend to rewrite a large portion of my program(s) and thus I often am too lazy to write proper docstrings as they would change anyway (<- very bad coding practice though ^^) Thanks for the feedback anyways :) From darragh.ssa at gmail.com Mon Jul 9 09:33:31 2012 From: darragh.ssa at gmail.com (Kruptein) Date: Mon, 9 Jul 2012 06:33:31 -0700 (PDT) Subject: Deditor 0.4.0 In-Reply-To: References: <2081b59a-40af-4fc8-a9c2-6d76b2d61e96@googlegroups.com> Message-ID: <633b49a2-3057-4186-9fb1-66a460a406e9@googlegroups.com> Op maandag 9 juli 2012 14:54:03 UTC+2 schreef Jean-Michel Pichavant het volgende: > Kruptein wrote: > > Op maandag 9 juli 2012 13:05:58 UTC+2 schreef Jean-Michel Pichavant het volgende: > > > >> Kruptein wrote: > >> > >>> Hey I released a new version of my python-focused text-editor. > >>> you can download it at http://launchpad.net/deditor > >>> > >>> What is it? > >>> Deditor is aimed to be a text-editor which can be used as a basic text-editor as gedit or with the right plugins become a full-feature ide. > >>> I focus on making it a python specific editor but you can use it to edit other files as well. > >>> It is python specific because the plugin system that is used (DPlug) is written in python and thus all plugins are written in python. Also some of the plugins there is one plugin that comes bundled with deditor that adds some python specific features like code-analyzing, code-inspection, auto-completion etc. > >>> > >>> So plugins are the main core of the program you can disable and enable plugins at your will. The plugins that come bundled are made to increase the joy of programming. > >>> > >>> NOTICE that this I don't regard this as a stable product yet. There is no high risk in data loss and there are definitely no privacy concerns but you should still be aware that there are bugs/malfunctions and that you will encounter them. > >>> > >>> I hope some of you like it and if you don't try to give some constructive criticism :) > >>> > >>> > >>> Most changes in regard to previous release are under the hood. so existing users might not notice a lot. > >>> Also the customize plugin's second configuration tab: syntax highlighting is bugged try to avoid it :p > >>> > >>> > >> Good job. > >> > >> I have 2 question: > >> Aren't you reinventing the wheel ? > >> No way to use tabs for tabulation ??? (I'm CEO of the 'space haters club') > >> > >> Otherwise, I found this bug : > >> Start the editor, click twice on 'Analyse code', and you'll get a traceback. > >> I looked into the related code: > >> > >> def dUpdate(self, trig, value=None): > >> if trig == "tabclosed": > >> return self.tabClosed(value) > >> > >> def tabClosed(self, tab): > >> """Checks if the tab that is closing is a project""" > >> if tab.parentTab == None: > >> pass > >> > >> > >> Your method interfaces are quite inconsistent, I sense this is quite > >> global to your code: > >> > >> 1/ dUpdate has None as default value for 'value' > >> 2/ tab.parentTab will fail if tab is None > >> 3/ on the traceback you get from the bug above, a bool has been given, > >> bool has no parentTab. > >> > >> > >> Here are 2 advices: > >> > >> 1/ Default values are for the fool/weak/noob/..., your pick. I tend to > >> use them only for backward compatibilty or for interface stability. > >> Otherwise, it's better not to use them. Some people still use them > >> appropriately but in your I think it may help. > >> > >> 2/ In your docstrings, note down the expected type of your parameters > >> (only 1 type ! (except for the None alternative)) and stick to it. > >> > >> Regards, > >> > >> JM > >> > > > > To begin with not everything that I want to see is yet implemented. A lot still has to be done for example indentation although I really hate tabs ;D I will give the option in a future release maybe even the next one. > > > > I'll check the bug as it probably is indeed a bug. > > > > Regarding the default value dUpdate is a method from the plugin system and is called when a trigger is updated. some triggers give an additional value for example a trigger that registers pressed buttons could potentially give which exact key as value. However some triggers don't need this additional value. If a plugin needs both types of triggers the method will need this default value to work. Also the dev version already changed that there always will be sent a value so no need for the default value anymore. > > > > > If you can, use the **kwargs syntax. > def foo(tabs, **kwargs): > # optional arg > if kwargs.get('saveFile', False): > self.saveFile(tab.file) > # required arg > if kwargs['saveFile']: > self.saveFile() > > > The type of kwargs will be consistent, it will be always a dictionnary, > possibly an empty one, but still a dictionnary, and best part of it, if > you change the number of argument in the call, you don't break your > interface. > > > Regarding the docstrings: as deditor still is under heavy development not all docstrings are correct or even there. > > > > > Yep, but writing the expected type of your parameters always help, in > particular during the dev phase. you can save the verbose part of the > documentation for later. > > Cheers, > > JM Yeah I started to use kwargs in some methods but it's only usefull in some cases imo. I'm a pretty decent python dev imo but I know that there is still a lot that I've to learn so often if I get to know something knew I tend to rewrite a large portion of my program(s) and thus I often am too lazy to write proper docstrings as they would change anyway (<- very bad coding practice though ^^) Thanks for the feedback anyways :) From duncan.booth at invalid.invalid Mon Jul 9 10:02:54 2012 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jul 2012 14:02:54 GMT Subject: How to safely maintain a status file References: Message-ID: Richard Baron Penman wrote: > Is there a better way? Or do I need to use a database? Using a database would seem to meet a lot of your needs. Don't forget that Python comes with a sqlite database engine included, so it shouldn't take you more than a few lines of code to open the database once and then write out your status every few seconds. import sqlite3 con = sqlite3.connect('status.db') ... with con: cur = con.cursor() cur.execute('UPDATE ...', ...) and similar code to restore the status or create required tables on startup. -- Duncan Booth http://kupuguy.blogspot.com From rosuav at gmail.com Mon Jul 9 10:47:45 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 10 Jul 2012 00:47:45 +1000 Subject: Discussion on some Code Issues In-Reply-To: <4ffacd61$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> <4ffa2c7b$0$29988$c3e8da3$5496439d@news.astraweb.com> <4ffacd61$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 9, 2012 at 10:24 PM, Steven D'Aprano wrote: > But it does depend on context. Sometimes you need more detail than just > "Python looks". You need to know precisely *how* Python looks, and how it > decides whether it has found or not. Agreed. So, looking back at the original context: A question was posed that isn't really about Python at all, but more about file systems. I gave a simple one-sentence answer that omitted heaps of details. It didn't seem likely that someone confused by path names would be changing the current directory inside the script, nor that the distinction of who evaluates a path would be significant (how often does _anyone_ care whether your path is parsed by Python, by the OS, or by the underlying file system?). ChrisA From tismer at stackless.com Mon Jul 9 11:51:25 2012 From: tismer at stackless.com (Christian Tismer) Date: Mon, 09 Jul 2012 17:51:25 +0200 Subject: tiffany 0.6.1 released In-Reply-To: <7x4nps3gxg.fsf@ruckus.brouhaha.com> References: <7x4nps3gxg.fsf@ruckus.brouhaha.com> Message-ID: <4FFAFDFD.5000205@stackless.com> On 30.06.12 18:25, Paul Rubin wrote: > Christian Tismer writes: >> Tiffany stands for any tiff. The tiny module solves a large set of >> problems, has no dependencies and just works wherever Python works. >> Tiffany was developed in the course of the *DiDoCa* project and will >> always appear on PyPi. > This sounds pretty neat. I didn't comment on it earlier because I > haven't tried it out, since I haven't had occasion to deal with tiff > files anytime recently. But I've had to process them for some projects > in the past, and tiffany would have been useful then. It's good to know > that it's out there. Meanwhile I got some feedback and test data. (Thanks to Christian and Anthon) It turns out to be a problem with multiple strips in a tiff file. PIL does not support that. Maybe I can find an easy solution, maybe I'm better off using smc.freeimage as suggested by Christian Heimes, we will see. Right now I'm pretty exhaused after EuroPython... cheers - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Karl-Liebknecht-Str. 121 : *Starship* http://starship.python.net/ 14482 Potsdam : PGP key -> http://pgp.uni-mainz.de work +49 173 24 18 776 mobile +49 173 24 18 776 fax n.a. PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From python.list at tim.thechases.com Mon Jul 9 13:40:59 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 12:40:59 -0500 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <4FFB17AB.3030303@tim.thechases.com> On 07/09/12 08:25, Roy Smith wrote: >> On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: > >>> - more detailed questions about the std. libraries (such as >>> datetime/email/csv/zipfile/networking/optparse/unittest) > > You need to be careful when you ask questions like this. I would expect > somebody to be aware of those and have a high-level understanding of > what they do, but certainly not remember the details of the exact syntax > and argument order. Even with stuff I use everyday (like unittest and > datetime), I have a browser open to the reference manual most of the > time. Yeah, the aim isn't to grill them on the minutia, but to get a feeling that they know the basics. The zipfile module offers a ZipFile object for reading/writing zip files with or without compression. The CSV file allows for reading/writing CSV files with definable delimiters and quoting/escaping. Etc. >>> - questions about PDB > > Heh. I would answer that with, "Python Debugger? I've never used it". The ability to know off the top of your head that it's the "Python Debugger" is more than enough :-) That's just first-order ignorance: you know what you don't know and can spend a few minutes reading up on it if you need it. The second[or higher]-order ignorance of not knowing what pdb is (or, if you need more powerful debugging, how to do it) is sign the person hasn't been programming in Python much. >>> Python History: >>> =============== >>> - decorators added in which version? >>> >>> - "batteries included" SQL-capible DB in which version? >>> >>> - the difference between "class Foo" and "class Foo(object)" >>> >>> - questions from "import this" about pythonic code > > With the exception of the question about new-style classes, these are > silly questions. I was around when both decorators and sqlite3 were > added. I couldn't possible tell you when to any precision better than > "2 dot something". I'd even be satisfied if a person just knew that such features weren't there all along and might need to be worked around for older deployments. > As for the zen of python, it's cute, and a piece of python > folklore, but hardly an essential part of being a good python p [Ed: something appears to have gotten truncated there] Yeah, it's more about a person being sufficiently steeped in python to know bits and pieces of the zen, and their ability to recognize/create pythonic code. I've seen enough Java-written-in-Python to know what I don't want :-) -tkc From rantingrickjohnson at gmail.com Mon Jul 9 13:49:07 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 9 Jul 2012 10:49:07 -0700 (PDT) Subject: Tkinter.event.widget: handler gets name instead of widget. References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: On Jul 9, 12:58?am, Terry Reedy wrote: > When posting problem code, you should post a minimal, self-contained > example that people can try on other systems and versions. Can you > create the problem with one record, which you could give, and one > binding? Do you need 4 fields, or would 1 'work'? I'll firmly back that sentiment. Fredric, if you cannot get the following simple code events to work properly, then how do you think you can get events working properly on something more complex? ## START CODE ARTISTRY ## import Tkinter as tk from Tkconstants import * class MyFrame(tk.Frame): def __init__(self, master, **kw): tk.Frame.__init__(self, master, **kw) self.bind('', self.evtMouseEnter) self.bind('', self.evtMouseLeave) self.bind('', self.evtButtonOneClick) def evtMouseEnter(self, event): event.widget.config(bg='magenta') def evtMouseLeave(self, event): event.widget.config(bg='SystemButtonFace') def evtButtonOneClick(self, event): event.widget.config(bg='green') if __name__ == '__main__': root = tk.Tk() for x in range(10): f = MyFrame(root, height=20, bd=1, relief=SOLID) f.pack(fill=X, expand=YES, padx=5, pady=5) root.mainloop() ## END CODE ARTISTRY ## ----------------------- More points to ponder: ----------------------- 1. Just because the Tkinter designers decided to use idiotic names for event sequences does not mean you are required to blindly follow their bad example (the whole: "if johnny jumps off a cliff...", thing comes to mind) 2. I would strongly recommend you invest more thought into your event handler identifiers. ALL event handlers should marked as *event handlers* using a prefix. I like to use the prefix "evt". Some people prefer other prefixes. In any case, just remember to be consistent. Also, event handler names should reflect WHAT event they are processing, not some esoteric functionality of the application like "pick_record" or "info_profile". However if you like, simply have the event handler CALL an outside func/meth. This type of consistency is what separates the men from the boys. 3. The Python Style Guide[1] frowns on superfluous white space (be it horizontal OR vertical!) I would strongly recommend you read and adapt as much of this style as you possibly can bear. Even if we don't all get along, it IS *very* important that we structure our code in a similar style. [1] http://www.python.org/dev/peps/pep-0008/ From rantingrickjohnson at gmail.com Mon Jul 9 14:44:11 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 9 Jul 2012 11:44:11 -0700 (PDT) Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <54b8ed0a-5b89-454a-81a7-ad96667ed15c@l32g2000yqc.googlegroups.com> On Jul 9, 12:40?pm, Tim Chase wrote: >?The second[or higher]-order > ignorance of not knowing what pdb is (or, if you need more powerful > debugging, how to do it) is sign the person hasn't been programming > in Python much. So guru knowledge of pdb is prerequisite to being accepted as a Pythonista? I find that ridiculous since *real* programmers don't use debuggers anyway. > [Ed: something appears to have gotten truncated there] ?Yeah, it's > more about a person being sufficiently steeped in python to know > bits and pieces of the zen, and their ability to recognize/create > pythonic code. ?I've seen enough Java-written-in-Python to know what > I don't want :-) I know you are a member of the group who has an aversion to strict OOP paradigm but is this a justified aversion, or just fear of OOP due to static evolution? Look, i don't like java's strict approach either, however, i do not have an aversion to OOP. From tjreedy at udel.edu Mon Jul 9 15:45:38 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 09 Jul 2012 15:45:38 -0400 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: On 7/9/2012 1:49 PM, Rick Johnson wrote: > On Jul 9, 12:58 am, Terry Reedy wrote: >> When posting problem code, you should post a minimal, self-contained >> example that people can try on other systems and versions. Can you >> create the problem with one record, which you could give, and one >> binding? Do you need 4 fields, or would 1 'work'? > > I'll firmly back that sentiment. Fredric, if you cannot get the > following simple code events to work properly, then how do you think > you can get events working properly on something more complex? > > ## START CODE ARTISTRY ## > import Tkinter as tk > from Tkconstants import * > > class MyFrame(tk.Frame): > def __init__(self, master, **kw): > tk.Frame.__init__(self, master, **kw) > self.bind('', self.evtMouseEnter) > self.bind('', self.evtMouseLeave) > self.bind('', self.evtButtonOneClick) > > def evtMouseEnter(self, event): > event.widget.config(bg='magenta') > > def evtMouseLeave(self, event): > event.widget.config(bg='SystemButtonFace') > > def evtButtonOneClick(self, event): > event.widget.config(bg='green') > > if __name__ == '__main__': > root = tk.Tk() > for x in range(10): > f = MyFrame(root, height=20, bd=1, relief=SOLID) > f.pack(fill=X, expand=YES, padx=5, pady=5) > root.mainloop() > ## END CODE ARTISTRY ## I copied and pasted this self-contained code into a 3.3 Idle edit window and lightly edited for 3.x. Change 'Tkinter' to 'tkinter', remove tkconstants import and prefix constants with 'tk.'. (The alternative: change 'tkconstants' to 'tkinter.constants', but I prefer prefixes). It runs as expected. import tkinter as tk class MyFrame(tk.Frame): def __init__(self, master, **kw): tk.Frame.__init__(self, master, **kw) self.bind('', self.evtMouseEnter) self.bind('', self.evtMouseLeave) self.bind('', self.evtButtonOneClick) def evtMouseEnter(self, event): event.widget.config(bg='magenta') def evtMouseLeave(self, event): event.widget.config(bg='SystemButtonFace') def evtButtonOneClick(self, event): event.widget.config(bg='green') if __name__ == '__main__': root = tk.Tk() for x in range(10): f = MyFrame(root, height=20, bd=1, relief=tk.SOLID) f.pack(fill=tk.X, expand=tk.YES, padx=5, pady=5) root.mainloop() Add details and data (maybe less than 10 records) until you get what you want or recreate problem. -- Terry Jan Reedy From demianbrecht at gmail.com Mon Jul 9 16:11:52 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Mon, 9 Jul 2012 13:11:52 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <2f9c3a3a-b163-4d71-a92d-1646cba09e0a@googlegroups.com> On Monday, 9 July 2012 10:40:59 UTC-7, Tim Chase wrote: > On 07/09/12 08:25, Roy Smith wrote: > >> On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: > > > >>> - more detailed questions about the std. libraries (such as > >>> datetime/email/csv/zipfile/networking/optparse/unittest) > > > > You need to be careful when you ask questions like this. I would expect > > somebody to be aware of those and have a high-level understanding of > > what they do, but certainly not remember the details of the exact syntax > > and argument order. Even with stuff I use everyday (like unittest and > > datetime), I have a browser open to the reference manual most of the > > time. > > Yeah, the aim isn't to grill them on the minutia, but to get a > feeling that they know the basics. The zipfile module offers a > ZipFile object for reading/writing zip files with or without > compression. The CSV file allows for reading/writing CSV files with > definable delimiters and quoting/escaping. Etc. > > > >>> - questions about PDB > > > > Heh. I would answer that with, "Python Debugger? I've never used it". > > The ability to know off the top of your head that it's the "Python > Debugger" is more than enough :-) That's just first-order > ignorance: you know what you don't know and can spend a few minutes > reading up on it if you need it. The second[or higher]-order > ignorance of not knowing what pdb is (or, if you need more powerful > debugging, how to do it) is sign the person hasn't been programming > in Python much. > > >>> Python History: > >>> =============== > >>> - decorators added in which version? > >>> > >>> - "batteries included" SQL-capible DB in which version? > >>> > >>> - the difference between "class Foo" and "class Foo(object)" > >>> > >>> - questions from "import this" about pythonic code > > > > With the exception of the question about new-style classes, these are > > silly questions. I was around when both decorators and sqlite3 were > > added. I couldn't possible tell you when to any precision better than > > "2 dot something". > > I'd even be satisfied if a person just knew that such features > weren't there all along and might need to be worked around for older > deployments. > > > As for the zen of python, it's cute, and a piece of python > > folklore, but hardly an essential part of being a good python p > > [Ed: something appears to have gotten truncated there] Yeah, it's > more about a person being sufficiently steeped in python to know > bits and pieces of the zen, and their ability to recognize/create > pythonic code. I've seen enough Java-written-in-Python to know what > I don't want :-) > > -tkc Definitely appreciate your approach, I've asked similar questions when interviewing. I also usually like to ask what a candidate likes and dislikes about Python, hoping for the GIL to creep up, along with an explanation as to what it is, implementations that don't have it along with methods of getting around the lock (although that would be a fairly advanced topic IMHO). If it doesn't come up, sometimes I'll pop it in depending on their level of experience. From demianbrecht at gmail.com Mon Jul 9 16:11:52 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Mon, 9 Jul 2012 13:11:52 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <2f9c3a3a-b163-4d71-a92d-1646cba09e0a@googlegroups.com> On Monday, 9 July 2012 10:40:59 UTC-7, Tim Chase wrote: > On 07/09/12 08:25, Roy Smith wrote: > >> On Tuesday, 30 October 2007 21:24:04 UTC+2, Tim Chase wrote: > > > >>> - more detailed questions about the std. libraries (such as > >>> datetime/email/csv/zipfile/networking/optparse/unittest) > > > > You need to be careful when you ask questions like this. I would expect > > somebody to be aware of those and have a high-level understanding of > > what they do, but certainly not remember the details of the exact syntax > > and argument order. Even with stuff I use everyday (like unittest and > > datetime), I have a browser open to the reference manual most of the > > time. > > Yeah, the aim isn't to grill them on the minutia, but to get a > feeling that they know the basics. The zipfile module offers a > ZipFile object for reading/writing zip files with or without > compression. The CSV file allows for reading/writing CSV files with > definable delimiters and quoting/escaping. Etc. > > > >>> - questions about PDB > > > > Heh. I would answer that with, "Python Debugger? I've never used it". > > The ability to know off the top of your head that it's the "Python > Debugger" is more than enough :-) That's just first-order > ignorance: you know what you don't know and can spend a few minutes > reading up on it if you need it. The second[or higher]-order > ignorance of not knowing what pdb is (or, if you need more powerful > debugging, how to do it) is sign the person hasn't been programming > in Python much. > > >>> Python History: > >>> =============== > >>> - decorators added in which version? > >>> > >>> - "batteries included" SQL-capible DB in which version? > >>> > >>> - the difference between "class Foo" and "class Foo(object)" > >>> > >>> - questions from "import this" about pythonic code > > > > With the exception of the question about new-style classes, these are > > silly questions. I was around when both decorators and sqlite3 were > > added. I couldn't possible tell you when to any precision better than > > "2 dot something". > > I'd even be satisfied if a person just knew that such features > weren't there all along and might need to be worked around for older > deployments. > > > As for the zen of python, it's cute, and a piece of python > > folklore, but hardly an essential part of being a good python p > > [Ed: something appears to have gotten truncated there] Yeah, it's > more about a person being sufficiently steeped in python to know > bits and pieces of the zen, and their ability to recognize/create > pythonic code. I've seen enough Java-written-in-Python to know what > I don't want :-) > > -tkc Definitely appreciate your approach, I've asked similar questions when interviewing. I also usually like to ask what a candidate likes and dislikes about Python, hoping for the GIL to creep up, along with an explanation as to what it is, implementations that don't have it along with methods of getting around the lock (although that would be a fairly advanced topic IMHO). If it doesn't come up, sometimes I'll pop it in depending on their level of experience. From nagle at animats.com Mon Jul 9 16:24:01 2012 From: nagle at animats.com (John Nagle) Date: Mon, 09 Jul 2012 13:24:01 -0700 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: On 7/8/2012 2:52 PM, Christian Heimes wrote: > You are contradicting yourself. Either the OS is providing a fully > atomic rename or it doesn't. All POSIX compatible OS provide an atomic > rename functionality that renames the file atomically or fails without > loosing the target side. On POSIX OS it doesn't matter if the target exists. Rename on some file system types (particularly NFS) may not be atomic. > > You don't need locks or any other fancy stuff. You just need to make > sure that you flush the data and metadata correctly to the disk and > force a re-write of the directory inode, too. It's a standard pattern on > POSIX platforms and well documented in e.g. the maildir RFC. > > You can use the same pattern on Windows but it doesn't work as good. That's because you're using the wrong approach. See how to use ReplaceFile under Win32: http://msdn.microsoft.com/en-us/library/aa365512%28VS.85%29.aspx Renaming files is the wrong way to synchronize a crawler. Use a database that has ACID properties, such as SQLite. Far fewer I/O operations are required for small updates. It's not the 1980s any more. I use a MySQL database to synchronize multiple processes which crawl web sites. The tables of past activity are InnoDB tables, which support transactions. The table of what's going on right now is a MEMORY table. If the database crashes, the past activity is recovered cleanly, the MEMORY table comes back empty, and all the crawler processes lose their database connections, abort, and are restarted. This allows multiple servers to coordinate through one database. John Nagle From anthra.norell at bluewin.ch Mon Jul 9 16:39:45 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Mon, 09 Jul 2012 22:39:45 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: <1341866385.2387.158.camel@hatchbox-one> On Mon, 2012-07-09 at 01:58 -0400, Terry Reedy wrote: > On 7/8/2012 5:19 PM, Frederic Rentsch wrote: > > Hi widget wizards, > > > > The manual describes the "event" attribute "widget" as "The widget > > which generated this event. This is a valid Tkinter widget instance, not > > a name. This attribute is set for all events." > > Same in 3.3, with nice example of using it. > > def turnRed(self, event): > event.widget["activeforeground"] = "red" > > self.button.bind("", self.turnRed) > > > Ans so it is--has been until on the latest occasion "event.widget" was > > not the widget, but its name, crashing the handler. > > Has event.widget been the widget only in other programs or previously > with the same program? I bind to Frames, each Frame calling the same handler that is supposed to change the background color. It is the Enter action that generates the event. No later the handler receives the event whose attribute widget is the widget's name (full path). My code doesn't create events anywhere. I suppose events vanish when the last handler terminates. . . . > When posting problem code, you should post a minimal, self-contained > example that people can try on other systems and versions. Attempting to strip the critical code, throwing out everything incidental to the problem so I could post something intelligible, I failed to fail: the bare essentials work. The problem appears to be in the incidental. > Can you > create the problem with one record, which you could give, and one > binding? Do you need 4 fields, or would 1 'work'? > It fails even with the Frame containing no Labels at all, like this: for n, record in enumerate(records): line_frame = Frame (self, name = _verbalize_number (n), width = 600, height = 20, relief = RAISED, **BUTTON_FRAME_) line_frame.bind ('', self.enter) ## No Labels at all: ## for i in self.range_n_fields: ## field = Label (line_frame, text = record [self.INDICES [i]], anchor = W, width = self.COLUMN_WIDTHS [i], **DB_LIST_LABEL_) ## field.grid (row = 0, column = i, sticky = NW) def enter (self, event): w = event.widget print 'hit list.enter (). Event, widget', event, w, w.__class__ w.config (bg = ENTERED_BG_COLOR) hit list.leave (). Event, widget .main-frame.data-frame.title-hit-list.one-zero Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "/home/fr/python/finance/piam/hit_list.py", line 114, in enter w.config (bg = ENTERED_BG_COLOR) AttributeError: 'str' object has no attribute 'config' _verbalize_number spells out the line numbers, because the manual says something about digits being reserved for the auto-generated widget names. I thought that assigned names containing digits might be a problem, but it wasn't. The dictionary arguments, by the way, are just style elements: colors, fonts, reliefs, etc. nothing functionally essential. > > > > # Dell E6500, Ubuntu 10.04, Python 2.6 > > You might try a current Python release, and the latest tcl/tk 8.5.11 > released last March (comes with 3.3.0 Windows release, don't know how on > Ubuntu). There might be (have been?) a bug with events on Frames, or on > Frames within Frames treated as widgets. > > -- > Terry Jan Reedy > Terry, I interspersed a couple of answers above. As to your last suggestion I got Python 2.7.3 and managed to compile it. I would have preferred something ready to install, but that doesn't seem to be available for Linux. The compile went smoothly. But it'll take me another day to reorganize, beginning with the Applications menu which still shows "IDLE (Python 2.6)", while terminals already call the new version 2.7.3, but it doesn't know where MySQLdb is, and possibly where other things are. So for now I can't report on this effort either. But I certainly appreciate your help. Many thanks. Frederic From anthra.norell at bluewin.ch Mon Jul 9 16:47:09 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Mon, 09 Jul 2012 22:47:09 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: <1341866829.2387.163.camel@hatchbox-one> On Mon, 2012-07-09 at 10:49 -0700, Rick Johnson wrote: > On Jul 9, 12:58 am, Terry Reedy wrote: > > When posting problem code, you should post a minimal, self-contained > > example that people can try on other systems and versions. Can you > > create the problem with one record, which you could give, and one > > binding? Do you need 4 fields, or would 1 'work'? > > I'll firmly back that sentiment. Fredric, if you cannot get the > following simple code events to work properly, then how do you think > you can get events working properly on something more complex? > > ## START CODE ARTISTRY ## > import Tkinter as tk > from Tkconstants import * > > class MyFrame(tk.Frame): > def __init__(self, master, **kw): > tk.Frame.__init__(self, master, **kw) > self.bind('', self.evtMouseEnter) > self.bind('', self.evtMouseLeave) > self.bind('', self.evtButtonOneClick) > > def evtMouseEnter(self, event): > event.widget.config(bg='magenta') > > def evtMouseLeave(self, event): > event.widget.config(bg='SystemButtonFace') > > def evtButtonOneClick(self, event): > event.widget.config(bg='green') > > if __name__ == '__main__': > root = tk.Tk() > for x in range(10): > f = MyFrame(root, height=20, bd=1, relief=SOLID) > f.pack(fill=X, expand=YES, padx=5, pady=5) > root.mainloop() > ## END CODE ARTISTRY ## > > ----------------------- > More points to ponder: > ----------------------- > 1. Just because the Tkinter designers decided to use idiotic names for > event sequences does not mean you are required to blindly follow their > bad example (the whole: "if johnny jumps off a cliff...", thing comes > to mind) > > 2. I would strongly recommend you invest more thought into your event > handler identifiers. ALL event handlers should marked as *event > handlers* using a prefix. I like to use the prefix "evt". Some people > prefer other prefixes. In any case, just remember to be consistent. > Also, event handler names should reflect WHAT event they are > processing, not some esoteric functionality of the application like > "pick_record" or "info_profile". However if you like, simply have the > event handler CALL an outside func/meth. This type of consistency is > what separates the men from the boys. > > 3. The Python Style Guide[1] frowns on superfluous white space (be it > horizontal OR vertical!) I would strongly recommend you read and adapt > as much of this style as you possibly can bear. Even if we don't all > get along, it IS *very* important that we structure our code in a > similar style. > > [1] http://www.python.org/dev/peps/pep-0008/ Rick, Thanks for your remarks. I spent most of the day working with Terry's input. And now I am falling asleep. So I shall study your inspirations tomorrow. Frederic From mhrivnak at hrivnak.org Mon Jul 9 16:47:22 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Mon, 9 Jul 2012 16:47:22 -0400 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: Please consider batching this data and doing larger writes. Thrashing the hard drive is not a good plan for performance or hardware longevity. For example, crawl an entire FQDN and then write out the results in one operation. If your job fails in the middle and you have to start that FQDN over, no big deal. If that's too big of a chunk for your purposes, perhaps break each FQDN up into top-level directories and crawl each of those in one operation before writing to disk. There are existing solutions for managing job queues, so you can choose what you like. If you're unfamiliar, maybe start by looking at celery. Michael On Mon, Jul 9, 2012 at 1:52 AM, Plumo wrote: >> What are you keeping in this status file that needs to be saved >> several times per second? Depending on what type of state you're >> storing and how persistent it needs to be, there may be a better way >> to store it. >> >> Michael > > This is for a threaded web crawler. I want to cache what URL's are > currently in the queue so if terminated the crawler can continue next > time from the same point. > -- > http://mail.python.org/mailman/listinfo/python-list From peter.milliken at gmail.com Mon Jul 9 17:22:44 2012 From: peter.milliken at gmail.com (Peter) Date: Mon, 9 Jul 2012 14:22:44 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" If the answer included programming then they were hired, if not, then they went to the "B" list. In my experience, anybody who is really interested in programming will have it as a hobby (and is keen to learn even if they don't currently have the knowledge you require) - otherwise it is "just a job". Every job has a learning curve - whether it is just the particular domain or even a new language, the individual who sees programming as more "than a job" will come up to speed much faster and be more productive in both the short and long term. Every programmer I have ever hired using this criteria worked out well. From peter.milliken at gmail.com Mon Jul 9 17:22:44 2012 From: peter.milliken at gmail.com (Peter) Date: Mon, 9 Jul 2012 14:22:44 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" If the answer included programming then they were hired, if not, then they went to the "B" list. In my experience, anybody who is really interested in programming will have it as a hobby (and is keen to learn even if they don't currently have the knowledge you require) - otherwise it is "just a job". Every job has a learning curve - whether it is just the particular domain or even a new language, the individual who sees programming as more "than a job" will come up to speed much faster and be more productive in both the short and long term. Every programmer I have ever hired using this criteria worked out well. From drsalists at gmail.com Mon Jul 9 17:34:50 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 9 Jul 2012 21:34:50 +0000 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: On Mon, Jul 9, 2012 at 8:24 PM, John Nagle wrote: > On 7/8/2012 2:52 PM, Christian Heimes wrote: > >> You are contradicting yourself. Either the OS is providing a fully >> atomic rename or it doesn't. All POSIX compatible OS provide an atomic >> rename functionality that renames the file atomically or fails without >> loosing the target side. On POSIX OS it doesn't matter if the target >> exists. >> > > Rename on some file system types (particularly NFS) may not be atomic. > Actually, ISTR that rename() is one of the few things on NFS that is atomic. http://bugs.python.org/issue8828 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Jul 9 18:23:39 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 10 Jul 2012 08:23:39 +1000 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: On Tue, Jul 10, 2012 at 3:49 AM, Rick Johnson wrote: > ALL event handlers should marked as *event > handlers* using a prefix. I like to use the prefix "evt". Some people > prefer other prefixes. In any case, just remember to be consistent. > Also, event handler names should reflect WHAT event they are > processing, not some esoteric functionality of the application like > "pick_record" or "info_profile". However if you like, simply have the > event handler CALL an outside func/meth. This type of consistency is > what separates the men from the boys. Or perhaps it separates the half-elves from the hobgoblins. Hard-and-fast rules are seldom valid in stylistic questions. There's nothing wrong with having a prefix like "evt" or "on" or whatever; there's also nothing wrong with a naming convention of PB_Open_Click (PB for "PushButton" (which is what that GUI toolkit called them), Open being what the button does, and Click is the event being handled - that's the VX-REXX convention). Or having no specific event handler and going straight to your "pick_record" function; that's fine too, especially if you have multiple entry-points to that. Frederic, you'll get a lot of advice on this list, but treat it as just that - advice. There are very few actual rules; read what people say and then make your own choices. ChrisA From jeanpierreda at gmail.com Mon Jul 9 18:53:18 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 9 Jul 2012 18:53:18 -0400 Subject: Python Interview Questions In-Reply-To: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: On Mon, Jul 9, 2012 at 5:22 PM, Peter wrote: > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" > If the answer included programming then they were hired, if not, then they went to the "B" list. Woe is the poor college grad, who wants to appear like a well-rounded individual and lists capoeira and gardening, instead. -- Devin From cs at zip.com.au Mon Jul 9 19:05:07 2012 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 10 Jul 2012 09:05:07 +1000 Subject: Python Interview Questions In-Reply-To: <54b8ed0a-5b89-454a-81a7-ad96667ed15c@l32g2000yqc.googlegroups.com> References: <54b8ed0a-5b89-454a-81a7-ad96667ed15c@l32g2000yqc.googlegroups.com> Message-ID: <20120709230507.GA16706@cskk.homeip.net> On 09Jul2012 11:44, Rick Johnson wrote: | On Jul 9, 12:40?pm, Tim Chase wrote: | >?The second[or higher]-order | > ignorance of not knowing what pdb is (or, if you need more powerful | > debugging, how to do it) is sign the person hasn't been programming | > in Python much. | | So guru knowledge of pdb is prerequisite to being accepted as a | Pythonista? I find that ridiculous since *real* programmers don't use | debuggers anyway. You've misread him. He's saying not knowing what PDB is and what it may be used for is a sign of low experience. Whether one uses it or not isn't what he's measuring, it's whether one knows what it is for and how it may be used. | > [...] ?I've seen enough Java-written-in-Python to know what | > I don't want :-) | | I know you are a member of the group who has an aversion to strict OOP | paradigm but is this a justified aversion, or just fear of OOP due to | static evolution? Look, i don't like java's strict approach either, | however, i do not have an aversion to OOP. More misreading. "Java-written-in-Python" (and its variants) means non-python code written in python, in this case from someone with a strong (or rigid) Java background who is not adept with Python idioms. It has nothing to do with OOP one way or the other. Surely we've all seen (and doubtless written) clumsy python code; this is an example. Cheers, -- Cameron Simpson A strong conviction that something must be done is the parent of many bad measures. - Daniel Webster From roy at panix.com Mon Jul 9 19:08:36 2012 From: roy at panix.com (Roy Smith) Date: Mon, 09 Jul 2012 19:08:36 -0400 Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> Message-ID: In article , Peter wrote: > One of my favourite questions when interviewing - and it was 100% reliable > :-) - "what are your hobbies?" "My hobby happens to be gardening, for which I don't expect to be paid." From cs at zip.com.au Mon Jul 9 19:12:35 2012 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 10 Jul 2012 09:12:35 +1000 Subject: Python Interview Questions In-Reply-To: References: Message-ID: <20120709231234.GA17189@cskk.homeip.net> On 09Jul2012 18:53, Devin Jeanpierre wrote: | On Mon, Jul 9, 2012 at 5:22 PM, Peter wrote: | > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" | > If the answer included programming then they were hired, if not, then they went to the "B" list. | | Woe is the poor college grad, who wants to appear like a well-rounded | individual and lists capoeira and gardening, instead. A new word! A quick google search confused me as to whether this was martial art or a form of dance. The GF suggested it was both. Having seen this: http://www.youtube.com/watch?v=Z8xxgFpK-NM I am now convinced :-) -- Cameron Simpson Hit the button Chewie! - Han Solo From lists at cheimes.de Mon Jul 9 19:33:06 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Jul 2012 01:33:06 +0200 Subject: Python Interview Questions In-Reply-To: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: Am 09.07.2012 23:22, schrieb Peter: > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" > > If the answer included programming then they were hired, if not, then they went to the "B" list. on the contrary! When a potential candidate has computer stuff as her main hobby then she goes on the no-hire list. I prefer people that can cope with stress and pressure as well as people who can think outside the box. When you work with computers all day at work *and* at home then you are unable to shut off mentally. Gardening is great hobbies for a developer. You need to be patient, reliable and provide constantly good work to grow your own vegetables. Christian From python.list at tim.thechases.com Mon Jul 9 19:37:00 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 18:37:00 -0500 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: <4FFB6B1C.2090201@tim.thechases.com> On 07/09/12 17:53, Devin Jeanpierre wrote: >> One of my favourite questions when interviewing - and it was >> 100% reliable :-) - "what are your hobbies?" If the answer >> included programming then they were hired, if not, then they >> went to the "B" list. > > Woe is the poor college grad, who wants to appear like a > well-rounded individual and lists capoeira and gardening, > instead. The problem is the "instead...if your list of hobbies includes capoeira and gardening in addition to programming, you're at least considered. :-) -tkc From roy at panix.com Mon Jul 9 19:40:18 2012 From: roy at panix.com (Roy Smith) Date: Mon, 09 Jul 2012 19:40:18 -0400 Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: In article , Christian Heimes wrote: > Am 09.07.2012 23:22, schrieb Peter: > > One of my favourite questions when interviewing - and it was 100% reliable > > :-) - "what are your hobbies?" > > > > If the answer included programming then they were hired, if not, then they > > went to the "B" list. > > on the contrary! When a potential candidate has computer stuff as her > main hobby then she goes on the no-hire list. I think this points out the silliness of these kinds of questions. There is no "right" answer. More to the point, the interviewee, when he/she gets one of these questions, probably goes into hyper-analysis mode: "Now, just what did he mean by that question?" He's likely to give the answer he thinks you want to hear. Do you really want to make hire/no-hire decisions based on somebody's ability to second-guess what you probably wanted to hear when you asked a pointless question? From lists at cheimes.de Mon Jul 9 19:41:44 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Jul 2012 01:41:44 +0200 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: Am 09.07.2012 22:24, schrieb John Nagle: > Rename on some file system types (particularly NFS) may not be atomic. The actual operation is always atomic but the NFS server may not notify you about success or failure atomically. See http://linux.die.net/man/2/rename, section BUGS. > That's because you're using the wrong approach. See how to use > ReplaceFile under Win32: > > http://msdn.microsoft.com/en-us/library/aa365512%28VS.85%29.aspx The page doesn't say that ReplaceFile is an atomic op. Christian From python.list at tim.thechases.com Mon Jul 9 19:42:25 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 18:42:25 -0500 Subject: Python Interview Questions In-Reply-To: <20120709231234.GA17189@cskk.homeip.net> References: <20120709231234.GA17189@cskk.homeip.net> Message-ID: <4FFB6C61.6090802@tim.thechases.com> On 07/09/12 18:12, Cameron Simpson wrote: > On 09Jul2012 18:53, Devin Jeanpierre wrote: > | On Mon, Jul 9, 2012 at 5:22 PM, Peter wrote: > | > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" > | > If the answer included programming then they were hired, if not, then they went to the "B" list. > | > | Woe is the poor college grad, who wants to appear like a well-rounded > | individual and lists capoeira and gardening, instead. > > A new word! A quick google search confused me as to whether this was > martial art or a form of dance. The GF suggested it was both. You were unfamiliar with the word "gardening" and unsure whether it was a martial art or a form of dance? http://groovewitch.files.wordpress.com/2011/07/ninja-garden-gnome-1.jpeg ?grins, ducks & runs? -tkc From emile at fenx.com Mon Jul 9 19:56:00 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 09 Jul 2012 16:56:00 -0700 Subject: Python Interview Questions In-Reply-To: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: On 7/9/2012 2:22 PM Peter said... > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" > > If the answer included programming then they were hired, if not, then they went to the "B" list. > > In my experience, anybody who is really interested in programming will have it as a hobby (and is keen to learn even if they don't currently have the knowledge you require) - otherwise it is "just a job". Every job has a learning curve - whether it is just the particular domain or even a new language, the individual who sees programming as more "than a job" will come up to speed much faster and be more productive in both the short and long term. > > Every programmer I have ever hired using this criteria worked out well. > Hence the age bias. Personally, I'm quite happy now that I've divorced my hobby from my career. And my family likes me better too. Emile From dncarac at gmail.com Mon Jul 9 20:01:51 2012 From: dncarac at gmail.com (dncarac at gmail.com) Date: Mon, 9 Jul 2012 17:01:51 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> Message-ID: <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> Tim, I've read your list and with one exception it all looks very reasonable. (As an hobbiest, I'm amazed at just how much I have picked up.) The set of questions I'm not sure I understand is the 'What version did ... appear?' questions. This, to me, doesn't seem to indicate any programming experience or expertise. A question asking 'Do you understand different versions?' and 'How would you find out whether a particular version can do a particular thing?' (i.e. which version can you use on GAE?) would seem to give good information. 'How do decorators work?' would seem to give good information. So my question is: what information are you looking for by asking which version introduced decorators? With respect, Den From dncarac at gmail.com Mon Jul 9 20:01:51 2012 From: dncarac at gmail.com (dncarac at gmail.com) Date: Mon, 9 Jul 2012 17:01:51 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> Message-ID: <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> Tim, I've read your list and with one exception it all looks very reasonable. (As an hobbiest, I'm amazed at just how much I have picked up.) The set of questions I'm not sure I understand is the 'What version did ... appear?' questions. This, to me, doesn't seem to indicate any programming experience or expertise. A question asking 'Do you understand different versions?' and 'How would you find out whether a particular version can do a particular thing?' (i.e. which version can you use on GAE?) would seem to give good information. 'How do decorators work?' would seem to give good information. So my question is: what information are you looking for by asking which version introduced decorators? With respect, Den From lists at cheimes.de Mon Jul 9 20:02:25 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Jul 2012 02:02:25 +0200 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: Am 10.07.2012 01:40, schrieb Roy Smith: > Do you really want to make hire/no-hire decisions based on somebody's > ability to second-guess what you probably wanted to hear when you asked > a pointless question? I don't want her/him to second-guess at all. I expect a straight and honest answer. Second-guessing leads to cheating and lying which doesn't work in the long run. "I don't like to disclose my personal life" is also a good answer as it shows that the candidate self-confidence and doesn't sell privacy for a job. From python.list at tim.thechases.com Mon Jul 9 20:19:51 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 19:19:51 -0500 Subject: Python Interview Questions In-Reply-To: <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> Message-ID: <4FFB7527.5070706@tim.thechases.com> On 07/09/12 19:01, dncarac at gmail.com wrote: > The set of questions I'm not sure I understand is the 'What > version did ... appear?' questions. This, to me, doesn't seem to > indicate any programming experience or expertise. A question > asking 'Do you understand different versions?' and 'How would you > find out whether a particular version can do a particular thing?' > (i.e. which version can you use on GAE?) would seem to give good > information. The reason *I* ask them is that we have some 2.4 installations (where things like "with" aren't available) and at the time I typed up the list, there was some earlier 2.2 and 2.3 code out there where decorators or sqlite[*] didn't work. So I guess it's a bit of a "how long have they been programming in python" experience aspect. Programmers that have been around a while often remember the frustration of $FEATURE_LACK and then the relief of a much better way to do it. The functionality of decorators was around far earlier, but the clean syntactic sugar made it much nicer to use. The sqlite/sqlite3 libraries were around, but you had to install them yourself (whether from source, a custom installer, or your package manager). As mentioned in another branch of this thread, I don't require python historians, but do prefer folks that know which features to check availability for deployment. -tkc [*] without installing an add-on From roy at panix.com Mon Jul 9 20:27:59 2012 From: roy at panix.com (Roy Smith) Date: Mon, 09 Jul 2012 20:27:59 -0400 Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> Message-ID: In article , Tim Chase wrote: > As mentioned in another branch of this thread, I don't require > python historians, but do prefer folks that know which features to > check availability for deployment. Heh. Tell me, when did strings get methods? :-) From python.list at tim.thechases.com Mon Jul 9 21:05:03 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 09 Jul 2012 20:05:03 -0500 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> Message-ID: <4FFB7FBF.5080301@tim.thechases.com> On 07/09/12 19:27, Roy Smith wrote: >> prefer folks that know which features to check availability for >> deployment. > > Heh. Tell me, when did strings get methods? :-) IIRC, ~2.0? I'm cognizant of the shift happening from the string module to string methods, but I wouldn't expect deep history knowledge--last I checked, RedHat still supports a RHEL version that ships with 2.4, so that's about as far back as I'd probe these days (so I'd drop the decorators question now). Certainly not a deal-breaker either way. Just more data points. -tkc From breamoreboy at yahoo.co.uk Mon Jul 9 21:23:49 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 10 Jul 2012 02:23:49 +0100 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: On 10/07/2012 00:33, Christian Heimes wrote: > Am 09.07.2012 23:22, schrieb Peter: >> One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" >> >> If the answer included programming then they were hired, if not, then they went to the "B" list. > > on the contrary! When a potential candidate has computer stuff as her > main hobby then she goes on the no-hire list. I prefer people that can > cope with stress and pressure as well as people who can think outside > the box. When you work with computers all day at work *and* at home then > you are unable to shut off mentally. > > Gardening is great hobbies for a developer. You need to be patient, > reliable and provide constantly good work to grow your own vegetables. > > Christian > I guess that's why I detest gardening :-) -- Cheers. Mark Lawrence. From wuwei23 at gmail.com Mon Jul 9 22:04:17 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 9 Jul 2012 19:04:17 -0700 (PDT) Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> Message-ID: <83b4889f-8201-4369-9fe4-631888a78a16@oo8g2000pbc.googlegroups.com> On Jul 10, 6:24?am, John Nagle wrote: > That's because you're using the wrong approach. See how to use > ReplaceFile under Win32: > > http://msdn.microsoft.com/en-us/library/aa365512%28VS.85%29.aspx I'm not convinced ReplaceFile is atomic: "The ReplaceFile function combines several steps within a single function. An application can call ReplaceFile instead of calling separate functions to save the data to a new file, rename the original file using a temporary name, rename the new file to have the same name as the original file, and delete the original file." About the best you can get in Windows, I think, is MoveFileTransacted, but you need to be running Vista or later: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365241(v=vs.85).aspx I agree with your suggestion of using something transactional that isn't bound to later Window versions, though. From sheetalsingh at shopzilla.com Tue Jul 10 00:02:28 2012 From: sheetalsingh at shopzilla.com (Sheetal Singh) Date: Tue, 10 Jul 2012 04:02:28 +0000 Subject: How to pick content from html using beatifulsoup Message-ID: <7EC567BF36771942AE9F9279F86F13703B455A@SZHQMSXNODE1B.shopzilla.corp> Hi, I am a newbie in python, I need to fetch names of side filters and save in csv [PFA screen shot]. Following is snippet from code: soup = BeautifulStoneSoup(html) # for e in soup.findAll('div'): # for c in e.findAll('h3'): # for d in c.findAll('li'): # print'@@@@@@@', d.extract() # # #select_pod=soup.findAll('div', {"class":"win aboutUs"}) # #promeg= select_pod[0].findAll("p")[0] # # # for dv in soup.findAll('div', {"class":"attribution"}): # ds = dv.findAll("

") # print ds select_pod = soup.findAll('div') print select_pod for j in select_pod: if j is not None: print j.findall('a') promeg = select_pod.findAll("

") #print '--', promeg #hreflist = [ each.get('value') for each in soup.findAll('

') ] for m in promeg : if m: print 'Data values', m fd1.writerow([x[2], m, i[0], "Data Found"]) Structure of HTML:

By Brand

By Seller

Output required in csv: By Brands Nokia Samsung . . By Seller Amazon Buy.com . . . Please suggest how to fetch details. Sheetal Singh -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: filters.png Type: image/png Size: 8445 bytes Desc: filters.png URL: From Shambhu.Rajak at kpitcummins.com Tue Jul 10 01:08:09 2012 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Tue, 10 Jul 2012 05:08:09 +0000 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: <408F64D89899604FB24015E64E10490C3B7FDDAE@KCHJEXMB01.kpit.com> I agree with Christian, a developer should have hobbies other than computer stuffs. Versatile environment give more Ability to think differently. I like playing guitar :-) Be enthu, run foolishly and learn intelligently. -Shambhu -----Original Message----- From: Christian Heimes [mailto:lists at cheimes.de] Sent: 10/07/2012 5:03 AM To: python-list at python.org Subject: Re: Python Interview Questions Am 09.07.2012 23:22, schrieb Peter: > One of my favourite questions when interviewing - and it was 100% reliable :-) - "what are your hobbies?" > > If the answer included programming then they were hired, if not, then they went to the "B" list. on the contrary! When a potential candidate has computer stuff as her main hobby then she goes on the no-hire list. I prefer people that can cope with stress and pressure as well as people who can think outside the box. When you work with computers all day at work *and* at home then you are unable to shut off mentally. Gardening is great hobbies for a developer. You need to be patient, reliable and provide constantly good work to grow your own vegetables. Christian From timr at probo.com Tue Jul 10 01:26:07 2012 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Jul 2012 22:26:07 -0700 Subject: How can I disable module of tkinter when compiling Python 2.5 on redhat9 ? References: Message-ID: cheetah wrote: > >I don't need it. It's not worth worrying about. You're talking about way less than a megabyte of disk space, and there is no performance penalty unless you're using it. In general, the parts of the Python standard library are not individually selectable. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ramapraba2653 at gmail.com Tue Jul 10 01:55:52 2012 From: ramapraba2653 at gmail.com (SUPREME) Date: Mon, 9 Jul 2012 22:55:52 -0700 (PDT) Subject: TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING Message-ID: <05152ce0-3bd9-4359-b780-af0336286fae@s6g2000pbi.googlegroups.com> ALL INTERVIEW QUESTIONS& STUDY MATERIAL http://newdotnetinterviewquestions.blogspot.in/ TOP DATING TIPS TO ENCOURAGE WOMEN FOR DATING http://datingsitesdatingtips.blogspot.in/ FOR LATEST MOVIE UPDATED LINKS ADE PREMA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/ade-prema-stills.html HANSIKA MOTWANI LATEST HOT PICS http://actressgallery-kalyani.blogspot.in/2012/07/hansika-motwani-actress.html HOT NEETHU CHANDRA LATEST PICS http://actressgallery-kalyani.blogspot.in/2012/07/neetu-chandra-actress.html ACTRESS AMRUTHA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/07/amrutha-actress.html SELATHUPONNU MOVIE HOT PHOTOS http://actressgallery-kalyani.blogspot.in/2012/07/selathuponnu-movie-stills.html SULAGNA PANIGRAHI HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/06/sulagna-panigrahi-actress.html RUBY PARIHAR HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.com/2012/06/actress-ruby-parihar.html ACTRESS YAMI GOUTHAM LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/06/yami-gautam-actress.html ACTRESS HOT STILLS IN SIIMA AWARDS 2012 http://actressgallery-kalyani.blogspot.in/2012/06/actress-siima-awards-2012-stills.html EM BABU LADDU KAVALA MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/06/em-babu-laddu-kavala-movie-stills.html SRMANARAYANA MOVIE HOT STILLS http://actressgallery-kalyani.blogspot.in/2012/06/srimannarayana-movie-stills.html KAJAL AGARWAL LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/06/kajal-agarwal-latest-stills.html SANA KHAN LATEST HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/sana-khan-latest-stills.html COOL BOYS HOT GIRLS MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/06/cool-boys-hot-girls-movie-stills.html MITAAYI MOVIE LATEST GALLERY http://actressgallery-kalyani.blogspot.in/2012/06/mitaayi-movie-stills.html NAGARJUNA DAMARUKAM MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/damarukam-movie-stills.html ALLU ARJUN JULAYI MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/julayi-movie-stills.html SUDIGADU MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/05/sudigadu-movie-stills.html MR 7 MOVIE FILM GALLERY http://actressgallery-kalyani.blogspot.in/2012/05/mr7-movie-stills.html ALL THE BEST MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/all-best-movie-stills.html Midatha Telugu movie Hot Namitha Stills http://actressgallery-kalyani.blogspot.com/2012/05/midatha-movie-stills.html OKA COLLEGE LOVE STORY MOVIE STILLS http://actressgallery-kalyani.blogspot.in/2012/05/oka-college-love-story-movie-stills.html KATRINA KAIF LATEST UNSEENED PHOTOS http://actressgallery-kalyani.blogspot.com/2012/05/katrina-kaif-latest-pics.html TAMIL ACTRESS ARUNDHATI HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/05/arundhati-tamil-actress.html THANDHAVAM MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2012/05/thandavam-movie-stills.html EEGA MOVIE LATEST STILLS http://actressgallery-kalyani.blogspot.com/2012/04/eega-movie-stills.html Mem Vayasuku Vacham Latest Hot Stills http://actressgallery-kalyani.blogspot.com/2012/04/mem-vayasuku-vacham-stills.html ILEANA LATEST HOT PHOTOSHOOT http://actressgallery-kalyani.blogspot.in/2012/01/ileana-latest-stills.html ACTREESS SUPRIYA SHAILJA LATEST STILLS http://actressgallery-kalyani.blogspot.in/2012/02/supriya-shailja-stills.html SHEELA LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2012/01/sheela-latest-stills.html KATRINA KAIF ITEM SONG STILLS http://actressgallery-kalyani.blogspot.com/2012/01/katrina-kaif-item-song-stills.html RITU KAUR LATEST PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2012/01/ritu-kaur-stills.html SHRUTI HASSAN HOT IN 3 MOVIE http://actressgallery-kalyani.blogspot.com/2011/11/shruti-hassan-in-3-movie.html HOT LINKS FOR YOUTH ONLY PRANEETHA HOT SPICY IMAGES http://actressimages-9.blogspot.in/2012/06/praneetha-latest-stills.html SHRUTHI HASSAN HALF SAREE STILLS http://actressimages-9.blogspot.in/2012/05/shruti-hassan-half-saree-stills.html TAMANNA HOT NAVEL PHOTOS http://actressimages-9.blogspot.in/2012/05/tamanna-navel-photos.html TRISHA LATEST HOT STILLS http://actressgallery9.blogspot.in/2012/05/trisha.html MONIKA LATEST HOT HD STLLS http://actressgallery9.blogspot.in/2012/05/monika-stills.html MALLIKA KAPOOR HOT SIZZLING STILLS http://actressimages-9.blogspot.in/2012/05/mallika-kapoor.html Richa Panai Stills http://actressimages-9.blogspot.com/2012/04/richa-panai-stills.html MADHAVI LATHA LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/04/madhavi-latha-stills.html KRITI KHARBANDA HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/kriti-kharbanda.html NEELAM UPADHYAY HOT PHOTOSHOOT http://actressimages-9.blogspot.in/2012/03/neelam-upadhyay.html SAMANTHA LATEST HOT ROMANTIC STILLS http://actressimages-9.blogspot.in/2012/03/samantha-latest-stills.html NAYANTHARA HOT WALLPAPERS http://actressimages-9.blogspot.in/2012/01/nayanthara.html ANU SMRUTHI LATEST HOT STILLS http://actressimages-9.blogspot.in/2012/02/anu-smirthi-stills.html AISHWARYA RAI LATEST HOT PICS http://actressimages-9.blogspot.in/2012/01/aishwarya-rai.html From rustompmody at gmail.com Tue Jul 10 02:29:31 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 9 Jul 2012 23:29:31 -0700 (PDT) Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: On Jul 10, 4:40?am, Roy Smith wrote: > In article , > ?Christian Heimes wrote: > > > Am 09.07.2012 23:22, schrieb Peter: > > > One of my favourite questions when interviewing - and it was 100% reliable > > > :-) - "what are your hobbies?" > > > > If the answer included programming then they were hired, if not, then they > > > went to the "B" list. > > > on the contrary! When a potential candidate has computer stuff as her > > main hobby then she goes on the no-hire list. > > I think this points out the silliness of these kinds of questions. > There is no "right" answer. ?More to the point, the interviewee, when > he/she gets one of these questions, probably goes into hyper-analysis > mode: "Now, just what did he mean by that question?" ?He's likely to > give the answer he thinks you want to hear. > > Do you really want to make hire/no-hire decisions based on somebody's > ability to second-guess what you probably wanted to hear when you asked > a pointless question? Add to that the Heisenberging that happens to interviewees (and interviewers) from reading this thread From steve+comp.lang.python at pearwood.info Tue Jul 10 03:33:59 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Jul 2012 07:33:59 GMT Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> On Tue, 10 Jul 2012 01:33:06 +0200, Christian Heimes wrote: > Am 09.07.2012 23:22, schrieb Peter: >> One of my favourite questions when interviewing - and it was 100% >> reliable :-) - "what are your hobbies?" >> >> If the answer included programming then they were hired, if not, then >> they went to the "B" list. > > on the contrary! When a potential candidate has computer stuff as her > main hobby then she goes on the no-hire list. I prefer people that can > cope with stress and pressure as well as people who can think outside > the box. When you work with computers all day at work *and* at home then > you are unable to shut off mentally. ...because the stuff you do on computers at work, and the stuff you do on computers at home, are obviously exactly the same thing. If they read for their job, and read at home, does that also mean they can't shut off? This is why I hate job interviews. You have like 30 minutes, or even as little as 30 seconds, to make a good impression on somebody who may or may not be capable of telling the difference between a cheese sandwich and a box of hair -- and even the *good* interviewers are probably making their judgement on the basis of subjective factors with no right or wrong answers. > Gardening is great hobbies for a developer. You need to be patient, > reliable and provide constantly good work to grow your own vegetables. And live in a house in the suburbs with enough room for a garden, good soil, and not in the shadow of buildings. And work hours where you are home during daylight hours. You know what else is a great hobby for a developer? Anything, or nothing, at all. -- Steven From lists at cheimes.de Tue Jul 10 03:59:07 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Jul 2012 09:59:07 +0200 Subject: tiffany 0.6.1 released In-Reply-To: <4FFAFDFD.5000205@stackless.com> References: <7x4nps3gxg.fsf@ruckus.brouhaha.com> <4FFAFDFD.5000205@stackless.com> Message-ID: Am 09.07.2012 17:51, schrieb Christian Tismer: > It turns out to be a problem with multiple strips in a tiff file. > PIL does not support that. Maybe I can find an easy solution, > maybe I'm better off using > > smc.freeimage > > as suggested by Christian Heimes, > > we will see. Right now I'm pretty exhaused after EuroPython... Yes, TIFF is a complex format. Even baseline TIFF has several ways to store data (e.g. chunky or planar configuration, different settings for stripes). PIL didn't support several features as well as bitonal compression (G3, G4). I'll clean up the code of smc.freeimage and release it on bitbucket over the next couple of days. Christian From rosuav at gmail.com Tue Jul 10 04:03:56 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 10 Jul 2012 18:03:56 +1000 Subject: Python Interview Questions In-Reply-To: <408F64D89899604FB24015E64E10490C3B7FDDAE@KCHJEXMB01.kpit.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <408F64D89899604FB24015E64E10490C3B7FDDAE@KCHJEXMB01.kpit.com> Message-ID: On Tue, Jul 10, 2012 at 3:08 PM, Shambhu Rajak wrote: > I agree with Christian, a developer should have hobbies other than computer stuffs. Versatile environment give more > Ability to think differently. > I like playing guitar :-) Music and programming do go VERY well together. My hobbies include online roleplaying (Dungeons & Dragons, etc), writing/managing a MUD, playing the church organ, and arranging 19th-century music. It's not at all an uncommon pairing. But would a job interviewer REALLY care that I spend my Sunday mornings up front, hiding behind two manuals and a set of faulty pedals? Or would it be of interest that I play the odd video game (and believe you me, some of the games I play are VERY odd)? If so, I hereby resign all hope of comprehending job interviews, and will fall back on Mr Hall Pycroft's notion[1] that there's absolutely no logic to them at all. ChrisA [1] cf Sherlock Holmes: The Adventure of the Stock-Broker's Clerk From lists at cheimes.de Tue Jul 10 04:11:22 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 10 Jul 2012 10:11:22 +0200 Subject: Python Interview Questions In-Reply-To: <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> Message-ID: Am 10.07.2012 09:33, schrieb Steven D'Aprano: > This is why I hate job interviews. You have like 30 minutes, or even as > little as 30 seconds, to make a good impression on somebody who may or > may not be capable of telling the difference between a cheese sandwich > and a box of hair -- and even the *good* interviewers are probably making > their judgement on the basis of subjective factors with no right or wrong > answers. IMHO one category of answers is always wrong: lies. You may oversell yourself a bit, you can (and should) keep private matters to yourself but don't lie. > And live in a house in the suburbs with enough room for a garden, good > soil, and not in the shadow of buildings. And work hours where you are > home during daylight hours. Almost everybody can garden under ideal conditions. I grow about 15 herbs, strawberries, tomatoes, chillies and flowers on a small balcony in the middle of the city. This year I'm going to harvest at least 200 tomatoes from two plants in a 1m * 40cm * 40cm box of soil. I even have a calabash plant that grows like crazy. See? :) Christian From jeanmichel at sequans.com Tue Jul 10 05:29:24 2012 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Jul 2012 11:29:24 +0200 Subject: Python Interview Questions In-Reply-To: <4FFB7FBF.5080301@tim.thechases.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> Message-ID: <4FFBF5F4.7020407@sequans.com> Tim Chase wrote: > On 07/09/12 19:27, Roy Smith wrote: > >>> prefer folks that know which features to check availability for >>> deployment. >>> >> Heh. Tell me, when did strings get methods? :-) >> > > IIRC, ~2.0? I'm cognizant of the shift happening from the string > module to string methods, but I wouldn't expect deep history > knowledge--last I checked, RedHat still supports a RHEL version that > ships with 2.4, so that's about as far back as I'd probe these days > (so I'd drop the decorators question now). Certainly not a > deal-breaker either way. Just more data points. > > -tkc > > > > Why would you want to hire someone that knows something pointless as the version where feature X has been introduced ? Just tell him that feature X has been introducted in version Y, costless 2.5sec training. Don't you want to hire someone that knows things you don't and benefit from each others abilities, learning from each others, improving the company global skill range ? JM From breamoreboy at yahoo.co.uk Tue Jul 10 05:42:54 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 10 Jul 2012 10:42:54 +0100 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <408F64D89899604FB24015E64E10490C3B7FDDAE@KCHJEXMB01.kpit.com> Message-ID: On 10/07/2012 09:03, Chris Angelico wrote: > On Tue, Jul 10, 2012 at 3:08 PM, Shambhu Rajak > wrote: >> I agree with Christian, a developer should have hobbies other than computer stuffs. Versatile environment give more >> Ability to think differently. >> I like playing guitar :-) > > Music and programming do go VERY well together. My hobbies include > online roleplaying (Dungeons & Dragons, etc), writing/managing a MUD, > playing the church organ, and arranging 19th-century music. It's not > at all an uncommon pairing. > > But would a job interviewer REALLY care that I spend my Sunday > mornings up front, hiding behind two manuals and a set of faulty > pedals? Or would it be of interest that I play the odd video game (and > believe you me, some of the games I play are VERY odd)? If so, I > hereby resign all hope of comprehending job interviews, and will fall > back on Mr Hall Pycroft's notion[1] that there's absolutely no logic > to them at all. > > ChrisA > > [1] cf Sherlock Holmes: The Adventure of the Stock-Broker's Clerk > Surely the purpose of asking questions about hobbies or similar is to establish whether or not the person is likely to fit in? Slightly different tack, you have to get into the interview, i.e. pass the first thirty seconds test. I recall reading in a book in the local library of a manager that wouldn't employ people unless they were wearing a new pair of shoes. Guess they didn't take many people on. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Jul 10 05:45:06 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 10 Jul 2012 10:45:06 +0100 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> Message-ID: On 10/07/2012 09:11, Christian Heimes wrote: > Almost everybody can garden under ideal conditions. I grow about 15 > herbs, strawberries, tomatoes, chillies and flowers on a small balcony > in the middle of the city. This year I'm going to harvest at least 200 > tomatoes from two plants in a 1m * 40cm * 40cm box of soil. I even have > a calabash plant that grows like crazy. See? :) > > Christian > Big 'ead :) -- Cheers. Mark Lawrence. From anthra.norell at bluewin.ch Tue Jul 10 06:03:34 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Tue, 10 Jul 2012 12:03:34 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: <1341914614.2289.18.camel@hatchbox-one> On Mon, 2012-07-09 at 10:49 -0700, Rick Johnson wrote: > On Jul 9, 12:58 am, Terry Reedy wrote: > > When posting problem code, you should post a minimal, self-contained > > example that people can try on other systems and versions. Can you > > create the problem with one record, which you could give, and one > > binding? Do you need 4 fields, or would 1 'work'? > > I'll firmly back that sentiment. Fredric, if you cannot get the > following simple code events to work properly, then how do you think > you can get events working properly on something more complex? > > ## START CODE ARTISTRY ## > import Tkinter as tk > from Tkconstants import * > > class MyFrame(tk.Frame): > def __init__(self, master, **kw): > tk.Frame.__init__(self, master, **kw) > self.bind('', self.evtMouseEnter) > self.bind('', self.evtMouseLeave) > self.bind('', self.evtButtonOneClick) > > def evtMouseEnter(self, event): > event.widget.config(bg='magenta') > > def evtMouseLeave(self, event): > event.widget.config(bg='SystemButtonFace') > > def evtButtonOneClick(self, event): > event.widget.config(bg='green') > > if __name__ == '__main__': > root = tk.Tk() > for x in range(10): > f = MyFrame(root, height=20, bd=1, relief=SOLID) > f.pack(fill=X, expand=YES, padx=5, pady=5) > root.mainloop() > ## END CODE ARTISTRY ## > This works perfectly well! What makes the case difficult is an exceptional misbehavior for no apparent reason. If I manage to strip the critical section of environmental details in the interest of concision and legibility and still reproduce the error I shall post it. So far I have failed: the stripped model I distilled yesterday worked fine. > ----------------------- > More points to ponder: > ----------------------- > 1. Just because the Tkinter designers decided to use idiotic names for > event sequences does not mean you are required to blindly follow their > bad example (the whole: "if johnny jumps off a cliff...", thing comes > to mind) > > 2. I would strongly recommend you invest more thought into your event > handler identifiers. ALL event handlers should marked as *event > handlers* using a prefix. I like to use the prefix "evt". Some people > prefer other prefixes. In any case, just remember to be consistent. > Also, event handler names should reflect WHAT event they are > processing, not some esoteric functionality of the application like > "pick_record" or "info_profile". However if you like, simply have the > event handler CALL an outside func/meth. This type of consistency is > what separates the men from the boys. > > 3. The Python Style Guide[1] frowns on superfluous white space (be it > horizontal OR vertical!) I would strongly recommend you read and adapt > as much of this style as you possibly can bear. Even if we don't all > get along, it IS *very* important that we structure our code in a > similar style. > > [1] http://www.python.org/dev/peps/pep-0008/ Excellent suggestions. Frederic From walter at livinglogic.de Tue Jul 10 10:49:05 2012 From: walter at livinglogic.de (=?UTF-8?B?V2FsdGVyIETDtnJ3YWxk?=) Date: Tue, 10 Jul 2012 16:49:05 +0200 Subject: Issues with `codecs.register` and `codecs.CodecInfo` objects In-Reply-To: <4ff7a54c$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <4ff7a54c$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FFC40E1.4030100@livinglogic.de> On 07.07.12 04:56, Steven D'Aprano wrote: > On Fri, 06 Jul 2012 12:55:31 -0400, Karl Knechtel wrote: > >> Hello all, >> >> While attempting to make a wrapper for opening multiple types of >> UTF-encoded files (more on that later, in a separate post, I guess), I >> ran into some oddities with the `codecs` module, specifically to do with >> `.register` ing `CodecInfo` objects. I'd like to report a bug or >> something, but there are several intertangled issues here and I'm not >> really sure how to report it so I thought I'd open the discussion. >> Apologies in advance if I get a bit rant-y, and a warning that this is >> fairly long. > [...] > > Yes, it's a strangely indirect API, and yes it looks like you have > identified a whole bucket full of problems with it. And no, I don't know > why that API was chosen. This API was chosen for backwards compatibility reasons when incremental encoders/decoders were introduced (in 2006). And yes: We missed the opportunity to clean that up to always use CodecInfo. > Changing to a cleaner, more direct (sensible?) API would be a fairly big > step. If you want to pursue this, the steps I recommend you take are: > > 1) understanding the reason for the old API (search the Internet > and particularly the python-dev at python.org archives); See e.g. http://mail.python.org/pipermail/patches/2006-March/019122.html > 2) have a plan for how to avoid breaking code that relies on the > existing API; > > 3) raise the issue on python-ideas at python.org to gather feedback > and see how much opposition or support it is likely to get; > they'll suggest whether a bug report is sufficient or if you'll > need a PEP; > > http://www.python.org/dev/peps/ > > > If you can provide a patch and a test suite, you will have a much better > chance of pushing it through. If not, you are reliant on somebody else > who can being interested enough to do the work. > > And one last thing: any new functionality will simply *not* be considered > for Python 2.x. Aim for Python 3.4, since the 2.x series is now in bug- > fix only maintenance mode and the 3.3 beta is no longer accepting new > functionality, only bug fixes. Servus, Walter From rustompmody at gmail.com Tue Jul 10 11:01:24 2012 From: rustompmody at gmail.com (rusi) Date: Tue, 10 Jul 2012 08:01:24 -0700 (PDT) Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> Message-ID: <296d9b7f-0b2b-4ac5-a3df-14252922a17d@re8g2000pbc.googlegroups.com> On Jul 10, 12:33?pm, Steven D'Aprano wrote: > This is why I hate job interviews. You have like 30 minutes, or even as > little as 30 seconds, to make a good impression on somebody who may or > may not be capable of telling the difference between a cheese sandwich > and a box of hair -- and even the *good* interviewers are probably making > their judgement on the basis of subjective factors with no right or wrong > answers. You make it sound terrible... But just think which is worse: jobs decided in 30 minutes or marriages decided in 30 seconds? From levinie001 at gmail.com Tue Jul 10 11:01:27 2012 From: levinie001 at gmail.com (levi nie) Date: Tue, 10 Jul 2012 23:01:27 +0800 Subject: what's the effect of cmp here? Message-ID: what's the effect of cmp here? The bList and cList is the same at last. code: aList=[3,2,5,4] bList=aList[:] bList.sort() print "bList is",bList cList=aList[:] cList.sort(cmp) print "cList is",cList -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Jul 10 11:02:53 2012 From: wescpy at gmail.com (wesley chun) Date: Tue, 10 Jul 2012 11:02:53 -0400 Subject: ANN: Intro+Intermediate Python, San Francisco, Aug 1-3 In-Reply-To: References: Message-ID: hello everyone, hope some of you enjoyed #EuroPython this past week/end, and perhaps i'll see some of you at OSCON next week! as promised, here's the one and only FINAL REMINDER of the hardcore intro+intermediate Python course i'm offering 2012 Aug 1-3 near the San Francisco airport. reach out to me directly with any questions and let other folks know who may be interested. best regards, --wesley On Thu, May 10, 2012 at 2:07 PM, wesley chun wrote: > Greetings! > > I'll be doing another hardcore Python course this summer in the San > Francisco area. If you're somewhat new to Python or have tinkered but > want to fill-in the holes, this course is for you. It's somewhat true > you can learn Python online, watching videos, or reading books, but it > still takes time and experience to master... I help accelerate this > process. The course is based on my bestselling "Core Python" books and > is made up of 3 full days complete with lectures and three hands-on > coding labs per day. > > Please pass on this message to your colleagues who also need to learn > Python. It's also a great excuse to coming to beautiful Northern > California for a summer vacation! More details at http://goo.gl/uW4oF > as well as the links in my .signature below. -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com From d at davea.name Tue Jul 10 11:11:45 2012 From: d at davea.name (Dave Angel) Date: Tue, 10 Jul 2012 11:11:45 -0400 Subject: what's the effect of cmp here? In-Reply-To: References: Message-ID: <4FFC4631.6090703@davea.name> On 07/10/2012 11:01 AM, levi nie wrote: > what's the effect of cmp here? The bList and cList is the same at last. > > code: > aList=[3,2,5,4] > > bList=aList[:] > bList.sort() > print "bList is",bList > > cList=aList[:] > cList.sort(cmp) > print "cList is",cList > > The main effect is for the reader of the code. When you supply your own callback to sort(), you're being explicit about how you want the items to be compared. If the default works for you, then you can omit supplying a function. -- DaveA From breamoreboy at yahoo.co.uk Tue Jul 10 11:22:27 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 10 Jul 2012 16:22:27 +0100 Subject: what's the effect of cmp here? In-Reply-To: References: Message-ID: On 10/07/2012 16:01, levi nie wrote: > aList=[3,2,5,4] > > bList=aList[:] > bList.sort() > print "bList is",bList > > cList=aList[:] > cList.sort(cmp) > print "cList is",cList > Why don't you tell us, you have the same documentatation avaialable as everybody else. -- Cheers. Mark Lawrence. From bc at freeuk.com Tue Jul 10 11:55:31 2012 From: bc at freeuk.com (BartC) Date: Tue, 10 Jul 2012 16:55:31 +0100 Subject: Python Interview Questions In-Reply-To: <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: "Peter" wrote in message news:35e7a860-fd41-4018-82f6-aabc3261064d at googlegroups.com... > One of my favourite questions when interviewing - and it was 100% reliable > :-) - "what are your hobbies?" > > If the answer included programming then they were hired, if not, then they > went to the "B" list. > > In my experience, anybody who is really interested in programming will > have it as a hobby (and is keen to learn even if they don't currently have > the knowledge you require) - otherwise it is "just a job". Won't they be tempted to work on their pet project instead of what they're being paid for? There's also the risk of mixing up software created at home, with that done at work, with all the intellectual property issues that might arise. -- Bartc From rosuav at gmail.com Tue Jul 10 12:05:40 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 11 Jul 2012 02:05:40 +1000 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> Message-ID: On Wed, Jul 11, 2012 at 1:55 AM, BartC wrote: > There's also the risk of mixing up software created at home, with that done > at work, with all the intellectual property issues that might arise. You just make the matter clear from the beginning, for instance: what's done at work stays at work, and copyright is assigned by the act of pushing to the repository. I've lifted oddments of code from my home projects to use at work; it's no different from using skills learned at home, which is exactly what a programmer is being paid for. This is another good reason to make license terms clear and explicit on every project you ever put a hand to. Doesn't matter who's lifting code from where to where, it's easy to work out whether it's permissible or not. ChrisA From ethan at stoneleaf.us Tue Jul 10 12:05:50 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 10 Jul 2012 09:05:50 -0700 Subject: Python Interview Questions In-Reply-To: <4FFBF5F4.7020407@sequans.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> Message-ID: <4FFC52DE.2080201@stoneleaf.us> Jean-Michel Pichavant wrote: > Why would you want to hire someone that knows something pointless as the > version where feature X has been introduced ? As an example from today, if someone claimed to have 5+ years of Python experience, but didn't know that 'with' was standard in 2.6 (or at least the end of the 2.x cycle) I would be suspicious that they actually had the experience they claimed. ~Ethan~ From steve+comp.lang.python at pearwood.info Tue Jul 10 12:34:10 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Jul 2012 16:34:10 GMT Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> Message-ID: <4ffc5982$0$29965$c3e8da3$5496439d@news.astraweb.com> On Tue, 10 Jul 2012 09:05:50 -0700, Ethan Furman wrote: > Jean-Michel Pichavant wrote: >> Why would you want to hire someone that knows something pointless as >> the version where feature X has been introduced ? > > As an example from today, if someone claimed to have 5+ years of Python > experience, but didn't know that 'with' was standard in 2.6 (or at least > the end of the 2.x cycle) I would be suspicious that they actually had > the experience they claimed. Be careful of jumping to conclusions though. Perhaps they have five years experience with Python 1.5, 2.3 and 2.4 on Centos systems. Of course, if they try to sell themselves as having five years experience with Python 3.2 and they don't know anything about the with statement, that tells you everything you need to know. -- Steven From rosuav at gmail.com Tue Jul 10 12:42:00 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 11 Jul 2012 02:42:00 +1000 Subject: Python Interview Questions In-Reply-To: <4ffc5982$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> <4ffc5982$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Jul 11, 2012 at 2:34 AM, Steven D'Aprano wrote: > Of course, if they try to sell themselves as having > five years experience with Python 3.2... ... then they've been borrowing Guido's time machine for personal purposes. ChrisA From steve+comp.lang.python at pearwood.info Tue Jul 10 12:44:05 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Jul 2012 16:44:05 GMT Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> Message-ID: <4ffc5bd4$0$29965$c3e8da3$5496439d@news.astraweb.com> On Tue, 10 Jul 2012 11:29:24 +0200, Jean-Michel Pichavant wrote: > Why would you want to hire someone that knows something pointless as the > version where feature X has been introduced ? Just tell him that feature > X has been introducted in version Y, costless 2.5sec training. Don't you > want to hire someone that knows things you don't and benefit from each > others abilities, learning from each others, improving the company > global skill range ? The reason for the question is to get some idea of how well the candidate actually knows Python. If you ask them questions that you don't know the answer to, how will you tell if they're right? I certainly wouldn't disqualify a candidate if they didn't know what version introduced (say) decorators. If they said "what's a decorator?" or "version 10", that would be a hint that they don't actually know much about Python. If they said "I don't know, I'm still stuck on Python 2.3", they would get a point for honesty and lose a point for being way out of date. If they said version 2.3 or 2.5 (it's actually 2.4), well, that's close enough. Of course, an acceptable answer would be "buggered if I know, but if you give me a minute, I'll google it for you". -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 10 12:51:37 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Jul 2012 16:51:37 GMT Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> Message-ID: <4ffc5d99$0$29965$c3e8da3$5496439d@news.astraweb.com> On Tue, 10 Jul 2012 10:11:22 +0200, Christian Heimes wrote: > Am 10.07.2012 09:33, schrieb Steven D'Aprano: >> This is why I hate job interviews. You have like 30 minutes, or even as >> little as 30 seconds, to make a good impression on somebody who may or >> may not be capable of telling the difference between a cheese sandwich >> and a box of hair -- and even the *good* interviewers are probably >> making their judgement on the basis of subjective factors with no right >> or wrong answers. > > IMHO one category of answers is always wrong: lies. You may oversell > yourself a bit, you can (and should) keep private matters to yourself > but don't lie. If only that were true. I know quite a few people who looked the interviewer straight in the eye and told the most bare-faced lies without a trace of shame, and got the job. Ten years on, at least one of them is making something around $300,000 a year, based entirely on his ability to smile and tell customers plausible lies. I can't lie to save my life, which is why I have trouble in interviews. But of course all good liars would say the same thing. -- Steven From info at wingware.com Tue Jul 10 12:55:29 2012 From: info at wingware.com (Wingware) Date: Tue, 10 Jul 2012 12:55:29 -0400 Subject: Wing IDE 4.1.7 released Message-ID: <4FFC5E81.2010702@wingware.com> Hi, Wingware has released version 4.1.7 of Wing IDE, our integrated development environment designed specifically for the Python programming language. Wing IDE provides a professional quality code editor with vi, emacs, and other key bindings, auto-completion, call tips, refactoring, context-aware auto-editing, a powerful graphical debugger, version control, unit testing, search, and many other features. For details see http://wingware.com/ This minor release includes: Support for Stackless Python 3.2 Support for Maya 2013 Support for Visual Studio 2010 builds of Python 2.6 and 2.7 Update Python 3.3 support to the beta1 release Pretty Print option in Python Shell and Debug Probe How-To for using Wing IDE with Pyramid (thanks to Eric Ongerth) Implemented vi mode :delm to delete marks Added open-url-from-editor and open-clicked-url-from-editor commands Ability to set options sent to Python while debugging Toolbar icon for viewing and changing the Python configuration Improved tab key action in Eclipse key binding Preference to disable editor scrolling past the last line Several auto-editing improvements Improved experimental Turbo completion mode Improved heuristic for auto-indent after paste Support _thread module under Python 3.x About 30 other minor improvements and bug fixes For a complete change log see http://wingware.com/pub/wingide/4.1.7/CHANGELOG.txt Free trial: http://wingware.com/wingide/trial Downloads: http://wingware.com/downloads Feature matrix: http://wingware.com/wingide/features More information: http://wingware.com/ Sales: http://wingware.com/store/purchase Upgrades: https://wingware.com/store/upgrade Questions? Don't hesitate to email us at sales at wingware.com. Thanks, -- Stephan Deibel Wingware | Python IDE Advancing Software Development www.wingware.com From rosuav at gmail.com Tue Jul 10 12:59:15 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 11 Jul 2012 02:59:15 +1000 Subject: Python Interview Questions In-Reply-To: <4ffc5d99$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> <4ffc5d99$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Jul 11, 2012 at 2:51 AM, Steven D'Aprano wrote: > If only that were true. I know quite a few people who looked the > interviewer straight in the eye and told the most bare-faced lies without > a trace of shame, and got the job. Ten years on, at least one of them is > making something around $300,000 a year, based entirely on his ability to > smile and tell customers plausible lies. So he's either a politician, a salesman, a lawyer, a counselor, a manager, a thespian, or a venture capitalist. And maybe a few other possibilities. Professional liars, all. :) ChrisA From ethan at stoneleaf.us Tue Jul 10 13:02:07 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 10 Jul 2012 10:02:07 -0700 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> <4ffc5982$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FFC600F.5000906@stoneleaf.us> Chris Angelico wrote: > On Wed, Jul 11, 2012 at 2:34 AM, Steven D'Aprano > wrote: >> Of course, if they try to sell themselves as having >> five years experience with Python 3.2... > > ... then they've been borrowing Guido's time machine for personal purposes. Reminds me of a job posting a few years ago where the prospective employer wanted three plus years experience in some language, and that language had only been created a year and a half before. ~Ethan~ From jeanmichel at sequans.com Tue Jul 10 13:07:19 2012 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 10 Jul 2012 19:07:19 +0200 Subject: Python Interview Questions In-Reply-To: <4ffc5bd4$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4ffc5bd4$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4FFC6147.7030908@sequans.com> Steven D'Aprano wrote: > On Tue, 10 Jul 2012 11:29:24 +0200, Jean-Michel Pichavant wrote: > > >> Why would you want to hire someone that knows something pointless as the >> version where feature X has been introduced ? Just tell him that feature >> X has been introducted in version Y, costless 2.5sec training. Don't you >> want to hire someone that knows things you don't and benefit from each >> others abilities, learning from each others, improving the company >> global skill range ? >> > > The reason for the question is to get some idea of how well the candidate > actually knows Python. If you ask them questions that you don't know the > answer to, how will you tell if they're right? > > I certainly wouldn't disqualify a candidate if they didn't know what > version introduced (say) decorators. If they said "what's a decorator?" > or "version 10", that would be a hint that they don't actually know much > about Python. If they said "I don't know, I'm still stuck on Python 2.3", > they would get a point for honesty and lose a point for being way out of > date. If they said version 2.3 or 2.5 (it's actually 2.4), well, that's > close enough. > > Of course, an acceptable answer would be "buggered if I know, but if you > give me a minute, I'll google it for you". > > > Must be a cultural thing. We don't question people experience that much here. They'll be challenged anyway during the trial period (6 months during which the contract can be cancelled anytime without any reason). Actually I think it would be considered quite rude to challenge someone with questions right after he told you he worked 5 years as technical leader on a software developped in python for instance. I've never been asked nor did I asked to go into such technical details. Interviews are more about years of experience, projects, working with teams, carreer expectations, distance between home and workplace, willingness to work weekends when required. I'm no saying one way is better than another. I'm making an observation on how different can be an interview from one location to another. JM From steve+comp.lang.python at pearwood.info Tue Jul 10 13:41:43 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Jul 2012 17:41:43 GMT Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> <4ffc5d99$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ffc6956$0$29965$c3e8da3$5496439d@news.astraweb.com> On Wed, 11 Jul 2012 02:59:15 +1000, Chris Angelico wrote: > On Wed, Jul 11, 2012 at 2:51 AM, Steven D'Aprano > wrote: >> If only that were true. I know quite a few people who looked the >> interviewer straight in the eye and told the most bare-faced lies >> without a trace of shame, and got the job. Ten years on, at least one >> of them is making something around $300,000 a year, based entirely on >> his ability to smile and tell customers plausible lies. > > So he's either a politician, a salesman, a lawyer, a counselor, a > manager, a thespian, or a venture capitalist. And maybe a few other > possibilities. Professional liars, all. :) Actually, he's a senior software developer for a major international software company whose name Might Seem familiar to you. To be honest, I can't tell you too much more about his job, as I've made it a practice not to learn too many details. -- Steven From subhabangalore at gmail.com Tue Jul 10 13:46:08 2012 From: subhabangalore at gmail.com (Subhabrata) Date: Tue, 10 Jul 2012 10:46:08 -0700 (PDT) Subject: Opening multiple Files in Different Encoding Message-ID: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Dear Group, I kept a good number of files in a folder. Now I want to read all of them. They are in different formats and different encoding. Using listdir/glob.glob I am able to find the list but how to open/read or process them for different encodings? If any one can help me out.I am using Python3.2 on Windows. Regards, Subhabrata Banerjee. From breamoreboy at yahoo.co.uk Tue Jul 10 13:50:38 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 10 Jul 2012 18:50:38 +0100 Subject: Python Interview Questions In-Reply-To: <6joov7lirmr9hiqk8rq9ojqj4jlt3kp8pu@invalid.netcom.com> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> <6joov7lirmr9hiqk8rq9ojqj4jlt3kp8pu@invalid.netcom.com> Message-ID: On 10/07/2012 18:12, Dennis Lee Bieber wrote: > On 10 Jul 2012 07:33:59 GMT, Steven D'Aprano > declaimed the following in > gmane.comp.python.general: > > >> may not be capable of telling the difference between a cheese sandwich >> and a box of hair -- and even the *good* interviewers are probably making > > They are both containers holding samples of protein > Does the hair contain much more roughage? -- Cheers. Mark Lawrence. From demianbrecht at gmail.com Tue Jul 10 14:08:56 2012 From: demianbrecht at gmail.com (Demian Brecht) Date: Tue, 10 Jul 2012 11:08:56 -0700 (PDT) Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <4ffbdae7$0$1796$c3e8da3$76491128@news.astraweb.com> <6joov7lirmr9hiqk8rq9ojqj4jlt3kp8pu@invalid.netcom.com> Message-ID: <1f94963b-a538-41e2-8c00-8df4f2629e63@googlegroups.com> I also judge candidates on their beards (http://www.wired.com/wiredenterprise/2012/06/beard-gallery/). If the beard's awesome enough, no questions needed. They're pro. From manengstudent at gmail.com Tue Jul 10 15:15:55 2012 From: manengstudent at gmail.com (Shamefaced) Date: Tue, 10 Jul 2012 12:15:55 -0700 (PDT) Subject: Adding to a List and displaying quantity in the list Message-ID: Hi I have coded a program whihc outputs what I like, but I am trying to modify it to add specific result info to a list and then display the number of items in the list. This is easy for me with basic code, but seems difficult when trying to adapt my program. My code and explanation is as follows: class Source(Process): """ Source generates customers randomly """ def generate(self, number, meanTBA, resource): for i in range(number): c = Customer(name="Customer%02d" % (i+1,)) activate(c, c.visit(b=resource)) #t = expovariate(1.0 / meanTBA) t = 10.0 yield hold, self, t class Customer(Process): """ Customer arrives, is served and leaves """ def visit(self, b): leavelist = [] /* Name of List defined */ arrive = now() #tib = expovariate(1.0 / timeInBank) tib = timeInBank /* Console Output results start here */ print("%8.3f %s: Here I am" % (now()/60, self.name)) yield (request, self, b), (hold, self,maxWaitTime) wait = now() - arrive if self.acquired(b): print("%8.3f %s: Waited %6.3f" % (now()/60, self.name, wait)) yield hold, self, tib yield release, self, b print("%8.3f %s: Finished" % (now()/60, self.name)) else: print("%8.3f %s: Waited too long %6.3f" % (now()/60, self.name, wait) + " time units have passed - Customer has left") leavelist.append(self.acquired) print len(leavelist) What I am looking to do is the "customers" who have "Waited too long" get added to my leavelist() as they occur. Does this make sense? Thank you. From python at mrabarnett.plus.com Tue Jul 10 15:26:22 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 10 Jul 2012 20:26:22 +0100 Subject: Opening multiple Files in Different Encoding In-Reply-To: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> References: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Message-ID: <4FFC81DE.6030505@mrabarnett.plus.com> On 10/07/2012 18:46, Subhabrata wrote: > Dear Group, > > I kept a good number of files in a folder. Now I want to read all of > them. They are in different formats and different encoding. Using > listdir/glob.glob I am able to find the list but how to open/read or > process them for different encodings? > > If any one can help me out.I am using Python3.2 on Windows. > You could try different encodings. If it raises a UnicodeDecodeError, then it's the wrong encoding, Otherwise just look at the decoding result and see whether it "looks" OK. I believe that one method is to look at the frequency distribution of characters compared with sample texts. From gordon at panix.com Tue Jul 10 16:30:31 2012 From: gordon at panix.com (John Gordon) Date: Tue, 10 Jul 2012 20:30:31 +0000 (UTC) Subject: Adding to a List and displaying quantity in the list References: Message-ID: In Shamefaced writes: > else: > print("%8.3f %s: Waited too long %6.3f" % (now()/60, self.name, wait) + " time units have passed - Customer has left") > leavelist.append(self.acquired) What is self.acquired? Judging from earlier code it appears to be a function, but here you're appending it to leavelist. Did you really mean to append a function object to leavelist? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From manengstudent at gmail.com Tue Jul 10 16:51:20 2012 From: manengstudent at gmail.com (Shamefaced) Date: Tue, 10 Jul 2012 13:51:20 -0700 (PDT) Subject: Adding to a List and displaying quantity in the list In-Reply-To: References: Message-ID: <348af93f-60b0-4947-b3e7-673fd8b100ac@googlegroups.com> else: > print("%8.3f %s: Waited too long %6.3f" % (now()/60, self.name, wait) + " time units have passed - Customer has left") > leavelist.append(self.acquired) Yeah, I should have changed that back to : leavelist.append(self.name) -- my thinking was that it would append the name of each item to the list.? From rantingrickjohnson at gmail.com Tue Jul 10 18:11:02 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 10 Jul 2012 15:11:02 -0700 (PDT) Subject: Tkinter.event.widget: handler gets name instead of widget. References: <1341782353.2041.136.camel@hatchbox-one> Message-ID: <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> I've tried to condense your code using the very limited info you have provided. I have removed unnecessarily configuring of widgets and exaggerated the widget borders to make debugging easier. Read below for Q&A. ## START CONDENSED CODE ## records = range(4) CNF_SUBFRAME = { 'bd':5, # rowFrame boder width. 'relief':RIDGE, } CNF_LABEL = { 'anchor':W, 'width':10, 'bg':'gray', } class FooFrame(tk.Frame): def __init__(self, master, **kw): tk.Frame.__init__(self, master, **kw) self.build_records() def build_records(self): # Should this method be called by __init__??? # Not sure if "records" is passed-in or global??? for n in range(len(records)): record = records[n] rowFrame = tk.Frame(self, name='-%d-'%n, **CNF_SUBFRAME) rowFrame.bind ('', self.evtEnter) rowFrame.bind ('', self.evtLeave) rowFrame.bind ('', self.evtButtonOneRelease) rowFrame.bind ('', self.evtButtonThreeRelease) rowFrame.grid (row=n+2, column=1, padx=5, pady=5) for i in range(4): lbtext = 'Label_'+str(i) label = tk.Label(rowFrame, text=lbtext, **CNF_LABEL) label.grid (row=0, column=i, sticky=NW) def evtEnter(self, event): w = event.widget print 'evtEnter', w.winfo_class() w.config(bg='magenta') def evtLeave(self, event): w = event.widget print 'evtLeave', w.winfo_class() w.config(bg='SystemButtonFace') def evtButtonOneRelease(self, event): w = event.widget print 'evtButtonOneRelease', w.winfo_class() w.config(bg='Green') def evtButtonThreeRelease(self, event): w = event.widget print 'evtButtonThreeRelease', w.winfo_class() w.config(bg='Blue') if __name__ == '__main__': root = tk.Tk() frame = FooFrame(root, width=100, height=100, bg='red', bd=1) frame.pack(padx=5, pady=5) root.mainloop() ## END CONDENSED CODE ## In the code sample provided, you will see that the label widgets stacked on each row will block "click" events on the containing "rowFrames" below them. You can get a click event (on the sub frames) to work by clicking the exaggerated border on the frames. All the events work properly for me, although this GUI interface seems unintuitive even with proper borders and colors. Fredric, I can't help but feel that you are not attacking the problem correctly. Please explain the following questions in detail so that i may be able to provide help: Q1. You have subclassed a Tkinter.Frame and you are building "rows" of sub-frames into this toplevel frame; with each row holding horizontally stacked label widgets. Okay, I can see a need to wrap up a "RowFrame" object, but i don't see a need to create a "RowFrameFactory". Can you explain this design decision? Q2. It seems odd to me that you want to engage the "rowFrame" widgets via events but NOT the Label widgets. Can you explain this design decision? From ramit.prasad at jpmorgan.com Tue Jul 10 18:29:29 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 10 Jul 2012 22:29:29 +0000 Subject: how to interact with Windows cmd? In-Reply-To: <5c91bf76-36de-4759-938a-92a9e801e38e@g4g2000pbn.googlegroups.com> References: <5c91bf76-36de-4759-938a-92a9e801e38e@g4g2000pbn.googlegroups.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741654D15A@SCACMX008.exchad.jpmchase.net> > what I want to do is > 1.open cmd > 2.waiting for user's typing > 3.when I type "dir" > 4.print the result of "dir" > 5.then I type some other commands, printing the result until I type > 'exit' > > I used > p=subprocess.Popen('cmd',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=s > ubprocess.PIPE,shell=True) > p=communicate('dir') > > it shows the first result but the problem is > 1. it's too long so the cmd split the result with "more?", so result > is not perfect > 2. after this, I typed like "cd .." but I/O is already closed so I > can't do another things.. > > Is there any good way? Not much experience with subprocess, but from what I have read on here shell=True is usually bad. If you are trying to use Python as a sort of bash replacement, you may want to take a look at iPython http://en.wikipedia.org/wiki/Ipython. Not Apple related! Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ian.g.kelly at gmail.com Tue Jul 10 18:59:11 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 10 Jul 2012 16:59:11 -0600 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> <4FFC52DE.2080201@stoneleaf.us> Message-ID: On Tue, Jul 10, 2012 at 4:26 PM, Dennis Lee Bieber wrote: > On Tue, 10 Jul 2012 09:05:50 -0700, Ethan Furman > declaimed the following in gmane.comp.python.general: > >> As an example from today, if someone claimed to have 5+ years of Python >> experience, but didn't know that 'with' was standard in 2.6 (or at least >> the end of the 2.x cycle) I would be suspicious that they actually had >> the experience they claimed. >> > > >From the 2.5 help file: > """ > 3.4.9 With Statement Context Managers > New in version 2.5. > """ In 2.5 the with statement requires a __future__ import, so can't be considered "standard". From rantingrickjohnson at gmail.com Tue Jul 10 21:06:10 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 10 Jul 2012 18:06:10 -0700 (PDT) Subject: Tkinter.event.widget: handler gets name instead of widget. References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> Message-ID: <25935b3c-b37d-465f-9855-7ecf2c3bdf4e@h10g2000yqn.googlegroups.com> Also: Q3: Why are you explicitly setting the name of your "subFrame" widgets instead of allowing Tkinter to assign a unique name?...AND are you aware of the conflicts that can arise from such changes[1]? Q4: Are you aware of the built-in function "enumerate"[2]? I see you are passing around indexes to iterables AND simultaneously needing the obj reference itself. I prefer to keep indexing to a minimum. If there is no bleeding edge performance issue to worry about (and there almost *always* never is) why not use enumerate? [1] http://www.pythonware.com/library/tkinter/introduction/x147-more-on-widget-names.htm [2] http://docs.python.org/release/3.0.1/library/functions.html#enumerate From drobinow at gmail.com Tue Jul 10 22:13:45 2012 From: drobinow at gmail.com (David Robinow) Date: Tue, 10 Jul 2012 22:13:45 -0400 Subject: Python Interview Questions In-Reply-To: <4FFC600F.5000906@stoneleaf.us> References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> <4FFBF5F4.7020407@sequans.com> <4ffc5982$0$29965$c3e8da3$5496439d@news.astraweb.com> <4FFC600F.5000906@stoneleaf.us> Message-ID: On Tue, Jul 10, 2012 at 1:02 PM, Ethan Furman wrote: ... > > Reminds me of a job posting a few years ago where the prospective employer > wanted three plus years experience in some language, and that language had > only been created a year and a half before. I saw several of those when Java was new. From rantingrickjohnson at gmail.com Tue Jul 10 22:44:29 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 10 Jul 2012 19:44:29 -0700 (PDT) Subject: Python Interview Questions References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <19849142-5214-4c20-87ca-667ba4e2b22e@googlegroups.com> <4FFB7FBF.5080301@tim.thechases.com> Message-ID: <697d96f8-9320-428e-9f3f-e52793dab8d1@o4g2000yqk.googlegroups.com> On Jul 10, 4:29?am, Jean-Michel Pichavant wrote: > Why would you want to hire someone that knows something pointless as the > version where feature X has been introduced ? Just tell him that feature > X has been introducted in version Y, costless 2.5sec training. Don't you > want to hire someone that knows things you don't and benefit from each > others abilities, learning from each others, improving the company > global skill range ? > > JM Ha! Intelligent people are scary to bosses. They want robots Jean. Robots that are *just* intelligent enough to reduce their own work load whist NOT intelligent enough to render them obsolete. From stefan_ml at behnel.de Wed Jul 11 00:05:29 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 11 Jul 2012 06:05:29 +0200 Subject: Python Interview Questions In-Reply-To: References: <1193768041.349129.26350@v3g2000hsg.googlegroups.com> <3e0ef383-9615-4b4d-89c1-e5519971189f@googlegroups.com> <35e7a860-fd41-4018-82f6-aabc3261064d@googlegroups.com> <408F64D89899604FB24015E64E10490C3B7FDDAE@KCHJEXMB01.kpit.com> Message-ID: Mark Lawrence, 10.07.2012 11:42: > I recall reading in a book in the local library > of a manager that wouldn't employ people unless they were wearing a new > pair of shoes. Guess they didn't take many people on. Managers tend to like wasting resources. Buying a new pair of shoes for each job interview sounds reasonable once you have a salary well beyond your own capabilities. Stefan From steve+comp.lang.python at pearwood.info Wed Jul 11 02:22:02 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 11 Jul 2012 06:22:02 GMT Subject: Opening multiple Files in Different Encoding References: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Message-ID: <4ffd1b8a$0$1781$c3e8da3$76491128@news.astraweb.com> On Tue, 10 Jul 2012 10:46:08 -0700, Subhabrata wrote: > Dear Group, > > I kept a good number of files in a folder. Now I want to read all of > them. They are in different formats and different encoding. Using > listdir/glob.glob I am able to find the list but how to open/read or > process them for different encodings? open('first file', encoding='uft-8') open('second file', encoding='latin1') How you decide which encoding to use is up to you. Perhaps you can keep a mapping of {filename: encoding} somewhere. Or perhaps you can try auto-detecting the encodings. The chardet module should help you there. -- Steven From fetchinson at googlemail.com Wed Jul 11 02:41:57 2012 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 11 Jul 2012 08:41:57 +0200 Subject: lambda in list comprehension acting funny Message-ID: funcs = [ lambda x: x**i for i in range( 5 ) ] print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) This gives me 16 16 16 When I was excepting 1 2 4 Does anyone know why? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From fetchinson at googlemail.com Wed Jul 11 02:43:11 2012 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 11 Jul 2012 08:43:11 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: > funcs = [ lambda x: x**i for i in range( 5 ) ] > print funcs[0]( 2 ) > print funcs[1]( 2 ) > print funcs[2]( 2 ) > > This gives me > > 16 > 16 > 16 > > When I was excepting > > 1 > 2 > 4 > > Does anyone know why? And more importantly, what's the simplest way to achieve the latter? :) -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jurko.gospodnetic at pke.hr Wed Jul 11 03:01:18 2012 From: jurko.gospodnetic at pke.hr (=?UTF-8?B?SnVya28gR29zcG9kbmV0acSH?=) Date: Wed, 11 Jul 2012 09:01:18 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: Hi. >> funcs = [ lambda x: x**i for i in range( 5 ) ] >> print funcs[0]( 2 ) >> >> This gives me >> 16 >> >> When I was excepting >> 1 >> >> Does anyone know why? Just the way Python lambda expressions bind their variable references. Inner 'i' references the outer scope's 'i' variable and not its value 'at the time the lambda got defined'. > And more importantly, what's the simplest way to achieve the latter? :) Try giving the lambda a default parameter (they get calculated and have their value stored at the time the lambda is defined) like this: funcs = [ lambda x, i=i: x**i for i in range( 5 ) ] Hope this helps. Best regards, Jurko Gospodneti? From fetchinson at googlemail.com Wed Jul 11 03:36:14 2012 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 11 Jul 2012 09:36:14 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: >>> funcs = [ lambda x: x**i for i in range( 5 ) ] >>> print funcs[0]( 2 ) >>> >>> This gives me >>> 16 >>> >>> When I was excepting >>> 1 >>> >>> Does anyone know why? > > Just the way Python lambda expressions bind their variable > references. Inner 'i' references the outer scope's 'i' variable and not > its value 'at the time the lambda got defined'. > > >> And more importantly, what's the simplest way to achieve the latter? :) > > Try giving the lambda a default parameter (they get calculated and > have their value stored at the time the lambda is defined) like this: > funcs = [ lambda x, i=i: x**i for i in range( 5 ) ] Thanks a lot! I worked around it by def p(i): return lambda x: x**i funcs = [ p(i) for i in range(5) ] But your variant is nicer (matter of taste of course). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From krecoun at gmail.com Wed Jul 11 03:51:38 2012 From: krecoun at gmail.com (=?UTF-8?B?Vm9qdMSbY2ggUG9sw6HFoWVr?=) Date: Wed, 11 Jul 2012 09:51:38 +0200 Subject: introduction and first question about multithreading Message-ID: <4FFD308A.7030904@gmail.com> Greetings, My name is Vojta and I am blind student. I am slowly learning Python for about 4 years and I like it alot, mostly its ability to run on various platforms. My primary system is Ubuntu 12.04, but I have Windows XP at hand. I am using python 2.7. I have learned basics from the book A byte of Python (for version 2.X) and something from Dive into Python. But most things I learned by trial and error and thanks to solutions on stackoverflow.com. I Don't know much about good programming concepts in Python, just in general, so feel free to educate me about them. I haven't created anything great yet, but I am working on a game for blind people. It is a simple game of reaction, but I have to start with something, my next plan is Sudoku game. I am using Pygame for handling of sounds and keyboard events, speech dispatcher under Linux and pyttsx under Windows to provide speech output, numpy for sound cutting and my two little and simple modules for providing menu system and unified interface for both speech engines. During the development, I discovered, that I have to use multithreading to be able to check for key presses and manage the game at the same time. I tried threading module but this wasn't enough for me, because function running in the separate thread needed to access variables in the main thread at least I couldn't find the way how to do that. So I switched to multiprocessing and started using pipes for communication between processes. All is working well, except for one thing. My menu module uses a loop to check for keyboard events through pygame. I don't import pygame into my module directly, but rather pass it through my main module like this: menu.pygame = pygame All was working well until I started using multiprocessing. I may have a probable cause but I need your help. In my main module I am running a similar loop for checking keyboard input in separate process. When a player loses, the loop finishes and I join the process. Then the menu module kicks in and should launch its own loop checking for pygame keyboard events, but right after doing it it prints: [xcb] Unknown sequence number while processing queue [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python: ../../src/xcb_io.c:273: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed received SigAbrt - core dumped Are atachments allowed here? I can send you my whole code. Please help me, if you can. Thank you very much, Vojta From anthra.norell at bluewin.ch Wed Jul 11 03:59:27 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Wed, 11 Jul 2012 09:59:27 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: <25935b3c-b37d-465f-9855-7ecf2c3bdf4e@h10g2000yqn.googlegroups.com> References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> <25935b3c-b37d-465f-9855-7ecf2c3bdf4e@h10g2000yqn.googlegroups.com> Message-ID: <1341993567.2330.40.camel@hatchbox-one> On Tue, 2012-07-10 at 18:06 -0700, Rick Johnson wrote: > Also: > > Q3: Why are you explicitly setting the name of your "subFrame" widgets > instead of allowing Tkinter to assign a unique name?...AND are you > aware of the conflicts that can arise from such changes[1]? > I find custom-named widgets easier to work with during development. I can tell what this is; ".main-frame.data-frame.title-hit-list.-10-". If I didn't assign names it would look something line this:".2837029.283725.283762.2848308". Once my program works I can drop custom-naming. I understand that conflicts may arise if one assigns numeric names. To find out whether the digits in the label names ('-10-' above) might be implicated, I changed to spelled-out names ('ten'). The change had no effect. The reference you list blow (x147-more-on-widget-names.htm) indeed says "don't use names which only contain digits". > Q4: Are you aware of the built-in function "enumerate"[2]? I see you > are passing around indexes to iterables AND simultaneously needing the > obj reference itself. I prefer to keep indexing to a minimum. If > there is no bleeding edge performance issue to worry about (and there > almost *always* never is) why not use enumerate? > Aware, yes. In the habit of, no. Thanks for the reminder. > [1] http://www.pythonware.com/library/tkinter/introduction/x147-more-on-widget-names.htm > [2] http://docs.python.org/release/3.0.1/library/functions.html#enumerate Frederic From cjw at ncf.ca Wed Jul 11 06:28:44 2012 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 11 Jul 2012 06:28:44 -0400 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: On 11/07/2012 2:41 AM, Daniel Fetchinson wrote: > funcs = [ lambda x: x**i for i in range( 5 ) ] > print funcs[0]( 2 ) > print funcs[1]( 2 ) > print funcs[2]( 2 ) > > This gives me > > 16 > 16 > 16 > > When I was excepting > > 1 > 2 > 4 > > Does anyone know why? > > Cheers, > Daniel > > I don't understand why you would expect 1, 2, 4. Perhaps parentheses will help the order of evaluation: funcs = [(lambda x: x**i) for i in range( 5 )] This gives: 1 16 81 Colin W. From roy at panix.com Wed Jul 11 09:20:54 2012 From: roy at panix.com (Roy Smith) Date: Wed, 11 Jul 2012 09:20:54 -0400 Subject: introduction and first question about multithreading References: Message-ID: In article , Vojt????ch Pol???????ek wrote: > Then the menu module kicks in and should launch its > own loop checking for pygame keyboard events, but right after doing it > it prints: > [xcb] Unknown sequence number while processing queue > [xcb] Most likely this is a multi-threaded client and XInitThreads has > not been called > [xcb] Aborting, sorry about that. I googled for "Unknown sequence number while processing queue" and found: http://www.gtkforums.com/viewtopic.php?f=3&t=55708 sounds like it addresses your problem. From chris at newcenturycomputers.net Wed Jul 11 10:06:10 2012 From: chris at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 11 Jul 2012 09:06:10 -0500 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator Message-ID: <4FFD8852.8020705@newcenturycomputers.net> I've held off announcing this until I was sure it was really stable; it's been 19 days since I made the last change to it, so here goes. PollyReports is my Python module for report generation. It is designed to be, quite literally, the "simplest thing that can possibly work" in the field of PDF generation from a database record set. There is a somewhat vague resemblance to GeraldoReports; I had problems with Geraldo's pagination which led me to develop PollyReports in a brief flurry of intense activity. It's on PyPI: http://pypi.python.org/pypi/PollyReports and on Github: https://github.com/Solomoriah/PollyReports and I have a blog where I talk about it (like anyone cares): http://opensource.gonnerman.org/?cat=4 Here's the README: PollyReports.py Copyright (c) 2012 Chris Gonnerman All Rights Reserved See the LICENSE file for more information. (Note: BSD licensed) ----------------------------------------------------------------------------------------- PollyReports.py provides a set of classes for database report writing. It assumes that you are using Reportlab to do PDF generation, but can work with any "canvas-like" object as desired. PollyReports provides the following framework for report generation: A Report object has a data source bound to it at instantiation. One or more Band objects (at least, a detail Band) must be added to it, and then the generate() method will be called to process the data source. The data source must be an iterator that produces objects that can be accessed via [] operations, meaning mainly dict, list, and tuple types, i.e. the most common types of records returned by standard database modules. The detail band is generated() once for each row. Band objects contain a list of Elements (generally at least one) which define how data from the row should be printed. An Element may print any normal data item or label and may be subclassed to handle other things like images. Generating a band in turn calls Element.generate() for each element, producing a list of Renderers with the first item in the list being the overall height of the band. The height is used to decide if the band will fit on the current page; if not, a new page will be created first. When the page is finally ready for the band, Renderer.render() will be called for each Renderer in the element list in order to actually render the data. As noted above, PollyReports expects a Reportlab-like canvas interface. The module has been kept as clean as possible, so that, though I don't actually recommend it, it would not be insane to say from PollyReports import * Importing only what you expect to use is still a better idea, of course. -- ------------------------------------------------------------------------------- Chris Gonnerman Owner, New Century Computers Phone 660-213-3822 Fax 660-213-3339 From jeandubois314 at gmail.com Wed Jul 11 11:37:31 2012 From: jeandubois314 at gmail.com (Jean Dubois) Date: Wed, 11 Jul 2012 08:37:31 -0700 (PDT) Subject: [newbie] Python and Qt4 Designer Message-ID: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> I'm trying to combine python-code made with QT4 designer with plain python statements like file = open("test","w") Can anyone tell me what I have to add to the following code just to open a file when clicking on the load-button and closing it by clicking on the save button. #!/usr/bin/env python # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'test.ui' # # Created: Wed Jul 11 17:21:35 2012 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.widget = QtGui.QWidget(Form) self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) self.widget.setObjectName(_fromUtf8("widget")) self.horizontalLayout = QtGui.QHBoxLayout(self.widget) self.horizontalLayout.setMargin(0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.pushButton_2 = QtGui.QPushButton(self.widget) self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) self.horizontalLayout.addWidget(self.pushButton_2) self.pushButton = QtGui.QPushButton(self.widget) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.horizontalLayout.addWidget(self.pushButton) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton_2.setText(QtGui.QApplication.translate("Form", "Save file", None, QtGui.QApplication.UnicodeUTF8)) self.pushButton.setText(QtGui.QApplication.translate("Form", "Load file", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) thanks in advance jean From ian.g.kelly at gmail.com Wed Jul 11 12:34:33 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 11 Jul 2012 10:34:33 -0600 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williams wrote: > I don't understand why you would expect 1, 2, 4. Because: funcs[0](2) == 2 ** 0 == 1 funcs[1](2) == 2 ** 1 == 2 funcs[2](2) == 2 ** 2 == 4 > Perhaps parentheses will help the order of evaluation: > > funcs = [(lambda x: x**i) for i in range( 5 )] > > This gives: > 1 > 16 > 81 No, that gives 16, 16, 16 just like the original. I don't understand why you would expect 1, 16, 81, unless you have misread the code. From subhabangalore at gmail.com Wed Jul 11 14:15:02 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Wed, 11 Jul 2012 11:15:02 -0700 (PDT) Subject: Opening multiple Files in Different Encoding In-Reply-To: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> References: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Message-ID: On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote: > Dear Group, > > I kept a good number of files in a folder. Now I want to read all of > them. They are in different formats and different encoding. Using > listdir/glob.glob I am able to find the list but how to open/read or > process them for different encodings? > > If any one can help me out.I am using Python3.2 on Windows. > > Regards, > Subhabrata Banerjee. Dear Group, No generally I know the glob.glob or the encodings as I work lot on non-ASCII stuff, but I recently found an interesting issue, suppose there are .doc,.docx,.txt,.xls,.pdf files with different encodings. 1) First I have to determine on the fly the file type. 2) I can not assign encoding="..." whatever be the encoding I have to read it. Any idea. Thinking. Thanks in Advance, Regards, Subhabrata Banerjee. From woooee at gmail.com Wed Jul 11 14:38:18 2012 From: woooee at gmail.com (woooee) Date: Wed, 11 Jul 2012 11:38:18 -0700 (PDT) Subject: lambda in list comprehension acting funny References: Message-ID: You should not be using lambda in this case .for x in [2, 3]: . funcs = [x**ctr for ctr in range( 5 )] . for p in range(5): . print x, funcs[p] . print From john_ladasky at sbcglobal.net Wed Jul 11 16:21:34 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 11 Jul 2012 13:21:34 -0700 (PDT) Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: Exactly. It's threads like these which remind me why I never use lambda. I would rather give a function an explicit name and adhere to the familiar Python syntax, despite the two extra lines of code. I don't even like the name "lambda". It doesn't tell you what it is (unless you're John McCarthy), a function that you won't re-use and so you don't really need to give it a persistent name. I haven't seen any lambdas in any Python library code, or in any of the third-party modules I use (numpy, matplotlib, Biopython). Do they exist? Because I have not been forced to do so, I haven't retained a space in the top drawer of my programming brain for lambda. I know the historical reason that Python ended up with lambda, it was requested by people in the Lisp community. While I appreciate some of the Lisp-like features which did find their way into Python (especially being able to treat code as data, and functions as objects), I've found that lambda does nothing for me. From oscar.j.benjamin at gmail.com Wed Jul 11 16:55:31 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 11 Jul 2012 21:55:31 +0100 Subject: Opening multiple Files in Different Encoding In-Reply-To: References: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Message-ID: On 11 July 2012 19:15, wrote: > On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote: > > Dear Group, > > > > I kept a good number of files in a folder. Now I want to read all of > > them. They are in different formats and different encoding. Using > > listdir/glob.glob I am able to find the list but how to open/read or > > process them for different encodings? > > > > If any one can help me out.I am using Python3.2 on Windows. > > > > Regards, > > Subhabrata Banerjee. > Dear Group, > > No generally I know the glob.glob or the encodings as I work lot on > non-ASCII stuff, but I recently found an interesting issue, suppose there > are .doc,.docx,.txt,.xls,.pdf files with different encodings. Some of the formats you have listed are not text-based. What do you mean by the encoding of e.g. a .doc or .xls file? My understanding is that these are binary files. You won't be able to read them without the help of a special module (I don't know of one that can). > 1) First I have to determine on the fly the file type. > 2) I can not assign encoding="..." whatever be the encoding I have to read > it. > Perhaps you just want to open the file as binary? The following will read the contents of any file binary or text regardless of encoding or anything else: f = open('spreadsheet.xls', 'rb') data = f.read() # returns binary data rather than text > > Any idea. Thinking. > > Thanks in Advance, > Regards, > Subhabrata Banerjee. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hansmu at xs4all.nl Wed Jul 11 18:22:06 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 12 Jul 2012 00:22:06 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: <4ffdfc8f$0$6921$e4fe514c@news2.news.xs4all.nl> On 11/07/12 20:38:18, woooee wrote: > You should not be using lambda in this case > .for x in [2, 3]: > . funcs = [x**ctr for ctr in range( 5 )] > . for p in range(5): > . print x, funcs[p] > . print The list is called "funcs" because it is meant to contain functions. Your code does not put functions in the list, so it doesn't do what he wants. He could do: funcs = [] for i in range(5): def f(x): return x**i funcs.append(f) print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) .... and it will print 16, 16, 16 for the same reason as the lambda version. On the other hand, this does what he wants: funcs = [] for i in range(5): def f(x, i=i): return x**i funcs.append(f) print funcs[0]( 2 ) print funcs[1]( 2 ) print funcs[2]( 2 ) The lambda keyword is a red herring. The question is really about functions, and how they handle non-local variables. The good news is that 'lambda' and 'def' work exactly the same in that regards. So once you understand the finer points about 'def', you no longer have a reason to avoid 'lambda'. Hope this helps, -- HansM From steve+comp.lang.python at pearwood.info Wed Jul 11 19:22:56 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 11 Jul 2012 23:22:56 GMT Subject: Opening multiple Files in Different Encoding References: <40633830-78ae-4cc6-8795-de5a352e0fb1@m2g2000pbv.googlegroups.com> Message-ID: <4ffe0ad0$0$29965$c3e8da3$5496439d@news.astraweb.com> On Wed, 11 Jul 2012 11:15:02 -0700, subhabangalore wrote: > On Tuesday, July 10, 2012 11:16:08 PM UTC+5:30, Subhabrata wrote: >> Dear Group, >> >> I kept a good number of files in a folder. Now I want to read all of >> them. They are in different formats and different encoding. Using >> listdir/glob.glob I am able to find the list but how to open/read or >> process them for different encodings? >> >> If any one can help me out.I am using Python3.2 on Windows. >> >> Regards, >> Subhabrata Banerjee. > Dear Group, > > No generally I know the glob.glob or the encodings as I work lot on > non-ASCII stuff, but I recently found an interesting issue, suppose > there are .doc,.docx,.txt,.xls,.pdf files with different encodings. You can have text files with different encodings, but not the others. .doc .docx .xls and .pdf are all binary files. You don't specify an encoding when you read them, because they aren't text -- encodings are for mapping bytes to text, not bytes to binary formats. In particular, .docx is compressed XML, so once you have uncompressed it, the contents XML, which is *always* UTF-8. > 1) First I have to determine on the fly the file type. Which is a different problem from your first post. On Windows, you determine the file type using the file extension. import os name, ext = os.path.splitext("my_file_name.bmp") will give you ext = ".bmp". Then what do you expect to do? You can open the file as a binary blob, but what do you expect then? f = open("my_file_name.bmp", "rb") Now what do you want to do with it? > 2) I can not assign > encoding="..." whatever be the encoding I have to read it. You can't set the encoding when you open files in binary mode, but binary files don't have an encoding. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 11 19:47:34 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 11 Jul 2012 23:47:34 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffe1096$0$29965$c3e8da3$5496439d@news.astraweb.com> On Wed, 11 Jul 2012 11:38:18 -0700, woooee wrote: > You should not be using lambda in this case > .for x in [2, 3]: > . funcs = [x**ctr for ctr in range( 5 )] > . for p in range(5): > . print x, funcs[p] > . print If you change the requirements, it's always easy to solve problems. But it is the wrong problem that you have solved. The problem we have been asked to solve is to create a sequence of function objects, so that they can be called later, when needed, *not* to pre-calculate the results. In this case, the most obvious solution is to store a local variable in each function object with the value you want. funcs = [(lambda x, i=i: x**i) for i in range(5)] creates a list of five functions: lambda x, i=0: x**i lambda x, i=1: x**i lambda x, i=2: x**i and so on. In this case, each function has two local variables, x and i, with i having a default value. The function parameter i is bound to the value of i when the function was created. Because parameter defaults are calculated once, when the function is created, this causes the value of i to stick to the newly created function, and we get the result we need. What happens if you don't use a parameter with a default value? funcs = [(lambda x: x**i) for i in range(5)] In this case, each function body contains one local variable, x, and one non-local or global variable, i. Because i is a non-local, the function doesn't store a value for it. Instead, the function stores a lump of data pointing to just enough of the environment to fetch the current value of the non-local i when needed. Since all five functions are in the same environment, they all see the same value of i when you call them, regardless of what the value of i was when they were created. This is little different from doing this: i = 1 def f1(x): return x**i i = 2 def f2(x): return x**i i = 3 def f3(x): return x**i Is there any surprise that all three functions return the same value? They all point to the same global variable i. I'm not sure what it is about lambda that fools people into thinking that it is different (I've even been fooled myself!) but it is not. -- Steven From simoncropper at fossworkflowguides.com Wed Jul 11 20:41:52 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Thu, 12 Jul 2012 10:41:52 +1000 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: <4FFD8852.8020705@newcenturycomputers.net> References: <4FFD8852.8020705@newcenturycomputers.net> Message-ID: <4FFE1D50.10604@fossworkflowguides.com> On 12/07/12 00:06, Chris Gonnerman wrote: > I've held off announcing this until I was sure it was really stable; > it's been 19 days since I made the last change to it, so here goes. > PollyReports is my Python module for report generation. It is designed > to be, quite literally, the "simplest thing that can possibly work" in > the field of PDF generation from a database record set. There is a > somewhat vague resemblance to GeraldoReports; I had problems with > Geraldo's pagination which led me to develop PollyReports in a brief > flurry of intense activity. > > It's on PyPI: http://pypi.python.org/pypi/PollyReports > and on Github: https://github.com/Solomoriah/PollyReports > and I have a blog where I talk about it (like anyone cares): > http://opensource.gonnerman.org/?cat=4 "I've noticed that acceptance of a new software module or package for developers in the Open Source/Free Software world is greatly affected by the availability of a good tutorial. I mean, it seems obvious, doesn't it? But I've also noticed that the original author of a project rarely writes a good tutorial." http://packages.python.org/PollyReports/tutorial.html Well I thought it was a good tutorial. It certainly empowers me with enough confidence to give it a try. That said... with more than a passing interest in software and content licensing I looked at how the work was licensed. A none-standard license like this makes most people stop and think "will this be a problem if I use this in my work?" How compatible is your license with the main software licenses currently available? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From steve+comp.lang.python at pearwood.info Wed Jul 11 20:52:08 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 00:52:08 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffe1fb8$0$29965$c3e8da3$5496439d@news.astraweb.com> On Wed, 11 Jul 2012 13:21:34 -0700, John Ladasky wrote: > Exactly. It's threads like these which remind me why I never use > lambda. I would rather give a function an explicit name and adhere to > the familiar Python syntax, despite the two extra lines of code. lambda is familiar Python syntax, or at least it should be if you consider yourself an expert Python programmer. And besides, this is not a problem with lambda. You get the *exact* same problem with "ordinary" function definitions. Of course you do -- lambdas *are* ordinary functions, they just have a more compact syntax. funcs = [] for i in range(5): def pwr(x): return x**i print("Testing 3**%d:" % i, pwr(3)) funcs.append(pwr) for j in range(5): print("Expected", 3**j, "got", funcs[j](3)) gives you *exactly* the same issue as with the lambda. This is not a problem with lambdas, this is a scoping issue. > I don't even like the name "lambda". It doesn't tell you what it is Whereas "def" does? If you can learn that "def" defines a function (as opposed to a class, a module, or anything else really) than it's not that hard to learn that "lambda" also defines a function. Although I do wonder whether people would be less scared of lambda, and less likely to imagine that it creates something with strange mysterious properties different from "regular functions", if the keyword was called "function" instead of lambda? > (unless you're John McCarthy), a function that you won't re-use and so > you don't really need to give it a persistent name. Whether or not a function has a persistent name has nothing to do with reuse. Anonymous functions can be reused. The driving motivation for lambdas is for callback functions, which are frequently reused, but you don't need or want to fill your global namespace up with potentially hundreds of callback functions. Lambda syntax is only incidentally good for saving a line or two. If the only benefit of lambda was to save a line of code, that would be stupid. The real reason for lambda is to avoid polluting your namespace with unnecessary names. Python allows us to easily and simply use anonymous strings, anonymous ints, anonymous objects of all types. Why should functions be treated as second-class? > I haven't seen any lambdas in any Python library code, or in any of the > third-party modules I use (numpy, matplotlib, Biopython). Do they > exist? Because I have not been forced to do so, I haven't retained a > space in the top drawer of my programming brain for lambda. There are over 800 uses of lambda in the standard library: [steve at ando ~]$ cd /usr/local/lib/python3.2 [steve at ando python3.2]$ grep lambda *.py */*.py | wc -l 829 (although some of the above are comments, doctests, etc.) See, for example, configparser, decimal, functools, gettext, inspect, pydoc, symtable, uuid, and others. pydoc and idlelib in particular make heavy use of lambda, and the test suite is overflowing with them -- over 600 uses in total. -- Steven From vincent.vandevyvre at swing.be Wed Jul 11 20:59:11 2012 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Thu, 12 Jul 2012 02:59:11 +0200 Subject: [newbie] Python and Qt4 Designer In-Reply-To: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: <4FFE215F.8020308@swing.be> On 11/07/12 17:37, Jean Dubois wrote: > I'm trying to combine python-code made with QT4 designer with plain > python statements like > file = open("test","w") > Can anyone tell me what I have to add to the following code just to > open a file when clicking on the load-button and closing it by > clicking on the save button. > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > # Form implementation generated from reading ui file 'test.ui' > # > # Created: Wed Jul 11 17:21:35 2012 > # by: PyQt4 UI code generator 4.8.3 > # > # WARNING! All changes made in this file will be lost! > > from PyQt4 import QtCore, QtGui > > try: > _fromUtf8 = QtCore.QString.fromUtf8 > except AttributeError: > _fromUtf8 = lambda s: s > > class Ui_Form(object): > def setupUi(self, Form): > Form.setObjectName(_fromUtf8("Form")) > Form.resize(400, 300) > self.widget = QtGui.QWidget(Form) > self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) > self.widget.setObjectName(_fromUtf8("widget")) > self.horizontalLayout = QtGui.QHBoxLayout(self.widget) > self.horizontalLayout.setMargin(0) > > self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) > self.pushButton_2 = QtGui.QPushButton(self.widget) > self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) > self.horizontalLayout.addWidget(self.pushButton_2) > self.pushButton = QtGui.QPushButton(self.widget) > self.pushButton.setObjectName(_fromUtf8("pushButton")) > self.horizontalLayout.addWidget(self.pushButton) > > self.retranslateUi(Form) > QtCore.QMetaObject.connectSlotsByName(Form) > > def retranslateUi(self, Form): > Form.setWindowTitle(QtGui.QApplication.translate("Form", > "Form", None, QtGui.QApplication.UnicodeUTF8)) > self.pushButton_2.setText(QtGui.QApplication.translate("Form", > "Save file", None, QtGui.QApplication.UnicodeUTF8)) > self.pushButton.setText(QtGui.QApplication.translate("Form", > "Load file", None, QtGui.QApplication.UnicodeUTF8)) > > > if __name__ == "__main__": > import sys > app = QtGui.QApplication(sys.argv) > Form = QtGui.QWidget() > ui = Ui_Form() > ui.setupUi(Form) > Form.show() > sys.exit(app.exec_()) > > > thanks in advance > jean Connect the signal clicked of your's buttons to your's functions. self.pushButton.clicked.connect(self.my_func) Here's all the truth: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html -- Vincent V.V. Oqapy . Qarte+7 . PaQager From james.pye at gmail.com Wed Jul 11 21:37:43 2012 From: james.pye at gmail.com (jwp) Date: Wed, 11 Jul 2012 18:37:43 -0700 (PDT) Subject: Automatic setup of meta path hooks? Message-ID: <126c13af-f5d0-46ca-b410-3fafd308b471@googlegroups.com> Hi, I'm working on a meta path hook that performs compilation of C extension modules on import ( github.com/jwp/py-c ; pip install c ). It mostly works, but I'm having a hard time finding a standard way to automatically install the hook upon interpreter startup. I've thought about just having depending projects install the loader themselves, but I was hoping to make it seamless...Not to mention, there's the possibility of the case where the extension module is compiled and installed with setup.py. In which case, the loader isn't necessary, so it seems inappropriate to reference and install the meta path hook in an outer package module. Am I missing something? Is there some setuptools/distribute magicalawesome that I can use? From fetchinson at googlemail.com Wed Jul 11 22:54:32 2012 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 12 Jul 2012 04:54:32 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe1096$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4ffe1096$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: >> You should not be using lambda in this case >> .for x in [2, 3]: >> . funcs = [x**ctr for ctr in range( 5 )] >> . for p in range(5): >> . print x, funcs[p] >> . print > > If you change the requirements, it's always easy to solve problems. But > it is the wrong problem that you have solved. > > The problem we have been asked to solve is to create a sequence of > function objects, so that they can be called later, when needed, *not* to > pre-calculate the results. > > In this case, the most obvious solution is to store a local variable in > each function object with the value you want. > > funcs = [(lambda x, i=i: x**i) for i in range(5)] > > creates a list of five functions: > > lambda x, i=0: x**i > lambda x, i=1: x**i > lambda x, i=2: x**i > and so on. > > In this case, each function has two local variables, x and i, with i > having a default value. The function parameter i is bound to the value of > i when the function was created. > > Because parameter defaults are calculated once, when the function is > created, this causes the value of i to stick to the newly created > function, and we get the result we need. > > What happens if you don't use a parameter with a default value? > > funcs = [(lambda x: x**i) for i in range(5)] > > In this case, each function body contains one local variable, x, and one > non-local or global variable, i. > > Because i is a non-local, the function doesn't store a value for it. > Instead, the function stores a lump of data pointing to just enough of > the environment to fetch the current value of the non-local i when > needed. Since all five functions are in the same environment, they all > see the same value of i when you call them, regardless of what the value > of i was when they were created. > > This is little different from doing this: > > i = 1 > def f1(x): return x**i > > i = 2 > def f2(x): return x**i > > i = 3 > def f3(x): return x**i > > Is there any surprise that all three functions return the same value? > They all point to the same global variable i. I'm not sure what it is > about lambda that fools people into thinking that it is different (I've > even been fooled myself!) but it is not. Thank you Steve! Precise and clear, as always! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jussij at zeusedit.com Wed Jul 11 23:10:56 2012 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: Wed, 11 Jul 2012 20:10:56 -0700 (PDT) Subject: ANN: Zeus - Windows IDE for Python Message-ID: The latest Zeus IDE Version 3.97o is now available: http://www.zeusedit.com/python.html This latest Zeus release adds improved Python debugger support. Other Pyhon language features include syntax highlighting, code completion, smart indenting, class browsing and code folding. Zeus is also fully scriptable in Python. NOTE: Zeus is shareware, runs natively on the Windows platform and can be run on Linux using Wine. Jussi Jumppanen Author: Zeus Editor From dihedral88888 at googlemail.com Wed Jul 11 23:39:45 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 11 Jul 2012 20:39:45 -0700 (PDT) Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: <62b4a584-42ca-4e10-af12-18b6f66eed76@googlegroups.com> On Thursday, July 12, 2012 12:34:33 AM UTC+8, Ian wrote: > On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williams <cjw at ncf.ca> wrote: > > I don't understand why you would expect 1, 2, 4. > > Because: > > funcs[0](2) == 2 ** 0 == 1 > funcs[1](2) == 2 ** 1 == 2 > funcs[2](2) == 2 ** 2 == 4 > > > Perhaps parentheses will help the order of evaluation: > > > > funcs = [(lambda x: x**i) for i in range( 5 )] > > > > This gives: > > 1 > > 16 > > 81 > > No, that gives 16, 16, 16 just like the original. I don't understand > why you would expect 1, 16, 81, unless you have misread the code. I'll contribute my way of python programming: def powerb(x, b): # return x**b One functor is enough! From dihedral88888 at googlemail.com Wed Jul 11 23:39:45 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 11 Jul 2012 20:39:45 -0700 (PDT) Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: <62b4a584-42ca-4e10-af12-18b6f66eed76@googlegroups.com> On Thursday, July 12, 2012 12:34:33 AM UTC+8, Ian wrote: > On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williams <cjw at ncf.ca> wrote: > > I don't understand why you would expect 1, 2, 4. > > Because: > > funcs[0](2) == 2 ** 0 == 1 > funcs[1](2) == 2 ** 1 == 2 > funcs[2](2) == 2 ** 2 == 4 > > > Perhaps parentheses will help the order of evaluation: > > > > funcs = [(lambda x: x**i) for i in range( 5 )] > > > > This gives: > > 1 > > 16 > > 81 > > No, that gives 16, 16, 16 just like the original. I don't understand > why you would expect 1, 16, 81, unless you have misread the code. I'll contribute my way of python programming: def powerb(x, b): # return x**b One functor is enough! From steve+comp.lang.python at pearwood.info Wed Jul 11 23:51:04 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 03:51:04 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffe49a8$0$1781$c3e8da3$76491128@news.astraweb.com> On Wed, 11 Jul 2012 20:39:45 -0700, 88888 Dihedral wrote: > I'll contribute my way of python programming: > > def powerb(x, b): # > return x**b Here's a shorter version: py> pow > One functor is enough! Nothing we have been discussing in this thread has been a functor, either in the Haskell sense or the C++ sense. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 11 23:53:03 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 03:53:03 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffe4a1f$0$1781$c3e8da3$76491128@news.astraweb.com> On Wed, 11 Jul 2012 21:05:30 -0400, Dennis Lee Bieber wrote: > {non sequitur: I still recall my archaic C++ class with the OOAD > assignment of designing said calculator -- we never had to implement > one, just design the basic classes/methods/attributes [on 3x5 cards] for > a four-banger. I managed to persuade the team I was on that an RPN > calculator would be simpler to (potentially) implement... And THEN > persuaded them to NOT use the equivalent of an ALU class, but to put the > math work into each operation button... "ALU class"? Googling gives me no clue. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 11 23:59:55 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 03:59:55 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> On Wed, 11 Jul 2012 08:41:57 +0200, Daniel Fetchinson wrote: > funcs = [ lambda x: x**i for i in range( 5 ) ] Here's another solution: from functools import partial funcs = [partial(lambda i, x: x**i, i) for i in range(5)] Notice that the arguments i and x are defined in the opposite order. That's because partial only applies positional arguments from the left. If there was a "right partial" that applies from the right, we could use the built-in instead: funcs = [rpartial(pow, i) for i in range(5)] -- Steven From tjreedy at udel.edu Thu Jul 12 00:24:27 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Jul 2012 00:24:27 -0400 Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe4a1f$0$1781$c3e8da3$76491128@news.astraweb.com> References: <4ffe4a1f$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: On 7/11/2012 11:53 PM, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 21:05:30 -0400, Dennis Lee Bieber wrote: > >> {non sequitur: I still recall my archaic C++ class with the OOAD >> assignment of designing said calculator -- we never had to implement >> one, just design the basic classes/methods/attributes [on 3x5 cards] for >> a four-banger. I managed to persuade the team I was on that an RPN >> calculator would be simpler to (potentially) implement... And THEN >> persuaded them to NOT use the equivalent of an ALU class, but to put the >> math work into each operation button... > > "ALU class"? > > Googling gives me no clue. 4th hit: Arithmetic Logic Unit (hardware) -- Wikipedia ALU class -- software version or simulation thereof. The hardware version of Dennis's distributed design would be interesting. Spreadsheets are based in part on the same idea of distributed logic and arithmetic. -- Terry Jan Reedy From dihedral88888 at googlemail.com Thu Jul 12 01:04:51 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 11 Jul 2012 22:04:51 -0700 (PDT) Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe49a8$0$1781$c3e8da3$76491128@news.astraweb.com> References: <4ffe49a8$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: <6b5861df-aa4c-42bc-b013-e0bf2b94ca7e@googlegroups.com> On Thursday, July 12, 2012 11:51:04 AM UTC+8, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 20:39:45 -0700, 88888 Dihedral wrote: > > > I'll contribute my way of python programming: > > > > def powerb(x, b): # > > return x**b > > Here's a shorter version: > > py> pow > <built-in function pow> > > > > One functor is enough! > > Nothing we have been discussing in this thread has been a functor, either > in the Haskell sense or the C++ sense. > > > > -- > Steven Well, I encountered this kind of problems before in OOP. I have to make sure my functor to keep the state variable values for different objects that call the same functor to behave correctly in order to avoid passing extra parameters in various objects using the same functor. From research at johnohagan.com Thu Jul 12 01:29:42 2012 From: research at johnohagan.com (John O'Hagan) Date: Thu, 12 Jul 2012 15:29:42 +1000 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: <20120712152942.b2d177117e71167c08edd4ee@johnohagan.com> On Wed, 11 Jul 2012 13:21:34 -0700 (PDT) John Ladasky wrote: > Exactly. It's threads like these which remind me why I never use lambda. I > would rather give a function an explicit name and adhere to the familiar > Python syntax, despite the two extra lines of code. I don't even like the > name "lambda". It doesn't tell you what it is (unless you're John McCarthy), > a function that you won't re-use and so you don't really need to give it a > persistent name. > > I haven't seen any lambdas in any Python library code, or in any of the > third-party modules I use (numpy, matplotlib, Biopython). Do they exist? > Because I have not been forced to do so, I haven't retained a space in the > top drawer of my programming brain for lambda. [...] +1 about the name, -1 about the usefulness. For example it's a clear and concise way to pass a key argument to min, max, sort and friends: sort(seq, key=lambda x: x.a) The alternative is to have trivial function definitions floating around the namespace which readers of the code have to search for. -- John From andipersti at gmail.com Thu Jul 12 01:35:48 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 12 Jul 2012 07:35:48 +0200 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: <4FFE1D50.10604@fossworkflowguides.com> References: <4FFD8852.8020705@newcenturycomputers.net> <4FFE1D50.10604@fossworkflowguides.com> Message-ID: <20120712073548.7057f9b04be372f9d4b04d0f@gmail.com> On Thu, 12 Jul 2012 10:41:52 +1000 Simon Cropper wrote: > That said... with more than a passing interest in software and > content licensing I looked at how the work was licensed. A > none-standard license like this makes most people stop and think > "will this be a problem if I use this in my work?" How compatible is > your license with the main software licenses currently available? Do you mean this license?: http://packages.python.org/PollyReports/license.html It's the standard license for NetBSD projects and approved by OSI: http://www.opensource.org/licenses/bsd-license.php and GPL-compatible: http://www.gnu.org/licenses/license-list.html#FreeBSD Bye, Andreas From steve+comp.lang.python at pearwood.info Thu Jul 12 02:18:42 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 06:18:42 GMT Subject: lambda in list comprehension acting funny References: <4ffe49a8$0$1781$c3e8da3$76491128@news.astraweb.com> <6b5861df-aa4c-42bc-b013-e0bf2b94ca7e@googlegroups.com> Message-ID: <4ffe6c42$0$1781$c3e8da3$76491128@news.astraweb.com> On Wed, 11 Jul 2012 22:04:51 -0700, 88888 Dihedral wrote: > I have to make sure my functor to keep the state variable values for > different objects that call the same functor to behave correctly in > order to avoid passing extra parameters in various objects using the > same functor. Yo dawg, I heard you liked functors, so I put a functor in your functor so you can train your markov chains with extra functor parameters to functor objects that are functor factory decorator functors. -- Steven From jeandubois314 at gmail.com Thu Jul 12 02:42:32 2012 From: jeandubois314 at gmail.com (Jean Dubois) Date: Wed, 11 Jul 2012 23:42:32 -0700 (PDT) Subject: Python and Qt4 Designer References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: On 12 jul, 02:59, Vincent Vande Vyvre wrote: > On 11/07/12 17:37, Jean Dubois wrote: > > > > > > > > > I'm trying to combine python-code made with QT4 designer with plain > > python statements like > > file = open("test","w") > > Can anyone tell me what I have to ?add to the following code just to > > open a file when clicking on the load-button and closing it by > > clicking on the save button. > > > #!/usr/bin/env python > > # -*- coding: utf-8 -*- > > > # Form implementation generated from reading ui file 'test.ui' > > # > > # Created: Wed Jul 11 17:21:35 2012 > > # ? ? ?by: PyQt4 UI code generator 4.8.3 > > # > > # WARNING! All changes made in this file will be lost! > > > from PyQt4 import QtCore, QtGui > > > try: > > ? ? _fromUtf8 = QtCore.QString.fromUtf8 > > except AttributeError: > > ? ? _fromUtf8 = lambda s: s > > > class Ui_Form(object): > > ? ? def setupUi(self, Form): > > ? ? ? ? Form.setObjectName(_fromUtf8("Form")) > > ? ? ? ? Form.resize(400, 300) > > ? ? ? ? self.widget = QtGui.QWidget(Form) > > ? ? ? ? self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) > > ? ? ? ? self.widget.setObjectName(_fromUtf8("widget")) > > ? ? ? ? self.horizontalLayout = QtGui.QHBoxLayout(self.widget) > > ? ? ? ? self.horizontalLayout.setMargin(0) > > > self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) > > ? ? ? ? self.pushButton_2 = QtGui.QPushButton(self.widget) > > ? ? ? ? self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) > > ? ? ? ? self.horizontalLayout.addWidget(self.pushButton_2) > > ? ? ? ? self.pushButton = QtGui.QPushButton(self.widget) > > ? ? ? ? self.pushButton.setObjectName(_fromUtf8("pushButton")) > > ? ? ? ? self.horizontalLayout.addWidget(self.pushButton) > > > ? ? ? ? self.retranslateUi(Form) > > ? ? ? ? QtCore.QMetaObject.connectSlotsByName(Form) > > > ? ? def retranslateUi(self, Form): > > ? ? ? ? Form.setWindowTitle(QtGui.QApplication.translate("Form", > > "Form", None, QtGui.QApplication.UnicodeUTF8)) > > ? ? ? ? self.pushButton_2.setText(QtGui.QApplication.translate("Form", > > "Save file", None, QtGui.QApplication.UnicodeUTF8)) > > ? ? ? ? self.pushButton.setText(QtGui.QApplication.translate("Form", > > "Load file", None, QtGui.QApplication.UnicodeUTF8)) > > > if __name__ == "__main__": > > ? ? import sys > > ? ? app = QtGui.QApplication(sys.argv) > > ? ? Form = QtGui.QWidget() > > ? ? ui = Ui_Form() > > ? ? ui.setupUi(Form) > > ? ? Form.show() > > ? ? sys.exit(app.exec_()) > > > thanks in advance > > jean > > Connect the signal clicked of your's buttons to your's functions. > > ? ? self.pushButton.clicked.connect(self.my_func) > > Here's all the truth: > > http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_... > > -- > Vincent V.V. > Oqapy . Qarte+7 > . PaQager thanks for the reference, could you just supply a small example for the code above to get me started? thanks in advance jean From franck at ditter.org Thu Jul 12 02:49:58 2012 From: franck at ditter.org (Franck Ditter) Date: Thu, 12 Jul 2012 08:49:58 +0200 Subject: lambda in list comprehension acting funny References: Message-ID: In article , Daniel Fetchinson wrote: > > funcs = [ lambda x: x**i for i in range( 5 ) ] > > print funcs[0]( 2 ) > > print funcs[1]( 2 ) > > print funcs[2]( 2 ) > > > > This gives me > > > > 16 > > 16 > > 16 > > > > When I was excepting > > > > 1 > > 2 > > 4 > > > > Does anyone know why? In Python 3.x : funcs = [lambda x: x**i for i in range(5)] list(map(lambda f: f(2),funcs)) --> [16, 16, 16, 16, 16] Ooops, cool semantics :-) In Racket Scheme (http://racket-lang.org), they seem to know lambdas : #lang racket ;;; quick and dirty list comprehension syntax as a macro, for fun : (define-syntax-rule (list-of expr for x in L) (map (lambda (x) expr) L)) (list-of (sqr x) for x in (range 5)) --> (0 1 4 9 16) (define funcs (list-of (lambda (x) (expt x i)) for i in (range 5))) (map (lambda (f) (f 2)) funcs) --> (1 2 4 8 16) franck From rosuav at gmail.com Thu Jul 12 02:59:06 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 12 Jul 2012 16:59:06 +1000 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: <20120712073548.7057f9b04be372f9d4b04d0f@gmail.com> References: <4FFD8852.8020705@newcenturycomputers.net> <4FFE1D50.10604@fossworkflowguides.com> <20120712073548.7057f9b04be372f9d4b04d0f@gmail.com> Message-ID: On Thu, Jul 12, 2012 at 3:35 PM, Andreas Perstinger wrote: > Do you mean this license?: > http://packages.python.org/PollyReports/license.html > > It's the standard license for NetBSD projects and approved by OSI: > http://www.opensource.org/licenses/bsd-license.php > > and GPL-compatible: > http://www.gnu.org/licenses/license-list.html#FreeBSD Can you state that on the page, perhaps? It'd mean that anyone who's familiar with the license can read one keyword and know what the terms are, rather than dig through the full text to see if it's really the same or not. ChrisA From breamoreboy at yahoo.co.uk Thu Jul 12 03:40:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 12 Jul 2012 08:40:37 +0100 Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe6c42$0$1781$c3e8da3$76491128@news.astraweb.com> References: <4ffe49a8$0$1781$c3e8da3$76491128@news.astraweb.com> <6b5861df-aa4c-42bc-b013-e0bf2b94ca7e@googlegroups.com> <4ffe6c42$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: On 12/07/2012 07:18, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 22:04:51 -0700, 88888 Dihedral wrote: > >> I have to make sure my functor to keep the state variable values for >> different objects that call the same functor to behave correctly in >> order to avoid passing extra parameters in various objects using the >> same functor. > > Yo dawg, I heard you liked functors, so I put a functor in your functor > so you can train your markov chains with extra functor parameters to > functor objects that are functor factory decorator functors. > > > functory :) Ooh, that's bad even by my standards. -- Cheers. Mark Lawrence. From robert.kern at gmail.com Thu Jul 12 05:06:53 2012 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Jul 2012 10:06:53 +0100 Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: On 7/11/12 9:21 PM, John Ladasky wrote: > Exactly. It's threads like these which remind me why I never use lambda. I would rather give a function an explicit name and adhere to the familiar Python syntax, despite the two extra lines of code. I don't even like the name "lambda". It doesn't tell you what it is (unless you're John McCarthy), a function that you won't re-use and so you don't really need to give it a persistent name. > > I haven't seen any lambdas in any Python library code, or in any of the third-party modules I use (numpy, matplotlib, Biopython). Do they exist? Because I have not been forced to do so, I haven't retained a space in the top drawer of my programming brain for lambda. I count 162 uses in the Python standard library, 69 uses in numpy, 108 in matplotlib, and 238 uses in Biopython. Adding in the unit tests for each would add significantly to those counts. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From alister.ware at ntlworld.com Thu Jul 12 05:44:15 2012 From: alister.ware at ntlworld.com (Alister) Date: Thu, 12 Jul 2012 09:44:15 GMT Subject: lambda in list comprehension acting funny References: Message-ID: On Wed, 11 Jul 2012 08:43:11 +0200, Daniel Fetchinson wrote: >> funcs = [ lambda x: x**i for i in range( 5 ) ] >> print funcs[0]( 2 ) >> print funcs[1]( 2 ) >> print funcs[2]( 2 ) >> >> This gives me >> >> 16 16 16 >> >> When I was excepting >> >> 1 >> 2 >> 4 >> >> Does anyone know why? > > And more importantly, what's the simplest way to achieve the latter? :) Having read Steve's explanation in the other thread (which I think has finally flipped the light switch on lambda for me) it only requires a minor change funcs=[ lambda x,y=i:x**y for i in range(5) ] although I cant actually think why this construct would be needed in practice, how are you actually using it -- * Simunye is so happy she has her mothers gene's you better give them back before she misses them! From andipersti at gmail.com Thu Jul 12 05:56:31 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 12 Jul 2012 11:56:31 +0200 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: References: <4FFD8852.8020705@newcenturycomputers.net> <4FFE1D50.10604@fossworkflowguides.com> <20120712073548.7057f9b04be372f9d4b04d0f@gmail.com> Message-ID: <20120712115631.1acf9b35c4482353cca01ee8@gmail.com> On Thu, 12 Jul 2012 16:59:06 +1000 Chris Angelico wrote: > On Thu, Jul 12, 2012 at 3:35 PM, Andreas Perstinger > wrote: > > Do you mean this license?: > > http://packages.python.org/PollyReports/license.html > > > > It's the standard license for NetBSD projects and approved by OSI: > > http://www.opensource.org/licenses/bsd-license.php > > > > and GPL-compatible: > > http://www.gnu.org/licenses/license-list.html#FreeBSD > > Can you state that on the page, perhaps? It'd mean that anyone who's > familiar with the license can read one keyword and know what the terms > are, rather than dig through the full text to see if it's really the > same or not. I'm not responsible for any of the tree pages I've mentioned. I've just looked at the "PollyReports"-license page because I was curious which "strange" license the original author uses. Then I noticed it's just one of the BSD-licenses, used Wikipedia to confirm it and searched for the two other pages to show that it isn't problematic at all. Bye, Andreas From steve+comp.lang.python at pearwood.info Thu Jul 12 07:29:49 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Jul 2012 11:29:49 GMT Subject: lambda in list comprehension acting funny References: Message-ID: <4ffeb52c$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 09:44:15 +0000, Alister wrote: > On Wed, 11 Jul 2012 08:43:11 +0200, Daniel Fetchinson wrote: > >>> funcs = [ lambda x: x**i for i in range( 5 ) ] [...] > Having read Steve's explanation in the other thread (which I think has > finally flipped the light switch on lambda for me) it only requires a > minor change > > funcs=[ lambda x,y=i:x**y for i in range(5) ] > > although I cant actually think why this construct would be needed in > practice, how are you actually using it I would expect that the example given is just sample code demonstrating the problem. A slightly more realistic case might be something like defining a bunch of callbacks for, say, a GUI application. For example, the good ol' calculator app, where you have ten buttons for digits 0-9. So you might give each button a callback function that inserts its own digit into the text field: buttons = [make_button(name=str(i)) for i in range(10)] That works fine. So now you go to add a callback to each one: buttons = [make_button(name=str(i), callback=lambda: FIELD.insert(i)) for i in range(10)] and lo and behold, the ten buttons named "0" through "9" all insert 9. The reason is that the callback functions aren't given the value of i, but only the name[1] "i". By the time the callbacks are actually used, i == 9 and all the buttons share the same value. [1] Technically closures may not store values by name, but the principle is sound: the function, when called later, looks up the current value of variable i, which is not necessarily the same as it was when the closure was originally defined. -- Steven From gandalf at shopzeus.com Thu Jul 12 08:30:41 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 12 Jul 2012 14:30:41 +0200 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: <4FFEC371.5040703@shopzeus.com> > You are contradicting yourself. Either the OS is providing a fully > atomic rename or it doesn't. All POSIX compatible OS provide an atomic > rename functionality that renames the file atomically or fails without > loosing the target side. On POSIX OS it doesn't matter if the target exists. This is not a contradiction. Although the rename operation is atomic, the whole "change status" process is not. It is because there are two operations: #1 delete old status file and #2. rename the new status file. And because there are two operations, there is still a race condition. I see no contradiction here. > > You don't need locks or any other fancy stuff. You just need to make > sure that you flush the data and metadata correctly to the disk and > force a re-write of the directory inode, too. It's a standard pattern on > POSIX platforms and well documented in e.g. the maildir RFC. It is not entirely true. We are talking about two processes. One is reading a file, another one is writting it. They can run at the same time, so flushing disk cache forcedly won't help. From gandalf at shopzeus.com Thu Jul 12 08:31:50 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 12 Jul 2012 14:31:50 +0200 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: <4FFEC3B6.5080409@shopzeus.com> > Renaming files is the wrong way to synchronize a > crawler. Use a database that has ACID properties, such as > SQLite. Far fewer I/O operations are required for small updates. > It's not the 1980s any more. I agree with this approach. However, the OP specifically asked about "how to update status file". From chris at newcenturycomputers.net Thu Jul 12 08:37:43 2012 From: chris at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 12 Jul 2012 07:37:43 -0500 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: References: <4FFD8852.8020705@newcenturycomputers.net> Message-ID: <4FFEC517.8080102@newcenturycomputers.net> Apparently my test hasn't kept up with my update. I'll get it revised soon and make a new release. BTW... who is Simon? I wrote the tutorial. (Solomoriah is an old handle I still use a lot since it's less common than Chris.) -- Chris. On 07/12/2012 03:32 AM, Johann Spies wrote: > On 12 July 2012 10:27, Johann Spies > wrote: > > > I get the same error when running the example code from > Simon's tutorial (sample02 - sample07). > > > Thanks Simon for your tutorial. > > Changing 'right = 1' in all the example code to 'align = "right" ' > solved the problem. > > I suspect the example code was not updated after recent changes. > > Regards > Johann > -- > Because experiencing your loyal love is better than life itself, > my lips will praise you. (Psalm 63:3) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rodrick.brown at gmail.com Thu Jul 12 08:50:46 2012 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Thu, 12 Jul 2012 08:50:46 -0400 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: <4FFE1D50.10604@fossworkflowguides.com> References: <4FFD8852.8020705@newcenturycomputers.net> <4FFE1D50.10604@fossworkflowguides.com> Message-ID: <-8086121043873136460@unknownmsgid> On Jul 11, 2012, at 8:44 PM, Simon Cropper wrote: > On 12/07/12 00:06, Chris Gonnerman wrote: >> I've held off announcing this until I was sure it was really stable; >> it's been 19 days since I made the last change to it, so here goes. >> PollyReports is my Python module for report generation. It is designed >> to be, quite literally, the "simplest thing that can possibly work" in >> the field of PDF generation from a database record set. There is a >> somewhat vague resemblance to GeraldoReports; I had problems with >> Geraldo's pagination which led me to develop PollyReports in a brief >> flurry of intense activity. >> >> It's on PyPI: http://pypi.python.org/pypi/PollyReports >> and on Github: https://github.com/Solomoriah/PollyReports >> and I have a blog where I talk about it (like anyone cares): >> http://opensource.gonnerman.org/?cat=4 > > "I've noticed that acceptance of a new software module or package for developers in the Open Source/Free Software world is greatly affected by the availability of a good tutorial. I mean, it seems obvious, doesn't it? But I've also noticed that the original author of a project rarely writes a good tutorial." http://packages.python.org/PollyReports/tutorial.html > The author has made the code available on Git Hub so you can easily contribute. Simple python classes and modules tend to be light on providing examples or tutorials when the docstrings may be sufficient for most. > Well I thought it was a good tutorial. It certainly empowers me with enough confidence to give it a try. > > That said... with more than a passing interest in software and content licensing I looked at how the work was licensed. A none-standard license like this makes most people stop and think "will this be a problem if I use this in my work?" How compatible is your license with the main software licenses currently available? > The BSD license has been around for many years even before GPL and it's quite popular amongst the anti GNU crowd. I'm not sure what you mean by non standard license? Is because it's none GPL? The BSD license is actually the most liberal open source license format available when looking to integrate open source applications into commercials ones. You're free to do as you will without tainting your software or providing your modifications you've made. > -- > Cheers Simon > > Simon Cropper - Open Content Creator > > Free and Open Source Software Workflow Guides > ------------------------------------------------------------ > Introduction http://www.fossworkflowguides.com > GIS Packages http://www.fossworkflowguides.com/gis > bash / Python http://www.fossworkflowguides.com/scripting > > > -- > http://mail.python.org/mailman/listinfo/python-list From lists at cheimes.de Thu Jul 12 09:05:26 2012 From: lists at cheimes.de (Christian Heimes) Date: Thu, 12 Jul 2012 15:05:26 +0200 Subject: How to safely maintain a status file In-Reply-To: <4FFEC371.5040703@shopzeus.com> References: <4FF9F454.40207@shopzeus.com> <4FFEC371.5040703@shopzeus.com> Message-ID: <4FFECB96.9040601@cheimes.de> Am 12.07.2012 14:30, schrieb Laszlo Nagy: > This is not a contradiction. Although the rename operation is atomic, > the whole "change status" process is not. It is because there are two > operations: #1 delete old status file and #2. rename the new status > file. And because there are two operations, there is still a race > condition. I see no contradiction here. Sorry, but you are wrong. It's just one operation that boils down to "point name to a different inode". After the rename op the file name either points to a different inode or still to the old name in case of an error. The OS guarantees that all processes either see the first or second state (in other words: atomic). POSIX has no operation that actually deletes a file. It just has an unlink() syscall that removes an associated name from an inode. As soon as an inode has no names and is not references by a file descriptor, the file content and inode is removed by the operating system. rename() is more like a link() followed by an unlink() wrapped in a system wide global lock. > It is not entirely true. We are talking about two processes. One is > reading a file, another one is writting it. They can run at the same > time, so flushing disk cache forcedly won't help. You need to flush the data to disk as well as the metadata of the file and its directory in order to survive a system crash. The close() syscall already makes sure that all data is flushed into the IO layer of the operating system. With POSIX semantics the reading process will either see the full content before the rename op or the full content after the rename op. The writing process can replace the name (rename op) while the reading process reads the status file because its file descriptor still points to the old status file. Christian From hansmu at xs4all.nl Thu Jul 12 09:19:48 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 12 Jul 2012 15:19:48 +0200 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> Message-ID: <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> On 12/07/12 14:30:41, Laszlo Nagy wrote: >> You are contradicting yourself. Either the OS is providing a fully >> atomic rename or it doesn't. All POSIX compatible OS provide an atomic >> rename functionality that renames the file atomically or fails without >> loosing the target side. On POSIX OS it doesn't matter if the target >> exists. > This is not a contradiction. Although the rename operation is atomic, > the whole "change status" process is not. It is because there are two > operations: #1 delete old status file and #2. rename the new status > file. And because there are two operations, there is still a race > condition. I see no contradiction here. On Posix systems, you can avoid the race condition. The trick is to skip step #1. The rename will implicitly delete the old file, and it will still be atomic. The whole process now consists of a single stop, so the whole process is now atomic. >> You don't need locks or any other fancy stuff. You just need to make >> sure that you flush the data and metadata correctly to the disk and >> force a re-write of the directory inode, too. It's a standard pattern on >> POSIX platforms and well documented in e.g. the maildir RFC. > It is not entirely true. We are talking about two processes. One is > reading a file, another one is writting it. They can run at the same > time, so flushing disk cache forcedly won't help. On Posix systems, it will work, and be atomic, even if one process is reading the old status file while another process is writing the new one. The old file will be atomically removed from the directory by the rename operation; it will continue to exists on the hard drive, so that the reading process can continue reading it. The old file will be deleted when the reader closes it. Or, if the system crashed before the old file is closed, it will deleted when the system is restarted. On Windows, things are very different. Hope this helps, -- HansM From andrea.crotti.0 at gmail.com Thu Jul 12 09:20:18 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 12 Jul 2012 14:20:18 +0100 Subject: adding a simulation mode In-Reply-To: References: <87liiyr48f.fsf@handshake.de> Message-ID: One thing that I don't quite understand is why some calls even if I catch the exception still makes the whole program quit. For example this try: copytree('sjkdf', 'dsflkj') Popen(['notfouhd'], shell=True) except Exception as e: print("here") behaves differently from: try: Popen(['notfouhd'], shell=True) copytree('sjkdf', 'dsflkj') except Exception as e: print("here") because if copytree fails it quits anyway. I also looked at the code but can't quite get why.. any idea? From d at davea.name Thu Jul 12 09:52:35 2012 From: d at davea.name (Dave Angel) Date: Thu, 12 Jul 2012 09:52:35 -0400 Subject: introduction and first question about multithreading In-Reply-To: <4FFD308A.7030904@gmail.com> References: <4FFD308A.7030904@gmail.com> Message-ID: <4FFED6A3.5050206@davea.name> On 07/11/2012 03:51 AM, Vojt?ch Pol??ek wrote: > Greetings, > My name is Vojta and I am blind student. I am slowly learning Python for > about 4 years and I like it alot, mostly its ability to run on various > platforms. > My primary system is Ubuntu 12.04, but I have Windows XP at hand. I am > using python 2.7. I have learned basics from the book A byte of Python > (for version 2.X) and something from Dive into Python. But most things I > learned by trial and error and thanks to solutions on stackoverflow.com. > I Don't know much about good programming concepts in Python, just in > general, so feel free to educate me about them. > > I haven't created anything great yet, but I am working on a game for > blind people. It is a simple game of reaction, but I have to start with > something, my next plan is Sudoku game. > I am using Pygame for handling of sounds and keyboard events, speech > dispatcher under Linux and pyttsx under Windows to provide speech > output, numpy for sound cutting and my two little and simple modules for > providing menu system and unified interface for both speech engines. > During the development, I discovered, that I have to use multithreading > to be able to check for key presses and manage the game at the same > time. I tried threading module but this wasn't enough for me, because > function running in the separate thread needed to access variables in > the main thread at least I couldn't find the way how to do that. So I > switched to multiprocessing and started using pipes for communication > between processes. All is working well, except for one thing. > My menu module uses a loop to check for keyboard events through pygame. > I don't import pygame into my module directly, but rather pass it > through my main module like this: > menu.pygame = pygame > All was working well until I started using multiprocessing. I may have a > probable cause but I need your help. > In my main module I am running a similar loop for checking keyboard > input in separate process. When a player loses, the loop finishes and I > join the process. Then the menu module kicks in and should launch its > own loop checking for pygame keyboard events, but right after doing it > it prints: > [xcb] Unknown sequence number while processing queue > [xcb] Most likely this is a multi-threaded client and XInitThreads has > not been called > [xcb] Aborting, sorry about that. > python: ../../src/xcb_io.c:273: poll_for_event: Assertion > `!xcb_xlib_threads_sequence_lost' failed > received SigAbrt - core dumped > Are atachments allowed here? I can send you my whole code. > Please help me, if you can. > Thank you very much, > Vojta Welcome to python-list. I'm glad you're enjoying Python. I haven't used pygame, but I know that (like almost all GUI toolkits) it uses an event loop for interacting with at least the keyboard. You should be able to add other code to that event loop in some manner, without going to the trouble of either multiple threads or multiple processes. But I'll ignore that and talk about multithreading. You say >function running in the separate thread needed to access variables in >the main thread at least I couldn't find the way how to do that but there is nothing special about threads. If you can figure out what namespace a variable is in, you can access it. In fact, one large reason people switch from multithread to multiple processes is to avoid the accidental reuse of variables. As for posting large code, you can upload it to a site like pastebin, and put a link in your message here. Don't expect too much, however, as most of us are averse at looking at a large fragment of somebody else's code. -- DaveA From andrea.crotti.0 at gmail.com Thu Jul 12 09:55:35 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 12 Jul 2012 14:55:35 +0100 Subject: adding a simulation mode In-Reply-To: References: <87liiyr48f.fsf@handshake.de> Message-ID: One way instead that might actually work is this def default_mock_action(func_name): def _default_mock_action(*args, **kwargs): print("running {} with args {} and {}".format(func_name, args, kwargs)) return _default_mock_action def mock_fs_actions(to_run): """Take a function to run, and run it in an environment which mocks all the possibly dangerous operations """ side_effect = [ 'copytree', 'copy', ] acts = dict((s, default_mock_action(s)) for s in side_effect) with patch('pytest.runner.commands.ShellCommand.run', default_mock_action('run')): with patch.multiple('shutil', **acts): to_run() So I can just pass the main function inside the mock like mock_fs_actions(main) and it seems to do the job, but I have to list manually all the things to mock and I'm not sure is the best idea anyway.. From gordon at panix.com Thu Jul 12 09:56:56 2012 From: gordon at panix.com (John Gordon) Date: Thu, 12 Jul 2012 13:56:56 +0000 (UTC) Subject: adding a simulation mode References: <87liiyr48f.fsf@handshake.de> Message-ID: In andrea crotti writes: > try: > copytree('sjkdf', 'dsflkj') > Popen(['notfouhd'], shell=True) > except Exception as e: > print("here") > behaves differently from: > try: > Popen(['notfouhd'], shell=True) > copytree('sjkdf', 'dsflkj') > except Exception as e: > print("here") > because if copytree fails it quits anyway. > I also looked at the code but can't quite get why.. any idea? copytree() could contain a call to sys.exit(), although that seems like a rude thing to do. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From chris at gonnerman.org Thu Jul 12 10:10:21 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Thu, 12 Jul 2012 09:10:21 -0500 Subject: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator In-Reply-To: <20120712115631.1acf9b35c4482353cca01ee8@gmail.com> References: <4FFD8852.8020705@newcenturycomputers.net> <4FFE1D50.10604@fossworkflowguides.com> <20120712073548.7057f9b04be372f9d4b04d0f@gmail.com> <20120712115631.1acf9b35c4482353cca01ee8@gmail.com> Message-ID: <4FFEDACD.4060206@gonnerman.org> Wow, I posted this on Github weeks ago, and got no feedback; put it on PyPI at the same time, with the same results; but one day on the Python list and I have lots of excellent feedback. I've just posted PollyReports 1.5.1, with no operational changes. The package includes a corrected testpolly.py file as well as corrected sample*.py files with "right = 1" changed to "align = 'right'". The license information has been revised to include the text "BSD 2-Clause License" so that no one has to think about whether or not it's actually a BSD license. If you downloaded the previous version, you don't really need the new one unless you're going through the tutorial. Thanks! -- Chris. From andrea.crotti.0 at gmail.com Thu Jul 12 10:17:03 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 12 Jul 2012 15:17:03 +0100 Subject: adding a simulation mode In-Reply-To: References: <87liiyr48f.fsf@handshake.de> Message-ID: Well that's what I thought, but I can't find any explicit exit anywhere in shutil, so what's going on there? From gordon at panix.com Thu Jul 12 11:10:32 2012 From: gordon at panix.com (John Gordon) Date: Thu, 12 Jul 2012 15:10:32 +0000 (UTC) Subject: adding a simulation mode References: <87liiyr48f.fsf@handshake.de> Message-ID: In andrea crotti writes: > Well that's what I thought, but I can't find any explicit exit > anywhere in shutil, so what's going on there? Try catching SystemExit specifically (it doesn't inherit from Exception, so "except Exception" won't catch it.) -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From andrea.crotti.0 at gmail.com Thu Jul 12 11:37:42 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 12 Jul 2012 16:37:42 +0100 Subject: adding a simulation mode In-Reply-To: References: <87liiyr48f.fsf@handshake.de> Message-ID: 2012/7/12 John Gordon : > In andrea crotti writes: > >> Well that's what I thought, but I can't find any explicit exit >> anywhere in shutil, so what's going on there? > > Try catching SystemExit specifically (it doesn't inherit from Exception, > so "except Exception" won't catch it.) > > -- Ah yes that actually works, but I think is quite dodgy, why was it done like this? In shutil there is still no mention of SystemExit, and trying to raise the single exceptions by and doens't still make it exit, so I would still like to know how it is possible just for curiosity.. From brochure at getpython.info Thu Jul 12 11:48:06 2012 From: brochure at getpython.info (PSF Python Brochure Project Team) Date: Thu, 12 Jul 2012 17:48:06 +0200 Subject: PSF Python Brochure is ready to print: accepting ad orders now! Message-ID: <4FFEF1B6.8090800@getpython.info> The PSF Python Brochure Project has finished the content and layout phase. The first full format pre-production issues were shown at the PSF booth during the EuroPython Conference 2012 in Florence, Italy, and caused a lot of excitement - to print the brochure we now need supporting sponsors. Please visit our website for more information about the brochure project: http://brochure.getpython.info/ This announcement is also available for online reading: http://brochure.getpython.info/news/newsletter-4-ready-to-print-and-order-now The Python brochure is ready to print ===================================== Now is the time to place your ad in the brochure! You can benefit from the PSF Python Brochure by buying ads or a reference entry in the brochure, to e.g. show case your company for recruiting purposes or consulting services. With over 10,000 printed copies distributed world-wide this is an excellent way to reach out to new developers and customers. >>> Don't miss the opportunity to place your ad in the very first >>> Python image brochure. Ads === The brochure will have an addendum with 2 double pages for ads. You can buy a half page or a full page ad. You will receive a box of around 120 free copies of the printed brochure after production. We have already sold 4 ads. There is still room for up to 4 half page ads. Reference Entry --------------- You can also buy a reference entry with a fixed layout on the last two pages of the Python Brochure including your full color logo and contact details. There is room for more than 30 entries. Pricing ------- * A half page ad costs EUR 2,650.00 (+ 19% German VAT, if applicable). * A full page ad costs EUR 5,300.00 (+ 19% German VAT, if applicable). * A reference entry can be purchased for EUR 500.00 (+ 19% German VAT, if applicable). Ad Placement ------------ We follow "first pay, first serve" until all ad slots are booked. Subsequent orders will be placed on a waiting list for the next edition. Individual ad placement is not possible. Deadline for Data & Approval ============================ The deadline for data delivery will be 2012 August 31st. You will receive a professional software proof PDF of your page prior to printing with 2 days left for approval and final corrections. For full technical details regarding data submission, formats and specifications for the ad content, please consult our Ad Guidelines. Ordering Procedure ================== For the order you will be redirected to the secure SSL encrypted site hosted by our production partner evenios publishing. The terms & conditions and data privacy statement for the order are published on encrypted.evenios.com . Please note that the payment is not processed by the PSF! You will receive an invoice issued by evenios publishing, the company producing and distributing the brochure. Order a half page ad -------------------- https://encrypted.evenios.com/en/mediadata/cart/order-forms/ad-sponsorship-order-form-1-2-page Order a full page ad -------------------- https://encrypted.evenios.com/en/mediadata/cart/order-forms/ad-sponsorship-order-form-1-1-page Order a reference entry sponsorship ----------------------------------- https://encrypted.evenios.com/en/mediadata/cart/order-forms/reference-sponsorship-entry-order-form Thanks, -- Marc-Andre Lemburg PSF Python Brochure Team ___________________________________________________________________________ >>> Website: http://brochure.getpython.info/ >>> Twitter: https://twitter.com/pythonbrochure >>> EMail: brochure at getpython.info From rridge at csclub.uwaterloo.ca Thu Jul 12 11:48:43 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 12 Jul 2012 11:48:43 -0400 Subject: How to safely maintain a status file References: <4FFEC371.5040703@shopzeus.com> Message-ID: Laszlo Nagy: > This is not a contradiction. Although the rename operation is atomic, > the whole "change status" process is not. It is because there are two > operations: #1 delete old status file and #2. rename the new status > file. And because there are two operations, there is still a race > condition. I see no contradiction here. Christian Heimes wrote: >Sorry, but you are wrong. It's just one operation that boils down to >"point name to a different inode". For some reason you're assuming POSIX semantics, an assumption that Laszlo Nagy did not make. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ian.g.kelly at gmail.com Thu Jul 12 12:53:25 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 12 Jul 2012 10:53:25 -0600 Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> References: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: On Wed, Jul 11, 2012 at 9:59 PM, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 08:41:57 +0200, Daniel Fetchinson wrote: > >> funcs = [ lambda x: x**i for i in range( 5 ) ] > > Here's another solution: > > from functools import partial > funcs = [partial(lambda i, x: x**i, i) for i in range(5)] > > > Notice that the arguments i and x are defined in the opposite order. > That's because partial only applies positional arguments from the left. > If there was a "right partial" that applies from the right, we could use > the built-in instead: > > funcs = [rpartial(pow, i) for i in range(5)] You know, partial does handle keyword arguments correctly: funcs = [partial(lambda x, i: x ** i, i=i) for i in range(5)] This might be bad practice though if there are other arguments to the right of the keywords that the eventual caller might want to specify, as those arguments would then effectively be keyword-only. The error message in that case is not particularly illuminating, either: >>> def f(a, b, c): ... return (a, b, c) ... >>> g = partial(f, b=42) >>> g(3, 14) Traceback (most recent call last): File "", line 1, in TypeError: f() got multiple values for keyword argument 'b' It would be a bit clearer if it instead noted that 'c' were keyword-only in the 'g' argspec. Cheers, Ian From sg552 at hotmail.co.uk Thu Jul 12 13:23:10 2012 From: sg552 at hotmail.co.uk (Rotwang) Date: Thu, 12 Jul 2012 18:23:10 +0100 Subject: lambda in list comprehension acting funny In-Reply-To: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> References: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: On 12/07/2012 04:59, Steven D'Aprano wrote: > On Wed, 11 Jul 2012 08:41:57 +0200, Daniel Fetchinson wrote: > >> funcs = [ lambda x: x**i for i in range( 5 ) ] > > Here's another solution: > > from functools import partial > funcs = [partial(lambda i, x: x**i, i) for i in range(5)] > > > Notice that the arguments i and x are defined in the opposite order. > That's because partial only applies positional arguments from the left. > If there was a "right partial" that applies from the right, we could use > the built-in instead: > > funcs = [rpartial(pow, i) for i in range(5)] I don't think anyone has suggested this yet: funcs = [(lambda i: lambda x: x**i)(i) for i in range(5)] It's a bit more opaque than other solutions, but it fits in one line and avoids defining functions with an implicit second argument, if that's desirable for some reason. -- I have made a thing that superficially resembles music: http://soundcloud.com/eroneity/we-berated-our-own-crapiness From gandalf at shopzeus.com Thu Jul 12 13:38:37 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 12 Jul 2012 19:38:37 +0200 Subject: How to safely maintain a status file In-Reply-To: <4FFECB96.9040601@cheimes.de> References: <4FF9F454.40207@shopzeus.com> <4FFEC371.5040703@shopzeus.com> <4FFECB96.9040601@cheimes.de> Message-ID: <4FFF0B9D.9000506@shopzeus.com> > Sorry, but you are wrong. It's just one operation that boils down to > "point name to a different inode". After the rename op the file name > either points to a different inode or still to the old name in case of > an error. The OS guarantees that all processes either see the first or > second state (in other words: atomic). > > POSIX has no operation that actually deletes a file. It just has an > unlink() syscall that removes an associated name from an inode. As soon > as an inode has no names and is not references by a file descriptor, the > file content and inode is removed by the operating system. rename() is > more like a link() followed by an unlink() wrapped in a system wide > global lock. Then please help me understand this. "Good" case: process #1: unlink(old status file) process #1: rename(new status file) process#2: open(new status file) process#2: read(new status file) "Bad" case: process #1: unlink(old status file) process#2: open(???) -- there is no file on disk here, this system call returns with an error! process #1: rename(new status file) If it would be possible to rename + unlink in one step, then it would be okay. Can you please explain what am I missing? From gandalf at shopzeus.com Thu Jul 12 13:43:19 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 12 Jul 2012 19:43:19 +0200 Subject: How to safely maintain a status file In-Reply-To: <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> Message-ID: <4FFF0CB7.3030007@shopzeus.com> >> This is not a contradiction. Although the rename operation is atomic, >> the whole "change status" process is not. It is because there are two >> operations: #1 delete old status file and #2. rename the new status >> file. And because there are two operations, there is still a race >> condition. I see no contradiction here. > On Posix systems, you can avoid the race condition. The trick is to > skip step #1. The rename will implicitly delete the old file, and > it will still be atomic. The whole process now consists of a single > stop, so the whole process is now atomic. Well, I didn't know that this is going to work. At least it does not work on Windows 7 (which should be POSIX compatible?) >>> f = open("test.txt","wb+") >>> f.close() >>> f2 = open("test2.txt","wb+") >>> f2.close() >>> import os >>> os.rename("test2.txt","test.txt") Traceback (most recent call last): File "", line 1, in WindowsError: [Error 183] File already exists >>> I have also tried this on FreeBSD and it worked. Now, let's go back to the original question: >>>This works well on Linux but Windows raises an error when status_file already exists. It SEEMS that the op wanted a solution for Windows.... From gandalf at shopzeus.com Thu Jul 12 13:46:17 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 12 Jul 2012 19:46:17 +0200 Subject: How to safely maintain a status file In-Reply-To: References: Message-ID: <4FFF0D69.2090901@shopzeus.com> >> Windows doesn't suppport atomic renames if the right side exists. I >> suggest that you implement two code paths: >> >> if os.name == "posix": >> rename = os.rename >> else: >> def rename(a, b): >> try: >> os.rename(a, b) >> except OSError, e: >> if e.errno != 183: >> raise >> os.unlink(b) >> os.rename(a, b) > > Problem is if the process is stopped between unlink and rename there > would no status file. Yes, and actually it does not need to be an abnormal termination. It is enough if the OS scheduler puts this process on hold for some time... But using a lock file, the problem can be solved. However in that case, reading a status file can be a blocking operation. From johnnydemag at sbcglobal.net Thu Jul 12 13:48:33 2012 From: johnnydemag at sbcglobal.net (John Magness) Date: Thu, 12 Jul 2012 10:48:33 -0700 (PDT) Subject: syntax error message Message-ID: <1342115313.72395.YahooMailRC@web83602.mail.sp1.yahoo.com> Using Python 3.2.3 In shell I made a simple program; dog=2,cat=3,cow=dog+cat Entered cow and received 5 as answer Saved-as Trial-1.py in a user folder Went to folder and select "edit with shell" for that file Trial-1.py displayed, clicked save, run and then run module to activate program got message in box "syntax error" and after I clicked OK the #2 in the heading Python 3.2.3 was high-lighted ?in red and the "or" and "for" words were changed to red letters and program seems to be text only. In other words, I am not able to re-use or change the program Help needed. John, a beginner -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Jul 12 14:17:33 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 12 Jul 2012 19:17:33 +0100 Subject: syntax error message In-Reply-To: <1342115313.72395.YahooMailRC@web83602.mail.sp1.yahoo.com> References: <1342115313.72395.YahooMailRC@web83602.mail.sp1.yahoo.com> Message-ID: <4FFF14BD.3020204@mrabarnett.plus.com> On 12/07/2012 18:48, John Magness wrote: > Using Python 3.2.3 > In shell I made a simple program; dog=2,cat=3,cow=dog+cat > Entered cow and received 5 as answer > Saved-as Trial-1.py in a user folder > Went to folder and select "edit with shell" for that file > Trial-1.py displayed, clicked save, run and then run module to activate > program > got message in box "syntax error" and after I clicked OK the #2 in the > heading Python 3.2.3 was high-lighted > in red and the "or" and "for" words were changed to red letters and > program seems to be text only. > In other words, I am not able to re-use or change the program > Help needed. > John, a beginner > You were entering it in interactive mode. When you saved it as "Trial-1.py" what you actually saved was all of the prompts and the output, which isn't a valid program (it has lots of other bits mixed in with it). If you click File->New Window you will get an empty window into which you can type your program. You can just open the file and then edit it to remove the unwanted bits. From dieter at handshake.de Thu Jul 12 14:38:43 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 12 Jul 2012 20:38:43 +0200 Subject: adding a simulation mode In-Reply-To: References: <87liiyr48f.fsf@handshake.de> Message-ID: <20479.6579.924835.535410@localhost.localdomain> andrea crotti wrote at 2012-7-12 14:20 +0100: >One thing that I don't quite understand is why some calls even if I >catch the exception still makes the whole program quit. >For example this > > try: > copytree('sjkdf', 'dsflkj') > Popen(['notfouhd'], shell=True) > except Exception as e: > print("here") > > >behaves differently from: > > try: > Popen(['notfouhd'], shell=True) > copytree('sjkdf', 'dsflkj') > except Exception as e: > print("here") > >because if copytree fails it quits anyway. >I also looked at the code but can't quite get why.. any idea? There are ways to quit a program immediately without giving exception handlers a chance to intervene -- though Python does not make this easy. Your code above should not do this. If it does, there is likely a bug. You told us, that the two alternatives above behaved differently -- I expect 'behaved differently with respect to the printing of "here"'. If you tell us, which alternative printed "here" and which did not, we would be able to deduce which of the "Popen" or "copytree" caused the immediate exit. "Popen" might contain a call to "os._exit" (one of the ways to immediately quit) -- though it should only call it in the forked child not in the calling process. "coyptree" might under exceptional circumstances (extremely deeply nested structures -- surely not for non-existent source and target) cause a stack overflow (which, too, can lead to immediate death). In addition, "Popen" and maybe even "copytree" may call platform dependent functions. Thus, platform information could be relevant. Under "*nix", you should be able to get some information from the exit code of a suddenly quiting process. It tells whether the process died from a fatal signal (a stack overflow would result in the fatal SIGSEGV) or whether it existed willingly with an exit code. -- Dieter From lists at cheimes.de Thu Jul 12 14:39:04 2012 From: lists at cheimes.de (Christian Heimes) Date: Thu, 12 Jul 2012 20:39:04 +0200 Subject: How to safely maintain a status file In-Reply-To: <4FFF0CB7.3030007@shopzeus.com> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> Message-ID: Am 12.07.2012 19:43, schrieb Laszlo Nagy: > Well, I didn't know that this is going to work. At least it does not > work on Windows 7 (which should be POSIX compatible?) Nope, Windows's file system layer is not POSIX compatible. For example you can't remove or replace a file while it is opened by a process. Lot's of small things work slightly differently on Windows or not at all. Christian From anthra.norell at bluewin.ch Thu Jul 12 14:53:54 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Thu, 12 Jul 2012 20:53:54 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> Message-ID: <1342119234.2313.42.camel@hatchbox-one> On Tue, 2012-07-10 at 15:11 -0700, Rick Johnson wrote: > I've tried to condense your code using the very limited info you have > provided. I have removed unnecessarily configuring of widgets and > exaggerated the widget borders to make debugging easier. Read below > for Q&A. > > ## START CONDENSED CODE ## > records = range(4) > > CNF_SUBFRAME = { > 'bd':5, # rowFrame boder width. > 'relief':RIDGE, > } > > CNF_LABEL = { > 'anchor':W, > 'width':10, > 'bg':'gray', > } > > class FooFrame(tk.Frame): > def __init__(self, master, **kw): > tk.Frame.__init__(self, master, **kw) > self.build_records() > > def build_records(self): > # Should this method be called by __init__??? > # Not sure if "records" is passed-in or global??? > for n in range(len(records)): > record = records[n] > rowFrame = tk.Frame(self, name='-%d-'%n, **CNF_SUBFRAME) > rowFrame.bind ('', self.evtEnter) > rowFrame.bind ('', self.evtLeave) > rowFrame.bind ('', > self.evtButtonOneRelease) > rowFrame.bind ('', > self.evtButtonThreeRelease) > rowFrame.grid (row=n+2, column=1, padx=5, pady=5) > for i in range(4): > lbtext = 'Label_'+str(i) > label = tk.Label(rowFrame, text=lbtext, **CNF_LABEL) > label.grid (row=0, column=i, sticky=NW) > > def evtEnter(self, event): > w = event.widget > print 'evtEnter', w.winfo_class() > w.config(bg='magenta') > > def evtLeave(self, event): > w = event.widget > print 'evtLeave', w.winfo_class() > w.config(bg='SystemButtonFace') > > def evtButtonOneRelease(self, event): > w = event.widget > print 'evtButtonOneRelease', w.winfo_class() > w.config(bg='Green') > > def evtButtonThreeRelease(self, event): > w = event.widget > print 'evtButtonThreeRelease', w.winfo_class() > w.config(bg='Blue') > > if __name__ == '__main__': > root = tk.Tk() > frame = FooFrame(root, width=100, height=100, bg='red', bd=1) > frame.pack(padx=5, pady=5) > root.mainloop() > ## END CONDENSED CODE ## > > > In the code sample provided, you will see that the label widgets > stacked on each row will block "click" events on the containing > "rowFrames" below them. You can get a click event (on the sub frames) > to work by clicking the exaggerated border on the frames. All the > events work properly for me, although this GUI interface seems > unintuitive even with proper borders and colors. > > Fredric, I can't help but feel that you are not attacking the problem > correctly. Please explain the following questions in detail so that i > may be able to provide help: > It works for me too. I spent another day running the offending class in a simplified environment and it worked flawlessly. In what way the environment makes the difference is anything but obvious. But it has got to be the environment. > Q1. You have subclassed a Tkinter.Frame and you are building "rows" of > sub-frames into this toplevel frame; with each row holding > horizontally stacked label widgets. Okay, I can see a need to wrap up > a "RowFrame" object, but i don't see a need to create a > "RowFrameFactory". Can you explain this design decision? > I sent this same response yesterday with a screen shot attached. The message didn't pass. It must have been rejected by a spam filter. So I try again without the screen shot. (Too bad. A picture is worth a thousand words). The "hit list" is a table of investment titles (stock, funds, bonds) that displays upon entry of a search pattern into a respective template. The table displays the matching records: name, symbol, ISIN, CUSIP, Sec. Any line can be click-selected. So they are to look like buttons. Representing the mentioned names and id codes in Label widgets was the simplest way I could come up with to align them in columns, admittedly without the benefit of much experience. But it does look good. the layout is fine. I find the Tkinter system quite challenging. Doing a layout isn't so much a matter of dimensioning and placing things as a struggle to trick a number of automatic dimensioning and placing mechanisms into obliging--mechanisms that are rather numerous and hard to remember. > Q2. It seems odd to me that you want to engage the "rowFrame" widgets > via events but NOT the Label widgets. Can you explain this design > decision? > Again, the labels serve to align the fields into columns. As to the bindings, I just now found out, that and can be bound to the line frame, but the mouse buttons don't act on the frame with the labels covering it wall to wall. Entry will lighten up the background of the line. Leave restores the normal color. will select the line, darkening the text. The coloring has to be done separately on each label across the line, as the labels cover the frame. That isn't a problem. I'm sorry I can't post an intelligible piece that does NOT work. I obviously can't post the whole thing. It is way too convoluted. But I will post an intelligible condensate the moment I manage to distill one without distilling away the flaw in question. At any rate I will post the solution when I find it, which I will however long that may take. Frederic From rantingrickjohnson at gmail.com Thu Jul 12 21:20:13 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Thu, 12 Jul 2012 18:20:13 -0700 (PDT) Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> Message-ID: On Jul 12, 2:39?pm, Christian Heimes wrote: > Windows's file system layer is not POSIX compatible. For example > you can't remove or replace a file while it is opened by a process. Sounds like a reasonable fail-safe to me. Not much unlike a car ignition that will not allow starting the engine if the transmission is in any *other* gear besides "park" or "neutral", OR a governor (be it mechanical or electrical) that will not allow the engine RPMs to exceed a maximum safe limit, OR even, ABS systems which "pulse" the brakes to prevent overzealous operators from loosing road-to-tire traction when decelerating the vehicle. You could say: "Hey, if someone is dumb enough to shoot themselves in the foot then let them"... however, sometimes fail-safes not only save the dummy from a life of limps, they also prevent catastrophic "collateral damage" to rest of us. From steve+comp.lang.python at pearwood.info Thu Jul 12 21:52:12 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 01:52:12 GMT Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> <4FFEC371.5040703@shopzeus.com> Message-ID: <4fff7f4c$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 15:05:26 +0200, Christian Heimes wrote: > You need to flush the data to disk as well as the metadata of the file > and its directory in order to survive a system crash. The close() > syscall already makes sure that all data is flushed into the IO layer of > the operating system. And some storage devices (e.g. hard drives, USB sticks) don't actually write data permanently even when you sync the device. They just write to a temporary cache, then report that they are done (liar liar pants on fire). Only when the cache is full, or at some random time at the device's choosing, do they actually write data to the physical media. The result of this is that even when the device tells you that the data is synched, it may not be. -- Steven From vincent.vandevyvre at swing.be Thu Jul 12 21:52:51 2012 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Fri, 13 Jul 2012 03:52:51 +0200 Subject: Python and Qt4 Designer In-Reply-To: References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: <4FFF7F73.1030902@swing.be> On 12/07/12 08:42, Jean Dubois wrote: > On 12 jul, 02:59, Vincent Vande Vyvre > wrote: >> On 11/07/12 17:37, Jean Dubois wrote: >> >> >> >> >> >> >> >>> I'm trying to combine python-code made with QT4 designer with plain >>> python statements like >>> file = open("test","w") >>> Can anyone tell me what I have to add to the following code just to >>> open a file when clicking on the load-button and closing it by >>> clicking on the save button. >>> #!/usr/bin/env python >>> # -*- coding: utf-8 -*- >>> # Form implementation generated from reading ui file 'test.ui' >>> # >>> # Created: Wed Jul 11 17:21:35 2012 >>> # by: PyQt4 UI code generator 4.8.3 >>> # >>> # WARNING! All changes made in this file will be lost! >>> from PyQt4 import QtCore, QtGui >>> try: >>> _fromUtf8 = QtCore.QString.fromUtf8 >>> except AttributeError: >>> _fromUtf8 = lambda s: s >>> class Ui_Form(object): >>> def setupUi(self, Form): >>> Form.setObjectName(_fromUtf8("Form")) >>> Form.resize(400, 300) >>> self.widget = QtGui.QWidget(Form) >>> self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) >>> self.widget.setObjectName(_fromUtf8("widget")) >>> self.horizontalLayout = QtGui.QHBoxLayout(self.widget) >>> self.horizontalLayout.setMargin(0) >>> self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) >>> self.pushButton_2 = QtGui.QPushButton(self.widget) >>> self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) >>> self.horizontalLayout.addWidget(self.pushButton_2) >>> self.pushButton = QtGui.QPushButton(self.widget) >>> self.pushButton.setObjectName(_fromUtf8("pushButton")) >>> self.horizontalLayout.addWidget(self.pushButton) >>> self.retranslateUi(Form) >>> QtCore.QMetaObject.connectSlotsByName(Form) >>> def retranslateUi(self, Form): >>> Form.setWindowTitle(QtGui.QApplication.translate("Form", >>> "Form", None, QtGui.QApplication.UnicodeUTF8)) >>> self.pushButton_2.setText(QtGui.QApplication.translate("Form", >>> "Save file", None, QtGui.QApplication.UnicodeUTF8)) >>> self.pushButton.setText(QtGui.QApplication.translate("Form", >>> "Load file", None, QtGui.QApplication.UnicodeUTF8)) >>> if __name__ == "__main__": >>> import sys >>> app = QtGui.QApplication(sys.argv) >>> Form = QtGui.QWidget() >>> ui = Ui_Form() >>> ui.setupUi(Form) >>> Form.show() >>> sys.exit(app.exec_()) >>> thanks in advance >>> jean >> Connect the signal clicked of your's buttons to your's functions. >> >> self.pushButton.clicked.connect(self.my_func) >> >> Here's all the truth: >> >> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_... >> >> -- >> Vincent V.V. >> Oqapy . Qarte+7 >> . PaQager > thanks for the reference, could you just supply a small example for > the code above to get me started? > > thanks in advance > jean Just add the connection at the end of the Ui_Form class and, of course, your function. You can find numbers of examples in your PyQt4 install folder. On my machine is located at /usr/share/doc/python-qt4-doc/examples And, for more inspiration, have a look at this site: http://diotavelli.net/PyQtWiki/ -- Vincent V.V. Oqapy . Qarte . PaQager From steve+comp.lang.python at pearwood.info Thu Jul 12 22:09:04 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 02:09:04 GMT Subject: adding a simulation mode References: <87liiyr48f.fsf@handshake.de> Message-ID: <4fff8340$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 15:17:03 +0100, andrea crotti wrote: > Well that's what I thought, but I can't find any explicit exit anywhere > in shutil, so what's going on there? Hard to say, since you don't give any context to your question. When replying to posts, please leave enough quoted to establish context. Neither email nor usenet are guaranteed delivery services, and they certainly don't guarantee to deliver messages in order. Assume that your readers may not have seen the message you are replying to, and you will probably get more and better responses. -- Steven From rosuav at gmail.com Thu Jul 12 22:12:01 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 13 Jul 2012 12:12:01 +1000 Subject: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> Message-ID: On Fri, Jul 13, 2012 at 11:20 AM, Rick Johnson wrote: > On Jul 12, 2:39 pm, Christian Heimes wrote: >> Windows's file system layer is not POSIX compatible. For example >> you can't remove or replace a file while it is opened by a process. > > Sounds like a reasonable fail-safe to me. POSIX says that files and file names are independent. I can open a file based on its name, delete the file based on its name, and still have the open file there. When it's closed, it'll be wiped from the disk. ChrisA From steve+comp.lang.python at pearwood.info Thu Jul 12 22:16:53 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 02:16:53 GMT Subject: adding a simulation mode References: <87liiyr48f.fsf@handshake.de> Message-ID: <4fff8514$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 16:37:42 +0100, andrea crotti wrote: > 2012/7/12 John Gordon : >> In andrea crotti >> writes: >> >>> Well that's what I thought, but I can't find any explicit exit >>> anywhere in shutil, so what's going on there? >> >> Try catching SystemExit specifically (it doesn't inherit from >> Exception, so "except Exception" won't catch it.) >> > > Ah yes that actually works, but I think is quite dodgy, why was it done > like this? Built-in exceptions SystemExit, KeyboardInterrupt and GeneratorExit deliberately do not inherit from Exception since they are not meant to be caught by "catch-all" try...except Exception clauses. You can see the exception hierarchy here: http://docs.python.org/library/exceptions.html#exception-hierarchy Please do NOT catch BaseException, since that is the wrong thing to do. If you must catch SystemExit, KeyboardInterrupt, etc. they you should do so as separate catch clauses: try: main() except SystemExit as e: print(e) # see if we can find out who is raising this except KeyboardInterrupt: print("Mwahahaha my pretty, you cannot cancel this!!!") print("...er, now what do I do?") except Exception: print("why am I catching exceptions I can't recover from?") -- Steven From steve+comp.lang.python at pearwood.info Thu Jul 12 22:20:05 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 02:20:05 GMT Subject: lambda in list comprehension acting funny References: <4ffe4bbb$0$1781$c3e8da3$76491128@news.astraweb.com> Message-ID: <4fff85d5$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 18:23:10 +0100, Rotwang wrote: > I don't think anyone has suggested this yet: > > funcs = [(lambda i: lambda x: x**i)(i) for i in range(5)] Oooh, nice! A factory function solution. Excellent! -- Steven From steve+comp.lang.python at pearwood.info Thu Jul 12 22:37:42 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 02:37:42 GMT Subject: adding a simulation mode References: <87liiyr48f.fsf@handshake.de> Message-ID: <4fff89f6$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 14:20:18 +0100, andrea crotti wrote: > One thing that I don't quite understand is why some calls even if I > catch the exception still makes the whole program quit. Without seeing your whole program, we can't possibly answer this. But by consulting my crystal ball, I bet you have something like this: try: do_stuff() # run your program except Exception as e: # pointlessly catch exceptions I can't handle, which has the # bonus of making debugging MUCH MUCH harder print("here") # end of file, nothing further to do When do_stuff() fails, "here" gets printed, and then the program exits because there's nothing else to do. Catching exceptions doesn't magically cause the code to continue from the point of the error. It doesn't work like that. Execution skips from where the error occurred to the except clause. Once the except clause has run, anything following the except clause runs, and then the program ends as normal. If you haven't already done so, I recommend you go through the tutorial: http://docs.python.org/py3k/tutorial/index.html in particular the part about exception handling: http://docs.python.org/py3k/tutorial/errors.html > For example this > > try: > copytree('sjkdf', 'dsflkj') > Popen(['notfouhd'], shell=True) > except Exception as e: > print("here") What is "Popen" and where is it from? My first guess was os.popen, but that doesn't take a shell argument: py> os.popen(['ls', '-l'], shell=True) Traceback (most recent call last): File "", line 1, in TypeError: popen() got an unexpected keyword argument 'shell' > behaves differently from: > > try: > Popen(['notfouhd'], shell=True) > copytree('sjkdf', 'dsflkj') > except Exception as e: > print("here") > > because if copytree fails it quits anyway. Well of course it does. If copytree fails, the try block ends and execution skips straight to the except block, which runs, and then the program halts because there's nothing else to be done. That at least is my guess, based on the described symptoms. -- Steven From steve+comp.lang.python at pearwood.info Thu Jul 12 23:13:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 03:13:47 GMT Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> Message-ID: <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 12:12:01 +1000, Chris Angelico wrote: > On Fri, Jul 13, 2012 at 11:20 AM, Rick Johnson > wrote: >> On Jul 12, 2:39 pm, Christian Heimes wrote: >>> Windows's file system layer is not POSIX compatible. For example you >>> can't remove or replace a file while it is opened by a process. >> >> Sounds like a reasonable fail-safe to me. Rick has obviously never tried to open a file for reading when somebody else has it opened, also for reading, and discovered that despite Windows being allegedly a multi-user operating system, you can't actually have multiple users read the same files at the same time. (At least not unless the application takes steps to allow it.) Or tried to back-up files while some application has got them opened. Or open a file while an anti-virus scanner is oh-so-slooooowly scanning it. Opening files for exclusive read *by default* is a pointless and silly limitation. It's also unsafe: if a process opens a file for exclusive read, and then dies, *no other process* can close that file. At least on POSIX systems, not even root can override a mandatory exclusive lock (it would be pretty pointless if it could), so a rogue or buggy program could wreck havoc with mandatory exclusive file locks. That's why Linux, by default, treats exclusive file locks as advisory (cooperative), not mandatory. In general, file locking is harder than it sounds, with many traps for the unwary, and of course the semantics are dependent on both the operating system and the file system. https://en.wikipedia.org/wiki/File_locking > POSIX says that files and file names are independent. I can open a file > based on its name, delete the file based on its name, and still have the > open file there. When it's closed, it'll be wiped from the disk. One neat trick is to open a file, then delete it from disk while it is still open. So long as your process is still running, you can write to this ghost file, as normal, but no other process can (easily) see it. And when your process ends, the file contents is automatically deleted. This is remarkably similar to what Python does with namespaces and dicts: # create a fake "file system" ns = {'a': [], 'b': [], 'c': []} # open a file myfile = ns['a'] # write to it myfile.append('some data') # delete it from the "file system" del ns['a'] # but I can still read and write to it myfile.append('more data') print(myfile[0]) # but anyone else will get an error if they try another_file = ns['a'] -- Steven From gheskett at wdtv.com Thu Jul 12 23:49:02 2012 From: gheskett at wdtv.com (Gene Heskett) Date: Thu, 12 Jul 2012 23:49:02 -0400 Subject: How to safely maintain a status file In-Reply-To: <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <201207122349.02669.gheskett@wdtv.com> On Thursday 12 July 2012 23:21:16 Steven D'Aprano did opine: > On Fri, 13 Jul 2012 12:12:01 +1000, Chris Angelico wrote: > > On Fri, Jul 13, 2012 at 11:20 AM, Rick Johnson > > > > wrote: > >> On Jul 12, 2:39 pm, Christian Heimes wrote: > >>> Windows's file system layer is not POSIX compatible. For example you > >>> can't remove or replace a file while it is opened by a process. > >> > >> Sounds like a reasonable fail-safe to me. > > Rick has obviously never tried to open a file for reading when somebody > else has it opened, also for reading, and discovered that despite > Windows being allegedly a multi-user operating system, you can't > actually have multiple users read the same files at the same time. > Chuckle. That was one of the 'features' that os9 on the trs-80 color computer had back in the 80's, and it was clean and well done because of the locking model the random block file manager had in OS9 for 6809 cpu's, no relation to the Mac OS9 other than a similar name. That color computer has a separate, text only video card I could plug in and display on an 80 column amber screen monitor. When I wanted to impress the visiting frogs, I often did something I have never been able to do on any other operating system since, start assembling a long assembly language file on one of the screens on the color monitor, hit the clear key to advance to the amber screen and start a listing on it of the assemblers output listing file. Because the file locking was applied only to the sector (256 bytes on that machine) being written at the instant, the listing would fly by till it caught up with the assemblers output, running into the lock and then dutifully following along, one sector behind the assemblers output, until the assembly was finished. That was in 1986 folks, and in the year of our Lord 2012, 26 years later, I still cannot do that in linux. When I ask why not, the replies seem to think I'm from outer space. Its apparently a concept that is not even attempted to be understood by the linux code carvers. Something is drastically wrong with that picture IMO. > (At least not unless the application takes steps to allow it.) > > Or tried to back-up files while some application has got them opened. That in fact, ran me out of the amiga business in 1999, a 30Gb drive failed on my full blown 040 + 64 megs of dram A2000. When the warranty drive arrived is when I found that due to file locks on the startup files, all of them involved with the booting of that machine, my high priced Diavolo Pro backup tapes didn't contain a single one of those files. The linux box with Red Hat 5.0 on it that I had built in late 1998 to see what linux was all about found space under that desk yet that evening and I never looked back. > Or > open a file while an anti-virus scanner is oh-so-slooooowly scanning it. > > Opening files for exclusive read *by default* is a pointless and silly > limitation. It's also unsafe: if a process opens a file for exclusive > read, and then dies, *no other process* can close that file. > > At least on POSIX systems, not even root can override a mandatory > exclusive lock (it would be pretty pointless if it could), so a rogue or > buggy program could wreck havoc with mandatory exclusive file locks. > That's why Linux, by default, treats exclusive file locks as advisory > (cooperative), not mandatory. > > In general, file locking is harder than it sounds, with many traps for > the unwary, and of course the semantics are dependent on both the > operating system and the file system. > > https://en.wikipedia.org/wiki/File_locking > > > POSIX says that files and file names are independent. I can open a > > file based on its name, delete the file based on its name, and still > > have the open file there. When it's closed, it'll be wiped from the > > disk. > > One neat trick is to open a file, then delete it from disk while it is > still open. So long as your process is still running, you can write to > this ghost file, as normal, but no other process can (easily) see it. > And when your process ends, the file contents is automatically deleted. > > This is remarkably similar to what Python does with namespaces and > dicts: > > # create a fake "file system" > ns = {'a': [], 'b': [], 'c': []} > # open a file > myfile = ns['a'] > # write to it > myfile.append('some data') > # delete it from the "file system" > del ns['a'] > # but I can still read and write to it > myfile.append('more data') > print(myfile[0]) > # but anyone else will get an error if they try > another_file = ns['a'] Cheers, Gene -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author) My web page: is up! You just wait, I'll sin till I blow up! -- Dylan Thomas From lamialily at cleverpun.com Fri Jul 13 00:03:23 2012 From: lamialily at cleverpun.com (Temia Eszteri) Date: Thu, 12 Jul 2012 21:03:23 -0700 Subject: Writing a wrapper - any tips? Message-ID: I'm going to be looking into writing a wrapper for the Allegro 5 game development libraries, either with ctypes or Cython. They technically have a basic 1:1 ctypes wrapper currently, but I wanted to make something more pythonic, because it'd be next to impossible to deal with the memory management cleanly in the script itself. Anything I should keep in mind? Any tips to pass on to a first-time module writer, pitfalls to watch out for, etc.? ~Temia P.S. I know another game development library, SDL, was wrapped for Python in the form of Pygame, but I *really* don't like SDL. -- The amazing programming device: fuelled entirely by coffee, it codes while awake and tests while asleep! From steve+comp.lang.python at pearwood.info Fri Jul 13 00:21:40 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 04:21:40 GMT Subject: How to safely maintain a status file References: <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4fffa254$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 23:49:02 -0400, Gene Heskett wrote: > When I wanted to impress the visiting frogs, I often did something I > have never been able to do on any other operating system since, start > assembling a long assembly language file on one of the screens on the > color monitor, hit the clear key to advance to the amber screen and > start a listing on it of the assemblers output listing file. > > Because the file locking was applied only to the sector (256 bytes on > that machine) being written at the instant, the listing would fly by > till it caught up with the assemblers output, running into the lock and > then dutifully following along, one sector behind the assemblers output, > until the assembly was finished. That was in 1986 folks, and in the > year of our Lord 2012, 26 years later, I still cannot do that in linux. Um, what you are describing sounds functionally equivalent to what tail -f does. > When I ask why not, the replies seem to think I'm from outer space. Its > apparently a concept that is not even attempted to be understood by the > linux code carvers. You could certainly create a pair of cooperative programs, one which keeps a lock on only the last block of the file, and a tail-like reader which honours that lock. But why bother? Just have the assembler append to the file, and let people use any reader they like, such as tail. Or have I misunderstood you? -- Steven From rantingrickjohnson at gmail.com Fri Jul 13 00:26:20 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Thu, 12 Jul 2012 21:26:20 -0700 (PDT) Subject: How to safely maintain a status file In-Reply-To: <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> On Thursday, July 12, 2012 10:13:47 PM UTC-5, Steven D'Aprano wrote: > Rick has obviously never tried to open a file for reading when somebody > else has it opened, also for reading, and discovered that despite Windows > being allegedly a multi-user operating system, you can't actually have > multiple users read the same files at the same time. You misread my response. My comment was direct result of Christian stating: (paraphrase) "On some systems you are not permitted to delete a file whilst the file is open " ...which seems to be consistent to me. Why would *anybody* want to delete a file whilst the file is open? Bringing back the car analogy again: Would you consider jumping from a moving vehicle a consistent interaction with the interface of a vehicle? Of course not. The interface for a vehicle is simple and consistent: 1. You enter the vehicle at location A 2. The vehicle transports you to location B 3. You exit the vehicle At no time during the trip would anyone expect you to leap from the vehicle. But when you delete open files, you are essentially leaping from the moving vehicle! This behavior goes against all expectations of consistency in an API -- and against all sanity when riding in a vehicle! > Opening files for exclusive read *by default* is a pointless and silly > limitation. It's also unsafe: if a process opens a file for exclusive > read, and then dies, *no other process* can close that file. Oh come on. Are you actually going to use "errors" or "unintended consequences", or even "Acts of God" to defend your argument? Okay. Okay. I suppose "IF" the car spontaneously combusted "THEN" the passengers would be wise to jump out, leaving the vehicle to the whims of inertia. > One neat trick is to open a file, then delete it from disk while it is > still open. So long as your process is still running, you can write to > this ghost file, as normal, but no other process can (easily) see it. And > when your process ends, the file contents is automatically deleted. Well "neat tricks" aside, I am of the firm belief that deleting files should never be possible whilst they are open. * Opening files requires that data exist on disk * Reading and writing files requires an open file obj * Closing files requires an open file object * And deleting files requires that the file NOT be open Would you also entertain the idea of reading or writing files that do not exist? (not including pseudo file objs like StringIO of course!). Summary: Neat tricks and Easter eggs are real hoot, but consistency in APIs is the key. From rustompmody at gmail.com Fri Jul 13 00:33:40 2012 From: rustompmody at gmail.com (rusi) Date: Thu, 12 Jul 2012 21:33:40 -0700 (PDT) Subject: lambda in list comprehension acting funny References: Message-ID: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> On Jul 11, 11:41?am, Daniel Fetchinson wrote: > funcs = [ lambda x: x**i for i in range( 5 ) ] > print funcs[0]( 2 ) > print funcs[1]( 2 ) > print funcs[2]( 2 ) > > This gives me > > 16 > 16 > 16 > > When I was excepting > > 1 > 2 > 4 > > Does anyone know why? > > Cheers, > Daniel Your expectations are reasonable. Heres the equivalent in Haskell from which python has taken comprehensions. --------------------------------- GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help Prelude> let funcs = [ (\ x -> x ^ i)| i <- [0..4]] Prelude> (funcs !! 0)(2) 1 Prelude> (funcs !! 1)(2) 2 Prelude> (funcs !! 2)(2) 4 Prelude> From rosuav at gmail.com Fri Jul 13 02:02:13 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 13 Jul 2012 16:02:13 +1000 Subject: How to safely maintain a status file In-Reply-To: <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> Message-ID: On Fri, Jul 13, 2012 at 2:26 PM, wrote: > On Thursday, July 12, 2012 10:13:47 PM UTC-5, Steven D'Aprano wrote: >> Rick has obviously never tried to open a file for reading when somebody >> else has it opened, also for reading, and discovered that despite Windows >> being allegedly a multi-user operating system, you can't actually have >> multiple users read the same files at the same time. > > You misread my response. My comment was direct result of Christian stating: > > (paraphrase) "On some systems you are not permitted to delete a file whilst the file is open " > > ...which seems to be consistent to me. Why would *anybody* want to delete a file whilst the file is open? POSIX doesn't let you delete files. It lets you dispose of filenames. Python does the same with its 'del'. The object (file) exists until the system decides otherwise. Here's a simpler example: Hardlinks. Suppose you have two names pointing to the same file; are you allowed to unlink one of them while you have the "other" open? ChrisA From steve+comp.lang.python at pearwood.info Fri Jul 13 02:36:45 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 06:36:45 GMT Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> Message-ID: <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 21:33:40 -0700, rusi wrote: > On Jul 11, 11:41?am, Daniel Fetchinson > wrote: >> funcs = [ lambda x: x**i for i in range( 5 ) ] print funcs[0]( 2 ) >> print funcs[1]( 2 ) >> print funcs[2]( 2 ) >> >> This gives me >> >> 16 >> 16 >> 16 >> >> When I was excepting >> >> 1 >> 2 >> 4 >> >> Does anyone know why? >> >> Cheers, >> Daniel > > Your expectations are reasonable. You forget to finish that sentence. "Your expectations are reasonable, for languages that don't have variables which can actually vary." *wink* For purely functional languages like Haskell, the behaviour you show below makes sense. Since Haskell doesn't allow variables to change their value, once a closure sees i=1 (say), then it must *always* see i=1. But that's not the case in Python, where the Haskell behaviour would be unfortunate. Imagine if you did this: VERBOSE = True def function(arg): if VERBOSE: print("calling function with arg %r" % arg) process(arg) You would expect the function to honour changes to the variable VERBOSE, would you not? Using Python's scoping rules for closures, it does. Using Haskell's rules, it wouldn't. > Heres the equivalent in Haskell from which python has taken > comprehensions. > --------------------------------- > GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help > > Prelude> let funcs = [ (\ x -> x ^ i)| i <- [0..4]] > Prelude> (funcs !! 0)(2) > 1 > Prelude> (funcs !! 1)(2) > 2 > Prelude> (funcs !! 2)(2) > 4 > Prelude> -- Steven From steve+comp.lang.python at pearwood.info Fri Jul 13 03:14:36 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 07:14:36 GMT Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> Message-ID: <4fffcadc$0$29965$c3e8da3$5496439d@news.astraweb.com> On Thu, 12 Jul 2012 21:26:20 -0700, rantingrickjohnson wrote: > On Thursday, July 12, 2012 10:13:47 PM UTC-5, Steven D'Aprano wrote: >> Rick has obviously never tried to open a file for reading when somebody >> else has it opened, also for reading, and discovered that despite >> Windows being allegedly a multi-user operating system, you can't >> actually have multiple users read the same files at the same time. > > You misread my response. My comment was direct result of Christian > stating: > > (paraphrase) "On some systems you are not permitted to delete a file > whilst the file is open " > > ...which seems to be consistent to me. Why would *anybody* want to > delete a file whilst the file is open? Because it is useful and a sensible thing to do. Why should one misbehaved application, keeping a file open, be allowed to hold every other application, and the file system, hostage? This is one of the many poor decisions which makes Windows so vulnerable to viruses and malware. If malware can arrange to keep itself open, you can't delete it. Thanks guys! > Bringing back the car analogy > again: Would you consider jumping from a moving vehicle a consistent > interaction with the interface of a vehicle? Of course not. The > interface for a vehicle is simple and consistent: > > 1. You enter the vehicle at location A > 2. The vehicle transports you to location B > 3. You exit the vehicle Amusingly, you neglected to specify "the vehicle stops" -- and rightly so, because of course having to stop the vehicle is not a *necessary* condition for exiting it, as tens of thousands of stunt men and women can attest. Not to mention people parachuting out of an airplane, pirates or commandos boarding a moving ship, pedestrians transferring from a slow moving walkway to a faster moving walkway, farmers jumping off a trailer while it is still being towed behind a tractor (and jumping back on again), and Bruce Willis in "Red" in very possibly the best slow-motion action sequence in the history of Hollywood. http://www.youtube.com/watch?v=xonMpj2YyDU > At no time during the trip would anyone expect you to leap from the > vehicle. Expected or not, you can do so. > But when you delete open files, you are essentially leaping > from the moving vehicle! This behavior goes against all expectations of > consistency in an API -- and against all sanity when riding in a > vehicle! Fortunately, files on a file system are not cars, and deleting open files is a perfectly reasonable thing to do, no more frightening than in Python deleting a reference to an object using the del statement. Imagine how stupid it would be if this happened: py> x = 42 py> y = x py> del y Traceback (most recent call last): File "", line 1, in DeleteError: cannot delete reference to object '42' until no other references to it exist Fortunately, Python doesn't do that -- it tracks when the object is no longer being accessed, and only then physically reclaims the memory used. And so it is on POSIX file systems: the file system keeps track of when the file on disk is no longer being accessed, and only then physically reclaims the blocks being used. Until then, deleting the file merely unlinks the file name from the blocks on disk, in the same way that "del y" merely unlinks the name y from the object 42. >> Opening files for exclusive read *by default* is a pointless and silly >> limitation. It's also unsafe: if a process opens a file for >> exclusive read, and then dies, *no other process* can close that file. > > Oh come on. Are you actually going to use "errors" or "unintended > consequences", or even "Acts of God" to defend your argument? Features have to be judged by their actual consequences, not some unrealistic sense of theoretical purity. The actual consequences of mandatory exclusive file locking is, *it sucks*. Windows users are used to having to reboot their server every few days because something is broken, so they might not mind rebooting it because some file is locked in a mandatory open state and not even the operating system can unlock it. But for those with proper operating systems who expect months of uninterrupted service, mandatory locking is a problem to be avoided, not a feature. > Okay. > Okay. I suppose "IF" the car spontaneously combusted "THEN" the > passengers would be wise to jump out, leaving the vehicle to the whims > of inertia. In this analogy, is the car the file name, the inode, or the directory? Are the passengers the file name(s), or the file contents, or the inode? Is the driver meant to be the file system? If I have a hard link to the file, does that mean the passengers are in two cars at once, or two lots of passengers in the same car? >> One neat trick is to open a file, then delete it from disk while it is >> still open. So long as your process is still running, you can write to >> this ghost file, as normal, but no other process can (easily) see it. >> And when your process ends, the file contents is automatically deleted. > > Well "neat tricks" aside, I am of the firm belief that deleting files > should never be possible whilst they are open. [condescension = ON] Good for you Rick. Having strongly held opinions on things you have only a limited understanding about is your right as an American. [condescension = OFF] > * Opening files requires that data exist on disk > * Reading and writing files requires an open file obj You have missed a step in jumping from files on disk to open file objects. Open file objects do not necessarily correspond to files on disk. For example, in standard Pascal, file objects are purely in-memory constructs emulating files on a tape drive, with no relationship to on-disk files. (Any half-decent Pascal compiler or interpreter will *also* give you ways to access real files on disk, but that isn't covered by the standard.) Even when the file object does come from an actual disk file, we can conclude that before you can open a file for reading, it must exist; but having opened it, there is no *necessary* requirement that it *remains* on disk. If you try to read from an open file object whose underlying file has been deleted, there are three perfectly reasonable behaviours: - you get an error; - it is the same result as if the file has been truncated to zero bytes; - deleting the file only deletes the *name*, not contents, until the last open file handle is shut, and then the contents are deleted. > * Closing files requires an open file object Naturally; but open file objects don't require that the on-disk file still exists. > * And deleting files requires that the file NOT be open Not at all. > Would you also entertain the idea of reading or writing files that do > not exist? (not including pseudo file objs like StringIO of course!). Define "file" and "exist". Because you are conflating at least three different things: a file name an inode (blocks on a disk) a file object Of course it is useful to break the abstraction that file objects must be files on disk. StringIO is one such example. Standard Pascal file objects is another. Likewise, it is useful to be able to read from an inode that is no longer connected to a file name. So, absolutely, yes, it is useful to be able to read and write from files that don't exist, under some circumstances. > Summary: Neat tricks and Easter eggs are real hoot, but consistency > in APIs is the key. A foolish consistency is the hobgoblin of little minds. -- Steven From __peter__ at web.de Fri Jul 13 03:26:31 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jul 2012 09:26:31 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> <1342119234.2313.42.camel@hatchbox-one> Message-ID: Frederic Rentsch wrote: > I'm sorry I can't post an intelligible piece that does NOT work. I > obviously can't post the whole thing. How about a pastebin then? Or even bitbucket/github as you need to track changes anyway? > It is way too convoluted. "Convoluted" code is much easier to debug than no code ;) Another random idea: run your code on a more recent python/tcl installation. If you are lucky you get a different error. From nuffnough at gmail.com Fri Jul 13 03:34:38 2012 From: nuffnough at gmail.com (nuffi) Date: Fri, 13 Jul 2012 00:34:38 -0700 (PDT) Subject: help needed with subprocess, pipes and parameters Message-ID: If I copy and paste the following command into a command window, it does what I need. c:\Programs\bob\bob.exe -x -y "C:\text\path\to some\file.txt" | c:\Programs\kate\kate.exe -A 2 --dc "Print Media Is Dead" --da "Author" --dt "Title" --hf "Times" --bb "14" --aa "" --font "Ariel" - "C:\rtf\path\to some\file.rtf" My mission is to recreate this command within a python script, so that I can pass a bunch of different parameters into it, and use it as a batch over a bunch of different papers. http://docs.python.org/library/subprocess.html seems to be the thing to use in python 2.7.3. I also checked out http://www.doughellmann.com/PyMOTW/subprocess/. My attempts run fine, create destination folders ok and prints done but don't actually seem to process the file. Is there some way to get subprocess to output the command it's generating so I can see what I'm doing wrong, rather than just the output of the command? How can I chekc that kate's opening the pipe left from bob? Bob may take some time to execute, will that matter? The code I came up with looks like this: import os, glob, subprocess sourceDir = "c:\\text\\" destDir = "c:\\rtf\\" bobPath = "C:\\Programs\\bob\\bob.exe" katePath = "C:\\Programs\\kate\\kate.exe" def get_new_path(doc): blah = doc.replace(sourceDir, destDir) if not os.path.isdir(blah): os.makedirs(blah) rtf = blah.replace('.txt', '.rtf') pathString = '- "' + (os.path.join(rtf)) + '"' return(pathString) def convert_doc(doc): dc = '--dc "Print Media Is Dead"' da = '--da "Author"' dt = '--dt "Title"' hf = '--hf "Times"' fn = '--font "Ariel"' bb = '--bb "14"' docpath = '"' + (os.path.join(doc)) + '"' path = get_new_path(doc) A = '-A 2' bob = subprocess.Popen([bobPath, '-x', '-y', docpath], stdout = subprocess.PIPE,) kate = subprocess.Popen([katePath, A, dc, da, dt, hf, fn, bb, path], stdin = bob.stdout, stdout = subprocess.PIPE,) end_of_pipe = kate.stdout #print kate #subprocess.call(['echo', "Test peice of text", '>', 'D:\\output.txt']) for line in end_of_pipe: print '\t', blah.strip() #raw_input() return('done') test = convert_doc("c:\\text\\path to\\some\\specific text file.txt") print(blah) == Thanks for looking :-) From martin.hellwig at gmail.com Fri Jul 13 03:39:32 2012 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Fri, 13 Jul 2012 00:39:32 -0700 (PDT) Subject: Writing a wrapper - any tips? In-Reply-To: References: Message-ID: <9a3fe09a-82dd-4623-a6da-15a23633db3b@googlegroups.com> On Friday, 13 July 2012 05:03:23 UTC+1, Temia Eszteri wrote: > I'm going to be looking into writing a wrapper for the Allegro 5 game > development libraries, either with ctypes or Cython. They technically > have a basic 1:1 ctypes wrapper currently, but I wanted to make > something more pythonic, because it'd be next to impossible to deal > with the memory management cleanly in the script itself. > > Anything I should keep in mind? Any tips to pass on to a first-time > module writer, pitfalls to watch out for, etc.? I would split the wrapping in layers, the lowest layer is a one on one exposure of the library with your wrapper, I would rather avoid ctypes for performance reasons, however if performance is not a concern ctypes is excellent and broadly available. The next layer is purely there to make the lower layer pythonic, i.e. apply namespaces, automatic handling of memory, PEP8 naming convetions, etc. etc. just what you would expect from a modern pure python module The next layer, if you want to, contains tools that are often used in that concept, think in the line of design patterns. hth -- mph From andrea.crotti.0 at gmail.com Fri Jul 13 04:54:37 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Fri, 13 Jul 2012 09:54:37 +0100 Subject: adding a simulation mode In-Reply-To: <4fff89f6$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <87liiyr48f.fsf@handshake.de> <4fff89f6$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2012/7/13 Steven D'Aprano : > Well of course it does. If copytree fails, the try block ends and > execution skips straight to the except block, which runs, and then the > program halts because there's nothing else to be done. > > That at least is my guess, based on the described symptoms. > Well I think that's what I was stupidly missing, I always had only one possibly failing thing in a try/except block, and I always gave for granted that it doesn't jump to the except block on first error, but of course it makes more sense if it does... Thanks a lot From johnpote at jptechnical.co.uk Fri Jul 13 05:46:20 2012 From: johnpote at jptechnical.co.uk (John Pote) Date: Fri, 13 Jul 2012 10:46:20 +0100 Subject: New Python build regr test___all__ fails at 'ctypes.macholib.dyld' Message-ID: Hi, I have built Python 2.7.3 from source and although the interpreter starts up and runs scripts (so far OK) the 'test___all__' regression test fails. The machine I'm building on is a virtual server running a version of Red Hat Linux Build commands: ./configure --prefix /usr make At the end of the make the following note is shown Python build finished, but the necessary bits to build these modules were not found: _bsddb _sqlite3 bsddb185 sunaudiodev Test command ./python Lib/test/regrtest.py -v test___all__ produces the following:- == CPython 2.7.3 (default, Jul 13 2012, 10:26:48) [GCC 3.2.2 20030217 (Red Hat Linux 8.0 3.2.2-2)] == Linux-2.4.29-hs-17-i686-with-glibc2.2 little-endian == /usr/local/home/aquamaster3/Python-2.7.3/Python-2.7.3/build/test_python_4517 Testing with flags: sys.flags(debug=0, py3k_warning=0, division_warning=0, division_new=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, tabcheck=0, verbose=0, unicode=0, bytes_warning=0, hash_randomization=0) test___all__ test_all (test.test___all__.AllTest) ... BaseHTTPServer Bastion CGIHTTPServer ConfigParser Cookie DocXMLRPCServer HTMLParser MimeWriter Queue SimpleHTTPServer SimpleXMLRPCServer SocketServer StringIO UserDict UserList UserString _LWPCookieJar _MozillaCookieJar __phello__.foo _abcoll _pyio _strptime _threading_local _weakrefset abc aifc antigravity anydbm argparse ast asynchat asyncore atexit audiodev base64 bdb binhex bisect bsddb bsddb.db bsddb.dbobj bsddb.dbrecio bsddb.dbshelve bsddb.dbtables bsddb.dbutils bsddb.test bsddb.test.test_all bsddb.test.test_associate bsddb.test.test_basics bsddb.test.test_compare bsddb.test.test_compat bsddb.test.test_cursor_pget_bug bsddb.test.test_db bsddb.test.test_dbenv bsddb.test.test_dbobj bsddb.test.test_dbshelve bsddb.test.test_dbtables bsddb.test.test_distributed_transactions bsddb.test.test_early_close bsddb.test.test_fileid bsddb.test.test_get_none bsddb.test.test_join bsddb.test.test_lock bsddb.test.test_misc bsddb.test.test_pickle bsddb.test.test_queue bsddb.test.test_recno bsddb.test.test_replication bsddb.test.test_sequence bsddb.test.test_thread cProfile calendar cgi cgitb chunk cmd code codecs codeop collections colorsys commands compileall compiler compiler.ast compiler.consts compiler.future compiler.misc compiler.pyassem compiler.pycodegen compiler.symbols compiler.syntax compiler.transformer compiler.visitor contextlib cookielib copy copy_reg csv ctypes ctypes._endian ctypes.macholib ctypes.macholib.dyld Aborted Any help in resolving this problem would be appreciated Regards, John --- Posted via news://freenews.netfront.net/ - Complaints to news at netfront.net --- From stefan_ml at behnel.de Fri Jul 13 05:49:23 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 13 Jul 2012 11:49:23 +0200 Subject: Writing a wrapper - any tips? In-Reply-To: <9a3fe09a-82dd-4623-a6da-15a23633db3b@googlegroups.com> References: <9a3fe09a-82dd-4623-a6da-15a23633db3b@googlegroups.com> Message-ID: Martin P. Hellwig, 13.07.2012 09:39: > On Friday, 13 July 2012 05:03:23 UTC+1, Temia Eszteri wrote: >> I'm going to be looking into writing a wrapper for the Allegro 5 game >> development libraries, either with ctypes or Cython. They technically >> have a basic 1:1 ctypes wrapper currently, but I wanted to make >> something more pythonic, because it'd be next to impossible to deal >> with the memory management cleanly in the script itself. >> >> Anything I should keep in mind? Any tips to pass on to a first-time >> module writer, pitfalls to watch out for, etc.? > > I would split the wrapping in layers, the lowest layer is a one on one > exposure of the library with your wrapper, I would rather avoid ctypes > for performance reasons, however if performance is not a concern ctypes > is excellent and broadly available. > > The next layer is purely there to make the lower layer pythonic, i.e. > apply namespaces, automatic handling of memory, PEP8 naming convetions, > etc. etc. just what you would expect from a modern pure python module > > The next layer, if you want to, contains tools that are often used in > that concept, think in the line of design patterns. And the good thing about Cython in this context is that even if performance *is* a concern, you can move code around between all three layers freely in order to adjust it to your performance requirements and even drop the lowest layer entirely. In fact, my advice is to really skip that lowest layer in a Cython wrapper, because if it's really just a 1:1 mapping, it's going to end up with a lot of boring and redundant code and you won't gain anything from it. Stefan From jeanmichel at sequans.com Fri Jul 13 06:09:22 2012 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 13 Jul 2012 12:09:22 +0200 Subject: Mocked object returning another Mocked object Message-ID: <4FFFF3D2.5030900@sequans.com> Greetings Fellow Group, I'd need your help to fix some issues I have with my unitary tests. I'm trying to bring them to the next level by Mocking equipments controlled by my application. Despite me reading http://www.voidspace.org.uk/python/mock/index.html I cannot figure out how to do the following : I have an App object with the 'target' attribute. This target is controlling a piece of hardware. The hardware itself holds a software, hence the target object having an 'api' attribute. I hope I make sense. So basically I'd like self.target.api.() to return a Mocked object (Mocking an Api object response). ** Question ** I do I make *all* method calls return a specifik Mock? target = Mock() result = target.api.start() # I'd like result to be a Mock I defined with the 'returnCode' attribute print result.returnCode 1 But I would like to do it for any method of api (the list is huge, setting each of them is not an option I think) so that in the end, result = target.api.start() result = target.api.stop() result = target.api.reset() result = target.api.loadSw() return all the same Mock object (with 'returnCode') Any idea ? Cheers, JM From ulrich.eckhardt at dominolaser.com Fri Jul 13 06:37:47 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Fri, 13 Jul 2012 12:37:47 +0200 Subject: Mocked object returning another Mocked object In-Reply-To: References: Message-ID: Am 13.07.2012 12:09, schrieb Jean-Michel Pichavant: > I have an App object with the 'target' attribute. This target is > controlling a piece of hardware. The hardware itself holds a software, > hence the target object having an 'api' attribute. I hope I make sense. > > So basically I'd like > > self.target.api.() > > to return a Mocked object (Mocking an Api object response). > > ** Question ** > > I do I make *all* method calls return a specifik Mock? > > target = Mock() > > result = target.api.start() I'm not sure where the "target" here comes in. As I understand it, the goal is to write the "api" object so that you can call any function on it... > I'd like result to be a Mock I defined > with the 'returnCode' attribute > > print result.returnCode > 1 ...and every function should just return the same return code. Right? > But I would like to do it for any method of api (the list is huge, > setting each of them is not an option I think) so that in the end, > > result = target.api.start() > result = target.api.stop() > result = target.api.reset() > result = target.api.loadSw() > > return all the same Mock object (with 'returnCode') There are two options I could think of: 1. Intercept attribute lookup From the top of my head, the syntax is something like this: class TargetMock(object): def __getattr__(self, name): def default_result(*vargs, **kwargs): return ReturnCode(1) return default_result This just ignores the name and returns a function returning the mock return code. I think you get the idea. 2. Intercept individual lookups class TargetMock(object): def _default(self, *vargs, **kwargs): return ReturnCode(1) start = _default stop = _default reset = _default loadSW = _default Yes, this ignores your claim that the list of functions is too big to add every function individually. I'd just add them on demand when a test accesses a function that isn't there yet. The advantage is that it shows clearly which of the functions are just stubs if you actually implement a few of them differently. If the list functions is really that huge but you have a class (the real driver class) that defines this API, then you could extract this list programmatically. That way, you could also ensure that your mock API doesn't provide functions not supported by the original. Good luck! Uli From summerholidaylearning at gmail.com Fri Jul 13 07:15:17 2012 From: summerholidaylearning at gmail.com (summerholidaylearning at gmail.com) Date: Fri, 13 Jul 2012 04:15:17 -0700 (PDT) Subject: Keeping the Console Open with IDLE In-Reply-To: References: Message-ID: <0040b385-2dbc-4b3b-af97-62a77686d2bb@googlegroups.com> On Friday, February 20, 2009 4:06:42 AM UTC, W. eWatson wrote: > I'm using IDLE for editing, but execute programs directly. If there are > execution or "compile" errors, the console closes before I can see what it > contains. How do I prevent that? > -- > W. eWatson > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Web Page: <www.speckledwithstars.net/> Thanks this solved my problem too(the same issue - I was also double clicking instead of right clicking - edit with IDLE - F5 to run) From albert at spenarnc.xs4all.nl Fri Jul 13 08:30:47 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 13 Jul 2012 12:30:47 GMT Subject: code review References: <87wr2oecf6.fsf <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4ff0f8e0$0$29988$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: >On Sun, 01 Jul 2012 05:55:24 -0400, Terry Reedy wrote: > >> On 7/1/2012 2:54 AM, Steven D'Aprano wrote: >> >>> So no, Python has always included chained comparisons, and yes, it is >>> shameful that a language would force you to unlearn standard notation >>> in favour of a foolish consistency with other operators. Comparisons >>> aren't special because they return bools. They are special because of >>> the way they are used. >>> >>> C treats comparison operators as if they were arithmetic operators, and >>> so the behaviour of a chained comparison is the same as the behaviour >>> as a sequence of arithmetic operators: a foolish consistency. Python >>> treats comparison operators as comparison operators, and gives them >>> behaviour appropriate to comparisons. >> >> I considered this a great feature of Python when I first learned it. >> Reading about how rare it is among programming languages to treat >> comparisons in the standard way in mathematics reinforces that. > >Apart from Python, Mathematica, Perl 6, CoffeeScript, Cobra and Clay give >chained comparisons the standard meaning. It is, or was, a feature >request for Boo, but I can't tell whether it has been implemented or not. Algol 68 does not. It has promoted operator symbols to first class citizens. In that context chained comparison operators cannot be made to work. Both Mathematica and Perl are ad-hoc-ish languages. I would hate Python go that way. >From now on, for each operator I would have to remember wether it is a supposedly comparison operator or not. Comparison operations on booleans make sense. I remember a FORTRAN compiler complaining about me comparing LOGICALS. The lack of abstraction! > > >C-like semantics are next to useless, except perhaps for obfuscation: > >http://stackoverflow.com/questions/4089284/why-does-0-5-3-return-true/ > >And surprising: > >http://answers.yahoo.com/question/index?qid=20090923172909AA4O9Hx > >C-like semantics are a clear case of purity of implementation overruling >functional usefulness. The worst of is, of course, = for assignment instead of := . This is a convention that Python follows, to my dismay. > >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From roy at panix.com Fri Jul 13 08:42:21 2012 From: roy at panix.com (Roy Smith) Date: Fri, 13 Jul 2012 08:42:21 -0400 Subject: Initial nose experience Message-ID: I've been using unittest for many years, but have steadfastly (perhaps stubbornly) avoided newfangled improvements like nose. I finally decided to take a serious look at nose. There were a few pain points I had to work through to get our existing collection of tests to run under nose. I figured I'd share them for the benefit of others who may be going through the same process. First nose won't import executable files, at least not by default. All of our test files are executable, with a "#!/usr/bin/env python" line at the top, and a "if __name__ == '__main__'" block, which does some setup and invokes unittest.main(), at the bottom. Going to the top of our source tree and typing "nosetests" was an uninspiring experience: > $ nosetests > > ---------------------------------------------------------------------- > Ran 0 tests in 0.001s > > OK The fix is either make them non-executable, or do "nosetests --exe". Next up was the the setup in the "if __name__ == '__main__'" block wasn't running. The solution here is to move all the setup to setUpModule(), where it belongs. SetUpModule() is new in Python 2.7 but it turns out it's trivial to drop that version into older systems (http://pypi.python.org/pypi/unittest2). We found a bunch of tests which require some specific setup before they could run (most blatantly, some selenium tests which depend on X11). When we were running tests semi-manually, that was not a big deal. With nose's "find them all and run them" strategy, this fails. The obvious fix is that every test needs to either set up the right environment, or be protected with the appropriate @skip decorator so it doesn't run if the environment isn't good. Lastly, nose, by default, doesn't say much. When things go wrong and you have no clue what's happening, --verbose and --debug are your friends. From albert at spenarnc.xs4all.nl Fri Jul 13 09:07:41 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 13 Jul 2012 13:07:41 GMT Subject: Using a CMS for small site? References: Message-ID: In article , Gilles wrote: >Hello > >Someone I know with no computer knowledge has a studio appartment to >rent in Paris and spent four months building a small site in Joomla to >find short-time renters. > >The site is just... >- a few web pages that include text (in four languages) and pictures >displayed in a Flash slide show >- a calendar to show availability >- a form to send e-mail with anti-SPAM support >- (ASAP) online payment > >Out of curiosity, are there CMS/frameworks in Python that can do this? >Django? Other? > >Is a full-fledged CMS even needed for something like that? Good old rcs would be fine. It is oldfashioned, so you need only 4 commands, compared to a bewildering display of icons. mkdir RCS ci * rcs -NSTABLE1: RCS/* Backup by tar cf /media/MYSTICK/project.tar RCS > >Thank you. -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From rustompmody at gmail.com Fri Jul 13 09:44:59 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 06:44:59 -0700 (PDT) Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 13, 11:36?am, Steven D'Aprano wrote: > On Thu, 12 Jul 2012 21:33:40 -0700, rusi wrote: > > On Jul 11, 11:41?am, Daniel Fetchinson > > wrote: > >> funcs = [ lambda x: x**i for i in range( 5 ) ] print funcs[0]( 2 ) > >> print funcs[1]( 2 ) > >> print funcs[2]( 2 ) > > >> This gives me > > >> 16 > >> 16 > >> 16 > > >> When I was excepting > > >> 1 > >> 2 > >> 4 > > >> Does anyone know why? > > >> Cheers, > >> Daniel > > > Your expectations are reasonable. > > You forget to finish that sentence. > > "Your expectations are reasonable, for languages that don't have > variables which can actually vary." > > *wink* > > For purely functional languages like Haskell, the behaviour you show > below makes sense. Since Haskell doesn't allow variables to change their > value, once a closure sees i=1 (say), then it must *always* see i=1. > > But that's not the case in Python, where the Haskell behaviour would be > unfortunate. Imagine if you did this: > > VERBOSE = True > > def function(arg): > ? ? if VERBOSE: > ? ? ? ? print("calling function with arg %r" % arg) > ? ? process(arg) > > You would expect the function to honour changes to the variable VERBOSE, > would you not? Using Python's scoping rules for closures, it does. Using > Haskell's rules, it wouldn't. Heres a more appropriate analog ------------------------------------------ VERBOSE = True def function(arg): if VERBOSE: print("calling function with arg %r" % arg) process(arg) def caller(): VERBOSE = False function(1) --------------------------------------------- Python semantics: function sees VERBOSE False Haskell semantics: function sees VERBOSE True From rustompmody at gmail.com Fri Jul 13 10:45:29 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 07:45:29 -0700 (PDT) Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: To come back to the OPs question. Variables can be assigned. Or they can be bound. [C++ programmers will be familiar with the difference between initialization and assignment] List comprehensions are defined in terms of assignment to the local variable rather than binding. Hence the issue. Below are two functions that simulate mapping (lambda x: x**i) where the i's come from some given list def binding_version(lst): if not lst: return [] i = lst[0] return [(lambda x: x ** i)] + binding_version(lst[1:]) def assign_version(lst): ret = [] for i in lst: ret.append(lambda x: x**i) return ret ---------------------- >>> fs= binding_version([0,1,2]) >>> fs[0](2) 1 >>> fs[1](2) 2 >>> fs[2](2) 4 >>> fs= assign_version([0,1,2]) >>> fs[0](2) 4 >>> fs[1](2) 4 >>> fs[2](2) 4 From steve+comp.lang.python at pearwood.info Fri Jul 13 11:04:21 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 13 Jul 2012 15:04:21 GMT Subject: code review References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 12:30:47 +0000, Albert van der Horst wrote: >>Apart from Python, Mathematica, Perl 6, CoffeeScript, Cobra and Clay >>give chained comparisons the standard meaning. It is, or was, a feature >>request for Boo, but I can't tell whether it has been implemented or >>not. > > Algol 68 does not. It has promoted operator symbols to first class > citizens. In that context chained comparison operators cannot be made to > work. > Both Mathematica and Perl are ad-hoc-ish languages. I would hate Python > go that way. Perl 5 does not have chained comparisons. Perl 6, which is more designed and less ad-hoc, does. > From now on, for each operator I would have to remember wether it is a > supposedly comparison operator or not. Are you often in the habit of using operators *without* remembering what they do? I can't speak for you, but it isn't often that I've found myself not remembering whether the less-than operator < means "compare two values" or "multiply two values". > Comparison operations on booleans make sense. Actually, no. Is True less than False, or is it greater? In boolean algebra, the question has no answer. It is only an implementation detail of Python that chooses False < True. Of course, equality and inequality make sense for all values. But the other comparison operators, < <= >= > only make sense for values which are ordered, like real numbers (but not complex numbers), strings, and similar, or for set comparisons (subset and superset). Arbitrary types may not define comparison operators. > I remember a FORTRAN > compiler complaining about me comparing LOGICALS. The lack of > abstraction! The opposite: LOGICALS are abstract values which do not define greater than or less than. > The worst of is, of course, = for assignment instead of := . This is a > convention that Python follows, to my dismay. *shrug* The worst is to use = for both equality and assignment, like some BASICs. At least Python does not allow assignment as an expression, so you can't make the typical C error of: if x = y: do_something() # oops meant x == y -- Steven From roy at panix.com Fri Jul 13 11:32:38 2012 From: roy at panix.com (Roy Smith) Date: Fri, 13 Jul 2012 08:32:38 -0700 (PDT) Subject: code review In-Reply-To: <4ff6eef2$0$29988$c3e8da3$5496439d@news.astraweb.com> References: <6c39594f-79cb-4d4f-967e-bbc3f68cdbdf@f8g2000pbf.googlegroups.com> <4fed59b7$0$29978$c3e8da3$5496439d@news.astraweb.com> <2662370.TGmo96CKe1@PointedEars.de> <87wr2oecf6.fsf@dpt-info.u-strasbg.fr> <4FEF7117.7000109@jollybox.de> <87bok0qr62.fsf@benfinney.id.au> <3a9d4b46-2e99-4c30-882b-8ee68cb809da@googlegroups.com> <4ff6eef2$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, July 6, 2012 9:58:10 AM UTC-4, Steven D'Aprano wrote: > (Sadly, when I say "we" I mean > collectively. Many language designers, and programmers, don't have the > foggiest clue as to what makes a good clean design. Hence C++ and PHP.) I'm not going to defend C++, but to be fair, a major driver of the design is that it had to be plug-compatible with C. From that you're stuck with the preprocessor and pointers. Much goes downhill when you start from there. PHP, yeah, that's just charlie-foxtrot from start to finish. From rosuav at gmail.com Fri Jul 13 11:36:47 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 14 Jul 2012 01:36:47 +1000 Subject: code review In-Reply-To: <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jul 14, 2012 at 1:04 AM, Steven D'Aprano wrote: > Actually, no. Is True less than False, or is it greater? In boolean > algebra, the question has no answer. It is only an implementation detail > of Python that chooses False < True. Maybe in boolean algebra, but in code, it's handy to have sortable bools. In SQL, for instance, I can use a boolean in an ORDER BY, perhaps followed by another criterion, and it's effectively sorting by "1 if some_boolean else 0" or in C notation "some_boolean ? 0 : 1" ChrisA From ramit.prasad at jpmorgan.com Fri Jul 13 12:00:30 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 13 Jul 2012 16:00:30 +0000 Subject: How to safely maintain a status file In-Reply-To: <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> > Well "neat tricks" aside, I am of the firm belief that deleting files should > never be possible whilst they are open. This is one of the few instances I think Windows does something better than OS X. Windows will check before you attempt to delete (i.e. move to Recycling Bin) while OS X will move a file to Trash quite happily only tell me it cannot remove the file when I try to empty the Trash. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Jul 13 12:12:40 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 13 Jul 2012 16:12:40 +0000 Subject: lambda in list comprehension acting funny In-Reply-To: References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416556142@SCACMX008.exchad.jpmchase.net> > VERBOSE = True > > def function(arg): > if VERBOSE: > print("calling function with arg %r" % arg) > process(arg) > > def caller(): > VERBOSE = False > function(1) > > --------------------------------------------- > Python semantics: function sees VERBOSE False > Haskell semantics: function sees VERBOSE True >>> def caller(): ... VERBOSE = False ... function(1) >>> def function(arg): ... if VERBOSE: ... print("calling function with arg %r" % arg) ... >>> VERBOSE = True >>> caller() calling function with arg 1 I might be being OCD, but caller needs `global VERBOSE` for that to work as you explain. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rustompmody at gmail.com Fri Jul 13 12:24:19 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 09:24:19 -0700 (PDT) Subject: code review References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 13, 8:36?pm, Chris Angelico wrote: > On Sat, Jul 14, 2012 at 1:04 AM, Steven D'Aprano > > wrote: > > Actually, no. Is True less than False, or is it greater? In boolean > > algebra, the question has no answer. It is only an implementation detail > > of Python that chooses False < True. > > Maybe in boolean algebra, but in code, it's handy to have sortable > bools. In SQL, for instance, I can use a boolean in an ORDER BY, > perhaps followed by another criterion, and it's effectively sorting by > "1 if some_boolean else 0" or in C notation "some_boolean ? 0 : 1" > > ChrisA Actually a boolean algebra is a lattice with some additional properties A lattice is a poset (partially ordered set) with suprema and infimas And so there is one natural order relation on any boolean algebra which may be defined as a ? b iff a ? b = a tl;dr version: In a boolean algebra, False is bottom and True is top From hansmu at xs4all.nl Fri Jul 13 12:33:36 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Jul 2012 18:33:36 +0200 Subject: adding a simulation mode In-Reply-To: <4fff8514$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <87liiyr48f.fsf@handshake.de> <4fff8514$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50004de0$0$6876$e4fe514c@news2.news.xs4all.nl> On 13/07/12 04:16:53, Steven D'Aprano wrote: > On Thu, 12 Jul 2012 16:37:42 +0100, andrea crotti wrote: > >> 2012/7/12 John Gordon : >>> In andrea crotti >>> writes: >>> >>>> Well that's what I thought, but I can't find any explicit exit >>>> anywhere in shutil, so what's going on there? >>> >>> Try catching SystemExit specifically (it doesn't inherit from >>> Exception, so "except Exception" won't catch it.) >>> >> >> Ah yes that actually works, but I think is quite dodgy, why was it done >> like this? It may be that the function you're calling found a problem that the author thinks is so grave that they shouldn't give you an opportunity to deal with it. If that's the case, I would be inclined to think that they are wrong. > Built-in exceptions SystemExit, KeyboardInterrupt and GeneratorExit > deliberately do not inherit from Exception since they are not meant to be > caught by "catch-all" try...except Exception clauses. > > You can see the exception hierarchy here: > > http://docs.python.org/library/exceptions.html#exception-hierarchy > > Please do NOT catch BaseException, since that is the wrong thing to do. I would agree if you had said "in production code". If you are investigating why a third-party function is stopping your interpreter, then catching BaseException may tell you that the code is raising the wrong kind of Exception. Once you know what kind the function is raising, you should catch only that particular excpetion subclass. > If you must catch SystemExit, KeyboardInterrupt, etc. they you should do > so as separate catch clauses: > > try: > main() > except SystemExit as e: > print(e) # see if we can find out who is raising this If you want to find out who is raising the exception, you could try this: except SystemExit: import traceback traceback.print_exc() That will print a complete stack trace. If you only need to know what kind of exception you have, you can do: print(repr(e)) A simple print(e) will print str(e), which in the case of SystemExit, is an empty string. That's not very informative. > except KeyboardInterrupt: > print("Mwahahaha my pretty, you cannot cancel this!!!") > print("...er, now what do I do?") > except Exception: > print("why am I catching exceptions I can't recover from?") Hope this helps, -- HansM From rustompmody at gmail.com Fri Jul 13 12:46:00 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 09:46:00 -0700 (PDT) Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4deb2389-e20a-4520-964d-7d996cf6b9b4@m2g2000pbv.googlegroups.com> On Jul 13, 9:12?pm, "Prasad, Ramit" wrote: > > VERBOSE = True > > > def function(arg): > > ? ? if VERBOSE: > > ? ? ? ?print("calling function with arg %r" % arg) > > ? ? process(arg) > > > def caller(): > > ? ? VERBOSE = False > > ? ? function(1) > > > --------------------------------------------- > > Python semantics: function sees VERBOSE False > > Haskell semantics: function sees VERBOSE True > >>> def caller(): > > ... ? ? VERBOSE = False > ... ? ? function(1)>>> def function(arg): > > ... ? ? if VERBOSE: > ... ? ? ? ?print("calling function with arg %r" % arg) > ... ? ?>>> VERBOSE = True > >>> caller() > > calling function with arg 1 > > I might be being OCD, but caller needs `global VERBOSE` for that to > work as you explain. Ok let me restate: if python were to work that way (without the global) we could say either a Python chooses to have dynamic scoping of variables or b There is a bug in python's scoping rules I would guess that most younger folks (who've not seen lisp and apl) would choose b We can say the same analogously in the context of ZF expressions when the i leaks as it does in the OPs example. Another tack on the same question: python 3 cleaned up the variable leakage from inside ZFs to outside. It missed cleaning up the leakage from one step to next. tl;dr version: Beware of mixing up functional and imperative programming Double-beware when you are a language designer From ramit.prasad at jpmorgan.com Fri Jul 13 13:08:16 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 13 Jul 2012 17:08:16 +0000 Subject: adding a simulation mode In-Reply-To: <50004de0$0$6876$e4fe514c@news2.news.xs4all.nl> References: <87liiyr48f.fsf@handshake.de> <4fff8514$0$29965$c3e8da3$5496439d@news.astraweb.com> <50004de0$0$6876$e4fe514c@news2.news.xs4all.nl> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416556225@SCACMX008.exchad.jpmchase.net> > > Please do NOT catch BaseException, since that is the wrong thing to do. > > I would agree if you had said "in production code". > > If you are investigating why a third-party function is stopping your > interpreter, then catching BaseException may tell you that the code > is raising the wrong kind of Exception. Once you know what kind the > function is raising, you should catch only that particular excpetion > subclass. I would say the opposite. In production code usually I want it to recover, log as much information as I need (including sending any notifications), and NOT just die. In development, not catching the exception will give me a full trace back automatically. Why bother with trying to catch and print something when the interpreter will do it for me? Not to mention that removes any hassle of trying to catch the "right" exception or figuring out the best way to print it. I suppose if there are arguments on the exception that were not printed then I might want to catch it, but has been rare in my experience. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Fri Jul 13 13:20:04 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 14 Jul 2012 03:20:04 +1000 Subject: lambda in list comprehension acting funny In-Reply-To: <4deb2389-e20a-4520-964d-7d996cf6b9b4@m2g2000pbv.googlegroups.com> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <4deb2389-e20a-4520-964d-7d996cf6b9b4@m2g2000pbv.googlegroups.com> Message-ID: On Sat, Jul 14, 2012 at 2:46 AM, rusi wrote: > Ok let me restate: if python were to work that way (without the > global) we could say either > a Python chooses to have dynamic scoping of variables > or > b There is a bug in python's scoping rules Or c, there's a declaration at the top: from __future__ import variable_declarations Like braces, it's a MASSIVE improvement to the language, and it's part of a huge conspiracy that it isn't there by default. But all it takes is a little future statement and you're on Python 4000! ChrisA (I shouldn't post at half past three in the morning. I get stupid... er.) From rosuav at gmail.com Fri Jul 13 13:24:13 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 14 Jul 2012 03:24:13 +1000 Subject: adding a simulation mode In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47416556225@SCACMX008.exchad.jpmchase.net> References: <87liiyr48f.fsf@handshake.de> <4fff8514$0$29965$c3e8da3$5496439d@news.astraweb.com> <50004de0$0$6876$e4fe514c@news2.news.xs4all.nl> <5B80DD153D7D744689F57F4FB69AF47416556225@SCACMX008.exchad.jpmchase.net> Message-ID: On Sat, Jul 14, 2012 at 3:08 AM, Prasad, Ramit wrote: > I would say the opposite. In production code usually I want it > to recover, log as much information as I need (including sending > any notifications), and NOT just die. > > In development, not catching the exception will give me a full > trace back automatically. Here's another take on the matter. In development, your script is your execution unit, so you let the interpreter print out your tracebacks. In production, there will usually be one, maybe two subunits (for instance, a TCP-based server might have the socket connection as an execution unit, and possibly a command parser inside that), and at the top of that subunit, you have a broad exception handler that resets that one unit (goes back and accepts another client, or waits for another command). Otherwise, wide-scope exception handling is usually a bad thing. ChrisA From chris at gonnerman.org Fri Jul 13 13:27:50 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Fri, 13 Jul 2012 12:27:50 -0500 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> Message-ID: <50005A96.3010305@gonnerman.org> On 07/13/2012 11:00 AM, Prasad, Ramit wrote: >> Well "neat tricks" aside, I am of the firm belief that deleting files should >> never be possible whilst they are open. > This is one of the few instances I think Windows does something better > than OS X. Windows will check before you attempt to delete (i.e. move > to Recycling Bin) while OS X will move a file to Trash quite happily > only tell me it cannot remove the file when I try to empty the Trash. While I was trained in the Unix way, and believe it is entirely appropriate to delete an open file. Even if I my program is the opener. It's just too handy to have temp files that disappear on their own. As opposed to periodically going to %TEMP% and deleting them manually. Gah. -- Chris. From hansmu at xs4all.nl Fri Jul 13 13:53:16 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Jul 2012 19:53:16 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> On 13/07/12 18:12:40, Prasad, Ramit wrote: >> VERBOSE = True >> >> def function(arg): >> if VERBOSE: >> print("calling function with arg %r" % arg) >> process(arg) >> >> def caller(): >> VERBOSE = False >> function(1) >> >> --------------------------------------------- >> Python semantics: function sees VERBOSE False >> Haskell semantics: function sees VERBOSE True >>>> def caller(): > ... VERBOSE = False > ... function(1) >>>> def function(arg): > ... if VERBOSE: > ... print("calling function with arg %r" % arg) > ... >>>> VERBOSE = True >>>> caller() > calling function with arg 1 > > I might be being OCD, but caller needs `global VERBOSE` for that to > work as you explain. That would be quite different from what Rusi is after. If you add `global VERBOSE` to `caller`, then there is only one variable named `VERBOSE` and what `function` does, depends on the most recent assignment to that variable. If you remove your `global VERBOSE`, then there are two variables by that name, one global and one local to `caller`. In that case, there is the question of which one `function` will use. The function `function` refers to a variable `VERBOSE` that isn't local. In some programming langauages, the interpreter would then scan the call stack at run-time, looking for a scope where that name is defined. It would find the local one in `caller`. This is known as "dynamic binding". Other interpreters use the `VERBOSE` that was in scope at the point in the program text where `function` was defined. In this case, that would be the global one. This is called "lexical binding". Some programming languages allow you to indicate on a per- variable basis whether you want dynamic or lexical binding. Python is firmly in the lexical camp. Dynamic binding is not available in Python, and never will be. Hope this helps, -- HansM From ramit.prasad at jpmorgan.com Fri Jul 13 13:59:59 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 13 Jul 2012 17:59:59 +0000 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: <50005A96.3010305@gonnerman.org> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> Message-ID: <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> > >> Well "neat tricks" aside, I am of the firm belief that deleting files > should > >> never be possible whilst they are open. > > This is one of the few instances I think Windows does something better > > than OS X. Windows will check before you attempt to delete (i.e. move > > to Recycling Bin) while OS X will move a file to Trash quite happily > > only tell me it cannot remove the file when I try to empty the Trash. > While I was trained in the Unix way, and believe it is entirely > appropriate to delete an open file. Even if I my program is the opener. > It's just too handy to have temp files that disappear on their own. > > As opposed to periodically going to %TEMP% and deleting them manually. Gah. In my experience things that are "too handy" are usually breaking what I consider "right". That being said, I am not entirely sure what I think is "right" in this circumstance. I suppose it depends on if I am the person deleting or the person who is looking at a file that is being deleted. Or the user who just wants the stupid computer to just Work. I lean slightly towards the POSIX handling with the addition that any additional write should throw an error. You are now saving to a file that will not exist the moment you close it and that is probably not expected. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Jul 13 14:06:31 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 13 Jul 2012 18:06:31 +0000 Subject: lambda in list comprehension acting funny In-Reply-To: <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> Message-ID: <5B80DD153D7D744689F57F4FB69AF474165562FE@SCACMX008.exchad.jpmchase.net> > >> VERBOSE = True > >> > >> def function(arg): > >> if VERBOSE: > >> print("calling function with arg %r" % arg) > >> process(arg) > >> > >> def caller(): > >> VERBOSE = False > >> function(1) > >> > >> --------------------------------------------- > >> Python semantics: function sees VERBOSE False > >> Haskell semantics: function sees VERBOSE True > > >>>> def caller(): > > ... VERBOSE = False > > ... function(1) > >>>> def function(arg): > > ... if VERBOSE: > > ... print("calling function with arg %r" % arg) > > ... > >>>> VERBOSE = True > >>>> caller() > > calling function with arg 1 > > > > I might be being OCD, but caller needs `global VERBOSE` for that to > > work as you explain. > > That would be quite different from what Rusi is after. > > If you add `global VERBOSE` to `caller`, then there is only one > variable named `VERBOSE` and what `function` does, depends on > the most recent assignment to that variable. > > If you remove your `global VERBOSE`, then there are two > variables by that name, one global and one local to `caller`. > In that case, there is the question of which one `function` > will use. > But that is not what Rusi writes. "Python semantics: function sees VERBOSE False" <- function will not see False without the use of global. > The function `function` refers to a variable `VERBOSE` that > isn't local. In some programming langauages, the interpreter > would then scan the call stack at run-time, looking for a scope > where that name is defined. It would find the local one in > `caller`. This is known as "dynamic binding". > > Other interpreters use the `VERBOSE` that was in scope at > the point in the program text where `function` was defined. > In this case, that would be the global one. This is called > "lexical binding". > > Some programming languages allow you to indicate on a per- > variable basis whether you want dynamic or lexical binding. > > Python is firmly in the lexical camp. Dynamic binding is not > available in Python, and never will be. True and a good explanation, but not what I understood Rusi to mean. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Fri Jul 13 14:19:24 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 14 Jul 2012 04:19:24 +1000 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> Message-ID: On Sat, Jul 14, 2012 at 3:59 AM, Prasad, Ramit wrote: > I lean slightly towards the POSIX handling with the addition that > any additional write should throw an error. You are now saving to > a file that will not exist the moment you close it and that is probably > not expected. There are several different possible "right behaviors" here, but they depend more on the application than anything else. With a log file, for instance, the act of deleting it is more a matter of truncating it (dispose of the old history), so the right thing to do is to start a fresh file. Solution: Close the file and re-open it periodically. But I don't know of an efficient way to do that with Windows semantics. Renaming/moving an open file in order to perform log rotation isn't all that easy. ChrisA From hansmu at xs4all.nl Fri Jul 13 14:28:13 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Jul 2012 20:28:13 +0200 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> Message-ID: <500068bd$0$6893$e4fe514c@news2.news.xs4all.nl> On 13/07/12 19:59:59, Prasad, Ramit wrote: > I lean slightly towards the POSIX handling with the addition that > any additional write should throw an error. You are now saving to > a file that will not exist the moment you close it and that is > probably not expected. I'd say: it depends. If the amount of data your script needs to process does not fit in RAM, then you may want to write some of it to a temporary file. On a Posix system, it's entirely normal to unlink() a temp file first thing after you've created it. The expectation is that the file will continue to exists, and be writeable, until you close it. In fact, there's a function in the standard library named tempfile.TemporaryFile that does exactly that: create a file and unlink it immediately. This function would be useless if you couldn't write to your temporary file. Hope this helps, -- HansM From ian.g.kelly at gmail.com Fri Jul 13 14:54:02 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 13 Jul 2012 12:54:02 -0600 Subject: lambda in list comprehension acting funny In-Reply-To: <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> Message-ID: On Fri, Jul 13, 2012 at 11:53 AM, Hans Mulder wrote: > The function `function` refers to a variable `VERBOSE` that > isn't local. In some programming langauages, the interpreter > would then scan the call stack at run-time, looking for a scope > where that name is defined. It would find the local one in > `caller`. This is known as "dynamic binding". > > Other interpreters use the `VERBOSE` that was in scope at > the point in the program text where `function` was defined. > In this case, that would be the global one. This is called > "lexical binding". > > Some programming languages allow you to indicate on a per- > variable basis whether you want dynamic or lexical binding. > > Python is firmly in the lexical camp. Dynamic binding is not > available in Python, and never will be. I don't believe that dynamic vs. lexical binding is what rusi was attempting to describe. If he was, then Python and Haskell would be a bad comparison since both are lexical. Rather, I think what he was trying to show was capture by reference vs. capture by value in the context of closures. Python uses capture by reference, and so the upvalue is the value of that reference at the time the closure is called. Haskell uses capture by value, and the upvalue is the value at the time of definition. I've also seen the distinction described as "early" vs. "late" binding on this list, but I'm not sure how precise that is -- I believe that terminology more accurately describes whether method and attribute names are looked up at compile-time or at run-time, late binding being the feature that makes duck typing possible. Cheers, Ian From hansmu at xs4all.nl Fri Jul 13 15:26:03 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 13 Jul 2012 21:26:03 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> Message-ID: <5000764c$0$6941$e4fe514c@news2.news.xs4all.nl> On 13/07/12 20:54:02, Ian Kelly wrote: > I've also seen the distinction described as "early" vs. "late" binding > on this list, but I'm not sure how precise that is -- I believe that > terminology more accurately describes whether method and attribute > names are looked up at compile-time or at run-time, late binding being > the feature that makes duck typing possible. I think that these terms describe the problem at the start of this thread: the OP was expecting early binding. However, Python does late binding, or "acts funny" as it says in the subject line. -- HansM From rodrick.brown at gmail.com Fri Jul 13 15:56:21 2012 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Fri, 13 Jul 2012 15:56:21 -0400 Subject: Keeping the Console Open with IDLE In-Reply-To: <0040b385-2dbc-4b3b-af97-62a77686d2bb@googlegroups.com> References: <0040b385-2dbc-4b3b-af97-62a77686d2bb@googlegroups.com> Message-ID: <6405430962613257681@unknownmsgid> I think you can use pythonw.exe which will read stdin and for any input before closing. (I read this a while back, ma guy here.) Sent from my iPhone On Jul 13, 2012, at 7:27 AM, "summerholidaylearning at gmail.com" wrote: > On Friday, February 20, 2009 4:06:42 AM UTC, W. eWatson wrote: >> I'm using IDLE for editing, but execute programs directly. If there are >> execution or "compile" errors, the console closes before I can see what it >> contains. How do I prevent that? >> -- >> W. eWatson >> >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> Web Page: <www.speckledwithstars.net/> > > Thanks this solved my problem too(the same issue - I was also double clicking instead of right clicking - edit with IDLE - F5 to run) > -- > http://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Fri Jul 13 15:57:34 2012 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 13 Jul 2012 20:57:34 +0100 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: <500068bd$0$6893$e4fe514c@news2.news.xs4all.nl> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> <500068bd$0$6893$e4fe514c@news2.news.xs4all.nl> Message-ID: <50007DAE.4050707@mrabarnett.plus.com> On 13/07/2012 19:28, Hans Mulder wrote: > On 13/07/12 19:59:59, Prasad, Ramit wrote: > >> I lean slightly towards the POSIX handling with the addition that >> any additional write should throw an error. You are now saving to >> a file that will not exist the moment you close it and that is >> probably not expected. > Strictly speaking, the file does exist, it's just that there are no names referring to it. When any handles to it are also closed, the file _can_ truly be deleted. As has been said before, in the *nix world, "unlink" _doesn't_ delete a file, it deletes a name. > I'd say: it depends. > > If the amount of data your script needs to process does not fit > in RAM, then you may want to write some of it to a temporary file. > On a Posix system, it's entirely normal to unlink() a temp file > first thing after you've created it. The expectation is that the > file will continue to exists, and be writeable, until you close it. > > In fact, there's a function in the standard library named > tempfile.TemporaryFile that does exactly that: create a file > and unlink it immediately. This function would be useless > if you couldn't write to your temporary file. > It's possible to create a temporary file even in Windows. From chris at gonnerman.org Fri Jul 13 16:15:13 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Fri, 13 Jul 2012 15:15:13 -0500 Subject: How to safely maintain a status file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> Message-ID: <500081D1.2000003@gonnerman.org> On 07/13/2012 12:59 PM, Prasad, Ramit wrote: > I lean slightly towards the POSIX handling with the addition that any > additional write should throw an error. You are now saving to a file > that will not exist the moment you close it and that is probably not > expected. Ramit But if I created, then deleted it while holding an open file descriptor, it is entirely likely that I intend to write to it. I'll admit, these days there are those in the Unix/Linux community that consider using an anonymous file a bad idea; I'm just not one of them. -- Chris. From lists at cheimes.de Fri Jul 13 16:21:39 2012 From: lists at cheimes.de (Christian Heimes) Date: Fri, 13 Jul 2012 22:21:39 +0200 Subject: [Python] RE: How to safely maintain a status file In-Reply-To: <50007DAE.4050707@mrabarnett.plus.com> References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> <500068bd$0$6893$e4fe514c@news2.news.xs4all.nl> <50007DAE.4050707@mrabarnett.plus.com> Message-ID: Am 13.07.2012 21:57, schrieb MRAB: > It's possible to create a temporary file even in Windows. Windows has a open() flag named O_TEMPORARY for temporary files. With O_TEMPORARY the file is removed from disk as soon as the file handle is closed. On POSIX OS it's common practice to unlink temporary files immediately after the open() call. From anthra.norell at bluewin.ch Fri Jul 13 16:24:59 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Fri, 13 Jul 2012 22:24:59 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> <1342119234.2313.42.camel@hatchbox-one> Message-ID: <1342211099.2350.68.camel@hatchbox-one> On Fri, 2012-07-13 at 09:26 +0200, Peter Otten wrote: > Frederic Rentsch wrote: > > > I'm sorry I can't post an intelligible piece that does NOT work. I > > obviously can't post the whole thing. > > How about a pastebin then? Or even bitbucket/github as you need to track > changes anyway? > > > It is way too convoluted. > > "Convoluted" code is much easier to debug than no code ;) > > Another random idea: run your code on a more recent python/tcl installation. > If you are lucky you get a different error. > So many good ideas! I can hardly keep up. Let me try anyway. I hesitate to ask dumb questions, but I guess I have to. What is python/tcl? I enlisted Google, Synaptic, apt-cache, apt-get, dpkg and scouring the profusion I couldn't detect any actionable piece of information, undoubtedly due to my modest expertise in matters of system administration. I next spent a day with an attempt to upgrade to Python 2.7.3, figuring that that might simultaneously take care of upgrading tcl. Accustomed to installing packages I had to venture into the unknown territory of compiling source, because no package was available. (Windows, Apple, yes. Linux, no). The compile went smoothly, but ended like this: ... build finished, but the necessary bits to build these modules were not found: _bsddb _curses _curses_panel _sqlite3 _ssl _tkinter bsddb185 bz2 dbm gdbm readline sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. I didn't know what to look for in setup.py, spent a couple of hours turning stones and encountered evidence of a bunch of missing header files, probably of other modules which I had installed rather than compiled. 2.7.3 came up in terminals, but not in an IDLE window. No wonder, _tkinter was reported not found; and so many others with it that, anxious to get on, I stopped venturing further into this labyrinth, erased everything 2.7.3 and now I'm back to 2.6 and would greatly appreciate advice on upgrading python/tcl. I shall look at pastebin and bitbucket/github right away. Frederic From ian at excess.org Fri Jul 13 16:54:48 2012 From: ian at excess.org (Ian Ward) Date: Fri, 13 Jul 2012 16:54:48 -0400 Subject: ANN: Urwid 1.0.2 Message-ID: Announcing Urwid 1.0.2 ---------------------- Urwid home page: http://excess.org/urwid/ Manual: http://excess.org/urwid/wiki/UrwidManual Tarball: http://excess.org/urwid/urwid-1.0.2.tar.gz About this release: =================== This is a stable bug-fix-only release. A number of bugs that could cause Urwid to crash in normal use have been fixed. Upgrading is recommended. New in 1.0.2: ============= * Fix for a bug when entering Unicode text into an Edit widget with a bytes caption * Fix a regression when not running in UTF-8 mode * Fix for a MainLoop.remove_watch_pipe() bug * Fix for a bug when packing empty Edit widgets * Fix for a ListBox "contents too long" error with very large Edit widgets * Prevent ListBoxes from selecting 0-height selectable widgets when moving up or down * Fix a number of bugs caused by 0-height widgets in a ListBox About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, Unicode support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From jeandubois314 at gmail.com Fri Jul 13 17:12:57 2012 From: jeandubois314 at gmail.com (Jean Dubois) Date: Fri, 13 Jul 2012 14:12:57 -0700 (PDT) Subject: Python and Qt4 Designer In-Reply-To: References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: Op vrijdag 13 juli 2012 03:52:51 UTC+2 schreef Vincent Vande Vyvre het volgende: > On 12/07/12 08:42, Jean Dubois wrote: > > On 12 jul, 02:59, Vincent Vande Vyvre <vincent.vandevy... at swing.be> > > wrote: > >> On 11/07/12 17:37, Jean Dubois wrote: > >> > >> > >> > >> > >> > >> > >> > >>> I'm trying to combine python-code made with QT4 designer with plain > >>> python statements like > >>> file = open("test","w") > >>> Can anyone tell me what I have to add to the following code just to > >>> open a file when clicking on the load-button and closing it by > >>> clicking on the save button. > >>> #!/usr/bin/env python > >>> # -*- coding: utf-8 -*- > >>> # Form implementation generated from reading ui file 'test.ui' > >>> # > >>> # Created: Wed Jul 11 17:21:35 2012 > >>> # by: PyQt4 UI code generator 4.8.3 > >>> # > >>> # WARNING! All changes made in this file will be lost! > >>> from PyQt4 import QtCore, QtGui > >>> try: > >>> _fromUtf8 = QtCore.QString.fromUtf8 > >>> except AttributeError: > >>> _fromUtf8 = lambda s: s > >>> class Ui_Form(object): > >>> def setupUi(self, Form): > >>> Form.setObjectName(_fromUtf8("Form")) > >>> Form.resize(400, 300) > >>> self.widget = QtGui.QWidget(Form) > >>> self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) > >>> self.widget.setObjectName(_fromUtf8("widget")) > >>> self.horizontalLayout = QtGui.QHBoxLayout(self.widget) > >>> self.horizontalLayout.setMargin(0) > >>> self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) > >>> self.pushButton_2 = QtGui.QPushButton(self.widget) > >>> self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) > >>> self.horizontalLayout.addWidget(self.pushButton_2) > >>> self.pushButton = QtGui.QPushButton(self.widget) > >>> self.pushButton.setObjectName(_fromUtf8("pushButton")) > >>> self.horizontalLayout.addWidget(self.pushButton) > >>> self.retranslateUi(Form) > >>> QtCore.QMetaObject.connectSlotsByName(Form) > >>> def retranslateUi(self, Form): > >>> Form.setWindowTitle(QtGui.QApplication.translate("Form", > >>> "Form", None, QtGui.QApplication.UnicodeUTF8)) > >>> self.pushButton_2.setText(QtGui.QApplication.translate("Form", > >>> "Save file", None, QtGui.QApplication.UnicodeUTF8)) > >>> self.pushButton.setText(QtGui.QApplication.translate("Form", > >>> "Load file", None, QtGui.QApplication.UnicodeUTF8)) > >>> if __name__ == "__main__": > >>> import sys > >>> app = QtGui.QApplication(sys.argv) > >>> Form = QtGui.QWidget() > >>> ui = Ui_Form() > >>> ui.setupUi(Form) > >>> Form.show() > >>> sys.exit(app.exec_()) > >>> thanks in advance > >>> jean > >> Connect the signal clicked of your's buttons to your's functions. > >> > >> self.pushButton.clicked.connect(self.my_func) > >> > >> Here's all the truth: > >> > >> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_... > >> > >> -- > >> Vincent V.V. > >> Oqapy <https://launchpad.net/oqapy> . Qarte+7 > >> <https://launchpad.net/qarte+7> . PaQager <https://launchpad.net/paqager> > > thanks for the reference, could you just supply a small example for > > the code above to get me started? > > > > thanks in advance > > jean > Just add the connection at the end of the Ui_Form class and, of course, > your function. > > You can find numbers of examples in your PyQt4 install folder. > On my machine is located at /usr/share/doc/python-qt4-doc/examples > > And, for more inspiration, have a look at this site: > http://diotavelli.net/PyQtWiki/ > > -- > Vincent V.V. > Oqapy <https://launchpad.net/oqapy> . Qarte > <https://launchpad.net/qarte> . PaQager <https://launchpad.net/paqager> Thanks for the extra docu references regards, jean From jeandubois314 at gmail.com Fri Jul 13 17:12:57 2012 From: jeandubois314 at gmail.com (Jean Dubois) Date: Fri, 13 Jul 2012 14:12:57 -0700 (PDT) Subject: Python and Qt4 Designer In-Reply-To: References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: Op vrijdag 13 juli 2012 03:52:51 UTC+2 schreef Vincent Vande Vyvre het volgende: > On 12/07/12 08:42, Jean Dubois wrote: > > On 12 jul, 02:59, Vincent Vande Vyvre <vincent.vandevy... at swing.be> > > wrote: > >> On 11/07/12 17:37, Jean Dubois wrote: > >> > >> > >> > >> > >> > >> > >> > >>> I'm trying to combine python-code made with QT4 designer with plain > >>> python statements like > >>> file = open("test","w") > >>> Can anyone tell me what I have to add to the following code just to > >>> open a file when clicking on the load-button and closing it by > >>> clicking on the save button. > >>> #!/usr/bin/env python > >>> # -*- coding: utf-8 -*- > >>> # Form implementation generated from reading ui file 'test.ui' > >>> # > >>> # Created: Wed Jul 11 17:21:35 2012 > >>> # by: PyQt4 UI code generator 4.8.3 > >>> # > >>> # WARNING! All changes made in this file will be lost! > >>> from PyQt4 import QtCore, QtGui > >>> try: > >>> _fromUtf8 = QtCore.QString.fromUtf8 > >>> except AttributeError: > >>> _fromUtf8 = lambda s: s > >>> class Ui_Form(object): > >>> def setupUi(self, Form): > >>> Form.setObjectName(_fromUtf8("Form")) > >>> Form.resize(400, 300) > >>> self.widget = QtGui.QWidget(Form) > >>> self.widget.setGeometry(QtCore.QRect(10, 20, 146, 25)) > >>> self.widget.setObjectName(_fromUtf8("widget")) > >>> self.horizontalLayout = QtGui.QHBoxLayout(self.widget) > >>> self.horizontalLayout.setMargin(0) > >>> self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) > >>> self.pushButton_2 = QtGui.QPushButton(self.widget) > >>> self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) > >>> self.horizontalLayout.addWidget(self.pushButton_2) > >>> self.pushButton = QtGui.QPushButton(self.widget) > >>> self.pushButton.setObjectName(_fromUtf8("pushButton")) > >>> self.horizontalLayout.addWidget(self.pushButton) > >>> self.retranslateUi(Form) > >>> QtCore.QMetaObject.connectSlotsByName(Form) > >>> def retranslateUi(self, Form): > >>> Form.setWindowTitle(QtGui.QApplication.translate("Form", > >>> "Form", None, QtGui.QApplication.UnicodeUTF8)) > >>> self.pushButton_2.setText(QtGui.QApplication.translate("Form", > >>> "Save file", None, QtGui.QApplication.UnicodeUTF8)) > >>> self.pushButton.setText(QtGui.QApplication.translate("Form", > >>> "Load file", None, QtGui.QApplication.UnicodeUTF8)) > >>> if __name__ == "__main__": > >>> import sys > >>> app = QtGui.QApplication(sys.argv) > >>> Form = QtGui.QWidget() > >>> ui = Ui_Form() > >>> ui.setupUi(Form) > >>> Form.show() > >>> sys.exit(app.exec_()) > >>> thanks in advance > >>> jean > >> Connect the signal clicked of your's buttons to your's functions. > >> > >> self.pushButton.clicked.connect(self.my_func) > >> > >> Here's all the truth: > >> > >> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_... > >> > >> -- > >> Vincent V.V. > >> Oqapy <https://launchpad.net/oqapy> . Qarte+7 > >> <https://launchpad.net/qarte+7> . PaQager <https://launchpad.net/paqager> > > thanks for the reference, could you just supply a small example for > > the code above to get me started? > > > > thanks in advance > > jean > Just add the connection at the end of the Ui_Form class and, of course, > your function. > > You can find numbers of examples in your PyQt4 install folder. > On my machine is located at /usr/share/doc/python-qt4-doc/examples > > And, for more inspiration, have a look at this site: > http://diotavelli.net/PyQtWiki/ > > -- > Vincent V.V. > Oqapy <https://launchpad.net/oqapy> . Qarte > <https://launchpad.net/qarte> . PaQager <https://launchpad.net/paqager> Thanks for the extra docu references regards, jean From breamoreboy at yahoo.co.uk Fri Jul 13 18:16:49 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 13 Jul 2012 23:16:49 +0100 Subject: Python professional certification Message-ID: Google tells me that various certifications are available but I'd like to know if any of these are approved by the PSF or whoever would be responsible? If there's anything out there I've missed it :-( -- Cheers. Mark Lawrence. From tjreedy at udel.edu Fri Jul 13 19:09:20 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jul 2012 19:09:20 -0400 Subject: code review In-Reply-To: References: <87wr2oecf6.fsf <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: >From now on, for each operator I would have to remember wether it > is a supposedly comparison operator or not. I believe the following rule is true: if a op b is True or False raises, then op is a potentially chained comparison operation. They are (not) equal (and (not) is), the 4 order comparisons, and (not) in. 'in' should be the only surprise and most confusing. >>> 1 < 3 in {3,4} True >>> 3 in {3,4} < {4} False 'and' and 'or' are not included because they do not always return a bool, and indeed, they are not binary operators in the usual sense because of short-circuiting. -- Terry Jan Reedy From tjreedy at udel.edu Fri Jul 13 19:23:53 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Jul 2012 19:23:53 -0400 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: <1342211099.2350.68.camel@hatchbox-one> References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> <1342119234.2313.42.camel@hatchbox-one> <1342211099.2350.68.camel@hatchbox-one> Message-ID: On 7/13/2012 4:24 PM, Frederic Rentsch wrote: > On Fri, 2012-07-13 at 09:26 +0200, Peter Otten wrote: >> Another random idea: run your code on a more recent python/tcl installation. That might have been clearer as python + tcl/tk installation. > I next spent a day with an attempt to upgrade to Python 2.7.3, > figuring that that might simultaneously take care of upgrading tcl. No, two completely separate actions. > ... build finished, but the necessary bits to build these modules were > not found: > > _bsddb > _curses > _curses_panel > _sqlite3 > _ssl > _tkinter > bsddb185 > bz2 > dbm > gdbm > readline > sunaudiodev I believe _tkinter is the only one of those you need to run idle. You need tcl/tk installed/compiled first to compile python with _tkinter. Easier on *nix than windows. Many *nix systems come with tcl/tk or easily install it with their package managers (same with some of the other prerequisites for other modules). -- Terry Jan Reedy From ethan at stoneleaf.us Fri Jul 13 20:00:06 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 13 Jul 2012 17:00:06 -0700 Subject: Python professional certification In-Reply-To: References: Message-ID: <5000B686.7040104@stoneleaf.us> Mark Lawrence wrote: > Google tells me that various certifications are available but I'd like > to know if any of these are approved by the PSF or whoever would be > responsible? If there's anything out there I've missed it :-( > There is an O'Reilly Python Certification class offered in conjunction with the Illinois Institute of Technology (or something like that) which was created by Steve Holden, and taught by him and a couple others. It's a great course of four classes. ~Ethan~ From gelonida at gmail.com Fri Jul 13 21:00:05 2012 From: gelonida at gmail.com (Gelonida N) Date: Sat, 14 Jul 2012 03:00:05 +0200 Subject: howto do a robust simple cross platform beep Message-ID: Hi, I just want to use a beep command that works cross platform. I tried the simplest approach (just printing the BEL character '\a' chr(7) to the console. This fails on my Ubuntu 12.04 host, as the pcspkr is in the list of the blacklisted kernel modules. I found another snippet trying to push a sine wave directly to /dev/audio but I don't have write permissions to /dev/audio. Other solutions seem to suggest to play a wav file, but of course first I had to write code creating me a wav file. How do others handle simple beeps? I just want to use them as alert, when certain events occur within a very long running non GUI application. Thanks for any info. What I do at the moment is: For Windows I use winsound.Beep For Linux I create some raw data and pipe it into sox's 'play' command. I don't consider this very elegant. From steve+comp.lang.python at pearwood.info Fri Jul 13 21:53:42 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 14 Jul 2012 01:53:42 GMT Subject: How to safely maintain a status file References: <4FF9F454.40207@shopzeus.com> <4ffecef4$0$6877$e4fe514c@news2.news.xs4all.nl> <4FFF0CB7.3030007@shopzeus.com> <4fff926b$0$29965$c3e8da3$5496439d@news.astraweb.com> <62e90523-a160-4e28-8109-9ce32d8952e1@googlegroups.com> <5B80DD153D7D744689F57F4FB69AF474165560E7@SCACMX008.exchad.jpmchase.net> <50005A96.3010305@gonnerman.org> <5B80DD153D7D744689F57F4FB69AF474165562E0@SCACMX008.exchad.jpmchase.net> Message-ID: <5000d126$0$29995$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 15:15:13 -0500, Chris Gonnerman wrote: > On 07/13/2012 12:59 PM, Prasad, Ramit wrote: >> I lean slightly towards the POSIX handling with the addition that any >> additional write should throw an error. You are now saving to a file >> that will not exist the moment you close it and that is probably not >> expected. Ramit > But if I created, then deleted it while holding an open file descriptor, > it is entirely likely that I intend to write to it. I'll admit, these > days there are those in the Unix/Linux community that consider using an > anonymous file a bad idea; I'm just not one of them. A badly-behaved application can write oodles and oodles of data to an unlinked file, which has the result of temporarily using up disk space that doesn't show up when you do an ls. For an inexperienced system administrator, this may appear mysterious. The solution is to us lsof to identify the unlinked file, which gives you the process id of the application, which you can then kill. As soon as you do that, the space is freed up again. Like all powerful tools, unlinked files can be abused. Underpowered tools can't be abused, but nor can they be used. -- Steven From rustompmody at gmail.com Fri Jul 13 22:31:24 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 19:31:24 -0700 (PDT) Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> Message-ID: <6d0f3582-0e34-4fa1-926d-7725ba275410@q5g2000pba.googlegroups.com> On Jul 13, 10:53?pm, Hans Mulder wrote: > If you add `global VERBOSE` to `caller`, then there is only one > variable named `VERBOSE` and what `function` does, depends on > the most recent assignment to that variable. > > If you remove your `global VERBOSE`, then there are two > variables by that name, one global and one local to `caller`. > In that case, there is the question of which one `function` > will use. Good point. See below. > > The function `function` refers to a variable `VERBOSE` that > isn't local. ?In some programming langauages, the interpreter > would then scan the call stack at run-time, looking for a scope > where that name is defined. ?It would find the local one in > `caller`. ?This is known as "dynamic binding". > > Other interpreters use the `VERBOSE` that was in scope at > the point in the program text where `function` was defined. > In this case, that would be the global one. ?This is called > "lexical binding". > > Some programming languages allow you to indicate on a per- > variable basis whether you want dynamic or lexical binding. > > Python is firmly in the lexical camp. ?Dynamic binding is not > available in Python, and never will be. Thats a good intention. The question is whether it is uniformly realized. Consider the following def foo(x): i = 100 if x: j = [i for i in range(10)] return i else: return i In python 2 two different 'i's could be returned. In python3 only one i can be returned. One could call it dynamic binding. Evidently Guido thinks it a bug which is why he changed it. The leakage of i in the OPs question is the same kind of bug. tl;dr version: This is 2012. Dynamic binding is considered a bug even by the lisp community where it originated. Lets at least call it a feature and a gotcha From steve+comp.lang.python at pearwood.info Fri Jul 13 23:19:12 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 14 Jul 2012 03:19:12 GMT Subject: howto do a robust simple cross platform beep References: Message-ID: <5000e530$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sat, 14 Jul 2012 03:00:05 +0200, Gelonida N wrote: > How do others handle simple beeps? > > I just want to use them as alert, when certain events occur within a > very long running non GUI application. Why? Do you hate your users? > What I do at the moment is: > > For Windows I use winsound.Beep > > For Linux I create some raw data and pipe it into sox's 'play' command. > > I don't consider this very elegant. There is no cross-platform way to play a beep. Every few years, people complain that Python doesn't have a standard way to play a simple alert sound. Why ask for volunteers to write and maintain the code, and suddenly they go silent. -- Steven From steve+comp.lang.python at pearwood.info Fri Jul 13 23:43:24 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 14 Jul 2012 03:43:24 GMT Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <6d0f3582-0e34-4fa1-926d-7725ba275410@q5g2000pba.googlegroups.com> Message-ID: <5000eadb$0$29995$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 19:31:24 -0700, rusi wrote: > Consider the following > > def foo(x): > i = 100 > if x: > j = [i for i in range(10)] > return i > else: > return i A simpler example: def foo(): i = 100 j = [i for i in range(10)] return i In Python 3, foo() returns 100; in Python 2, it returns 9. > In python 2 two different 'i's could be returned. In python3 only one i > can be returned. > One could call it dynamic binding. One could also call it a tractor, but it isn't either of those things. The difference is whether or not list comprehensions create their own scope. In Python 2, they don't; in Python 3, they do. Personally I don't have an opinion as to which is better, but in neither case does this have any thing to do with lexical versus dynamic binding. > Evidently Guido thinks it a bug which is why he changed it. It was a case that either list comps be changed to *not* expose their loop variable, or generator expressions be changed *to* expose their loop variable. The Python 2 situation where list comps and gen expressions have opposite behaviour was unfortunate. > The leakage of i in the OPs question is the same kind of bug. Not at all. The OP was *deliberately* creating a closure using i -- under those circumstances, it would be a bug if i *didn't* leak. The OP's gotcha was: 1) he expected the closure to use early binding, where i in each function was bound to the value of i in the enclosing scope at the moment the function was defined; 2) but Python actually uses late binding for closures, where the value of i in each function is set to the value of i in the enclosing scope when the function is called. As far as I can tell, Python always uses late binding for scopes; the only time it does early binding is for default values of function parameters. -- Steven From rustompmody at gmail.com Sat Jul 14 00:53:10 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 13 Jul 2012 21:53:10 -0700 (PDT) Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <6d0f3582-0e34-4fa1-926d-7725ba275410@q5g2000pba.googlegroups.com> <5000eadb$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <70a01a5b-a884-4d41-b313-da2fefd2d825@l6g2000pbf.googlegroups.com> On Jul 14, 8:43?am, Steven D'Aprano wrote: > On Fri, 13 Jul 2012 19:31:24 -0700, rusi wrote: > > Consider the following > > > def foo(x): > > ? ? i = 100 > > ? ? if x: > > ? ? ? ? j = [i for i in range(10)] > > ? ? ? ? return i > > ? ? else: > > ? ? ? ? return i > > A simpler example: > > def foo(): > ? ? i = 100 > ? ? j = [i for i in range(10)] > ? ? return i > > In Python 3, foo() returns 100; in Python 2, it returns 9. You did not get the point. Converting my example to your format: def foo_steven(n): i = 100 j = [i for i in range(n)] return i $ python3 Python 3.2.3 (default, Jun 26 2012, 00:38:09) [GCC 4.7.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def foo_steven(n): ... i = 100 ... j = [i for i in range(n)] ... return i ... >>> foo_steven(0) 100 >>> foo_steven(4) 100 >>> $ python Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def foo_steven(n): ... i = 100 ... j = [i for i in range(n)] ... return i ... >>> foo_steven(0) 100 >>> foo_steven(3) 2 >>> Python 2: When n>0 comprehension scope i is returned When n=0 function scope i is returned Python 3: The return statement is lexically outside the comprehension and so that outside-scope's i is returned in all cases. From moogyd at yahoo.co.uk Sat Jul 14 01:50:08 2012 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Fri, 13 Jul 2012 22:50:08 -0700 (PDT) Subject: [OT] Simulation Results Managment Message-ID: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Hi, This is a general question, loosely related to python since it will be the implementation language. I would like some suggestions as to manage simulation results data from my ASIC design. For my design, - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of these test cases we have: - a number of properties (P_AA_BB_CC) - For each property, the following information is given - Property name (P_NAME) - Number of times it was checked (within the testcase) N_CHECKED - Number of times if failed (within the testcase) N_FAILED - A simulation runs a testcase with a set of parameters. - Simple example, SLOW_CLOCK, FAST_CLOCK, etc - For the design, I will run regression every night (at least), so I will have results from multiple timestamps We have < 1000 TESTCASES, and < 1000 PROPERTIES. At the moment, I have a script that extracts property information from simulation logfile, and provides single PASS/FAIL and all logfiles stored in a directory structure with timestamps/testnames and other parameters embedded in paths I would like to be easily look at (visualize) the data and answer the questions - When did this property last fail, and how many times was it checked - Is this property checked in this test case. Initial question: How to organize the data within python? For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, N_FAILED I then have to store multiple instances of testcase based on date (and simulation parameters. Any comments, suggestions? Thanks, Steven From steve+comp.lang.python at pearwood.info Sat Jul 14 03:46:45 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 14 Jul 2012 07:46:45 GMT Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <6d0f3582-0e34-4fa1-926d-7725ba275410@q5g2000pba.googlegroups.com> <5000eadb$0$29995$c3e8da3$5496439d@news.astraweb.com> <70a01a5b-a884-4d41-b313-da2fefd2d825@l6g2000pbf.googlegroups.com> Message-ID: <500123e5$0$29995$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 21:53:10 -0700, rusi wrote: > On Jul 14, 8:43?am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> On Fri, 13 Jul 2012 19:31:24 -0700, rusi wrote: >> > Consider the following >> >> > def foo(x): >> > ? ? i = 100 >> > ? ? if x: >> > ? ? ? ? j = [i for i in range(10)] >> > ? ? ? ? return i >> > ? ? else: >> > ? ? ? ? return i >> >> A simpler example: >> >> def foo(): >> ? ? i = 100 >> ? ? j = [i for i in range(10)] >> ? ? return i >> >> In Python 3, foo() returns 100; in Python 2, it returns 9. > > You did not get the point. I got the point. I just thought it was unnecessarily complex and that it doesn't demonstrate what you think it does. > Converting my example to your format: > > def foo_steven(n): > i = 100 > j = [i for i in range(n)] > return i > > $ python3 > Python 3.2.3 (default, Jun 26 2012, 00:38:09) [GCC 4.7.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> def foo_steven(n): > ... i = 100 > ... j = [i for i in range(n)] > ... return i > ... >>>> foo_steven(0) > 100 >>>> foo_steven(4) > 100 Yes, we know that in Python 3, list comprehensions create their own scope, and the loop variable does not leak. > $ python > Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> def foo_steven(n): > ... i = 100 > ... j = [i for i in range(n)] > ... return i > ... >>>> foo_steven(0) > 100 >>>> foo_steven(3) > 2 Yes, we know that in Python 2, list comprehensions don't create their own scope, and consequently the list variable does leak. > Python 2: > When n>0 comprehension scope i is returned > When n=0 function scope i is returned Incorrect. In Python 2, *there is no comprehension scope*. There is only local scope. In Python 2, regardless of the value of n, the local variable i is ALWAYS returned. It just happens that sometimes the local variable i is modified by the list comprehension, and sometimes it isn't. In Python 2, this is no more mysterious than this piece of code: def example(n): i = 100 for i in range(n): pass return i py> example(0) 100 py> example(4) 3 If the loop doesn't execute, the loop variable isn't modified. In Python 2, it doesn't matter whether you use a for-loop or a list comprehension, the loop variable is local to the function. > Python 3: The return statement is lexically outside the comprehension > and so that outside-scope's i is returned in all cases. Correct. In Python 3, list comprehensions now match generator expressions and introduce their own scope which does not effect the local function scope. Some history: http://bugs.python.org/issue510384 http://bugs.python.org/issue1110705 -- Steven From __peter__ at web.de Sat Jul 14 03:47:30 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Jul 2012 09:47:30 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> <1342119234.2313.42.camel@hatchbox-one> <1342211099.2350.68.camel@hatchbox-one> Message-ID: Terry Reedy wrote: > On 7/13/2012 4:24 PM, Frederic Rentsch wrote: >> On Fri, 2012-07-13 at 09:26 +0200, Peter Otten wrote: > >>> Another random idea: run your code on a more recent python/tcl >>> installation. > > That might have been clearer as python + tcl/tk installation. Yes, sorry; I meant that both the python and tcl/tk version matter. You can find out the latter with $ python -c 'import Tkinter as tk; print tk.TclVersion, tk.TkVersion' 8.5 8.5 >> I next spent a day with an attempt to upgrade to Python 2.7.3, >> figuring that that might simultaneously take care of upgrading tcl. > > No, two completely separate actions. > >> ... build finished, but the necessary bits to build these modules were >> not found: >> >> _bsddb >> _curses >> _curses_panel >> _sqlite3 >> _ssl >> _tkinter >> bsddb185 >> bz2 >> dbm >> gdbm >> readline >> sunaudiodev > > I believe _tkinter is the only one of those you need to run idle. > > You need tcl/tk installed/compiled first to compile python with > _tkinter. Easier on *nix than windows. Many *nix systems come with > tcl/tk or easily install it with their package managers (same with some > of the other prerequisites for other modules). If you don't want to compile tcl/tk yourself you need to install the tk-dev package. I recommend that you install libreadline-dev, too -- without readline it is painful to use the interactive interpreter. From ian.g.kelly at gmail.com Sat Jul 14 05:26:53 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 14 Jul 2012 03:26:53 -0600 Subject: code review In-Reply-To: References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Jul 13, 2012 at 5:09 PM, Terry Reedy wrote: > >> From now on, for each operator I would have to remember wether it >> is a supposedly comparison operator or not. > > > I believe the following rule is true: if a op b is True or False raises, I don't follow. Raises what? > then op is a potentially chained comparison operation. They are (not) equal > (and (not) is), the 4 order comparisons, and (not) in. 'in' should be the > only surprise and most confusing. >>>> 1 < 3 in {3,4} > True >>>> 3 in {3,4} < {4} > False > > 'and' and 'or' are not included because they do not always return a bool, > and indeed, they are not binary operators in the usual sense because of > short-circuiting. The only one of those operators that can be said to always return a bool is "is (not)". The others (apart from "and" and "or") all can be overloaded to return anything you want (for example, sqlalchemy overloads them to return expression objects that are later compiled into SQL), and chaining still occurs regardless of the types they are applied to. From dihedral88888 at googlemail.com Sat Jul 14 06:31:12 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 14 Jul 2012 03:31:12 -0700 (PDT) Subject: lambda in list comprehension acting funny In-Reply-To: References: Message-ID: <34872b84-3724-41d0-92ca-b7fec60b0efc@googlegroups.com> Alister? 2012?7?12????UTC+8??5?44?15???? > On Wed, 11 Jul 2012 08:43:11 +0200, Daniel Fetchinson wrote: > > >> funcs = [ lambda x: x**i for i in range( 5 ) ] > >> print funcs[0]( 2 ) > >> print funcs[1]( 2 ) > >> print funcs[2]( 2 ) > >> > >> This gives me > >> > >> 16 16 16 > >> > >> When I was excepting > >> > >> 1 > >> 2 > >> 4 > >> > >> Does anyone know why? > > > > And more importantly, what's the simplest way to achieve the latter? :) > > Having read Steve's explanation in the other thread (which I think has > finally flipped the light switch on lambda for me) it only requires a > minor change > > funcs=[ lambda x,y=i:x**y for i in range(5) ] > > although I cant actually think why this construct would be needed in > practice, how are you actually using it > > > -- > * Simunye is so happy she has her mothers gene's > <Dellaran> you better give them back before she misses them! Uhn, there are 5 objects in the list if not factored well to be executed in the run time. From invis87 at gmail.com Sat Jul 14 07:27:24 2012 From: invis87 at gmail.com (invis) Date: Sat, 14 Jul 2012 04:27:24 -0700 (PDT) Subject: from octave to python Message-ID: <403486d4-6afc-4da6-aadc-7b2a0d4270d0@googlegroups.com> Hello everyone ! I used Octave for matrix computations, but looks like Python will be useful everywhere so it is good idea to migrate (imho ofc). But I am novice here and dont know how to get things that was easy in Octave, for example: [intersect iA iB] = intersect(a, b) To do this in Python I use numpy.intersect1d(numpy.array, numpy.array), but how to get indexces ? P.S. sry for my english, hope you can understand what I mean :) From lists at cheimes.de Sat Jul 14 08:38:28 2012 From: lists at cheimes.de (Christian Heimes) Date: Sat, 14 Jul 2012 14:38:28 +0200 Subject: How to safely maintain a status file In-Reply-To: <4fff7f4c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4FF9F454.40207@shopzeus.com> <4FFEC371.5040703@shopzeus.com> <4fff7f4c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 13.07.2012 03:52, schrieb Steven D'Aprano: > And some storage devices (e.g. hard drives, USB sticks) don't actually > write data permanently even when you sync the device. They just write to > a temporary cache, then report that they are done (liar liar pants on > fire). Only when the cache is full, or at some random time at the > device's choosing, do they actually write data to the physical media. > > The result of this is that even when the device tells you that the data > is synched, it may not be. Yes, that's another issue. Either you have to buy expensive enterprise hardware with UPS batteries or you need to compensate for failures on software level (e.g. Hadoop cluster). We have big storage devices with double redundant controllers, on board buffer batteries, triple redundant power supplies, special RAID disks, multipath IO fiber channel links and external backup solution to keep our data reasonable safe. Christian From invis87 at gmail.com Sat Jul 14 09:17:45 2012 From: invis87 at gmail.com (invis) Date: Sat, 14 Jul 2012 06:17:45 -0700 (PDT) Subject: from octave to python In-Reply-To: <403486d4-6afc-4da6-aadc-7b2a0d4270d0@googlegroups.com> References: <403486d4-6afc-4da6-aadc-7b2a0d4270d0@googlegroups.com> Message-ID: <6fb74b9d-e1ca-4aa8-bd48-dea7f54ff2bb@googlegroups.com> ???????, 14 ???? 2012??., 15:27:24 UTC+4 ???????????? invis ???????: > Hello everyone ! > > I used Octave for matrix computations, but looks like Python will be useful everywhere so it is good idea to migrate (imho ofc). > > But I am novice here and dont know how to get things that was easy in Octave, for example: > [intersect iA iB] = intersect(a, b) > > To do this in Python I use numpy.intersect1d(numpy.array, numpy.array), but how to get indexces ? > > P.S. sry for my english, hope you can understand what I mean :) Answer here: http://stackoverflow.com/questions/11483863/python-intersection-indices-numpy-array From torriem at gmail.com Sat Jul 14 10:45:31 2012 From: torriem at gmail.com (Michael Torrie) Date: Sat, 14 Jul 2012 08:45:31 -0600 Subject: Python and Qt4 Designer In-Reply-To: References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: <5001860B.3060202@gmail.com> On 07/13/2012 03:12 PM, Jean Dubois wrote: > Thanks for the extra docu references In this day and age, I think compiling ui files to code is probably on the way out. Instead you should consider using the ui files directly in your code. This has the advantage of letting you change the gui somewhat without having to recompile all the time. Here is are some links that gives one way of loading and parsing the ui file directly: http://www.riverbankcomputing.com/pipermail/pyqt/2007-April/015902.html http://bitesofcode.blogspot.ca/2011/10/comparison-of-loading-techniques.html From rustompmody at gmail.com Sat Jul 14 13:13:06 2012 From: rustompmody at gmail.com (rusi) Date: Sat, 14 Jul 2012 10:13:06 -0700 (PDT) Subject: Python and Qt4 Designer References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> Message-ID: <1bb0d4df-3937-4d5f-aedb-734e0c54eb85@f9g2000pbd.googlegroups.com> On Jul 14, 7:45?pm, Michael Torrie wrote: > On 07/13/2012 03:12 PM, Jean Dubois wrote: > > > Thanks for the extra docu references > > In this day and age, I think compiling ui files to code is probably on > the way out. ?Instead you should consider using the ui files directly in > your code. ?This has the advantage of letting you change the gui > somewhat without having to recompile all the time. > > Here is are some links that gives one way of loading and parsing the ui > file directly: > > http://www.riverbankcomputing.com/pipermail/pyqt/2007-April/015902.htmlhttp://bitesofcode.blogspot.ca/2011/10/comparison-of-loading-techniqu... I looked at the second link and find code like this: app = None if ( not app ): app = QtGui.QApplication([]) Maybe I'm dense but whats that if doing there? Frankly I seem to be a bit jinxed with gui stuff. A few days ago someone was singing the praises of some new themed tk stuff. I could not get the first two lines -- the imports -- to work and then gave up From dieter at handshake.de Sat Jul 14 13:54:37 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sat, 14 Jul 2012 19:54:37 +0200 Subject: howto do a robust simple cross platform beep References: <5000e530$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87ipdq8bz6.fsf@handshake.de> Steven D'Aprano writes: >> How do others handle simple beeps? >> >> I just want to use them as alert, when certain events occur within a >> very long running non GUI application. > > Why? Do you hate your users? I, too, would find it useful -- for me (although I do not hate myself). Surely, you know an alarm clock. Usually, it gives an audible signal when it is time to do something. A computer can in principle be used as a flexible alarm clock - but it is not so easy with the audible signal... An audible signal has the advantage (over a visual one) that you can recognize it even when you are not looking at the screen (because you are thinking). Unfortunately, I had to give up. My new computer lacks a working speaker... From miki.tebeka at gmail.com Sat Jul 14 14:43:35 2012 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 14 Jul 2012 11:43:35 -0700 (PDT) Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: <7dab9ed5-6109-40ad-9886-55dd99ecefc9@googlegroups.com> > How do others handle simple beeps? http://pymedia.org/ ? I *think* the "big" UI frameworks (Qt, wx ...) have some sound support. From miki.tebeka at gmail.com Sat Jul 14 14:43:35 2012 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 14 Jul 2012 11:43:35 -0700 (PDT) Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: <7dab9ed5-6109-40ad-9886-55dd99ecefc9@googlegroups.com> > How do others handle simple beeps? http://pymedia.org/ ? I *think* the "big" UI frameworks (Qt, wx ...) have some sound support. From rosuav at gmail.com Sat Jul 14 14:49:11 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 15 Jul 2012 04:49:11 +1000 Subject: howto do a robust simple cross platform beep In-Reply-To: <87ipdq8bz6.fsf@handshake.de> References: <5000e530$0$29995$c3e8da3$5496439d@news.astraweb.com> <87ipdq8bz6.fsf@handshake.de> Message-ID: On Sun, Jul 15, 2012 at 3:54 AM, Dieter Maurer wrote: > I, too, would find it useful -- for me (although I do not hate myself). > > Surely, you know an alarm clock. Usually, it gives an audible signal > when it is time to do something. A computer can in principle be used > as a flexible alarm clock - but it is not so easy with the audible signal... > An audible signal has the advantage (over a visual one) that you can > recognize it even when you are not looking at the screen (because you > are thinking). > > Unfortunately, I had to give up. My new computer lacks a working > speaker... There's a simple cheat you can do. Just invoke some other application to produce the sound! My current alarm clock comes in two modes: it either picks a random MIDI file from Gilbert and Sullivan's "Ruddigore", or it plays the "Alice: Madness Returns" theme; in each case it just invokes the file with its default association (see the "start" command in Windows, or "gnome-open" in, well, GNOME). Of course, working speaker IS a prerequisite. ChrisA From clickfirm2007 at gmail.com Sat Jul 14 14:53:50 2012 From: clickfirm2007 at gmail.com (Mohamed Gad) Date: Sat, 14 Jul 2012 11:53:50 -0700 (PDT) Subject: Download Now 4 F.REE .. Watch TV Shows, Music Videos and more Message-ID: <80a1639f-3870-49dc-b515-feb3bd3ce3e4@q29g2000vby.googlegroups.com> Check this amazing offer now .. * Watch TV Shows, Movie Trailers, Music Videos and more! Video Buzz uses the power of the YouTube? API to give you instant access to any video you want! >> http://imgrox.com/x/0/4574/71386/ Enjoy :) >> http://imgrox.com/x/0/4574/71386/ From tjreedy at udel.edu Sat Jul 14 16:42:17 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Jul 2012 16:42:17 -0400 Subject: code review In-Reply-To: References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/14/2012 5:26 AM, Ian Kelly wrote: > On Fri, Jul 13, 2012 at 5:09 PM, Terry Reedy wrote: >> I believe the following rule is true: if a op b is True or False raises, Sorry, left out 'or' in 'or raises' > > I don't follow. Raises what? an Exception. >> then op is a potentially chained comparison operation. They are (not) equal >> (and (not) is), the 4 order comparisons, and (not) in. 'in' should be the >> only surprise and most confusing. >>>>> 1 < 3 in {3,4} >> True >>>>> 3 in {3,4} < {4} >> False >> >> 'and' and 'or' are not included because they do not always return a bool, >> and indeed, they are not binary operators in the usual sense because of >> short-circuiting. > > The only one of those operators that can be said to always return a > bool is "is (not)". The others (apart from "and" and "or") all can be > overloaded to return anything you want OK, add 'by default, without over-rides ;-). or 'for builtin classes'. Python's flexibility makes it really hard to make any general statement. In my book-in-progress, I am currently resorting to saying "In Python*, ..." whenever I know and remember that it is possibly to over-ride the customary behavior described in '...'. -- Terry Jan Reedy From lordgodofglory at gmail.com Sat Jul 14 17:13:49 2012 From: lordgodofglory at gmail.com (Godof Glory) Date: Sat, 14 Jul 2012 14:13:49 -0700 (PDT) Subject: JESUS IS LORD Message-ID: JESUS IS LORD, and believe in your heart that GOD raised HIM from the dead, thou shalt be saved, and thy house.(cf. THE HOLY BIBLE: ROMANS 10:9 and ACTS 16:31b) Have you received THE LORD GOD OF ISRAEL?S MOST BELOVED and ONLY BEGOTTEN SON, THE LORD JESUS CHRIST, to be your personal Lord and Savior? If not, say this prayer: ?LORD GOD, please forgive me of my sins. Thank YOU for YOUR Faithfulness in always being with me and loving me so much to send me YOUR MOST BELOVED and ONLY BEGOTTEN SON, THE LORD JESUS CHRIST, to die on the cross for me. I receive HIM now into my heart and life to be my Lord and Savior. I pray this in the name of GOD, THE FATHER; GOD, THE SON; and GOD, THE HOLY SPIRIT. ? Amen.? ?So let everyone in Israel know for certain that GOD has made this JESUS, whom you crucified, to be both Lord and Messiah!? ACTS 2:36 "For I say unto you, Ye shall not see me henceforth, till ye shall say, Blessed is he that cometh in the name of the Lord." Matthew 23:39 Visit and share with family, friends, fans, and followers: www.BIBLEstudycd.com/Lessons.html May you be blessed abundantly! Hallelujah! THE GOSPEL: http://www.ebible.com/kjv/Matthew http://www.ebible.com/kjv/Mark http://www.ebible.com/kjv/Luke http://www.ebible.com/kjv/John From steve+comp.lang.python at pearwood.info Sat Jul 14 19:29:02 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 14 Jul 2012 23:29:02 GMT Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> Message-ID: <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> On Fri, 13 Jul 2012 12:54:02 -0600, Ian Kelly wrote: > On Fri, Jul 13, 2012 at 11:53 AM, Hans Mulder wrote: >> The function `function` refers to a variable `VERBOSE` that isn't >> local. In some programming langauages, the interpreter would then scan >> the call stack at run-time, looking for a scope where that name is >> defined. It would find the local one in `caller`. This is known as >> "dynamic binding". >> >> Other interpreters use the `VERBOSE` that was in scope at the point in >> the program text where `function` was defined. In this case, that would >> be the global one. This is called "lexical binding". >> >> Some programming languages allow you to indicate on a per- variable >> basis whether you want dynamic or lexical binding. >> >> Python is firmly in the lexical camp. Dynamic binding is not available >> in Python, and never will be. I don't remember whether it is Javascript or PHP that uses dynamic binding, but whichever it is, it is generally considered to be a bad idea, at least as the default or only behaviour. Bash is another language with dynamic binding. Some very old versions of Lisp use dynamic binding, because it was the easiest to implement. Most modern languages use lexical (also known as static) binding, because it is more sensible. Here is an illustration of the difference: suppose we have two modules, library.py and main.py: # library.py x = 23 def func(y): return x + y # main.py import library x = 1000 print func(1) If main.py prints 24 (and it does), then Python is using lexical scoping. But if it prints 1001 (which it doesn't), then it is using dynamic scoping. The obvious problem with dynamic binding is that the behaviour of a function may vary depending on where you call it. > I don't believe that dynamic vs. lexical binding is what rusi was > attempting to describe. If he was, then Python and Haskell would be a > bad comparison since both are lexical. Rather, I think what he was > trying to show was capture by reference vs. capture by value in the > context of closures. Python uses capture by reference, and so the > upvalue is the value of that reference at the time the closure is > called. Haskell uses capture by value, and the upvalue is the value at > the time of definition. I don't think "by reference" versus "by value" are good terms to use here, since they risk conflating the issue with "call by reference" versus "call by value" semantics. I prefer "late" versus "early", as you suggest below. > I've also seen the distinction described as "early" vs. "late" binding > on this list, but I'm not sure how precise that is -- I believe that > terminology more accurately describes whether method and attribute names > are looked up at compile-time or at run-time, Not necessarily *compile* time, but the distinction is between when the function is defined (which may at compile time, or it may be at run time) versus when the function is called. I think that gets to the heart of the issue, not whether the capture copies a value or a reference. At some point, the capture must make use of the value: whether it does so via a direct C-style memory location copy, or an object pointer, or some other mechanism, is irrelevant. What matters is whether that value is grabbed at the time the closure is created, or when the closure is called. > late binding being the > feature that makes duck typing possible. That is conflating two entirely distinct subjects. Python 1.5 had duck- typing but no closures, so the one certainly does not depend on the other. Duck-typing is more a philosophy than a language feature: the language must be typed, and the programmer must prefer to program to a protocol or a specification rather than to membership of a type. -- Steven From leif.poorman at gmail.com Sat Jul 14 19:56:41 2012 From: leif.poorman at gmail.com (Leif) Date: Sat, 14 Jul 2012 16:56:41 -0700 (PDT) Subject: Request for useful functions on dicts Message-ID: <38c6d4cb-89b3-4f78-a966-be5ddccec845@googlegroups.com> Hi, everybody. I am trying to collect all the functions I've found useful for working with dicts into a library: https://github.com/leifp/dictutil If you have a favorite dict-related func / class, or know of similar projects, please let me know (or open an issue on github). Bear in mind that the functions don't even have to come from python; if you have a favorite PHP / APL / COBOL / etc associative array function, that's fair game. Thanks, Leif P. S. I'm participating in Julython [ http://www.julython.org/ ], and it's fun. You should all join and show everyone that your city has the most open source python activity. From drsalists at gmail.com Sat Jul 14 20:11:19 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 14 Jul 2012 17:11:19 -0700 Subject: lambda in list comprehension acting funny In-Reply-To: <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jul 14, 2012 at 4:29 PM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > I don't remember whether it is Javascript or PHP that uses dynamic > binding, but whichever it is, it is generally considered to be a bad > idea, at least as the default or only behaviour. > > Bash is another language with dynamic binding. Some very old versions of > Lisp use dynamic binding, because it was the easiest to implement. Most > modern languages use lexical (also known as static) binding, because it > is more sensible. > > Here is an illustration of the difference: suppose we have two modules, > library.py and main.py: > > # library.py > x = 23 > def func(y): > return x + y > > # main.py > import library > x = 1000 > print func(1) > I've not heard this discussed in a while. ISTR it was "lexical scoping" vs "dynamic scoping", but I wouldn't be surprised at all if it's known by both pairs of names. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hansmu at xs4all.nl Sat Jul 14 20:39:45 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 15 Jul 2012 02:39:45 +0200 Subject: howto do a robust simple cross platform beep In-Reply-To: References: <5000e530$0$29995$c3e8da3$5496439d@news.astraweb.com> <87ipdq8bz6.fsf@handshake.de> Message-ID: <50021151$0$6858$e4fe514c@news2.news.xs4all.nl> On 14/07/12 20:49:11, Chris Angelico wrote: > On Sun, Jul 15, 2012 at 3:54 AM, Dieter Maurer wrote: >> I, too, would find it useful -- for me (although I do not hate myself). >> >> Surely, you know an alarm clock. Usually, it gives an audible signal >> when it is time to do something. A computer can in principle be used >> as a flexible alarm clock - but it is not so easy with the audible signal... >> An audible signal has the advantage (over a visual one) that you can >> recognize it even when you are not looking at the screen (because you >> are thinking). >> >> Unfortunately, I had to give up. My new computer lacks a working >> speaker... > > There's a simple cheat you can do. Just invoke some other application > to produce the sound! My current alarm clock comes in two modes: it > either picks a random MIDI file from Gilbert and Sullivan's > "Ruddigore", or it plays the "Alice: Madness Returns" theme; in each > case it just invokes the file with its default association (see the > "start" command in Windows, or "gnome-open" in, well, GNOME). > > Of course, working speaker IS a prerequisite. The other prerequisite is that the use is physically near the compueter where your Python process is running. If, for exmple, I'm ssh'ed into my webserver, then sending a sound file to the server's speaker may startle someone in the data centre, but it won't attract my attention. If, OTOH, you do: print "\7" , then an ASCII bell will be sent across the network, and my terminal emulator will beep. It all depends. -- HansM From ndbecker2 at gmail.com Sat Jul 14 20:42:39 2012 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 14 Jul 2012 20:42:39 -0400 Subject: [OT] Simulation Results Managment References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Message-ID: moogyd at yahoo.co.uk wrote: > Hi, > This is a general question, loosely related to python since it will be the > implementation language. I would like some suggestions as to manage simulation > results data from my ASIC design. > > For my design, > - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of > these test cases we have: > - a number of properties (P_AA_BB_CC) > - For each property, the following information is given > - Property name (P_NAME) > - Number of times it was checked (within the testcase) N_CHECKED > - Number of times if failed (within the testcase) N_FAILED > - A simulation runs a testcase with a set of parameters. > - Simple example, SLOW_CLOCK, FAST_CLOCK, etc > - For the design, I will run regression every night (at least), so I will have > results from multiple timestamps We have < 1000 TESTCASES, and < 1000 > PROPERTIES. > > At the moment, I have a script that extracts property information from > simulation logfile, and provides single PASS/FAIL and all logfiles stored in a > directory structure with timestamps/testnames and other parameters embedded in > paths > > I would like to be easily look at (visualize) the data and answer the > questions - When did this property last fail, and how many times was it > checked - Is this property checked in this test case. > > Initial question: How to organize the data within python? > For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, > N_FAILED I then have to store multiple instances of testcase based on date > (and simulation parameters. > > Any comments, suggestions? > Thanks, > Steven One small suggestion, I used to store test conditions and results in log files, and then write parsers to read the results. The formats kept changing (add more conditions/results!) and maintenance was a pain. Now, in addition to a text log file, I write a file in pickle format containing a dict of all test conditions and results. Much more convenient. From rosuav at gmail.com Sat Jul 14 20:49:48 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 15 Jul 2012 10:49:48 +1000 Subject: lambda in list comprehension acting funny In-Reply-To: <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano wrote: > Not necessarily *compile* time, but the distinction is between when the > function is defined (which may at compile time, or it may be at run time) > versus when the function is called. I'd treat the def/lambda statement as "compile time" and the () operator as "run time". ChrisA From rosuav at gmail.com Sat Jul 14 21:07:24 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 15 Jul 2012 11:07:24 +1000 Subject: howto do a robust simple cross platform beep In-Reply-To: <50021151$0$6858$e4fe514c@news2.news.xs4all.nl> References: <5000e530$0$29995$c3e8da3$5496439d@news.astraweb.com> <87ipdq8bz6.fsf@handshake.de> <50021151$0$6858$e4fe514c@news2.news.xs4all.nl> Message-ID: On Sun, Jul 15, 2012 at 10:39 AM, Hans Mulder wrote: > The other prerequisite is that the use is physically near the > compueter where your Python process is running. > > If, for exmple, I'm ssh'ed into my webserver, then sending a sound > file to the server's speaker may startle someone in the data centre, > but it won't attract my attention. If, OTOH, you do: > > print "\7" > > , then an ASCII bell will be sent across the network, and my > terminal emulator will beep. > Sure, though other of the OP's ideas preclude that too. But you could use any network protocol that acknowledges sound (MUDs use \7 following the terminal). ChrisA From rantingrickjohnson at gmail.com Sat Jul 14 21:15:05 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sat, 14 Jul 2012 18:15:05 -0700 (PDT) Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: <4ed2a36d-a034-45d8-84f7-aa71ff17d8b5@googlegroups.com> On Friday, July 13, 2012 8:00:05 PM UTC-5, gelonida wrote: > I just want to use a beep command that works cross platform. [...] I > just want to use them as alert, when certain events occur within a > very long running non GUI application. I can see a need for this when facing a non GUI interface. But even "IF" you do manage to play a sound in a cross platform manner; if the speaker volume is too low, or the speakers are turned off, or the computer does not have speakers connected, etc... your user will never hear the alert! In this case, beeping the built-in speaker has the fail-safe advantage. Why not wrap up the functionality and release a module yourself? If you are not sure how to access the speaker on one or more OSs then ask on the list. I would love to see some community effort behind this. PS: Better make sure this module does not exist though ;-) From rantingrickjohnson at gmail.com Sat Jul 14 21:15:05 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sat, 14 Jul 2012 18:15:05 -0700 (PDT) Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: <4ed2a36d-a034-45d8-84f7-aa71ff17d8b5@googlegroups.com> On Friday, July 13, 2012 8:00:05 PM UTC-5, gelonida wrote: > I just want to use a beep command that works cross platform. [...] I > just want to use them as alert, when certain events occur within a > very long running non GUI application. I can see a need for this when facing a non GUI interface. But even "IF" you do manage to play a sound in a cross platform manner; if the speaker volume is too low, or the speakers are turned off, or the computer does not have speakers connected, etc... your user will never hear the alert! In this case, beeping the built-in speaker has the fail-safe advantage. Why not wrap up the functionality and release a module yourself? If you are not sure how to access the speaker on one or more OSs then ask on the list. I would love to see some community effort behind this. PS: Better make sure this module does not exist though ;-) From rantingrickjohnson at gmail.com Sat Jul 14 23:10:27 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sat, 14 Jul 2012 20:10:27 -0700 (PDT) Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> Message-ID: On Thursday, July 12, 2012 1:53:54 PM UTC-5, Frederic Rentsch wrote: > The "hit list" is a table of investment titles (stock, funds, bonds) > that displays upon entry of a search pattern into a respective template. > The table displays the matching records: name, symbol, ISIN, CUSIP, Sec. > Any line can be click-selected. So they are to look like buttons. Hmm. If they "appear" like a button widget anyway, then why not just use a button widget? > Representing the mentioned names and id codes in Label widgets was the > simplest way I could come up with to align them in columns, admittedly > without the benefit of much experience. But it does look good. the > layout is fine. But is it really the "simplest"? :) ## START CODE ## import Tkinter as tk from Tkconstants import * colWidths = (5,10,30,5) N_COLS = len(colWidths) N_ROWS = 6 root = tk.Tk() for r in range(N_ROWS): # Create some imaginary text to display in each column. # Also try using string methods "center" and "rjust" to # see alternative justification of text. lst = [str(r).ljust(colWidths[r]) for r in range(N_COLS)] b=tk.Button(root, text=''.join(lst)) b.pack(padx=5, pady=5) root.mainloop() ## END CODE ## You could easily expand that into something reusable. Now. If you need to place fancy borders around the texts, or use multiple fonts, or use images, or blah blah blah... then you may want to use the "canvas items" provided by the Tkinter.Canvas widget INSTEAD of buttons. With the canvas, you can create a simple rectangle (canvas.create_rectangle) that represents a button's outside dimension and give it a "button styled" border. Then you can bind click events to mimic the button press action. Then you can place canvas_text items on top of that fake button and configure them to be invisible to click events. These text items will not interfer like the Tkinter.Label widgets are currently doing. However, i would suggest the Tkinter.Button solution is the easiest by far. > I find the Tkinter system quite challenging. Doing a layout isn't so > much a matter of dimensioning and placing things as a struggle to trick > a number of automatic dimensioning and placing mechanisms into > obliging--mechanisms that are rather numerous and hard to remember. I don't think i agree with that assessment. ## START TANGENTIAL MEANDERINGS ## I find the geometry management of Tkinter to be quite powerful whilst being simultaneously simplistic. You only have three main types of management: "Grid", "Place", and "Pack". Each of which has a very specific usage. One caveat to know is that you can NEVER mix "Grid" and "Pack" in the same container widget! I find myself using grid and pack the most, with grid being at the top of the list. Now, i will agree that grid can be confusing at first until you understand how to "rowconfigure" and "columnconfigue" the containing widget (be it a frame or a toplevel). There is also the "sticky" attribute to consider. ## END TANGENTIAL MEANDERINGS ## But all in all, i would say the most difficult part of the Tkinter geometry management API is coming to grips as to which of the three geometry managers is the best choice for the particular problem at hand -- and you will find yourself using more than one manager in a single GUI app! But i don't see you solving this problem by stacking one widget on another. I believe it's time to seek out a new solution. EASY: Using rows of Tkinter.Button coupled with a per-formatted text string. ADVANCED: Creating "pseudo buttons" on a canvas and stacking text objects (or whatever you like) on them. From rantingrickjohnson at gmail.com Sat Jul 14 23:10:27 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sat, 14 Jul 2012 20:10:27 -0700 (PDT) Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> Message-ID: On Thursday, July 12, 2012 1:53:54 PM UTC-5, Frederic Rentsch wrote: > The "hit list" is a table of investment titles (stock, funds, bonds) > that displays upon entry of a search pattern into a respective template. > The table displays the matching records: name, symbol, ISIN, CUSIP, Sec. > Any line can be click-selected. So they are to look like buttons. Hmm. If they "appear" like a button widget anyway, then why not just use a button widget? > Representing the mentioned names and id codes in Label widgets was the > simplest way I could come up with to align them in columns, admittedly > without the benefit of much experience. But it does look good. the > layout is fine. But is it really the "simplest"? :) ## START CODE ## import Tkinter as tk from Tkconstants import * colWidths = (5,10,30,5) N_COLS = len(colWidths) N_ROWS = 6 root = tk.Tk() for r in range(N_ROWS): # Create some imaginary text to display in each column. # Also try using string methods "center" and "rjust" to # see alternative justification of text. lst = [str(r).ljust(colWidths[r]) for r in range(N_COLS)] b=tk.Button(root, text=''.join(lst)) b.pack(padx=5, pady=5) root.mainloop() ## END CODE ## You could easily expand that into something reusable. Now. If you need to place fancy borders around the texts, or use multiple fonts, or use images, or blah blah blah... then you may want to use the "canvas items" provided by the Tkinter.Canvas widget INSTEAD of buttons. With the canvas, you can create a simple rectangle (canvas.create_rectangle) that represents a button's outside dimension and give it a "button styled" border. Then you can bind click events to mimic the button press action. Then you can place canvas_text items on top of that fake button and configure them to be invisible to click events. These text items will not interfer like the Tkinter.Label widgets are currently doing. However, i would suggest the Tkinter.Button solution is the easiest by far. > I find the Tkinter system quite challenging. Doing a layout isn't so > much a matter of dimensioning and placing things as a struggle to trick > a number of automatic dimensioning and placing mechanisms into > obliging--mechanisms that are rather numerous and hard to remember. I don't think i agree with that assessment. ## START TANGENTIAL MEANDERINGS ## I find the geometry management of Tkinter to be quite powerful whilst being simultaneously simplistic. You only have three main types of management: "Grid", "Place", and "Pack". Each of which has a very specific usage. One caveat to know is that you can NEVER mix "Grid" and "Pack" in the same container widget! I find myself using grid and pack the most, with grid being at the top of the list. Now, i will agree that grid can be confusing at first until you understand how to "rowconfigure" and "columnconfigue" the containing widget (be it a frame or a toplevel). There is also the "sticky" attribute to consider. ## END TANGENTIAL MEANDERINGS ## But all in all, i would say the most difficult part of the Tkinter geometry management API is coming to grips as to which of the three geometry managers is the best choice for the particular problem at hand -- and you will find yourself using more than one manager in a single GUI app! But i don't see you solving this problem by stacking one widget on another. I believe it's time to seek out a new solution. EASY: Using rows of Tkinter.Button coupled with a per-formatted text string. ADVANCED: Creating "pseudo buttons" on a canvas and stacking text objects (or whatever you like) on them. From rustompmody at gmail.com Sat Jul 14 23:25:14 2012 From: rustompmody at gmail.com (rusi) Date: Sat, 14 Jul 2012 20:25:14 -0700 (PDT) Subject: Simulation Results Managment References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Message-ID: On Jul 14, 10:50?am, moo... at yahoo.co.uk wrote: > Hi, > This is a general question, loosely related to python since it will be the implementation language. > I would like some suggestions as to manage simulation results data from my ASIC design. > > For my design, > - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of these test cases we have: > ? - a number of properties (P_AA_BB_CC) > ? - For each property, the following information is given > ? ? - Property name (P_NAME) > ? ? - Number of times it was checked (within the testcase) N_CHECKED > ? ? - Number of times if failed (within the testcase) N_FAILED > - A simulation runs a testcase with a set of parameters. > ? - Simple example, SLOW_CLOCK, FAST_CLOCK, etc > - For the design, I will run regression every night (at least), so I will have results from multiple timestamps > We have < 1000 TESTCASES, and < 1000 PROPERTIES. > > At the moment, I have a script that extracts property information from simulation logfile, and provides single PASS/FAIL and all logfiles stored in a directory structure with timestamps/testnames and other parameters embedded in paths > > I would like to be easily look at (visualize) the data and answer the questions > - When did this property last fail, and how many times was it checked > - Is this property checked in this test case. > > Initial question: How to organize the data within python? > For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, N_FAILED > I then have to store multiple instances of testcase based on date (and simulation parameters. > > Any comments, suggestions? > Thanks, > Steven Not sure if you are asking about: 1. Python data structure organization or 2. Organization of data outside python for conveniently getting in and out of python For 2. if the data is modestly sized and is naturally managed with builtin python types -- lists and dictionaries -- yaml gives a nice fit. I used pyyaml some years ago, today I guess json which is similar, is the way to go. For 1, you need to say what are your questions/issues. From rantingrickjohnson at gmail.com Sun Jul 15 00:03:05 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sat, 14 Jul 2012 21:03:05 -0700 (PDT) Subject: Keeping the Console Open with IDLE In-Reply-To: References: Message-ID: On Thursday, February 19, 2009 10:06:42 PM UTC-6, W. eWatson wrote: > I'm using IDLE for editing, but execute programs directly. If there are > execution or "compile" errors, the console closes before I can see what it > contains. How do I prevent that? Q: If you are in fact using IDLE to edit your code file, then why not just "run" the files directly from the IDLE menu (Menu->Run->Run Module)? If you select this command, IDLE will display a shell window containing all the stdout and stderr messages. I think this would be the easiest approach for a neophyte administrator like yourself. See this tutorial for more info: https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html There are many methods of executing a python script. Using the IDLE "run" command is just one of them. Some others include: 1. Double clicking the file icon in a file browser 2. Typing the full path of the script into a windows Command Prompt. Considering i have a script in my "C drive" named "foo.py", i could type the command "C:\foo.py" to execute the script from a windows command prompt. But my fingers don't need any exercise, so i just double click the icon or use the "run" command of my IDE. Done deal. From clp2 at rebertia.com Sun Jul 15 00:50:54 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 14 Jul 2012 21:50:54 -0700 Subject: help needed with subprocess, pipes and parameters In-Reply-To: References: Message-ID: On Friday, July 13, 2012, nuffi wrote: > > If I copy and paste the following command into a command window, it does > what I need. > > c:\Programs\bob\bob.exe -x -y "C:\text\path\to some\file.txt" | > c:\Programs\kate\kate.exe -A 2 --dc "Print Media Is Dead" --da "Author" > --dt "Title" --hf "Times" --bb "14" --aa "" --font "Ariel" - > "C:\rtf\path\to some\file.rtf" > > My mission is to recreate this command within a python script, so that I > can pass a bunch of different parameters into it, and use it as a batch > over a bunch of different papers. > > > The code I came up with looks like this: > > import os, glob, subprocess > > sourceDir = "c:\\text\\" > destDir = "c:\\rtf\\" > bobPath = "C:\\Programs\\bob\\bob.exe" > katePath = "C:\\Programs\\kate\\kate.exe" > > def get_new_path(doc): > blah = doc.replace(sourceDir, destDir) > if not os.path.isdir(blah): > os.makedirs(blah) > rtf = blah.replace('.txt', '.rtf') > pathString = '- "' + (os.path.join(rtf)) + '"' > return(pathString) > > > def convert_doc(doc): > dc = '--dc "Print Media Is Dead"' > da = '--da "Author"' > dt = '--dt "Title"' > hf = '--hf "Times"' > fn = '--font "Ariel"' > bb = '--bb "14"' > docpath = '"' + (os.path.join(doc)) + '"' > path = get_new_path(doc) > A = '-A 2' > bob = subprocess.Popen([bobPath, '-x', '-y', docpath], stdout = > subprocess.PIPE,) > kate = subprocess.Popen([katePath, A, dc, da, dt, hf, fn, bb, path], > stdin = bob.stdout, stdout = subprocess.PIPE,) Your tokenization of the command is wrong. Read the Note box in the subprocess docs for guidance on how to get it right: http://docs.python.org/library/subprocess.html#popen-constructor Cheers, Chris via iPhone -- Cheers, Chris -- http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From moogyd at yahoo.co.uk Sun Jul 15 01:26:26 2012 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sat, 14 Jul 2012 22:26:26 -0700 (PDT) Subject: Simulation Results Managment In-Reply-To: References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Message-ID: <8a8fa1fa-a197-4d9d-8d21-977c0e6c6dc6@googlegroups.com> On Sunday, July 15, 2012 5:25:14 AM UTC+2, rusi wrote: > On Jul 14, 10:50?am, moo... at yahoo.co.uk wrote: > > Hi, > > This is a general question, loosely related to python since it will be the implementation language. > > I would like some suggestions as to manage simulation results data from my ASIC design. > > > > For my design, > > - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of these test cases we have: > > ? - a number of properties (P_AA_BB_CC) > > ? - For each property, the following information is given > > ? ? - Property name (P_NAME) > > ? ? - Number of times it was checked (within the testcase) N_CHECKED > > ? ? - Number of times if failed (within the testcase) N_FAILED > > - A simulation runs a testcase with a set of parameters. > > ? - Simple example, SLOW_CLOCK, FAST_CLOCK, etc > > - For the design, I will run regression every night (at least), so I will have results from multiple timestamps > > We have < 1000 TESTCASES, and < 1000 PROPERTIES. > > > > At the moment, I have a script that extracts property information from simulation logfile, and provides single PASS/FAIL and all logfiles stored in a directory structure with timestamps/testnames and other parameters embedded in paths > > > > I would like to be easily look at (visualize) the data and answer the questions > > - When did this property last fail, and how many times was it checked > > - Is this property checked in this test case. > > > > Initial question: How to organize the data within python? > > For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, N_FAILED > > I then have to store multiple instances of testcase based on date (and simulation parameters. > > > > Any comments, suggestions? > > Thanks, > > Steven > > Not sure if you are asking about: > 1. Python data structure organization > or > 2. Organization of data outside python for conveniently getting in and > out of python > > For 2. if the data is modestly sized and is naturally managed with > builtin python types -- lists and dictionaries -- yaml gives a nice > fit. I used pyyaml some years ago, today I guess json which is > similar, is the way to go. > > For 1, you need to say what are your questions/issues. Hi Rusi, For (1), I guess that the only question I had was how to handle regression results. But I think that the most logical way for string this data is as a dict with key = datestamp, and entries being list of testcases/results. For (2), I will look at both these. Thanks for the help. Steven From moogyd at yahoo.co.uk Sun Jul 15 01:29:49 2012 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sat, 14 Jul 2012 22:29:49 -0700 (PDT) Subject: [OT] Simulation Results Managment In-Reply-To: References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Message-ID: <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> On Sunday, July 15, 2012 2:42:39 AM UTC+2, Neal Becker wrote: > me wrote: > > > Hi, > > This is a general question, loosely related to python since it will be the > > implementation language. I would like some suggestions as to manage simulation > > results data from my ASIC design. > > > > For my design, > > - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of > > these test cases we have: > > - a number of properties (P_AA_BB_CC) > > - For each property, the following information is given > > - Property name (P_NAME) > > - Number of times it was checked (within the testcase) N_CHECKED > > - Number of times if failed (within the testcase) N_FAILED > > - A simulation runs a testcase with a set of parameters. > > - Simple example, SLOW_CLOCK, FAST_CLOCK, etc > > - For the design, I will run regression every night (at least), so I will have > > results from multiple timestamps We have < 1000 TESTCASES, and < 1000 > > PROPERTIES. > > > > At the moment, I have a script that extracts property information from > > simulation logfile, and provides single PASS/FAIL and all logfiles stored in a > > directory structure with timestamps/testnames and other parameters embedded in > > paths > > > > I would like to be easily look at (visualize) the data and answer the > > questions - When did this property last fail, and how many times was it > > checked - Is this property checked in this test case. > > > > Initial question: How to organize the data within python? > > For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, > > N_FAILED I then have to store multiple instances of testcase based on date > > (and simulation parameters. > > > > Any comments, suggestions? > > Thanks, > > Steven > > One small suggestion, > I used to store test conditions and results in log files, and then write parsers > to read the results. The formats kept changing (add more conditions/results!) > and maintenance was a pain. > > Now, in addition to a text log file, I write a file in pickle format containing > a dict of all test conditions and results. Much more convenient. Hi Neal, We already store the original log files. Does pickle have any advantages over json/yaml? Thanks, Steven From moogyd at yahoo.co.uk Sun Jul 15 01:29:49 2012 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sat, 14 Jul 2012 22:29:49 -0700 (PDT) Subject: [OT] Simulation Results Managment In-Reply-To: References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> Message-ID: <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> On Sunday, July 15, 2012 2:42:39 AM UTC+2, Neal Becker wrote: > me wrote: > > > Hi, > > This is a general question, loosely related to python since it will be the > > implementation language. I would like some suggestions as to manage simulation > > results data from my ASIC design. > > > > For my design, > > - I have a number of simulations testcases (TEST_XX_YY_ZZ), and within each of > > these test cases we have: > > - a number of properties (P_AA_BB_CC) > > - For each property, the following information is given > > - Property name (P_NAME) > > - Number of times it was checked (within the testcase) N_CHECKED > > - Number of times if failed (within the testcase) N_FAILED > > - A simulation runs a testcase with a set of parameters. > > - Simple example, SLOW_CLOCK, FAST_CLOCK, etc > > - For the design, I will run regression every night (at least), so I will have > > results from multiple timestamps We have < 1000 TESTCASES, and < 1000 > > PROPERTIES. > > > > At the moment, I have a script that extracts property information from > > simulation logfile, and provides single PASS/FAIL and all logfiles stored in a > > directory structure with timestamps/testnames and other parameters embedded in > > paths > > > > I would like to be easily look at (visualize) the data and answer the > > questions - When did this property last fail, and how many times was it > > checked - Is this property checked in this test case. > > > > Initial question: How to organize the data within python? > > For a single testcase, I could use a dict. Key P_NAME, data in N_CHECKED, > > N_FAILED I then have to store multiple instances of testcase based on date > > (and simulation parameters. > > > > Any comments, suggestions? > > Thanks, > > Steven > > One small suggestion, > I used to store test conditions and results in log files, and then write parsers > to read the results. The formats kept changing (add more conditions/results!) > and maintenance was a pain. > > Now, in addition to a text log file, I write a file in pickle format containing > a dict of all test conditions and results. Much more convenient. Hi Neal, We already store the original log files. Does pickle have any advantages over json/yaml? Thanks, Steven From torriem at gmail.com Sun Jul 15 01:31:38 2012 From: torriem at gmail.com (Michael Torrie) Date: Sat, 14 Jul 2012 23:31:38 -0600 Subject: Python and Qt4 Designer In-Reply-To: <1bb0d4df-3937-4d5f-aedb-734e0c54eb85@f9g2000pbd.googlegroups.com> References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> <1bb0d4df-3937-4d5f-aedb-734e0c54eb85@f9g2000pbd.googlegroups.com> Message-ID: <500255BA.5080102@gmail.com> On 07/14/2012 11:13 AM, rusi wrote: > I looked at the second link and find code like this: > > app = None if ( not app ): app = QtGui.QApplication([]) > > Maybe I'm dense but whats that if doing there? > > Frankly I seem to be a bit jinxed with gui stuff. A few days ago > someone was singing the praises of some new themed tk stuff. I could > not get the first two lines -- the imports -- to work and then gave > up Since you haven't had any experience with gui development then probably loading ui files isn't the right place to start. First principles (creating gui widgets from scratch) would be it. In any case, the line in question is quite simple. It creates a QApplication object, which is basically the engine that drives all Qt applications. Once you call .run() on it, it takes over and handles all the mouse events and such for you. In fact you do not have any control over the program's execution from this point on, other than to define event call-back methods or functions that are called by the widgets when things happen, like mouse clicks. All gui toolkits operate this way. You set up the widgets, then you run the main engine or main event loop and control never returns to your main program until something triggers the end (like closing a window or the quit menu item is pressed). Probably a complete working example is what you need to see, that is documented. I primarily work with Gtk, but I'll whip up a Qt one tomorrow if I can. From dieter at handshake.de Sun Jul 15 02:35:10 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sun, 15 Jul 2012 08:35:10 +0200 Subject: [OT] Simulation Results Managment References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> Message-ID: <87k3y5h6qp.fsf@handshake.de> moogyd at yahoo.co.uk writes: > ... > Does pickle have any advantages over json/yaml? It can store and retrieve almost any Python object with almost no effort. Up to you whether you see it as an advantage to be able to store objects rather than (almost) pure data with a rather limited type set. Of course, "pickle" is a proprietary Python format. Not so easy to decode it with something else than Python. In addition, when you store objects, the retrieving application must know the classes of those objects -- and its knowledge should not be too different from how those classes looked when the objects have been stored. I like very much to work with objects (rather than with pure data). Therefore, I use "pickle" when I know that the storing and retrieving applications all use Python. I use pure (and restricted) data formats when non Python applications come into play. From vincent.vandevyvre at swing.be Sun Jul 15 03:58:37 2012 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sun, 15 Jul 2012 09:58:37 +0200 Subject: Python and Qt4 Designer In-Reply-To: <500255BA.5080102@gmail.com> References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> <1bb0d4df-3937-4d5f-aedb-734e0c54eb85@f9g2000pbd.googlegroups.com> <500255BA.5080102@gmail.com> Message-ID: <5002782D.7080009@swing.be> On 15/07/12 07:31, Michael Torrie wrote: > On 07/14/2012 11:13 AM, rusi wrote: >> I looked at the second link and find code like this: >> >> app = None if ( not app ): app = QtGui.QApplication([]) >> >> Maybe I'm dense but whats that if doing there? >> >> Frankly I seem to be a bit jinxed with gui stuff. A few days ago >> someone was singing the praises of some new themed tk stuff. I could >> not get the first two lines -- the imports -- to work and then gave >> up > Since you haven't had any experience with gui development then probably > loading ui files isn't the right place to start. First principles > (creating gui widgets from scratch) would be it. > > In any case, the line in question is quite simple. It creates a > QApplication object, which is basically the engine that drives all Qt > applications. Once you call .run() on it, it takes over and handles all > the mouse events and such for you. In fact you do not have any control > over the program's execution from this point on, other than to define > event call-back methods or functions that are called by the widgets when > things happen, like mouse clicks. > > All gui toolkits operate this way. You set up the widgets, then you run > the main engine or main event loop and control never returns to your > main program until something triggers the end (like closing a window or > the quit menu item is pressed). > > Probably a complete working example is what you need to see, that is > documented. I primarily work with Gtk, but I'll whip up a Qt one > tomorrow if I can. Rusi is not the op, and his question is about these lines app = None if ( not app ): not this one app = QtGui.QApplication([]) which should be written like this app = QtGui.QApplication(sys.argv) -- Vincent V.V. Oqapy . Qarte . PaQager From steve+comp.lang.python at pearwood.info Sun Jul 15 04:32:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Jul 2012 08:32:47 GMT Subject: lambda in list comprehension acting funny References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 10:49:48 +1000, Chris Angelico wrote: > On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano > wrote: >> Not necessarily *compile* time, but the distinction is between when the >> function is defined (which may at compile time, or it may be at run >> time) versus when the function is called. > > I'd treat the def/lambda statement as "compile time" and the () operator > as "run time". But function definitions occur at run time, not compile time -- they are executable statements, not instructions to the compiler to define a function. For example: py> dis("def f(x): return x+1") # Python 3.2 1 0 LOAD_CONST 0 (", line 1>) 3 MAKE_FUNCTION 0 6 STORE_NAME 0 (f) 9 LOAD_CONST 1 (None) 12 RETURN_VALUE The code object is pre-compiled at compile time, but the function and name-binding (the "def") doesn't occur until runtime. At compile time, Python parses the source code and turns it into byte- code. Class and function definitions are executed at run time, the same as any other statement. I'm not sure if this is a difference that makes a difference or not; I think it is, but don't know enough about how closures and scoping rules work in other languages to be sure that it does make a difference. -- Steven From bahamutzero8825 at gmail.com Sun Jul 15 04:34:46 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 15 Jul 2012 03:34:46 -0500 Subject: Implicit conversion to boolean in if and while statements Message-ID: <500280A6.6070608@gmail.com> This has probably been discussed before, but why is there an implicit conversion to a boolean in if and while statements? if not None: print('hi') prints 'hi' since bool(None) is False. If this was discussed in a PEP, I would like a link to it. There are so many PEPs, and I wouldn't know which ones to look through. Converting 0 and 1 to False and True seems reasonable, but I don't see the point in converting other arbitrary values. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rosuav at gmail.com Sun Jul 15 04:44:09 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 15 Jul 2012 18:44:09 +1000 Subject: lambda in list comprehension acting funny In-Reply-To: <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 15, 2012 at 6:32 PM, Steven D'Aprano wrote: > At compile time, Python parses the source code and turns it into byte- > code. Class and function definitions are executed at run time, the same > as any other statement. Between the parse step and the 'def' execution, a code object is created. When you call it, that code object already exists. Nothing else really matters, unless there's a bug in the Python optimizer or something weird like that. The nearest thing Python _has_ to a "compile time" is the execution of def. ChrisA From rosuav at gmail.com Sun Jul 15 04:47:05 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 15 Jul 2012 18:47:05 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500280A6.6070608@gmail.com> References: <500280A6.6070608@gmail.com> Message-ID: On Sun, Jul 15, 2012 at 6:34 PM, Andrew Berg wrote: > Converting 0 and 1 to False and True seems reasonable, but I don't see > the point in converting other arbitrary values. It's for convenience. Unfortunately, not all languages treat all types the same way. It's very handy, though, to be able to use if not foo: foo = some_initializer when foo starts out as, say, None. Or []. Or, in fact, any other "empty" value. ChrisA From stefan_ml at behnel.de Sun Jul 15 05:17:12 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 15 Jul 2012 11:17:12 +0200 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500280A6.6070608@gmail.com> References: <500280A6.6070608@gmail.com> Message-ID: Andrew Berg, 15.07.2012 10:34: > This has probably been discussed before, but why is there an implicit > conversion to a boolean in if and while statements? There isn't. This has nothing to do with "if" or "while". All objects have a truth value in Python, evaluating to True by default (object), unless they implement the test themselves. As Chris said, very convenient. Stefan From tjreedy at udel.edu Sun Jul 15 06:27:43 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jul 2012 06:27:43 -0400 Subject: lambda in list comprehension acting funny In-Reply-To: <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/15/2012 4:32 AM, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 10:49:48 +1000, Chris Angelico wrote: > >> On Sun, Jul 15, 2012 at 9:29 AM, Steven D'Aprano >> wrote: >>> Not necessarily *compile* time, but the distinction is between when the >>> function is defined (which may at compile time, or it may be at run >>> time) versus when the function is called. >> >> I'd treat the def/lambda statement as "compile time" and the () operator >> as "run time". > > But function definitions occur at run time, not compile time -- they are > executable statements, not instructions to the compiler to define a > function. The () operator is 'call time'. The main points are a) the execution of def statements and lambda expressions and the execution of calls happen at different run times. b) default arg objects are calculated at def/lambda time. c) names in def bodies and lambda expressions are resolved at call time. and d) people more often forget c) when thinking about lambda expressions that for def statements. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Sun Jul 15 06:56:57 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Jul 2012 10:56:57 GMT Subject: Implicit conversion to boolean in if and while statements References: Message-ID: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 03:34:46 -0500, Andrew Berg wrote: > This has probably been discussed before, By the hoary hosts of Hoggoth, has it ever! > but why is there an implicit > conversion to a boolean in if and while statements? It's nothing to do with if and while. All Python objects are duck-typed as bools. 1) It's generally part of the duck-typing philosophy. If an object quacks like a bool, why not treat it as a bool? 2) It's useful and convenient for short-circuit boolean expressions such as any(), all(), and various things like: for x in mylist or []: ... is better than: if mylist is not None: for x in mylist: ... 3) Rather than distinguishing "true" from "false", a more useful dichotomy is between "something" and "nothing". Python includes a number of ways of spelling "nothing" of various types, such as: None, 0, 0.0, '', [], {}, set() and nearly everything else is "something". 4) Other languages such as Ruby, Javascript, PHP, Clojure and others also distinguish between true-like and false-like ("truthy" and "falsey") values. Although some of them have made some pretty weird and arbitrary choices for what counts as true-like and false-like, without Python's general principle that "nothing" values should be false. (E.g. Javascript considers Boolean(false) to be a true value!!!) 5) Prior to Python 2.2, there was no bool type and no True and False values. In fact, here is an impassioned plea from an educator begging Guido not to introduce True and False to the language, because duck-typed truthy/falsey values are *so much better*. http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360?hl=en Sadly, or happily, Python did grow True and False values, but the fundamental distinction between something and nothing still exists. (For the record, I can only think of one trap for the unwary: time objects are false at *exactly* midnight.) -- Steven From ndbecker2 at gmail.com Sun Jul 15 07:24:59 2012 From: ndbecker2 at gmail.com (Neal Becker) Date: Sun, 15 Jul 2012 07:24:59 -0400 Subject: [OT] Simulation Results Managment References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> <87k3y5h6qp.fsf@handshake.de> Message-ID: Dieter Maurer wrote: > moogyd at yahoo.co.uk writes: >> ... >> Does pickle have any advantages over json/yaml? > > It can store and retrieve almost any Python object with almost no effort. > > Up to you whether you see it as an advantage to be able to store > objects rather than (almost) pure data with a rather limited type set. > > > Of course, "pickle" is a proprietary Python format. Not so easy to > decode it with something else than Python. In addition, when > you store objects, the retrieving application must know the classes > of those objects -- and its knowledge should not be too different > from how those classes looked when the objects have been stored. > > > I like very much to work with objects (rather than with pure data). > Therefore, I use "pickle" when I know that the storing and retrieving > applications all use Python. I use pure (and restricted) data formats > when non Python applications come into play. Typically what I want to do is post-process (e.g. plot) results using python scripts, so using pickle is great for that. From samuel.marks at orionvm.com.au Sun Jul 15 11:19:29 2012 From: samuel.marks at orionvm.com.au (samuel.marks at orionvm.com.au) Date: Sun, 15 Jul 2012 08:19:29 -0700 (PDT) Subject: 2 + 2 = 5 In-Reply-To: <%IoJr.487993$ra1.293468@fx05.am4> References: <7x7guj2u8a.fsf@ruckus.brouhaha.com> <4ff5c8fe$0$6623$9b4e6d93@newsspool2.arcor-online.net> <%IoJr.487993$ra1.293468@fx05.am4> Message-ID: <25b4d162-9ce4-4f53-a2ec-5ce526a60a88@googlegroups.com> On Friday, July 6, 2012 8:39:58 AM UTC+10, Andrew Cooper wrote: > On 05/07/2012 22:46, Evan Driscoll wrote: > > On 01/-10/-28163 01:59 PM, Alexander Blinne wrote: > >> 5+0 is actually 4+0, because 5 == 4, so 5+0 gives 4. > >> 5+1 is actually 4+1, which is 5, but 5 is again 4. > >> 5+2 is 4+2 which is 6. > > > > Now all I can think is "Hoory for new math, new-hoo-hoo math" :-) > > > > Evan > > It wont do you a bit of good to read new math! > > (My mind was on exactly the same track) > > ~Andrew +1 From rantingrickjohnson at gmail.com Sun Jul 15 11:35:04 2012 From: rantingrickjohnson at gmail.com (rantingrickjohnson at gmail.com) Date: Sun, 15 Jul 2012 08:35:04 -0700 (PDT) Subject: Keeping the Console Open with IDLE In-Reply-To: References: <54c56179-6f92-41e9-bad7-afa8b28d0671@l38g2000vba.googlegroups.com> Message-ID: <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> On Friday, February 20, 2009 9:41:42 AM UTC-6, David Smith wrote: > What I meant was open open the command prompt, type cd, space, DO NOT > hit enter yet. Drag the folder with your script into the command prompt > window. Then go to the command prompt window and hit enter. This > should compose a command similar to the following: And why the hell would you resort to such contrived contortions as that? Are you masochistic? DoubleClicking an icon will take me less that one second. How long does this sequence take: 1. Open a command prompt 2. type "c" 3. type "d" 4. type "space" 5. hover over the folder icon with your mouse 5.5. Oops, i missed. Go back to step 5! 6. Mouse click the file "icon" 7. Mouse drag the file "icon" 8. Position the mouse over prompt window 9. Release the "icon" 10. Press the "Enter" key Can anybody say "!Ay, caramba!"? Besides, you can skip most of those steps by Shift+RightClicking the file icon and choosing "Open Command Window Here". But, why the hell would you EVEN do that when two simple clicks will suffice? "practicality beats purity" From rosuav at gmail.com Sun Jul 15 11:57:00 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 01:57:00 +1000 Subject: Keeping the Console Open with IDLE In-Reply-To: <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> References: <54c56179-6f92-41e9-bad7-afa8b28d0671@l38g2000vba.googlegroups.com> <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> Message-ID: On Mon, Jul 16, 2012 at 1:35 AM, wrote: > Besides, you can skip most of those steps by Shift+RightClicking the file icon and choosing "Open Command Window Here". That's not standard. Me, I can invoke git bash anywhere I want it, but that doesn't mean I'd recommend installing git just so that people can get command lines with less steps. ChrisA From ian.g.kelly at gmail.com Sun Jul 15 12:19:16 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Jul 2012 10:19:16 -0600 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano wrote: > (For the record, I can only think of one trap for the unwary: time > objects are false at *exactly* midnight.) Ugh, that's irritating. I can't think of any scenario where I would ever want the semantics "if timeval (is not midnight):". This reinforces the point that if you only want to test whether you have None, you should use "is not None" rather than relying on __bool__. From rantingrickjohnson at gmail.com Sun Jul 15 12:19:19 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 09:19:19 -0700 (PDT) Subject: Keeping the Console Open with IDLE In-Reply-To: References: <54c56179-6f92-41e9-bad7-afa8b28d0671@l38g2000vba.googlegroups.com> <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> Message-ID: <8cdc7271-8775-4ac4-9ff3-7423b18e3a99@googlegroups.com> On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote: > On Mon, Jul 16, 2012 at 1:35 AM, wrote: > > Besides, you can skip most of those steps by Shift+RightClicking > > the file icon and choosing "Open Command Window Here". > > That's not standard. Me, I can invoke git bash anywhere I want it, but > that doesn't mean I'd recommend installing git just so that people can > get command lines with less steps. I don't understand Chris? It's obvious that the OP is on a windows box; for which no installation is required. And, what is so egregious about "less steps"(sic)? Do you prefer to be unproductive? Did you forget the lazy programmers creed? Is your employer paying you by the hour? ...all good questions. From rantingrickjohnson at gmail.com Sun Jul 15 12:19:19 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 09:19:19 -0700 (PDT) Subject: Keeping the Console Open with IDLE In-Reply-To: References: <54c56179-6f92-41e9-bad7-afa8b28d0671@l38g2000vba.googlegroups.com> <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> Message-ID: <8cdc7271-8775-4ac4-9ff3-7423b18e3a99@googlegroups.com> On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote: > On Mon, Jul 16, 2012 at 1:35 AM, wrote: > > Besides, you can skip most of those steps by Shift+RightClicking > > the file icon and choosing "Open Command Window Here". > > That's not standard. Me, I can invoke git bash anywhere I want it, but > that doesn't mean I'd recommend installing git just so that people can > get command lines with less steps. I don't understand Chris? It's obvious that the OP is on a windows box; for which no installation is required. And, what is so egregious about "less steps"(sic)? Do you prefer to be unproductive? Did you forget the lazy programmers creed? Is your employer paying you by the hour? ...all good questions. From rustompmody at gmail.com Sun Jul 15 12:20:34 2012 From: rustompmody at gmail.com (rusi) Date: Sun, 15 Jul 2012 09:20:34 -0700 (PDT) Subject: Simulation Results Managment References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> Message-ID: <519ddc1b-4538-43a1-b925-325de59e8802@km7g2000pbc.googlegroups.com> On Jul 15, 11:35?am, Dieter Maurer wrote: > moo... at yahoo.co.uk writes: > > ... > > Does pickle have any advantages over json/yaml? > > It can store and retrieve almost any Python object with almost no effort. > > Up to you whether you see it as an advantage to be able to store > objects rather than (almost) pure data with a rather limited type set. > > Of course, "pickle" is a proprietary Python format. Not so easy to > decode it with something else than Python. In addition, when > you store objects, the retrieving application must know the classes > of those objects -- and its knowledge should not be too different > from how those classes looked when the objects have been stored. > > I like very much to work with objects (rather than with pure data). > Therefore, I use "pickle" when I know that the storing and retrieving > applications all use Python. I use pure (and restricted) data formats > when non Python applications come into play. Pickle -> JSON -> Yaml are roughly in increasing order of human-friendliness and decreasing order of machine friendliness (where machine means python 'machine') This means that - Pickle is most efficient, Yaml least - Pickle comes with python from as far back as I know Json started coming somewhere round 2.5 (I think) (py)yaml needs to be installed separately - reading pickled data will spoil your eyes whereas yaml is pleasant to read (just like python) From rosuav at gmail.com Sun Jul 15 12:40:47 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 02:40:47 +1000 Subject: Keeping the Console Open with IDLE In-Reply-To: <8cdc7271-8775-4ac4-9ff3-7423b18e3a99@googlegroups.com> References: <54c56179-6f92-41e9-bad7-afa8b28d0671@l38g2000vba.googlegroups.com> <0ac932eb-7801-45be-914f-0cdd8079bb20@googlegroups.com> <8cdc7271-8775-4ac4-9ff3-7423b18e3a99@googlegroups.com> Message-ID: On Mon, Jul 16, 2012 at 2:19 AM, Rick Johnson wrote: > On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote: >> On Mon, Jul 16, 2012 at 1:35 AM, wrote: >> > Besides, you can skip most of those steps by Shift+RightClicking >> > the file icon and choosing "Open Command Window Here". >> >> That's not standard. Me, I can invoke git bash anywhere I want it, but >> that doesn't mean I'd recommend installing git just so that people can >> get command lines with less steps. > > I don't understand Chris? It's obvious that the OP is on a windows box; for which no installation is required. I have here a Windows XP system (shh, it doesn't know there's Linux between it and the hardware) which has no such context-menu item. Ergo it is not standard and cannot be assumed to be on the target computer, and installation IS required. > And, what is so egregious about "less steps"(sic)? Do you prefer to be unproductive? Did you forget the lazy programmers creed? Is your employer paying you by the hour? ...all good questions. And if you're going to quibble about "fewer steps" then you should probably have an apostrophe in "lazy programmers' creed". Just sayin'. ChrisA From rantingrickjohnson at gmail.com Sun Jul 15 12:50:05 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 09:50:05 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote: > On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano > wrote: > > (For the record, I can only think of one trap for the unwary: time > > objects are false at *exactly* midnight.) > > Ugh, that's irritating. I can't think of any scenario where I would > ever want the semantics "if timeval (is not midnight):". This > reinforces the point that if you only want to test whether you have > None, you should use "is not None" rather than relying on __bool__. I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this: ## EXAMPLE A ## py> if money: ... do_something() The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative: ## EXAMPLE B ## py> if bool(money): ... do_something() Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute. We must NEVER present "if" in such confusing manner as ExampleA. I believe Guido made a grave mistake allowing this syntax to flourish. His intentions where noble, to save people a few keystrokes, but all he accomplished was to pave a road directly into hell. "Explict is better than Implict" From rantingrickjohnson at gmail.com Sun Jul 15 12:50:05 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 09:50:05 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote: > On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano > wrote: > > (For the record, I can only think of one trap for the unwary: time > > objects are false at *exactly* midnight.) > > Ugh, that's irritating. I can't think of any scenario where I would > ever want the semantics "if timeval (is not midnight):". This > reinforces the point that if you only want to test whether you have > None, you should use "is not None" rather than relying on __bool__. I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this: ## EXAMPLE A ## py> if money: ... do_something() The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative: ## EXAMPLE B ## py> if bool(money): ... do_something() Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute. We must NEVER present "if" in such confusing manner as ExampleA. I believe Guido made a grave mistake allowing this syntax to flourish. His intentions where noble, to save people a few keystrokes, but all he accomplished was to pave a road directly into hell. "Explict is better than Implict" From bahamutzero8825 at gmail.com Sun Jul 15 13:02:37 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 15 Jul 2012 12:02:37 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5002F7AD.1000209@gmail.com> On 7/15/2012 5:56 AM, Steven D'Aprano wrote: > 3) Rather than distinguishing "true" from "false", a more useful > dichotomy is between "something" and "nothing". Python includes a number > of ways of spelling "nothing" of various types, such as: > > None, 0, 0.0, '', [], {}, set() > > and nearly everything else is "something". Okay, I see the value in this, but I don't understand why None has a truth value. I would expect None to mean "doesn't exist" or "unknown" or something like that - e.g., a value of 0 means 0 jelly beans in the jar and None means there isn't a jar. FWIW, I have, for a reason I forget, gotten into the habit of writing "if x is not None" when testing for None. However, I have not been writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'" when testing for True (in cases where a value of True or False makes sense, but any other value would not). Should I? -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From bahamutzero8825 at gmail.com Sun Jul 15 13:16:00 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 15 Jul 2012 12:16:00 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5002FAD0.8040701@gmail.com> On 7/15/2012 11:19 AM, Ian Kelly wrote: > Ugh, that's irritating. I can't think of any scenario where I would > ever want the semantics "if timeval (is not midnight):". It's not implemented with such a test, but logging.handlers.TimedRotatingFileHandler has an option to rollover at midnight. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From ian.g.kelly at gmail.com Sun Jul 15 13:38:06 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Jul 2012 11:38:06 -0600 Subject: Request for useful functions on dicts In-Reply-To: <38c6d4cb-89b3-4f78-a966-be5ddccec845@googlegroups.com> References: <38c6d4cb-89b3-4f78-a966-be5ddccec845@googlegroups.com> Message-ID: On Sat, Jul 14, 2012 at 5:56 PM, Leif wrote: > Hi, everybody. I am trying to collect all the functions I've found useful for working with dicts into a library: > > https://github.com/leifp/dictutil > > If you have a favorite dict-related func / class, or know of similar projects, please let me know (or open an issue on github). Bear in mind that the functions don't even have to come from python; if you have a favorite PHP / APL / COBOL / etc associative array function, that's fair game. Nothing in particular comes to mind, but I'll be happy to critique what you've already got. One thing that bothers me a bit is that get_in will accept any iterable, but set_in and update_in can only accept a sequence in order to do the slicing. Here's an alternate implementation for set_in that takes any iterable: def set_in(d, ks, v): tmp = d i = None for i, next_key in enumerate(ks): if i > 0: tmp = tmp.setdefault(current_key, {}) current_key = next_key if i is None: raise KeyError("Empty keys iterable") tmp[current_key] = v update_in could be rewritten similarly. You might also notice that I'm not returning d here. That's because the Pythonic way is to either create a new object and return it, or mutate the existing object and return None. If you mutate the existing object and return it, that can lead to confusion about which style the method takes. This is why list.append (for example) always returns None. In Python 2.7+, intersection and difference could be written using dictviews, which act like sets. partition_on_value, partition_on_key: The only difference between these is whether it passes the key or the value to the predicate. You could just pass both and let the predicate decide which one (or both) to use, and then you only need a single function. Also, why a predicate specifically? This could be generalized to partition any equivalence relation, not just those with only two equivalence classes: def partition(f, d): """Partition the dict according to an equivalence relation. Calls f(key, value) for all (key, value) pairs in the dict d. The return value of f must be hashable. Returns a new dict where the keys are distinct return values of f, and the values are dicts containing the equivalence classes distinguished by those return values. """ partition = defaultdict(dict) for k, v in d.iteritems(): partition[f(k, v)][k] = v return partition If you still wanted the predicate semantics, you could then define that as a wrapper: def partition_pred(f, d): p = partition(lambda k,v: bool(f(k,v)), d) return p[True], p[False] issubdict could be implemented as a subset operation. I haven't timed it so it may not really be any faster, but this way the looping is in C instead of in Python: def issubdict(d1, d2): return set(d1.items()).issubset(d2.items()) Finally, isempty(d) is basically equivalent to "not d", which is both shorter and faster. Cheers, Ian From ian.g.kelly at gmail.com Sun Jul 15 13:45:10 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Jul 2012 11:45:10 -0600 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5002FAD0.8040701@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002FAD0.8040701@gmail.com> Message-ID: On Sun, Jul 15, 2012 at 11:16 AM, Andrew Berg wrote: > On 7/15/2012 11:19 AM, Ian Kelly wrote: >> Ugh, that's irritating. I can't think of any scenario where I would >> ever want the semantics "if timeval (is not midnight):". > It's not implemented with such a test, but > logging.handlers.TimedRotatingFileHandler has an option to rollover at > midnight. Nor could it be implemented with such a test, since the rollover check would then have to run at exactly midnight for the test to evaluate false. If it were off by 1 microsecond, it would miss it. From ian.g.kelly at gmail.com Sun Jul 15 14:01:58 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 15 Jul 2012 12:01:58 -0600 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On Sun, Jul 15, 2012 at 10:50 AM, Rick Johnson wrote: > I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax issue. Consider this: > > ## EXAMPLE A ## > py> if money: > ... do_something() > > The syntax "if money" implies we are testing/measuring some attribute of "money", but what exactly about money are we testing/measuring? The problem lies in the syntax. To understand this syntax, we must first interpret what *IF* means, and we should *NEVER* need to interpret such a well defined word as *IF*! This syntax is far too opaque. Consider the alternative: > > ## EXAMPLE B ## > py> if bool(money): > ... do_something() > > Now we have a hint. Even if we don't understand the inner workings of the "bool" function, we *do* understand that the statement "bool(money)" *must* return True or the block *will not* execute. So now instead of having to understand how "if" handles arbitrary values, we have to understand how "bool" handles arbitrary values. How is that an improvement? What should "if" do if presented a value that isn't True or False? Raise a TypeError? Next thing we know, people get so used to wrapping everything they present to "if" in a "bool()" call, that they start writing silly things like "if bool(x == 7)" and "if bool(isinstance(x, int))". Why? Because it's faster and easier to automatically wrap the value in "bool" than it is to put in the effort to verify that the value will always be a bool to begin with in order to avoid a useless and annoying exception. At the point that happens, the "bool()" is effectively just part of the if syntax, and we're back to where we started. From python at bdurham.com Sun Jul 15 14:02:29 2012 From: python at bdurham.com (python at bdurham.com) Date: Sun, 15 Jul 2012 14:02:29 -0400 Subject: Initial nose experience In-Reply-To: References: Message-ID: <1342375349.18080.140661102289537.19683E83@webmail.messagingengine.com> Hi Roy, > I've been using unittest for many years, but have steadfastly (perhaps stubbornly) avoided newfangled improvements like nose. I finally decided to take a serious look at nose. Thanks for sharing your nose experience. What motivated you to migrate from unittest to nose? After years of using unittest, what would you say are the pros and cons of nose? Thank you, Malcolm From rantingrickjohnson at gmail.com Sun Jul 15 14:56:49 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 11:56:49 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote: > So now instead of having to understand how "if" handles arbitrary > values, we have to understand how "bool" handles arbitrary values. > How is that an improvement? Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic. > What should "if" do if presented a value that isn't True or False? > Raise a TypeError? YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent. > Next thing we know, people get so used to wrapping everything they > present to "if" in a "bool()" call, that they start writing silly > things like "if bool(x == 7)" and "if bool(isinstance(x, int))". We cannot prevent morons from doing stupid things. "x==7" IS an explicit statement that evaluates to either True or False. Likewise, isinstance(obj, type) is a function that evaluates to either True or False. Wrapping either example in a bool call is redundant and only obfuscates the meaning. True equals True and False equal False. Why do you need to test that truth? The only time you will be forced to use the bool is when you are NOT using rich comparisons or NOT using truth testing functions in a condition. The following require NO bool function: obj == obj -> bool obj != obj -> bool obj > obj -> bool obj < obj -> bool obj >= obj -> bool obj <= obj -> bool isinstance(obj, type) -> bool callable(obj) -> bool hasattr(obj, name) -> bool issubclass(obj, name) -> bool ..along with any function that returns a bool Whereas: "if obj" -> Some esoteric semantics that defies all logic! > Why? > Because it's faster and easier to automatically wrap the value in > "bool" than it is to put in the effort to verify that the value will > always be a bool to begin with in order to avoid a useless and > annoying exception. No, because we want our code to be EXPLICIT and consistent! Remember, writing obfuscated code is easy, however, interpreting obfuscated code is difficult! A good measure of your programming skill is to see how easily your code is read by the majority. """If it's difficult to explain, it's probably a bad idea""". "if blah" is difficult to explain, whereas "if bool(blah)" is not. > At the point that happens, the "bool()" is > effectively just part of the if syntax, and we're back to where we > started. That's a ridiculous conclusion. See points above^^^ From rantingrickjohnson at gmail.com Sun Jul 15 14:56:49 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sun, 15 Jul 2012 11:56:49 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote: > So now instead of having to understand how "if" handles arbitrary > values, we have to understand how "bool" handles arbitrary values. > How is that an improvement? Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic. > What should "if" do if presented a value that isn't True or False? > Raise a TypeError? YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent. > Next thing we know, people get so used to wrapping everything they > present to "if" in a "bool()" call, that they start writing silly > things like "if bool(x == 7)" and "if bool(isinstance(x, int))". We cannot prevent morons from doing stupid things. "x==7" IS an explicit statement that evaluates to either True or False. Likewise, isinstance(obj, type) is a function that evaluates to either True or False. Wrapping either example in a bool call is redundant and only obfuscates the meaning. True equals True and False equal False. Why do you need to test that truth? The only time you will be forced to use the bool is when you are NOT using rich comparisons or NOT using truth testing functions in a condition. The following require NO bool function: obj == obj -> bool obj != obj -> bool obj > obj -> bool obj < obj -> bool obj >= obj -> bool obj <= obj -> bool isinstance(obj, type) -> bool callable(obj) -> bool hasattr(obj, name) -> bool issubclass(obj, name) -> bool ..along with any function that returns a bool Whereas: "if obj" -> Some esoteric semantics that defies all logic! > Why? > Because it's faster and easier to automatically wrap the value in > "bool" than it is to put in the effort to verify that the value will > always be a bool to begin with in order to avoid a useless and > annoying exception. No, because we want our code to be EXPLICIT and consistent! Remember, writing obfuscated code is easy, however, interpreting obfuscated code is difficult! A good measure of your programming skill is to see how easily your code is read by the majority. """If it's difficult to explain, it's probably a bad idea""". "if blah" is difficult to explain, whereas "if bool(blah)" is not. > At the point that happens, the "bool()" is > effectively just part of the if syntax, and we're back to where we > started. That's a ridiculous conclusion. See points above^^^ From roy at panix.com Sun Jul 15 14:58:22 2012 From: roy at panix.com (Roy Smith) Date: Sun, 15 Jul 2012 14:58:22 -0400 Subject: Initial nose experience References: Message-ID: In article , python at bdurham.com wrote: > Hi Roy, > > > I've been using unittest for many years, but have steadfastly > (perhaps stubbornly) avoided newfangled improvements like nose. > I finally decided to take a serious look at nose. > > Thanks for sharing your nose experience. > > What motivated you to migrate from unittest to nose? Mostly I was just looking for a better way to run our existing tests. We've got a bunch of tests written in standard unittest, but no good way to start at the top of the tree and run them all with a single command. From suziemrezitti at gmail.com Sun Jul 15 15:06:51 2012 From: suziemrezitti at gmail.com (Suzi Mrezutttii) Date: Sun, 15 Jul 2012 12:06:51 -0700 (PDT) Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! Message-ID: COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! After Jews created Israel illegally, Israel became the main base of criminal operations for the most insane type of Jews called Zionists. Israeli Jews murdered JFK in 1963 because JFK did not allow them to have atomic bombs. Read the book "Final Judgment" by Michael Piper, available online in pdf, also google for video presentation by author. Since Americans let the Jews get away with JFK murder, just four years later in 1967, Israeli Jews murdered 34 servicemen of American Navy, and seriously wounded 174, when Jews tried repeatedly to sink the USS Liberty and blame Egypt for it. Watch online the video interviews with the actual survivors, then compare the facts to the lies spread by Jews through their propaganda outlets like wikipedia. One interview with a survivor should have been enough to turn all responsible Jews and American Traitors into fertilizer within 24 hours. Since Americans let Jews get away with JFK and USS Liberty murders, Israeli Jews murdered 3000 Americans in 9/11, this time to make USA invade Afghanistan/Iraq for Jews, and to enable Jews to impose their Jew Laws (Jaws) like "Patriot Act". Watch online the video "9/11 Missing Links" made in cooperation with contacts inside FBI, CIA, National Security Agency, US Military, who are still loyal to USA. All Jews covered up for Israeli Zionists, with the help from Traitors in Washington DC, because all Jews always protect themselves as single Jew Tribe. Jews are not the sweet/smart/suffering individuals as they present themselves using their own Jew propaganda machines. Jews are full of hate and suffer from a whole range of genetic mental diseases like schizophrenia, paranoia, psychopathy, sexual perversions like pedophilia/homosexuality/etc, and many others, that make them prone to criminal/parasitic/corruptive behavior. Banking Jews started their corruption of USA in 1913 with creation of the Fed. The Great Depression of 1930's was the direct result of Jew corruption. Jews used Great Depression as an opportunity to corrupt/ expand the federal government because parasites like Jews exploit host organisms through central systems. After Hitler came to power in 1933 and removed Jews from all important positions, Germany experienced unprecedented economic growth while the rest of the world controlled by Jews suffered through Great Depression. Jews did not like this precedent and immediately in 1933 Jews declared economic war on Germany. Hitler invaded Poland in 1939 only because Poland was infested with five million Jews who constantly were harassing Germany. Jews used their media power to brainwash White Americans to fight White Germans for Jews. All the official "history" has been written by lying Jews and it should be called Jewstory instead of History. Jews are not Whites but insane mongrels who hate Whites. Jews started all the jokes about Whites like Dumb Blondes, Rednecks, Polish Jokes. The sheeple merely parroted after the Jew media. Jews are the ones who promote all those Blacks you see in the media, sports, schools, or business. Jews constantly stir up conflicts between Whites and Blacks by propagandizing the shootings of Blacks in order to take your attention away from all Jew scams. Since 9/11 Jews intensified their "Racism" tactics and their famous "Holocaust" tactics because more Americans learn every day that Jews did 9/11. Jews know they are the biggest Criminals on Earth, and that is why Jews manufactured the "Holocaust" Scam where Jews masquerade as the biggest Victims on Earth. Jews are Masters of biggest Lies and Deceptions. Without their control of brainwashing media, Jews would be nothing more than insane rats. Only Jew scams enabled many Jews to masquerade with Ivy League diplomas, Nobel Prizes, Oscars. Jews run their college/ Awards scams like Wall Street or elections scams. Independent investigations of all Ivy League colleges would show that most Jew students are frauds with standardized tests taken by somebody else or their test results falsified by corrupt admissions offices. The biggest Jew Nobel Prize winner Einstein was a fraud and plagiarist. All you know about famous Jew "scientists" is what Jews told you, the same Jews who made you believe the "Manned Moon Landings" or "Man-Made Global Warming". Jews never invented anything but Scams and Hoaxes. Jews in Israel rank well below average in IQ scores among all nations. Basically, Israel is a hellhole where tens of billions of dollars of American taxpayers' money are wasted on worthless Jews each year. Jews control the US Government illegally. The American democracy is a myth. Most of "US Presidents" since 1913 were crypto Jews (FDR, Eisenhower, LBJ, Obama with Jew mother) or Jew puppets. Recently, Jews in US Congress imposed on Americans yet another Jew Law (Jaw) called "National Defense Authorization Act" that threatens any American who tries to defend The US Constitution with its Bill of Rights. However, the ultimate power lies in the economies, now all mortally wounded by Jews. Jews were too greedy by exporting all real American jobs and forcing Americans to live on debt for too long. Once enough good Americans reach poverty levels, the game will be over for Jews, especially if their psychotic relatives in Israel pull another USS Liberty or 9/11. How can Jews control the US Government with such a small Jew population? How can Jews amass so much wealth if Jews are not very intelligent? In order to answer such questions you have to look at the Big Picture painted for you by Mother Nature a long time ago. For thousands of years, each society had a small parasitic ruling class and a large working class needed to sustain the society. Mother Nature created such a social order to facilitate the evolutionary process because living conditions for humans were very tough. Mother Nature knew that a ruling class does not have to be very intelligent because any substantial intellect leads automatically to creativity needed only by working class. Instead, Mother Nature developed our human psychology in such a way that a ruling class could rule merely by displaying symbols of power like ornamental clothes, big buildings, rituals, propaganda, and so on. For this to work, a ruling class had to be filled with psychopaths only smart enough to band together for this scam to go on, and a working class had to be filled with intelligent people busy with doing all the creative work. At least the ruling and working classes were ethnically related until around 18th century when the biggest parasitic psychopaths called Jews learned enough about the game played by ruling classes. At that time, Jews decided to have a piece of the ruling action for themselves by creating central banks or starting revolutions. Jews were around for thousands of years. Clearly, Mother Nature created Jews on her bad hair day because Jews hated all non-Jews including her best creations. This hatred made Jews the perfect tool to exploit the weaknesses of both ruling and working classes of all normal societies. By destroying the old social orders, Jews acted like maggots decomposing dead animals. Mother Nature kept Jews around for thousands of years because she needed them to change slowly the old social orders. Otherwise, Mother Nature would abort Jews a long time ago because Jews lack the intellect to create anything. Decomposition of the old social orders was largely completed by Jews in early 20th century, at least in the Western World. Since then, Jews have been trying to become the ruling class for the whole world. Apparently, Mother Nature now uses Jews to internationalize all societies in order to speed up the evolution process because there are clear benefits in global cooperation. However, Mother Nature is well aware that Jews are useless beyond this point. Jews corrupted all politics, economies, military, sciences, business, medicine and healthcare, education, agriculture, and all others. Through their insanity, Jews started two world wars and are about to start the third one, Jews killed millions with their invention of communism, Jews polluted the whole world with nuclear technologies, Jews destroyed agriculture and food supplies with GMO crops, Jews killed millions with the poisons produced by their pharmaceutical companies, Jews imposed on societies their pedophilia and homosexuality, Jews run the biggest crime networks including illegal drugs and prostitution/pornography, and on and on. The old ruling classes would not be able to do so much harm to the working classes because there were many different societies with different ruling classes and the classes within each society were ethnically related. This means that fraudulent ruling classes could last forever without the working classes ever waking up. However, Mother Nature wants to make all psychopathic rulers extinct once they served their purpose in Nature. Mankind cannot live forever while locked in the old psychology addicted to psychopathic rulers, Jews or non-Jews. That is why Mother Nature used the biggest parasitic psychopaths Jews to force out the old parasitic ruling classes first, and now Mother Nature is using the same Jews to exploit/harm the working classes in order to initiate the next evolutionary step. Many people are already ready to deal with the Jew problem. However, most people still refuse to deal with it because they are still locked in the old psychology developed by Mother Nature thousands of years ago. The latter group of people will wake up at the latest when the economies collapse. Realize that Mother Nature made Jews screw up the attack on USS Liberty so that the survivors could tell you the truth about the US Government controlled by Jews. Mother Nature created the Internet for you so that you can research all Scams and Hoaxes done by Jews. In other words, Mother Nature realizes that it is time for you to change and Jews have to go. Mother Nature keeps Jews around so that you can see for yourself with your own eyes that something is wrong with you. If Jews can get away with their "Manned Moon Landings" or their 9/11 controlled demolitions by merely using their brainwashing media then it is time for you to CHANGE! Help Mother Nature by not watching any Jew TV or movies! Help Mother Nature to change your own psychology. Otherwise, Mother Nature will bring the change violently! From hansmu at xs4all.nl Sun Jul 15 15:25:57 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 15 Jul 2012 21:25:57 +0200 Subject: lambda in list comprehension acting funny In-Reply-To: References: <03943ea6-5914-4de4-821c-055bed1d5804@f9g2000pbd.googlegroups.com> <4fffc1fd$0$29965$c3e8da3$5496439d@news.astraweb.com> <5000608c$0$6930$e4fe514c@news2.news.xs4all.nl> <500200be$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002802f$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50031945$0$6955$e4fe514c@news2.news.xs4all.nl> On 15/07/12 10:44:09, Chris Angelico wrote: > On Sun, Jul 15, 2012 at 6:32 PM, Steven D'Aprano > wrote: >> At compile time, Python parses the source code and turns it into byte- >> code. Class and function definitions are executed at run time, the same >> as any other statement. > > Between the parse step and the 'def' execution, a code object is > created. When you call it, that code object already exists. Nothing > else really matters, unless there's a bug in the Python optimizer or > something weird like that. The nearest thing Python _has_ to a > "compile time" is the execution of def. > > ChrisA "Compile time" is the phase when your Python code is turned into byte code, or a SyntaxError is raised. In this phase, a "code object" is created for the function. "Function definition time" is when the "def" command is executed. In this phase, default arguments are computed, and a "function object" is created. Among the attributes of the function object are the code object, and "cell" objects containing the bindings for its non-local variables. These bindings are used to read the variable's current value at the time the function uses the variable. -- HansM From leif.poorman at gmail.com Sun Jul 15 15:47:26 2012 From: leif.poorman at gmail.com (Leif) Date: Sun, 15 Jul 2012 12:47:26 -0700 (PDT) Subject: Request for useful functions on dicts In-Reply-To: References: <38c6d4cb-89b3-4f78-a966-be5ddccec845@googlegroups.com> Message-ID: <43241b7d-3fb6-410b-a3fe-0c5b11287925@googlegroups.com> Thanks for the suggestions, Ian! I implemented most of them and pushed the code. > That's because the Pythonic way is to either create a new object and > return it, or mutate the existing object and return None. You're saying what I was already thinking. > In Python 2.7+, intersection and difference could be written using > dictviews, which act like sets. I'm debating with myself right now whether to support 2.5 and 2.6. > def partition(f, d): Good idea, thanks. > issubdict could be implemented as a subset operation. I haven't timed The current implementation is a bit faster, and it's quite a bit faster on the common (for me) case, where one argument is much smaller than the other. I wrote it that way because if m=len(first), n=len(second), the amount of work is O(min(m,n)). Your implementation is O(m + n). Not really a big deal, unless e.g. m << n. --Leif From leif.poorman at gmail.com Sun Jul 15 15:47:26 2012 From: leif.poorman at gmail.com (Leif) Date: Sun, 15 Jul 2012 12:47:26 -0700 (PDT) Subject: Request for useful functions on dicts In-Reply-To: References: <38c6d4cb-89b3-4f78-a966-be5ddccec845@googlegroups.com> Message-ID: <43241b7d-3fb6-410b-a3fe-0c5b11287925@googlegroups.com> Thanks for the suggestions, Ian! I implemented most of them and pushed the code. > That's because the Pythonic way is to either create a new object and > return it, or mutate the existing object and return None. You're saying what I was already thinking. > In Python 2.7+, intersection and difference could be written using > dictviews, which act like sets. I'm debating with myself right now whether to support 2.5 and 2.6. > def partition(f, d): Good idea, thanks. > issubdict could be implemented as a subset operation. I haven't timed The current implementation is a bit faster, and it's quite a bit faster on the common (for me) case, where one argument is much smaller than the other. I wrote it that way because if m=len(first), n=len(second), the amount of work is O(min(m,n)). Your implementation is O(m + n). Not really a big deal, unless e.g. m << n. --Leif From tjreedy at udel.edu Sun Jul 15 16:09:44 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jul 2012 16:09:44 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/15/2012 12:19 PM, Ian Kelly wrote: > On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano > wrote: >> (For the record, I can only think of one trap for the unwary: time >> objects are false at *exactly* midnight.) > > Ugh, that's irritating. I can't think of any scenario where I would > ever want the semantics "if timeval (is not midnight):". This When printing time tables, midnight may be either 24:00 or 0:00, depending on whether it is the end or start of a journey. That could, of course, be done by explicit if time == midnight: rather than if not time:. Whether to change the current behavior was discussed on python-ideas a couple of months ago. I believe inertia and back-compatibity and the rare use case won. > reinforces the point that if you only want to test whether you have > None, you should use "is not None" rather than relying on __bool__. Right. -- Terry Jan Reedy From tjreedy at udel.edu Sun Jul 15 16:28:02 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Jul 2012 16:28:02 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5002F7AD.1000209@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> Message-ID: On 7/15/2012 1:02 PM, Andrew Berg wrote: > On 7/15/2012 5:56 AM, Steven D'Aprano wrote: >> 3) Rather than distinguishing "true" from "false", a more useful >> dichotomy is between "something" and "nothing". Python includes a number >> of ways of spelling "nothing" of various types, such as: >> >> None, 0, 0.0, '', [], {}, set() >> >> and nearly everything else is "something". > Okay, I see the value in this, but I don't understand why None has a > truth value. Because everything does (or should). > I would expect None to mean "doesn't exist" or "unknown" or > something like that - e.g., a value of 0 means 0 jelly beans in the jar > and None means there isn't a jar. > > FWIW, I have, for a reason I forget, gotten into the habit of writing > "if x is not None" when testing for None. If x might possibly be any other false value (as is, I think, the usual case), that is the right thing to do. Even if no other false value is possible, I would still use 'is not None' just to be clear what the false alternative is, and to guard against mistakes (like not knowing that time values can be false) or code changes that add the possibility of ohter false values. > However, I have not been > writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'" > when testing for True (in cases where a value of True or False makes > sense, but any other value would not). Should I? If you only want to execute the if branch when x is literally the bool object True and x could be some other non-bool true value such as 1 or 'a' or [1], etc, then you should. If x is guaranteed to be True or False, which is the case you more or less proposed, then you should not. For instance, "if isinstance(x, int) is True:" or "if (n > 3) is True:" are redundant. -- Terry Jan Reedy From rosuav at gmail.com Sun Jul 15 17:53:09 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 07:53:09 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On Mon, Jul 16, 2012 at 4:56 AM, Rick Johnson wrote: > On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote: > >> So now instead of having to understand how "if" handles arbitrary >> values, we have to understand how "bool" handles arbitrary values. >> How is that an improvement? > > Because we are keeping the condition consistent. We are not relying on implicit resolution of an object's value based on some dark, esoteric and inconsistent rules that defy all normal logic. > >> What should "if" do if presented a value that isn't True or False? >> Raise a TypeError? > > YES! Because IT IS the author's responsibility to present a condition that evaluates to either True or False. Anything else would be ridiculously inconsistent. Then the construct "if bool(some_condition):" is redundant. What you've described is a viable system (REXX, for instance, demands that an IF statement be given strictly either a 1 or a 0 (there's no True and False values, but you're not allowed to use 527 as a True value, it has to be 1)), but it's still redundant to attempt the cast. For instance, this REXX function will logically negate a value twice, thus forcing it to boolean: bool: procedure return \\arg(1) But if it's given a non-bool, it'll just bomb, exactly the same as the if statement would. So Ian's point still stands. ChrisA From rantingrickjohnson at gmail.com Sun Jul 15 21:21:06 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 18:21:06 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> On Jul 15, 4:53?pm, Chris Angelico wrote: > Then the construct "if bool(some_condition):" is redundant. Wrong again, pay attention Chris! It's ONLY redundant IF "some_condition" is a rich comparison: like "(a==b)" OR a boolean function: like "callable(a)". If HOWEVER we want to "truth test" an object (as in: "if obj") we should be FORCED to use the bool! Why? Because explicit is better than implicit and readability counts if we want to create maintainable code bases! if bool(obj) and a==b: # Correct! if obj and a==b: # Incorrect! Both lines of code currently produce the same result because "somebody" decided to give objects esoteric boolean values. Sure, we saved a few key stokes in a condition, but sadly at the cost of readability and consistency. I see no reason why choosing implicit resolution is better than explicit resolution. Saving six keystrokes is simply not enough! Python's motto has always been "readability counts", and for that reason, we should return to Explicit Boolean Resolution if we want to adhere to those principals. From hamilton at nothere.com Sun Jul 15 21:26:52 2012 From: hamilton at nothere.com (hamilton) Date: Sun, 15 Jul 2012 19:26:52 -0600 Subject: Diagramming code Message-ID: Is there any software to help understand python code ? Thanks hamilton From clp2 at rebertia.com Sun Jul 15 21:38:53 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 15 Jul 2012 18:38:53 -0700 Subject: Diagramming code In-Reply-To: References: Message-ID: On Sun, Jul 15, 2012 at 6:26 PM, hamilton wrote: > Subject: Diagramming code > > Is there any software to help understand python code ? What sort of diagrams? Control flow diagrams? Class diagrams? Sequence diagrams? Module dependency diagrams? There are many different types you could be referring to. Here's a relatively comprehensive list: http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview Regards, Chris -- UML: Kill it with fire! From rosuav at gmail.com Sun Jul 15 21:51:13 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 11:51:13 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick wrote: > If HOWEVER we want to "truth test" an object (as in: "if obj") we > should be FORCED to use the bool! Why? Because explicit is better than > implicit and readability counts if we want to create maintainable code > bases! > > if bool(obj) and a==b: # Correct! > if obj and a==b: # Incorrect! That still doesn't answer the question of what bool(obj) should do if obj is not a bool, and why if can't do the exact same thing, since if, by definition, is looking for a boolean state selector. ChrisA From hamilton at nothere.com Sun Jul 15 21:57:29 2012 From: hamilton at nothere.com (hamilton) Date: Sun, 15 Jul 2012 19:57:29 -0600 Subject: Diagramming code In-Reply-To: References: Message-ID: On 7/15/2012 7:38 PM, Chris Rebert wrote: > On Sun, Jul 15, 2012 at 6:26 PM, hamilton wrote: >> Subject: Diagramming code >> >> Is there any software to help understand python code ? > > What sort of diagrams? Control flow diagrams? Class diagrams? Sequence > diagrams? Module dependency diagrams? There are many different types > you could be referring to. Here's a relatively comprehensive list: > http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview > > Regards, > Chris > -- > UML: Kill it with fire! > OK then, let me ask, how do you guys learn/understand large projects ? hamilton From clp2 at rebertia.com Sun Jul 15 22:13:12 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 15 Jul 2012 19:13:12 -0700 Subject: Diagramming code In-Reply-To: References: Message-ID: On Sun, Jul 15, 2012 at 6:57 PM, hamilton wrote: > On 7/15/2012 7:38 PM, Chris Rebert wrote: >> >> On Sun, Jul 15, 2012 at 6:26 PM, hamilton wrote: >>> >>> Subject: Diagramming code >>> >>> Is there any software to help understand python code ? >> >> What sort of diagrams? Control flow diagrams? Class diagrams? Sequence >> diagrams? Module dependency diagrams? There are many different types >> you could be referring to. Here's a relatively comprehensive list: >> http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview >> >> Regards, >> Chris >> -- >> UML: Kill it with fire! > > OK then, let me ask, how do you guys learn/understand large projects ? In case you're responding to my trailing semi-satirical comment, let me clarify: I was remarking on UML specifically, not software-related diagrams in general. Cheers, Chris From steve+comp.lang.python at pearwood.info Sun Jul 15 22:13:56 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 02:13:56 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote: > On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano > wrote: >> (For the record, I can only think of one trap for the unwary: time >> objects are false at *exactly* midnight.) > > Ugh, that's irritating. I can't think of any scenario where I would > ever want the semantics "if timeval (is not midnight):". Yes, it is a genuine gotcha. Time values are numbers, and zero is falsey, so midnight is falsey even though it shouldn't be. There's no good solution here, since we have a conflict between treating time values as time values ("midnight is nothing special") and as numbers ("midnight == 0 which is falsey"). The only "solution" is to throw out duck-typing of boolean values, which is tossing the baby out with the bathwater -- bool duck-typing works fine for everything else. > This > reinforces the point that if you only want to test whether you have > None, you should use "is not None" rather than relying on __bool__. Often you should, but I didn't mention anything about testing for None. Testing objects in a boolean context is more than just testing for None. I have just written a bunch of code with about two dozen examples similar to this: for item in (seq or []): do_something_with(item) iterates over seq if it is non-empty, or the empty list. Writing it like this would be more painful, more complex, less readable and less idiomatic: if seq is not None: for item in seq: do_something_with(item) not to mention completely unnecessary if you have already checked that seq is either None or a sequence, and not some other arbitrary value. (If seq really could be any type at all, then an explicit identity test against None is required.) One of my favourites: value = (dict or {}).get('key') instead of: value = None if dict is None else dict.get('key') -- Steven From jeanpierreda at gmail.com Sun Jul 15 22:15:13 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 15 Jul 2012 22:15:13 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: On Sun, Jul 15, 2012 at 9:51 PM, Chris Angelico wrote: >> if bool(obj) and a==b: # Correct! >> if obj and a==b: # Incorrect! > > That still doesn't answer the question of what bool(obj) should do if > obj is not a bool, and why if can't do the exact same thing, since if, > by definition, is looking for a boolean state selector. If can obviously do the exact same thing -- it does, in Python. I don't agree with the angle that Rick is spinning, so let me write my own: By forcing the objects in conditional to be booleans, you are forced to do something to non-booleans to convert them. By doing so, you will help inform the reader what the non-boolean is, which makes it easier for them to figure out the code. For example, instead of "if stack:" or "if bool(stack):", we could use "if stack.isempty():". This line tells us explicitly that stack is a container. Or instead of "if dist:" or "if bool(dist):" we could use "if dist == 0:". This tells us explicitly that stack is a number. Supposedly this makes it easier to read code. It certainly reads more like English! :) As far as I know, the only use of having a polymorphic boolean conversion is reducing the amount of typing we do. Generally objects with otherwise different interfaces are not interchangeable just because they can be converted to booleans, so you wouldn't lose much by being forced to explicitly convert to boolean with something interface-specific. -- Devin From rantingrickjohnson at gmail.com Sun Jul 15 22:31:23 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 19:31:23 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: On Jul 15, 8:51?pm, Chris Angelico wrote: > On Mon, Jul 16, 2012 at 11:21 AM, Ranting Rick > > wrote: > > If HOWEVER we want to "truth test" an object (as in: "if obj") we > > should be FORCED to use the bool! Why? Because explicit is better than > > implicit and readability counts if we want to create maintainable code > > bases! > > > if bool(obj) and a==b: # Correct! > > if obj and a==b: ? ? ? # Incorrect! > > That still doesn't answer the question of what bool(obj) should do if > obj is not a bool, and why if can't do the exact same thing, since if, > by definition, is looking for a boolean state selector. > > ChrisA My point is no different than this example: py> cost = 1.75 py> cost 1.75 py> 'Cost = ' + cost Traceback (most recent call last): File "", line 1, in 'Cost = ' + cost TypeError: cannot concatenate 'str' and 'float' objects py> 'Cost = ' + str(cost) 'Cost = 1.75' We DON'T want Python to silently convert "cost" to a string. What we DO want is to force the author to use the str function thereby making the conversion explicit. Same with converting objects to bools. We DON'T want "if" to magically convert a non-boolean into a boolean. What we DO want is to force the author to use the bool function thereby making the conversion explicit. By doing so we transform confusion into comprehension. By doing so we maintain the principals of readability counts. From steve+comp.lang.python at pearwood.info Sun Jul 15 22:38:35 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 02:38:35 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 12:02:37 -0500, Andrew Berg wrote: > On 7/15/2012 5:56 AM, Steven D'Aprano wrote: >> 3) Rather than distinguishing "true" from "false", a more useful >> dichotomy is between "something" and "nothing". Python includes a >> number of ways of spelling "nothing" of various types, such as: >> >> None, 0, 0.0, '', [], {}, set() >> >> and nearly everything else is "something". > Okay, I see the value in this, but I don't understand why None has a > truth value. And this is exactly the sort of mental confusion that Laura Crichton warned about (see the link I included earlier). Thinking about "truth values" is harmful, since that's arbitrary. That way goes to Javascript, PHP, Ruby etc. that seem to arbitrary pick whatever things are truthy or falsey according to some random whim, or according to some implementation detail that is meaningless outside of the implementation, such as Javascript insisting that while false is falsey, if you box it in an object it becomes truthy. It's crap like that which gives duck-typing bools a bad name. The distinction you should consider is: - is it something, or nothing? (relative to the type in question, of course) Python (at least the built-ins, third-party code can do any old crap they want) is consistent in this. Instances which represent something/non- emptiness are true, those which represent nothing/emptiness are false. 0? That's the int that represents nothing, so it's false. 23.723? That's one of many floats that represents something, so it's true. 'spam'? That's one of many non-empty strings, so it's true. ''? That's an empty string, that it, it contains nothing, so it is false. None? That represents a lack of a thing, that is, nothing, so it's false. (Please don't get into a great philosophical debate over whether nothingness is itself something. That impressed me when I was 15. But now I know about reification: just because we have a name for a concept doesn't mean that the concept is something concrete. None is an object, but it *represents* the lack of an object.) > I would expect None to mean "doesn't exist" or "unknown" or > something like that - e.g., a value of 0 means 0 jelly beans in the jar > and None means there isn't a jar. How you interpret some_variable = None depends on what some_variable represents. If some_variable represents "number of jelly beans in a jar", then that should be 0 if there is no jar. If you want to create a language with ternary truth values (yes, no, mu) or some larger number (yes, no, maybe, mu, contradiction, unknowable, ...) be my guest. Just do everyone a favour and do some research on the large literature on non-boolean logic systems first. > FWIW, I have, for a reason I forget, gotten into the habit of writing > "if x is not None" when testing for None. However, I have not been > writing "if x is True: ..."/"elif x is False: ..."/"else: 'ruh-roh'" > when testing for True (in cases where a value of True or False makes > sense, but any other value would not). Should I? Only if you want people to laugh at you. If you *genuinely* want to implement Java in Python, then be explicit about your type-testing: if isinstance(x, bool) and x: ... or even if type(x) is bool and x: ... # disallow subclasses Otherwise, where do you stop? if x is True is True is True is True is True is ... Or you could just write idiomatic Python code, including duck-typing, and that includes duck-typing bools. Why do you care if somebody calls your function with flag=1 instead of flag=True? -- Steven From rantingrickjohnson at gmail.com Sun Jul 15 22:41:34 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 19:41:34 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2e6b36a0-122a-4776-b866-ccd5412bb775@l32g2000yqb.googlegroups.com> On Jul 15, 9:13?pm, Steven D'Aprano wrote: > I have just written a bunch of code with about two dozen examples similar > to this: > > for item in (seq or []): > ? ? do_something_with(item) > > iterates over seq if it is non-empty, or the empty list. Writing it like > this would be more painful, more complex, less readable and less > idiomatic: > > if seq is not None: > ? ? for item in seq: > ? ? ? ? do_something_with(item) > > not to mention completely unnecessary if you have already checked that > seq is either None or a sequence, and not some other arbitrary value. Short circuitry is a powerful tool! But why the heck would your sequences ever be None? Are you using None as a default? And if so, why not use an empty sequence instead ([], {}, "")? From rantingrickjohnson at gmail.com Sun Jul 15 22:58:20 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 19:58:20 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: <50ddab08-0e8d-4f74-8d71-9cc2f538a2f1@m8g2000yqo.googlegroups.com> On Jul 15, 9:15?pm, Devin Jeanpierre wrote: > For example, instead of "if stack:" or "if bool(stack):", we could use > "if stack.isempty():". This line tells us explicitly that stack is a > container. Or instead of "if dist:" or "if bool(dist):" we could use > "if dist == 0:". This tells us explicitly that stack is a number. > Supposedly this makes it easier to read code. It certainly reads more > like English! :) Yes, but this approach involves adding new "value testing" methods to every object. Whilst these specific methods would probably inject more comprehension than using bool, i believe the bool function can handle this problem better due to its monolithic and generic nature. No need to memorize which method is needed for strings, or integers, or lists, etc... just use bool and everything works. As for the semantics, we should let the object decide how to respond to a __bool__() request. But what's the point of having a bool function if we refuse to use it correctly? We force str, int, and float conversion all day, but not the bool? Where is the consistency? Where is the bool!? From rosuav at gmail.com Sun Jul 15 22:58:40 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 12:58:40 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <2e6b36a0-122a-4776-b866-ccd5412bb775@l32g2000yqb.googlegroups.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> <2e6b36a0-122a-4776-b866-ccd5412bb775@l32g2000yqb.googlegroups.com> Message-ID: On Mon, Jul 16, 2012 at 12:41 PM, Ranting Rick wrote: > On Jul 15, 9:13 pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> I have just written a bunch of code with about two dozen examples similar >> to this: >> >> for item in (seq or []): >> do_something_with(item) > > Short circuitry is a powerful tool! But why the heck would your > sequences ever be None? Are you using None as a default? And if so, > why not use an empty sequence instead ([], {}, "")? Function default arguments spring to mind, especially if the list will be mutated afterwards. ChrisA From steve+comp.lang.python at pearwood.info Sun Jul 15 22:58:44 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 02:58:44 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote: > If HOWEVER we want to "truth test" an object (as in: "if obj") we should > be FORCED to use the bool! Why? Because explicit is better than implicit And this is why Rick always writes code like: integer_value_three = int(1) + int(2) assert (int(integer_value_three) == \ int(3) is True) is True, str("arithmetic failed") list_containing_three_values_which_are_all_integers_but_might_later_have_more_or_fewer_values_or_other_types = list([1, 2, integer_value_three]) because you can never have too much explicitness. Who wouldn't want to read code like that? > and readability counts if we want to create maintainable code bases! Yes you, Rick, are correct, that is to say not wrong, that readability, that is to say the quality of ease of reading the text in question, counts, that is to say that it matters to people who care about ease of reading, when our motivation is to create, that is to say write, maintainable code bases, that is to say unified collections of code which can have software errors fixed and new features added with relatively small amounts of effort on behalf of the human programmer. And that, the reason given in the sentence above, is the reason that we, collectively all programmers, should prefer to be explicit, not merely conveying meaning by implication about everything we, collectively all programmers, write, including typing, use of speech-recognition software, or any future technological process by which text or program code or both is transcribed from the idea of the human person to a permanent form recorded where other people, or non-human sentient beings, can read or otherwise gain access to it for the purpose of understanding the content of the test or program code or both. -- Steven From rosuav at gmail.com Sun Jul 15 23:05:48 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 13:05:48 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano wrote: > And that, the reason given in the sentence above, is the reason that we, > collectively all programmers, should prefer to be explicit, not merely > conveying meaning by implication about everything we, collectively all > programmers, write, including typing, use of speech-recognition software, > or any future technological process by which text or program code or both > is transcribed from the idea of the human person to a permanent form > recorded where other people, or non-human sentient beings, can read or > otherwise gain access to it for the purpose of understanding the content > of the test or program code or both. I'd rather be booled in oil. ChrisA *ducks for cover* From rantingrickjohnson at gmail.com Sun Jul 15 23:21:41 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 20:21:41 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 15, 9:58?pm, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote: > > If HOWEVER we want to "truth test" an object (as in: "if obj") we should > > be FORCED to use the bool! Why? Because explicit is better than implicit > > And this is why Rick always writes code like: ... Traceback (most recent quip last): Author: "", line 7, in LogicalFallacyError: "Reductio ad absurdum" From steve+comp.lang.python at pearwood.info Mon Jul 16 00:03:29 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 04:03:29 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote: > For example, instead of "if stack:" or "if bool(stack):", we could use > "if stack.isempty():". This line tells us explicitly that stack is a > container. isempty is not a container method. py> container = [] py> container.isempty() Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'isempty' Your code tells us explicitly that stack is expected to be an object with an isempty() method. What does that mean? Who knows? calories = macdonalds.fries('large') calories.isempty() => returns True When you want to write polymorphic code to handle your stack, you end up doing something like this: if isinstance(stack, MyStackClass): flag = stack.isempty() else: try: # list, collections.deque, many others flag = len(stack) == 0 except AttributeError: try: if sys.version < '3': flag = not stack.__nonzero__() else: flag = not stack.__bool__() except AttributeError: # Is this even possible in Python 3? flag = False # I guess... # If we get here, flag is true if stack is empty. if flag: ... Yeah, explicit is *so much better* for readability. Can't you just *feel* how much more readable all those irrelevant implementation details are? If you're smart, you wrap all of the above in a function: def isempty(stack): # blah blah as above But if you're *really* smart, you write to the interface and let Python take care of the polymorphic details for you: if not stack: ... (Assuming that stack defines __nonzero__ or __len__ correctly, which it better if it claims to be a container.) It boggles my mind that people who are perfectly happy to program to an interface or protocol when it comes to (say) iterables, numbers or even big complex classes with dozens of methods, suddenly freak out at the thought that you can say "if obj" and obj is duck-typed. There's a distinct lack of concrete, actual problems from duck-typing bools, and a heavy over-abundance of strongly-held opinion that such a thing is self-evidently wrong. > As far as I know, the only use of having a polymorphic boolean > conversion is reducing the amount of typing we do. The same could be said about *every* polymorphic function. The benefit is not just because you don't wear out your keyboard as fast. The benefit is the same for all other polymorphic code: it lets you write better code faster with fewer bugs and less need for unnecessary type restrictions. If there are a few corner cases where you actually *need* to restrict the type of your flags to a actual bool, well, Python gives you the tools to do so. Just as you can restrict the type of a sequence to exactly a list and nothing else, or a number as exactly a float and nothing else. Just do your type tests before you start operating on the object, and reject anything that doesn't match what you want. But that should be the exception, not the rule. > Generally objects > with otherwise different interfaces are not interchangeable just because > they can be converted to booleans, so you wouldn't lose much by being > forced to explicitly convert to boolean with something > interface-specific. Until somebody writes an awesomely fast stack class in C and gives it an is_empty() method instead of isempty, and your code can't use it because you made unnecessary assumptions about the implementation. -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 16 00:20:40 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 04:20:40 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 20:21:41 -0700, Ranting Rick wrote: > On Jul 15, 9:58?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote: >> > If HOWEVER we want to "truth test" an object (as in: "if obj") we >> > should be FORCED to use the bool! Why? Because explicit is better >> > than implicit >> >> And this is why Rick always writes code like: > ... > > Traceback (most recent quip last): > Author: "", line 7, in > LogicalFallacyError: "Reductio ad absurdum" Deary deary me Rick. Reductio ad adsurdum is not a fallacy. It is a counter-argument to an argument or claim, by showing that the premise of the original claim leads to an absurd conclusion. You have claimed that we should always be explicit whenever we write. But you do not actually live up to your own advice, because you can't: it is absurd to try to be explicit about everything all the time. You have misunderstood the purpose of the Zen of Python: it is not to claim that everything should be explicit, but to avoid code that is hard to understand because things which need to be explicit for clarity are implied by other parts of your code. (It's not like explicit and implicit are distinct -- everything depends on something implicit, if only the meaning of the words you use to describe it.) It certainly doesn't mean that the semantics of Python the language must be written out explicitly every time you use each feature. for x in sequence: # Yes, implies that we iterate over the values for loop variable named x in iterable sequence iterate over values and assign the loop variable each time you go around the loop executing the following block each time: # No, since that tells us what we already know and just adds # meaningless verbosity for the sake of faux "explicitness" -- Steven From rantingrickjohnson at gmail.com Mon Jul 16 00:53:51 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 21:53:51 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 15, 11:03?pm, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote: > It boggles my mind that people who are perfectly happy to program to an > interface or protocol when it comes to (say) iterables, numbers or even > big complex classes with dozens of methods, suddenly freak out at the > thought that you can say "if obj" and obj is duck-typed. "if obj" is in essence doing "if bool(obj)" behind the scenes. My question is: Why hide such valuable information from the reader? It's obvious that "if bool(obj)" will return a boolean; whereas "if obj" is ambiguous. > There's a distinct lack of concrete, actual problems from duck-typing > bools, and a heavy over-abundance of strongly-held opinion that such a > thing is self-evidently wrong. If the multitudes of misunderstandings from "if obj" on this list have not convinced you yet, then i lack the energy to educate you! > > As far as I know, the only use of having a polymorphic boolean > > conversion is reducing the amount of typing we do. > > The same could be said about *every* polymorphic function. For which "bool" IS! Wikipedia to the rescue: """In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function.""" bool("a") -> True bool(0) -> False bool([1,2,3]) -> True bool(True) -> True > The benefit is not just because you don't wear out your keyboard as fast. > The benefit is the same for all other polymorphic code: it lets you write > better code faster with fewer bugs and less need for unnecessary type > restrictions. There are NO type restrictions for bool. > If there are a few corner cases where you actually *need* to restrict the > type of your flags to a actual bool, well, Python gives you the tools to > do so. Yes, the bool() From rantingrickjohnson at gmail.com Mon Jul 16 01:03:52 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Sun, 15 Jul 2012 22:03:52 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 15, 11:20?pm, Steven D'Aprano wrote: > (It's not like explicit and implicit are distinct -- everything depends > on something implicit, if only the meaning of the words you use to > describe it.) > > It certainly doesn't mean that the semantics of Python the language must > be written out explicitly every time you use each feature. Of course not. Don't be ridiculous. > for x in sequence: [...] This syntax is explicit *enough*. We don't need to be any more explicit. But if you are going to argue that "if obj" is *explicit enough*, then apply your argument consistently to "String"+1.75 also. Why must we be explicit about string conversion BUT not boolean conversion? Can you reduce this to the absurd? Or will you just choose to ignore this valid point? From rosuav at gmail.com Mon Jul 16 01:57:39 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 15:57:39 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 16, 2012 at 2:53 PM, Ranting Rick wrote: > "if obj" is in essence doing "if bool(obj)" behind the scenes. My > question is: Why hide such valuable information from the reader? It's > obvious that "if bool(obj)" will return a boolean; whereas "if obj" is > ambiguous. Proves nothing. At least when there are less names used, there's less possibility of monkey-patching. >>> def bool(n): ... return 5 ... >>> if bool([]): ... print("Yay?") ... Yay? ChrisA From rosuav at gmail.com Mon Jul 16 02:00:06 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 16 Jul 2012 16:00:06 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 16, 2012 at 3:03 PM, Ranting Rick wrote: > But if you are going to argue that "if obj" is *explicit enough*, then > apply your argument consistently to "String"+1.75 also. Why must we be > explicit about string conversion BUT not boolean conversion? Can you > reduce this to the absurd? Or will you just choose to ignore this > valid point? Personally, I'm quite okay with automatic upcasts to string. But if you want to be explicit, particularly with floats, the solution often is not to use str(), but a proper number-formatting routine. You want "String%f"%1.75 for full power. But when you're just letting the language do the translation, it's much of a muchness whether you put an explicit toString() call in. ChrisA From breamoreboy at yahoo.co.uk Mon Jul 16 02:30:14 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Jul 2012 07:30:14 +0100 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 16/07/2012 04:05, Chris Angelico wrote: > On Mon, Jul 16, 2012 at 12:58 PM, Steven D'Aprano > wrote: >> And that, the reason given in the sentence above, is the reason that we, >> collectively all programmers, should prefer to be explicit, not merely >> conveying meaning by implication about everything we, collectively all >> programmers, write, including typing, use of speech-recognition software, >> or any future technological process by which text or program code or both >> is transcribed from the idea of the human person to a permanent form >> recorded where other people, or non-human sentient beings, can read or >> otherwise gain access to it for the purpose of understanding the content >> of the test or program code or both. > > I'd rather be booled in oil. > > ChrisA > *ducks for cover* > What a silly bunt[1] :) *also ducks for cover* [1] from a Monty Python sketch for those who don't know about a guy who pronounces c's as b's, hence Kings Bollege Bambridge -- Cheers. Mark Lawrence. From wuwei23 at gmail.com Mon Jul 16 03:21:12 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 16 Jul 2012 00:21:12 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <45561803-f733-4900-b397-e5e81604a3bb@re8g2000pbc.googlegroups.com> On Jul 16, 2:53?pm, Ranting Rick wrote: > "if obj" is in essence doing "if bool(obj)" behind the scenes. My > question is: Why hide such valuable information from the reader? If @decorator is in essence doing "function = decorator(function)" behind the scenes, why hide that? If classes are just syntactic sugar for dicts of functions, why hide that? > It's > obvious that "if bool(obj)" will return a boolean; whereas "if obj" is > ambiguous. It's only ambiguous if you're the sort of idiot who believes every language should conform to their a priori expectations. The behaviour is _documented and standard_, so it's in no way ambiguous unless someone has actively failed to do _their_ part and _educate themselves_: http://docs.python.org/library/stdtypes.html#truth-value-testing > If the multitudes of misunderstandings from "if obj" on this list have > not convinced you yet By that argument, _every_ Python feature that is misunderstood should be modified to meet the expectations of those who have refused to understand the language. In which case, why even bother having different languages with different ways of doing...oh wait, I'm talking to the monoculture king. Forget that line of reasoning. Also: citation or STFU. Provide links to 3 threads from the last month that have revolved around misunderstanding of truth values. > > > As far as I know, the only use of having a polymorphic boolean > > > conversion is reducing the amount of typing we do. > > > The same could be said about *every* polymorphic function. > > For which "bool" IS! Yes. That was Steven's point, which you missed in all of your usual mouth frothing. From wuwei23 at gmail.com Mon Jul 16 03:27:18 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 16 Jul 2012 00:27:18 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 16, 3:03?pm, Ranting Rick wrote: > But if you are going to argue that "if obj" is *explicit enough*, then > apply your argument consistently to "String"+1.75 also. Why must we be > explicit about string conversion BUT not boolean conversion? What _other_ than booleans can you expect a condition to reduce down to? Seriously. What might you possibly expect 'obj' in 'if obj' to be? Tuesday? The colour mauve? That sinking feeling that you're entering into a debate that's far above your ability to understand it? Now: as an expression "String"+1.75 can be _anywhere_, so _what_ you want will very much be contextual. Do you want "String1.75"? Do you want float("String") + 1.75? Do you want it to error? So yes, here you very much need to be explicit. > Can you reduce this to the absurd? You've already taken care of that. From steve+comp.lang.python at pearwood.info Mon Jul 16 03:52:04 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 07:52:04 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5003c824$0$1527$c3e8da3$76491128@news.astraweb.com> On Sun, 15 Jul 2012 22:03:52 -0700, Ranting Rick wrote: > But if you are going to argue that "if obj" is *explicit enough*, then > apply your argument consistently to "String"+1.75 also. Why must we be > explicit about string conversion BUT not boolean conversion? The problem with "String" + 1.75 is not lack of explicitness, but ambiguity. The + is operator is plenty explicit, but it is ambiguous when the operands have different types. Should it...? - truncate "String" at the first non-digit (hence "") and then coerce it to 0.0, and hence return the float 1.75? - coerce "String" to a float NaN on the basis that "String" is not a number, and hence return NaN? - coerce 1.75 to a string, and hence return "String1.75"? The first behaviour is rather dubious, but a good case could be made for the second or third. Python takes a fourth approach, and refuses to allow such mixed type operations. If + always meant "numeric addition", and & was used for string concatenation, then we could have unambiguous expressions using mixed types: 1 + 1.75 # int + float always coerces to float 1 + "2" # int + str always coerces to int 1 & "2" # int & str always coerces to str but since & is used for integer bitwise-and, and + is used for both concatenation and addition, we can't, and so Python raises an exception. For arithmetic, there is an unambiguous hierarchy of types, the numeric tower, which tells us which types coerce to what, e.g.: int -> float -> complex But there is no such hierarchy when it comes to (say) mixed strings and lists, etc., and hence Python raises an exception rather than guessing which type you wanted as the result. This is completely irrelevant when it comes to bools -- we don't have to coerce a value into another type, we just need to know if it is something or nothing. The object itself is best able to make that decision, hence delegating it to a protocol and method: - If the object is a container, and it has a length of 0, it is empty and hence nothing (falsey); if it has a non-zero length, it is non-empty and hence something (truthy). - Otherwise ask the container whether it is something or nothing by calling __nonzero__ (the original name) or __bool__. Python makes a rather big blunder, at least from the perspective of consistency. Bools are ints: py> issubclass(bool, int) True py> isinstance(True, int) True py> isinstance(False, int) True but there are things that can be converted into bools that can't be converted into ints, even though bools *are* ints! Contradiction. py> x = [None, 42, ''] py> bool(x) True py> int(x) Traceback (most recent call last): File "", line 1, in TypeError: int() argument must be a string or a number, not 'list' Since x can be converted into True, and True == 1, you should be able to convert x into 1. But that's crazy, since x = [None, 42, '']. *shrug* I don't call this a gotcha, but it is one of the more ugly consequences of Python's bool implementation. > Can you > reduce this to the absurd? Or will you just choose to ignore this valid > point? Mu. (Neither true nor false.) -- Steven From ulrich.eckhardt at dominolaser.com Mon Jul 16 03:58:46 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 16 Jul 2012 09:58:46 +0200 Subject: Diagramming code In-Reply-To: References: Message-ID: Am 16.07.2012 03:57, schrieb hamilton: > OK then, let me ask, how do you guys learn/understand large projects ? 1. Use the program. This gives you an idea what features are there and a bit how it could be structured. 2. Build the program, to see what is done to get the program running. This should give you an idea what pieces there are and where they are [from]. 3. Read design documentation (which is too often outdated) which should give you an idea what the intention of the project's structure is. 4. Read the code documentation (which is hopefully more up to date). This should give you an idea about responsibilities within the code. 5. Read the code itself. This can also be done while single-stepping through it with a debugger, just to see it run. Of course there are also secondary resources like developers' and users' mailinglists, websites, bugtrackers that provide information and help. Sometimes, drawing a few diagrams from steps 3 and 4 to document relationships between things is helpful. IMHO having a text describing the relationships in prose is superior to that though. In particular a diagram can't describe the rationale for something, you need prose for that. HTH & YMMV Uli From steve+comp.lang.python at pearwood.info Mon Jul 16 04:05:16 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 08:05:16 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> <2e6b36a0-122a-4776-b866-ccd5412bb775@l32g2000yqb.googlegroups.com> Message-ID: <5003cb3c$0$1527$c3e8da3$76491128@news.astraweb.com> On Sun, 15 Jul 2012 19:41:34 -0700, Ranting Rick wrote: > Short circuitry is a powerful tool! But why the heck would your > sequences ever be None? Are you using None as a default? And if so, why > not use an empty sequence instead ([], {}, "")? Mostly for explicitness. I want to be able to say that there is *explicitly* no seq, not merely that it happens to be a list which right now is empty but later might not be. Using None for missing values is idiomatic Python. You should approve, if only for the sake of consistency: None is meant to be used as "no such value", and that's exactly how I am using it, even at the cost of my convenience when writing the code. -- Steven From joel.goldstick at gmail.com Mon Jul 16 05:00:42 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 16 Jul 2012 05:00:42 -0400 Subject: Diagramming code In-Reply-To: References: Message-ID: On Mon, Jul 16, 2012 at 3:58 AM, Ulrich Eckhardt wrote: > Am 16.07.2012 03:57, schrieb hamilton: > >> OK then, let me ask, how do you guys learn/understand large projects ? > > > 1. Use the program. This gives you an idea what features are there and a bit > how it could be structured. > 2. Build the program, to see what is done to get the program running. This > should give you an idea what pieces there are and where they are [from]. > 3. Read design documentation (which is too often outdated) which should give > you an idea what the intention of the project's structure is. > 4. Read the code documentation (which is hopefully more up to date). This > should give you an idea about responsibilities within the code. > 5. Read the code itself. This can also be done while single-stepping through > it with a debugger, just to see it run. > > Of course there are also secondary resources like developers' and users' > mailinglists, websites, bugtrackers that provide information and help. > > Sometimes, drawing a few diagrams from steps 3 and 4 to document > relationships between things is helpful. IMHO having a text describing the > relationships in prose is superior to that though. In particular a diagram > can't describe the rationale for something, you need prose for that. > > HTH & YMMV > > Uli > -- > http://mail.python.org/mailman/listinfo/python-list Do you know about pydoc? Its a great way to get a handle on your modules. It doesn't make diagrams, but a synopsis of what is in the module. It makes use of docstrings, for the module and each class and function in the module. -- Joel Goldstick From anthra.norell at bluewin.ch Mon Jul 16 06:32:09 2012 From: anthra.norell at bluewin.ch (Frederic Rentsch) Date: Mon, 16 Jul 2012 12:32:09 +0200 Subject: Tkinter.event.widget: handler gets name instead of widget. In-Reply-To: References: <1341782353.2041.136.camel@hatchbox-one> <89816e26-fc20-4cdc-ba6c-f252231d43ba@f16g2000yqg.googlegroups.com> Message-ID: <1342434729.2741.174.camel@hatchbox-one> On Sat, 2012-07-14 at 20:10 -0700, rantingrickjohnson at gmail.com wrote: > On Thursday, July 12, 2012 1:53:54 PM UTC-5, Frederic Rentsch wrote: > > > The "hit list" is a table of investment titles (stock, funds, bonds) > > that displays upon entry of a search pattern into a respective template. > > The table displays the matching records: name, symbol, ISIN, CUSIP, Sec. > > Any line can be click-selected. So they are to look like buttons. > > Hmm. If they "appear" like a button widget anyway, then why not just use a button widget? > Why indeed? Why does one do simple things in a complicated way? Stations on the sinuous path the explorer takes surveying unknown territory, I guess. Your example below is just what I need. Thanks! > > Representing the mentioned names and id codes in Label widgets was the > > simplest way I could come up with to align them in columns, admittedly > > without the benefit of much experience. But it does look good. the > > layout is fine. > > But is it really the "simplest"? :) > > ## START CODE ## > import Tkinter as tk > from Tkconstants import * > > colWidths = (5,10,30,5) > N_COLS = len(colWidths) > N_ROWS = 6 > > root = tk.Tk() > for r in range(N_ROWS): > # Create some imaginary text to display in each column. > # Also try using string methods "center" and "rjust" to > # see alternative justification of text. > lst = [str(r).ljust(colWidths[r]) for r in range(N_COLS)] > b=tk.Button(root, text=''.join(lst)) > b.pack(padx=5, pady=5) > root.mainloop() > ## END CODE ## > > You could easily expand that into something reusable. > > Now. If you need to place fancy borders around the texts, or use multiple fonts, or use images, or blah blah blah... then you may want to use the "canvas items" provided by the Tkinter.Canvas widget INSTEAD of buttons. > > With the canvas, you can create a simple rectangle (canvas.create_rectangle) that represents a button's outside dimension and give it a "button styled" border. Then you can bind click events to mimic the button press action. Then you can place canvas_text items on top of that fake button and configure them to be invisible to click events. These text items will not interfer like the Tkinter.Label widgets are currently doing. > > However, i would suggest the Tkinter.Button solution is the easiest by far. > > > I find the Tkinter system quite challenging. Doing a layout isn't so > > much a matter of dimensioning and placing things as a struggle to trick > > a number of automatic dimensioning and placing mechanisms into > > obliging--mechanisms that are rather numerous and hard to remember. > > I don't think i agree with that assessment. > Sticky, justify, side, anchor, width, height, pad, ipad . . . a plethora of similar formatting concepts with applicability, precedence and effect rules that are certainly easy to work with once one knows them inside out. Until such time it's much trial-and-error, and reading of course, which also frequently involves guessing what is meant and cross-checking by experiment. For instance, I had to find a way to control the size of frames. The geometry mangers deflate everything bottom to top and utterly ignore width and height specifications unless the widget is empty. The solution I found was "spanners", frames slimmed down to zero whose length acts as a foot in the door of their parent, as it were. I suspect there are better ways. > ## START TANGENTIAL MEANDERINGS ## > I find the geometry management of Tkinter to be quite powerful whilst being simultaneously simplistic. You only have three main types of management: "Grid", "Place", and "Pack". Each of which has a very specific usage. One caveat to know is that you can NEVER mix "Grid" and "Pack" in the same container widget! I find myself using grid and pack the most, with grid being at the top of the list. > > Now, i will agree that grid can be confusing at first until you understand how to "rowconfigure" and "columnconfigue" the containing widget (be it a frame or a toplevel). There is also the "sticky" attribute to consider. > ## END TANGENTIAL MEANDERINGS ## > Thanks for the reminder. > But all in all, i would say the most difficult part of the Tkinter geometry management API is coming to grips as to which of the three geometry managers is the best choice for the particular problem at hand -- and you will find yourself using more than one manager in a single GUI app! > > But i don't see you solving this problem by stacking one widget on another. I believe it's time to seek out a new solution. > I agree. Your idea of using pre-formatted text in buttons is definitely the way to go. > EASY: Using rows of Tkinter.Button coupled with a per-formatted text string. > ADVANCED: Creating "pseudo buttons" on a canvas and stacking text objects (or whatever you like) on them. I'll keep that in mind. Finally I can report that I found the error I started this thread with. (Attribute 'widget' of an event was type str) I have a Frame "Data" as a container of all sorts of things, among which lists with selectable lines (the "Hit Lists"). Two such lists get initiated with said data frame as parent, and they instantly get removed (grid_remove) to be resuscitated (grid) later on demand. Both lists are assigned to respective attributes of a Main object that controls everything. At some point Hit List 1 gets resuscitated and is passed records to display, which it does. Selecting one of the records backfires with the mentioned error. Comparing ids I noticed that id (Main.children ['data-frame'].children ['hit-list-1']) is different from id (Main.Hit_List_1) when it should be the same. I conclude that it is a bad idea to prepare widgets one expects to need, grid_remove them and grid them temporarily on demand. They get into each other's way if they share parents and the place in the layout. The way to go is to create them on demand and destroy them when they're done. Thanks again to all who provided directions and shared their thoughts. Frederic From duncan.booth at invalid.invalid Mon Jul 16 06:43:50 2012 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jul 2012 10:43:50 GMT Subject: code review References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 13 Jul 2012 12:30:47 +0000, Albert van der Horst wrote: >> The worst of is, of course, = for assignment instead of := . This is >> a convention that Python follows, to my dismay. > > *shrug* > > The worst is to use = for both equality and assignment, like some > BASICs. At least Python does not allow assignment as an expression, so > you can't make the typical C error of: > > if x = y: do_something() # oops meant x == y > Technically of course Python doesn't have assignment, it just binds names. Albert raised the subject of Algol 68 which if I remember correctly used := for assignment and = to bind names (although unlike Python you couldn't then re-bind the name to another object in the same scope). -- Duncan Booth http://kupuguy.blogspot.com From phihag at phihag.de Mon Jul 16 06:54:06 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 16 Jul 2012 12:54:06 +0200 Subject: Initial nose experience In-Reply-To: References: Message-ID: <5003F2CE.4050903@phihag.de> On 07/15/2012 08:58 PM, Roy Smith wrote: >> What motivated you to migrate from unittest to nose? > Mostly I was just looking for a better way to run our existing tests. > We've got a bunch of tests written in standard unittest, but no good way > to start at the top of the tree and run them all with a single command. Currently, $ python -m unittest does nothing useful (afaik). Would it break anything to look in . , ./test, ./tests for any files matching test_* , and execute those? - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From roy at panix.com Mon Jul 16 07:33:38 2012 From: roy at panix.com (Roy Smith) Date: Mon, 16 Jul 2012 07:33:38 -0400 Subject: Initial nose experience References: Message-ID: In article , python at bdurham.com wrote: > After years of using unittest, what would you say are the pros and > cons of nose? BTW, although I'm currently using nose just as a unittest aggregator, I can see some nice advantages to native nose functionality. The most obvious is that tests can be plain-old static functions at the top level of a module. In unittest, you have to subclass TestCase, then write methods for that (showing its JUnit/SUnit roots). In 99% of the tests I write, I don't do anything special in my TestCase subclasses, so that's all just boilerplate busywork. I like the idea that I can skip that all now. From ben+python at benfinney.id.au Mon Jul 16 07:34:36 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 16 Jul 2012 21:34:36 +1000 Subject: code review References: <4ff0f8e0$0$29988$c3e8da3$5496439d@news.astraweb.com> <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87k3y4uegj.fsf@benfinney.id.au> Duncan Booth writes: > Technically of course Python doesn't have assignment, it just binds > names. Names, or other references. I'd argue that Python has assignment, and assignment in Python is identical with binding references to objects. But then, the Python documentation refers to ?variables? as though they exist in Python, which I'd argue they don't. It's all very confusing :-) -- \ ?Religious faith is the one species of human ignorance that | `\ will not admit of even the *possibility* of correction.? ?Sam | _o__) Harris, _The End of Faith_, 2004 | Ben Finney From __peter__ at web.de Mon Jul 16 07:47:19 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Jul 2012 13:47:19 +0200 Subject: Initial nose experience References: <5003F2CE.4050903@phihag.de> Message-ID: Philipp Hagemeister wrote: > Currently, $ python -m unittest does nothing useful (afaik). Would it > break anything to look in . , ./test, ./tests for any files matching > test_* , and execute those? http://docs.python.org/library/unittest#test-discovery From phihag at phihag.de Mon Jul 16 08:37:33 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 16 Jul 2012 14:37:33 +0200 Subject: unittest: Improve discoverability of discover (Was: Initial nose experience) In-Reply-To: References: <5003F2CE.4050903@phihag.de> Message-ID: <50040B0D.3090706@phihag.de> On 07/16/2012 01:47 PM, Peter Otten wrote: > http://docs.python.org/library/unittest#test-discovery That's precisely it. Can we improve the discoverability of the discover option, for example by making it the default action, or including a message "use discover to find test files automatically" if there are no arguments? - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From ben+python at benfinney.id.au Mon Jul 16 08:37:58 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 16 Jul 2012 22:37:58 +1000 Subject: Initial nose experience References: Message-ID: <87y5mjubix.fsf@benfinney.id.au> Roy Smith writes: > In article , > python at bdurham.com wrote: > > > After years of using unittest, what would you say are the pros and > > cons of nose? > > BTW, although I'm currently using nose just as a unittest aggregator Be aware that Python 2.7 and higher has unit test discovery in the standard library: $ python -m unittest discover will look through all packages within the current directory and collect unit tests it finds, then run them and report . You can get the same in earlier versions of Python with ?unittest2? . -- \ ?I prayed for twenty years but received no answer until I | `\ prayed with my legs.? ?Frederick Douglass, escaped slave | _o__) | Ben Finney From phihag at phihag.de Mon Jul 16 08:49:08 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 16 Jul 2012 14:49:08 +0200 Subject: unittest: Improve discoverability of discover (Was: Initial nose experience) In-Reply-To: <50040B0D.3090706@phihag.de> References: <5003F2CE.4050903@phihag.de> <50040B0D.3090706@phihag.de> Message-ID: <50040DC4.4000900@phihag.de> On 07/16/2012 02:37 PM, Philipp Hagemeister wrote: > Can we improve the discoverability of the discover > option, for example by making it the default action, or including a > message "use discover to find test files automatically" if there are no > arguments? Oops, already implemented as of Python 3.2. Sorry, should've checked before. - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From storchaka at gmail.com Mon Jul 16 09:01:45 2012 From: storchaka at gmail.com (Serhiy Storchaka) Date: Mon, 16 Jul 2012 16:01:45 +0300 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On 15.07.12 19:50, Rick Johnson wrote: > We must NEVER present "if" in such confusing manner as ExampleA. ## EXAMPLE C ## py> if bool(money) == True: ... do_something() From andrea.crotti.0 at gmail.com Mon Jul 16 09:38:17 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 16 Jul 2012 14:38:17 +0100 Subject: assertraises behaviour Message-ID: I found that the behaviour of assertRaises used as a context manager a bit surprising. This small example doesn't fail, but the OSError exception is cathed even if not declared.. Is this the expected behaviour (from the doc I would say it's not). (Running on arch-linux 64 bits and Python 2.7.3, but it doesn the same with Python 3.2.3) import unittest class TestWithRaises(unittest.TestCase): def test_ass(self): with self.assertRaises(AssertionError): assert False, "should happen" raise OSError("should give error") if __name__ == '__main__': unittest.main() From lists at cheimes.de Mon Jul 16 09:55:18 2012 From: lists at cheimes.de (Christian Heimes) Date: Mon, 16 Jul 2012 15:55:18 +0200 Subject: assertraises behaviour In-Reply-To: References: Message-ID: Am 16.07.2012 15:38, schrieb andrea crotti: > This small example doesn't fail, but the OSError exception is cathed > even if not declared.. > Is this the expected behaviour (from the doc I would say it's not). > (Running on arch-linux 64 bits and Python 2.7.3, but it doesn the same > with Python 3.2.3) > > import unittest > > class TestWithRaises(unittest.TestCase): > def test_ass(self): > with self.assertRaises(AssertionError): > assert False, "should happen" > raise OSError("should give error") The OSError isn't catched as the code never reaches the line with "raise OSError". In other words "raise OSError" is never executed as the exception raised by "assert False" stops the context manager. You should avoid testing more than one line of code in a with self.assertRaises() block. Christian From torriem at gmail.com Mon Jul 16 09:56:19 2012 From: torriem at gmail.com (Michael Torrie) Date: Mon, 16 Jul 2012 07:56:19 -0600 Subject: Python and Qt4 Designer In-Reply-To: <5002782D.7080009@swing.be> References: <63ac761b-a0a2-4d77-a3ca-f93069fab82a@s1g2000vbj.googlegroups.com> <1bb0d4df-3937-4d5f-aedb-734e0c54eb85@f9g2000pbd.googlegroups.com> <500255BA.5080102@gmail.com> <5002782D.7080009@swing.be> Message-ID: <50041D83.5020103@gmail.com> On 07/15/2012 01:58 AM, Vincent Vande Vyvre wrote: > Rusi is not the op, and his question is about these lines > > app = None > if ( not app ): Yeah that's a no-op. The original author of that code is clearly confused there. > > not this one > > app = QtGui.QApplication([]) > > which should be written like this > > app = QtGui.QApplication(sys.argv) Yeah. The QApplication not only is the main engine, but it also parses the command-line for certain flags that influence Qt's behavior, similar to gtk's main function that also parses command-line flags (specific to gtk's operation). From subhabangalore at gmail.com Mon Jul 16 10:17:26 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Mon, 16 Jul 2012 07:17:26 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: On Sunday, July 8, 2012 10:47:00 PM UTC+5:30, Chris Angelico wrote: > On Mon, Jul 9, 2012 at 3:05 AM, <subhabangalore at gmail.com> wrote: > > On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: > >> On Sun, Jul 8, 2012 at 3:42 PM, <subhabangalore at gmail.com> wrote: > >> > file_open=open("/python32/doc1.txt","r") > >> Also, as has already been mentioned: keeping your data files in the > >> Python binaries directory isn't usually a good idea. More common to > >> keep them in the same directory as your script, which would mean that > >> you don't need a path on it at all. > > No file path! Amazing. I do not know I like to know one small example please. > > open("doc1.txt","r") > > Python will look for a file called doc1.txt in the directory you run > the script from (which is often going to be the same directory as your > .py program). > > > Btw, some earlier post said, line.split() to convert line into bag of words can be done with power(), but I did not find it, if any one can help. I do close files do not worry. New style I'd try. > > I don't know what power() function you're talking about, and can't > find it in the previous posts; the nearest I can find is a post from > Ranting Rick which says a lot of guff that you can ignore. (Rick is a > professional troll. Occasionally he says something useful and > courteous; more often it's one or the other, or neither.) > > As to the closing of files: There are a few narrow issues that make it > worth using the 'with' statement, such as exceptions; mostly, it's > just a good habit to get into. If you ignore it, your file will > *usually* be closed fairly soon after you stop referencing it, but > there's no guarantee. (Someone else will doubtless correct me if I'm > wrong, but I'm pretty sure Python guarantees to properly flush and > close on exit, but not necessarily before.) > > ChrisA Dear Group, The problem is more or less solved. Thank you for giving varied ways of thinking on the problem. Everytime I visit the group I learn so many things. Thank you all for taking your kind time to try to absolve the issue. Regards, Subhabrata Banerjee. From subhabangalore at gmail.com Mon Jul 16 10:17:26 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Mon, 16 Jul 2012 07:17:26 -0700 (PDT) Subject: Discussion on some Code Issues In-Reply-To: References: <3c4e2ef9-bf7e-4fbc-bf12-6780fdc3e5d4@googlegroups.com> <09adb3cf-f3f2-4acc-b561-a36dcf15ecc7@googlegroups.com> <11832de7-a064-494e-b3e8-32a2f15a6902@googlegroups.com> Message-ID: On Sunday, July 8, 2012 10:47:00 PM UTC+5:30, Chris Angelico wrote: > On Mon, Jul 9, 2012 at 3:05 AM, <subhabangalore at gmail.com> wrote: > > On Sunday, July 8, 2012 1:33:25 PM UTC+5:30, Chris Angelico wrote: > >> On Sun, Jul 8, 2012 at 3:42 PM, <subhabangalore at gmail.com> wrote: > >> > file_open=open("/python32/doc1.txt","r") > >> Also, as has already been mentioned: keeping your data files in the > >> Python binaries directory isn't usually a good idea. More common to > >> keep them in the same directory as your script, which would mean that > >> you don't need a path on it at all. > > No file path! Amazing. I do not know I like to know one small example please. > > open("doc1.txt","r") > > Python will look for a file called doc1.txt in the directory you run > the script from (which is often going to be the same directory as your > .py program). > > > Btw, some earlier post said, line.split() to convert line into bag of words can be done with power(), but I did not find it, if any one can help. I do close files do not worry. New style I'd try. > > I don't know what power() function you're talking about, and can't > find it in the previous posts; the nearest I can find is a post from > Ranting Rick which says a lot of guff that you can ignore. (Rick is a > professional troll. Occasionally he says something useful and > courteous; more often it's one or the other, or neither.) > > As to the closing of files: There are a few narrow issues that make it > worth using the 'with' statement, such as exceptions; mostly, it's > just a good habit to get into. If you ignore it, your file will > *usually* be closed fairly soon after you stop referencing it, but > there's no guarantee. (Someone else will doubtless correct me if I'm > wrong, but I'm pretty sure Python guarantees to properly flush and > close on exit, but not necessarily before.) > > ChrisA Dear Group, The problem is more or less solved. Thank you for giving varied ways of thinking on the problem. Everytime I visit the group I learn so many things. Thank you all for taking your kind time to try to absolve the issue. Regards, Subhabrata Banerjee. From andrea.crotti.0 at gmail.com Mon Jul 16 10:37:38 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 16 Jul 2012 15:37:38 +0100 Subject: assertraises behaviour In-Reply-To: References: Message-ID: 2012/7/16 Christian Heimes : > > The OSError isn't catched as the code never reaches the line with "raise > OSError". In other words "raise OSError" is never executed as the > exception raised by "assert False" stops the context manager. > > You should avoid testing more than one line of code in a with > self.assertRaises() block. > > Christian > > -- > http://mail.python.org/mailman/listinfo/python-list Ok now it's more clear, and normally I only test one thing in the block. But I find this quite counter-intuitive, because in the block I want to be able to run something that raises the exception I catch (and which I'm aware of), but if another exception is raised it *should* show it and fail in my opinion.. From aishahalim at gmail.com Mon Jul 16 11:02:40 2012 From: aishahalim at gmail.com (Aisha Halim) Date: Mon, 16 Jul 2012 10:02:40 -0500 Subject: OpenHatch - Chicago Python Workshop Message-ID: Hi, I'm not sure if it's ok to post regarding a small local workshop (based on Railsbridge and the Boston Python Workshop) here so please direct me elsewhere if I am mistaken: OpenHatch's first Chicago Python workshop is heading our way, on August 17th - 18th. These events are tailored for women and their friends who have none or limited programming experience. They are also welcoming and respectful of trans women. Men are welcome as guests of women who are attending (please RSVP as well). Register here: http://www.meetup.com/Chicago-Python-Workshop/events/72904002/ More information: https://openhatch.org/wiki/Chicago_Python_Workshop_1 Super cool video on OpenHatch, their motivation, results: http://pyvideo.org/video/719/diversity-in-practice-how-the-boston-python-user We'd like more exposure in local women groups (ladies of all ages are welcome) and if you think we missed out on any other channels, please let us know, or pass this on. Also if anyone is interested in helping or would like to give some input, please join the cpw list (http://lists.openhatch.org/mailman/listinfo/cpw-staff) Thanks! -Aisha From __peter__ at web.de Mon Jul 16 11:10:49 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Jul 2012 17:10:49 +0200 Subject: assertraises behaviour References: Message-ID: andrea crotti wrote: > 2012/7/16 Christian Heimes : >> >> The OSError isn't catched as the code never reaches the line with "raise >> OSError". In other words "raise OSError" is never executed as the >> exception raised by "assert False" stops the context manager. >> >> You should avoid testing more than one line of code in a with >> self.assertRaises() block. >> >> Christian >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Ok now it's more clear, and normally I only test one thing in the block. > But I find this quite counter-intuitive, because in the block I want > to be able to run something that raises the exception I catch (and > which I'm aware of), but if another exception is raised it *should* > show it and fail in my opinion.. That doesn't sound like "it's clearer". Perhaps it helps if you translate your code into a standard try...except: >>> class A(Exception): pass ... >>> class B(Exception): pass ... >>> try: ... raise A ... raise B ... except A as e: ... print "caught %r" % e ... caught A() The try block is left at the "raise A' statement" -- Python doesn't have an equivalent of Basic's "resume next". Therefore B (or OSError) is never raised. PS: Strictly speaking your "assert False" is equivalent to if __debug__ and False: raise AssertionError Therefore you *can* trigger the OSError by invoking the interpreter with the "-O" option: $ python -c 'assert False; raise OSError' Traceback (most recent call last): File "", line 1, in AssertionError $ python -O -c 'assert False; raise OSError' Traceback (most recent call last): File "", line 1, in OSError From steve+comp.lang.python at pearwood.info Mon Jul 16 11:29:59 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Jul 2012 15:29:59 GMT Subject: Style question: metaclass self vs cls? Message-ID: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> Here's a style question for you: in a metaclass, what should I call the instance parameter of methods, "cls" or "self"? class ExampleMeta(type): def method(self, *args): ... I'm not quite sure if that feels right. On the one hand, self is the ExampleMeta instance alright... but on the other, self is actually a class, so I feel I want to call it "cls" rather than "self", which makes it more obvious that you're looking at a metaclass. On the third-hand, it may be confusing that the argument is called "cls" but not decorated with classdecorator. I'm very slightly leaning towards writing metaclasses like this: class ExampleMeta(type): def __new__(meta, *args): ... def method(cls, *args): ... class Example(metaclass=ExampleMeta): def another_method(self): ... What do others do? -- Steven From tinnews at isbd.co.uk Mon Jul 16 11:51:07 2012 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Mon, 16 Jul 2012 16:51:07 +0100 Subject: PyQt QCalendarWidget events question Message-ID: I am trying to use the PyQt4 calendar widget to perform some different actions on specific dates. There are three events available:- selectionChanged() activated(QDate) clicked(QDate) On trying all these out it would appear that the event handlers get called as follows:- The clicked(QDate) event gets called if you click on an already selected date. The selectionChanged() and then the clicked(QDate) events are called when you click on a new date. The selectionChanged(), then the clicked(QDate) and then the activated(QDate) events are called if you double-click on a new date. The clicked(QDate) and then the activated(QDate) events are called if you double-click on an already selected date. How can I get a single-click on a date to get 'Action1' and double-click on a date to get 'Action2'? -- Chris Green From tinnews at isbd.co.uk Mon Jul 16 12:28:38 2012 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Mon, 16 Jul 2012 17:28:38 +0100 Subject: PyQt QCalendarWidget events question References: Message-ID: tinnews at isbd.co.uk wrote: > I am trying to use the PyQt4 calendar widget to perform some different > actions on specific dates. There are three events available:- > > selectionChanged() > activated(QDate) > clicked(QDate) > > On trying all these out it would appear that the event handlers get > called as follows:- > > The clicked(QDate) event gets called if you click on an already > selected date. > > The selectionChanged() and then the clicked(QDate) events are > called when you click on a new date. > > The selectionChanged(), then the clicked(QDate) and then the > activated(QDate) events are called if you double-click on a new date. > > The clicked(QDate) and then the activated(QDate) events are called > if you double-click on an already selected date. > > > How can I get a single-click on a date to get 'Action1' and double-click > on a date to get 'Action2'? I'm sorry, this got sent a bit before I'd completed it. The trouble is that I want to run Action1 if I single-click on a date whether or not it's a changed date and I want to run Action2 if I double-click on a date whether or not it's a changed date. However I don't see how I can do this because of the order in which the event handlers are called. Is there any way to manipulate this so I can get the result I want? At the moment the only way I can see to do it is to wait a while after a click and then look at what actions occurred but this seems a real bodge. -- Chris Green From andrea.crotti.0 at gmail.com Mon Jul 16 12:38:07 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 16 Jul 2012 17:38:07 +0100 Subject: assertraises behaviour In-Reply-To: References: Message-ID: Good thanks, but there is something that implements this behaviour.. For example nose runs all the tests, and if there are failures it goes on and shows the failed tests only in the end, so I think it is possible to achieve somehow, is that correct? From fred.sells at adventistcare.org Mon Jul 16 13:02:13 2012 From: fred.sells at adventistcare.org (Sells, Fred) Date: Mon, 16 Jul 2012 13:02:13 -0400 Subject: Diagramming code In-Reply-To: References: Message-ID: You leave many relevant questions unanswered. 1. Is the original developer/team available or have you been left with the code and little or no doc's? 2. How big is big in terms of the number of files/modules in the project? 3. Is there a reasonable structure to the project in terms of directories and a meaningful hierarchy 4. Does the project currently work and you just have to maintain/enhance it or was it "abandoned" by the original team in an unknown state and you have to save a sinking ship? 5. Are you an experienced Python programmer or a beginner. 6. Is the original code "pythonic" (i.e. clean and simple with brief, well organized methods) or do you have functions over 50 lines of code with multiple nested control statements and meaningless variable names? 7. Is there any documentation that defines what it should do and how it should do it. i.e. how do you know when it's working? These issues are not really Python specific, but if you've been given a "broken" project that has 200 poorly organized modules and little or no documentation and no access to the original team, a good first step would be to update your resume ;) OK then, let me ask, how do you guys learn/understand large projects ? hamilton -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Mon Jul 16 13:27:45 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Jul 2012 19:27:45 +0200 Subject: assertraises behaviour References: Message-ID: andrea crotti wrote: > Good thanks, but there is something that implements this behaviour.. > For example nose runs all the tests, and if there are failures it goes > on and shows the failed tests only in the end, so I think it is > possible to achieve somehow, is that correct? No, I don't see how the code you gave above can fail with an OSError. Can you give an example that produces the desired behaviour with nose? Maybe we can help you translate it to basic unittest. From albert at spenarnc.xs4all.nl Mon Jul 16 13:57:45 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 16 Jul 2012 17:57:45 GMT Subject: Implicit conversion to boolean in if and while statements References: <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> Message-ID: In article , Ranting Rick wrote: >We DON'T want Python to silently convert "cost" to a string. What we >DO want is to force the author to use the str function thereby making >the conversion explicit. We do want Python to silently convert "cost" to a string in the proper context. cost= 3.75 print( cost ) > >Same with converting objects to bools. I think "if" is sufficient context to convert something to a boolean. It now is a matter of good taste and what fits best in Python as a whole. Nothing to be dogmatic about. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From albert at spenarnc.xs4all.nl Mon Jul 16 14:03:56 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 16 Jul 2012 18:03:56 GMT Subject: Implicit conversion to boolean in if and while statements References: <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <50038364$0$29995$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: >On Sun, 15 Jul 2012 18:21:06 -0700, Ranting Rick wrote: > >> If HOWEVER we want to "truth test" an object (as in: "if obj") we should >> be FORCED to use the bool! Why? Because explicit is better than implicit > >And this is why Rick always writes code like: > >integer_value_three = int(1) + int(2) >assert (int(integer_value_three) == \ > int(3) is True) is True, str("arithmetic failed") >list_containing_three_values_which_are_all_integers_but_might_later_have_more_or_fewer_values_or_other_types = list([1, 2, integer_value_three]) > >because you can never have too much explicitness. Who wouldn't want >to read code like that? Java programmers? (Couldn't resist ;-) ) >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From ethan at stoneleaf.us Mon Jul 16 14:13:33 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 16 Jul 2012 11:13:33 -0700 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500459CD.8060904@stoneleaf.us> Steven D'Aprano wrote: > On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote: >> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano wrote: >>> (For the record, I can only think of one trap for the unwary: time >>> objects are false at *exactly* midnight.) >> >> Ugh, that's irritating. I can't think of any scenario where I would >> ever want the semantics "if timeval (is not midnight):". > > Yes, it is a genuine gotcha. Time values are numbers, and zero is falsey, > so midnight is falsey even though it shouldn't be. > > There's no good solution here, since we have a conflict between treating > time values as time values ("midnight is nothing special") and as numbers > ("midnight == 0 which is falsey"). --> import datetime --> mn = datetime.time(0) --> mn datetime.time(0, 0) --> mn == 0 False Apparently, midnight does not equal zero. Possibly because it should be truthy. ;) ~Ethan~ From hamilton at nothere.com Mon Jul 16 14:36:18 2012 From: hamilton at nothere.com (hamilton) Date: Mon, 16 Jul 2012 12:36:18 -0600 Subject: Diagramming code In-Reply-To: References: Message-ID: Thank you Fred. I am new to python and am reviewing code I find online. Some projects do have docs that spell out what its doing, but many projects that I have download have just the code. I have my own personal style to decypher C and C++ code. But python is still foreign to me. hamilton On 7/16/2012 11:02 AM, Sells, Fred wrote: > You leave many relevant questions unanswered. > > 1. Is the original developer/team available or have you been left with > the code and little or no doc's? > > 2. How big is big in terms of the number of files/modules in the > project? > > 3. Is there a reasonable structure to the project in terms of > directories and a meaningful hierarchy > > 4. Does the project currently work and you just have to maintain/enhance > it or was it "abandoned" by the original team in an unknown state and > you have to save a sinking ship? > > 5. Are you an experienced Python programmer or a beginner. > > 6. Is the original code "pythonic" (i.e. clean and simple with brief, > well organized methods) or do you have functions over 50 lines of code > with multiple nested control statements and meaningless variable names? > > 7. Is there any documentation that defines what it should do and how it > should do it. i.e. how do you know when it's working? > > These issues are not really Python specific, but if you've been given a > "broken" project that has 200 poorly organized modules and little or no > documentation and no access to the original team, a good first step > would be to update your resume ;) > > OK then, let me ask, how do you guys learn/understand large projects ? > > hamilton > > -- > http://mail.python.org/mailman/listinfo/python-list > From miki.tebeka at gmail.com Mon Jul 16 15:47:40 2012 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 16 Jul 2012 12:47:40 -0700 (PDT) Subject: Diagramming code In-Reply-To: References: Message-ID: <11eb95a3-f358-4f57-89f0-ba72abf3cb01@googlegroups.com> > Is there any software to help understand python code ? For module dependency you can try http://furius.ca/snakefood/ From jjposner at optimum.net Mon Jul 16 15:58:05 2012 From: jjposner at optimum.net (John Posner) Date: Mon, 16 Jul 2012 15:58:05 -0400 Subject: PyQt QCalendarWidget events question In-Reply-To: References: Message-ID: <5004724D.7080407@optimum.net> On 7/16/2012 12:28 PM, tinnews at isbd.co.uk wrote: > tinnews at isbd.co.uk wrote: >> I am trying to use the PyQt4 calendar widget to perform some different >> actions on specific dates. There are three events available:- >> >> selectionChanged() >> activated(QDate) >> clicked(QDate) >> >> On trying all these out it would appear that the event handlers get >> called as follows:- >> >> The clicked(QDate) event gets called if you click on an already >> selected date. >> >> The selectionChanged() and then the clicked(QDate) events are >> called when you click on a new date. >> >> The selectionChanged(), then the clicked(QDate) and then the >> activated(QDate) events are called if you double-click on a new date. >> >> The clicked(QDate) and then the activated(QDate) events are called >> if you double-click on an already selected date. >> >> >> How can I get a single-click on a date to get 'Action1' and double-click >> on a date to get 'Action2'? > I'm sorry, this got sent a bit before I'd completed it. The trouble > is that I want to run Action1 if I single-click on a date whether or > not it's a changed date and I want to run Action2 if I double-click on > a date whether or not it's a changed date. However I don't see how I > can do this because of the order in which the event handlers are > called. > > Is there any way to manipulate this so I can get the result I want? > At the moment the only way I can see to do it is to wait a while after > a click and then look at what actions occurred but this seems a real > bodge. I suspect that the consensus would be "don't do that" -- having single-click and double click perform unrelated actions. But here's an implementation based on the advice at http://www.qtcentre.org/threads/7858-Double-Click-Capturing (use Ctrl-Break to break out of the event loop) import PyQt4.QtCore as C import PyQt4.QtGui as G class Button(G.QPushButton): def __init__(self, text): G.QPushButton.__init__(self, text) # flag to suppress second mouseReleaseEvent # in this double-click event sequence: # 1. mousePressEvent # 2. mouseReleaseEvent # 3. mouseDoubleClickEvent # 4. mouseReleaseEvent self.double_clicked = False def mouseReleaseEvent(self, evt): # executed for first mouseReleaseEvent if not self.double_clicked: self.first_click_timer = C.QTimer() self.first_click_timer.setSingleShot(True) # double-click must occur within 1/4 second of first-click release self.first_click_timer.setInterval(250) self.first_click_timer.timeout.connect(self.single_click_action) self.first_click_timer.start() # executed for second mouseReleaseEvent else: # reset the flag self.double_clicked = False def single_click_action(self): print "Performing single-click action" def mouseDoubleClickEvent(self, evt): # suppress the single-click action; perform double-click action instead self.first_click_timer.stop() print "Performing double-click action" # prepare for second mouseReleaseEvent self.double_clicked = True # main program app = G.QApplication([]) button = Button("Click or double-click me") button.show() app.exec_() HTH, John From bahamutzero8825 at gmail.com Mon Jul 16 16:33:08 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 16 Jul 2012 15:33:08 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50047A84.6020208@gmail.com> On 7/15/2012 9:38 PM, Steven D'Aprano wrote: >> I would expect None to mean "doesn't exist" or "unknown" or >> something like that - e.g., a value of 0 means 0 jelly beans in the jar >> and None means there isn't a jar. > > How you interpret some_variable = None depends on what some_variable > represents. If some_variable represents "number of jelly beans in a jar", > then that should be 0 if there is no jar. What is None supposed to mean then, and what should I do when I have to make a distinction between "doesn't exist" and "empty"? Sure, if I need to count the total number of jelly beans in all my stores, the distinction is meaningless, but if I need to find out which stores sell jelly beans so I know which stores need to be restocked, the distinction is quite important. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From andrea.crotti.0 at gmail.com Mon Jul 16 16:41:31 2012 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Mon, 16 Jul 2012 21:41:31 +0100 Subject: Diagramming code In-Reply-To: References: Message-ID: <50047C7B.2050304@gmail.com> On 07/16/2012 02:26 AM, hamilton wrote: > Is there any software to help understand python code ? > > Thanks > > hamilton Sometimes to get some nice graphs I use gprof2dot (http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) or doxygen (http://www.stack.nl/~dimitri/doxygen/) gprof2dot analyses the output of the profiling that you get running the code through the python profiler, doing for example: python -m cProfile -o $STATS $FNAME $@ $GPROF2DOT -f pstats $STATS | dot -T$TYPE -o $OUT doxygen is more useful for C++ but it's also able to infer a few things (without running) from a python project.. From ethan at stoneleaf.us Mon Jul 16 16:54:32 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 16 Jul 2012 13:54:32 -0700 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50047A84.6020208@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> Message-ID: <50047F88.7030603@stoneleaf.us> Andrew Berg wrote: > On 7/15/2012 9:38 PM, Steven D'Aprano wrote: >>> I would expect None to mean "doesn't exist" or "unknown" or >>> something like that - e.g., a value of 0 means 0 jelly beans in the jar >>> and None means there isn't a jar. >> >> How you interpret some_variable = None depends on what some_variable >> represents. If some_variable represents "number of jelly beans in a jar", >> then that should be 0 if there is no jar. > > What is None supposed to mean then, and what should I do when I have to > make a distinction between "doesn't exist" and "empty"? Sure, if I need > to count the total number of jelly beans in all my stores, the > distinction is meaningless, but if I need to find out which stores sell > jelly beans so I know which stores need to be restocked, the distinction > is quite important. I'm not sure what Steven was trying to say there, but for me: jar with no jellybeans == 0 no jar == None ~Ethan~ From gandalf at shopzeus.com Mon Jul 16 17:17:58 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 16 Jul 2012 23:17:58 +0200 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50048506.50707@shopzeus.com> >> ... >> >> Traceback (most recent quip last): >> Author: "", line 7, in >> LogicalFallacyError: "Reductio ad absurdum" > > Deary deary me Rick. Reductio ad adsurdum is not a fallacy. It is a > counter-argument to an argument or claim, by showing that the premise of > the original claim leads to an absurd conclusion. > > You have claimed that we should always be explicit whenever we write. But > you do not actually live up to your own advice, because you can't: it is > absurd to try to be explicit about everything all the time. You have > misunderstood the purpose of the Zen of Python: it is not to claim that > everything should be explicit, but to avoid code that is hard to > understand because things which need to be explicit for clarity are > implied by other parts of your code. I agree. There is no pont in abolutizing explicitness anyway. It is not a yes/no question. You cannot tell that somebody is "not explicit". It is not something that can be decided. But you can say that he was "not explicit enough" in a concrete case. There is an accepted level of explicitness. You can probably always be more expicit, or less explicit. Being more explicit is not the goal. But is a good practice to be more explicit if it helps you achieve the real goal. For example, writting a program that can be maintained easily. From trevor.carlston at gmail.com Mon Jul 16 17:20:38 2012 From: trevor.carlston at gmail.com (trevor.carlston at gmail.com) Date: Mon, 16 Jul 2012 14:20:38 -0700 (PDT) Subject: No more Python support in NetBeans 7.0 In-Reply-To: <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> References: <4a98.4d8b560e.5ebee@altium.nl> <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> Message-ID: On Wednesday, October 26, 2011 8:06:16 PM UTC-6, w... at naveed.net wrote: > Sorry to comment on an old topic, but I wanted to clarify for others like me who might get the wrong idea. > > It looks like this is no longer true. Netbeans 7 might be supporting python after all. > > http://wiki.netbeans.org/Python70Roadmap I checked the date on that document it's last update was 5 November 2009 From trevor.carlston at gmail.com Mon Jul 16 17:22:37 2012 From: trevor.carlston at gmail.com (trevor.carlston at gmail.com) Date: Mon, 16 Jul 2012 14:22:37 -0700 (PDT) Subject: No more Python support in NetBeans 7.0 In-Reply-To: <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> References: <4a98.4d8b560e.5ebee@altium.nl> <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> Message-ID: <563e1056-9bc3-4fff-a965-2f05b1600bab@googlegroups.com> On Wednesday, October 26, 2011 8:06:16 PM UTC-6, w... at naveed.net wrote: > Sorry to comment on an old topic, but I wanted to clarify for others like me who might get the wrong idea. > > It looks like this is no longer true. Netbeans 7 might be supporting python after all. > > http://wiki.netbeans.org/Python70Roadmap This article is dated January 29th of 2011 http://netbeans.org/projects/www/lists/nbpython-dev/archive/2011-01/message/0 From gandalf at shopzeus.com Mon Jul 16 17:26:18 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 16 Jul 2012 23:26:18 +0200 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50038364$0$29995$c3e8da3$5496439d@news.astraweb.com> <50039698$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500486FA.9000606@shopzeus.com> > This syntax is explicit *enough*. We don't need to be any more > explicit. > > But if you are going to argue that "if obj" is *explicit enough*, then > apply your argument consistently to "String"+1.75 also. Why must we be > explicit about string conversion BUT not boolean conversion? Can you > reduce this to the absurd? Or will you just choose to ignore this > valid point? Not all decisions in Python are based purely on the "explicit enough" thing. Some things in the language cannot be explained using explicitness alone. So, when we cannot fully explain the ' why String+1.75 ' question with statements about explicitness then it doesn't mean that anybody lied or wrote something wrong. :-) From tjreedy at udel.edu Mon Jul 16 18:21:06 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Jul 2012 18:21:06 -0400 Subject: Style question: metaclass self vs cls? In-Reply-To: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/16/2012 11:29 AM, Steven D'Aprano wrote: > Here's a style question for you: in a metaclass, what should I call the > instance parameter of methods, "cls" or "self"? > > class ExampleMeta(type): > def method(self, *args): ... > > I'm not quite sure if that feels right. On the one hand, self is the > ExampleMeta instance alright... but on the other, self is actually a > class, so I feel I want to call it "cls" rather than "self", which makes > it more obvious that you're looking at a metaclass. I have never seriously written a metaclass, but as a reader I would prefer 'cls'. > On the third-hand, it may be confusing that the argument is called "cls" > but not decorated with classdecorator. To me, that reinforces 'looking as a metaclass'. An @classmethod in a class is a class method specific to the particular class. A method in a metaclass is a method common to all classes of the metaclass. They could be written differently, yet calling the first param 'cls' either way seems reasonable. > I'm very slightly leaning towards writing metaclasses like this: > > class ExampleMeta(type): > def __new__(meta, *args): ... > def method(cls, *args): ... > > class Example(metaclass=ExampleMeta): > def another_method(self): ... > What do others do? Not too many people write real metaclasses. Python lets you chose. Have you looked at the C code of type? (Not that you are bound by it.) -- Terry Jan Reedy From amc96 at cam.ac.uk Mon Jul 16 18:24:08 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Mon, 16 Jul 2012 23:24:08 +0100 Subject: Diagramming code In-Reply-To: References: Message-ID: On 16/07/2012 21:41, Andrea Crotti wrote: > On 07/16/2012 02:26 AM, hamilton wrote: >> Is there any software to help understand python code ? >> >> Thanks >> >> hamilton > > Sometimes to get some nice graphs I use gprof2dot > (http://code.google.com/p/jrfonseca/wiki/Gprof2Dot) > or doxygen (http://www.stack.nl/~dimitri/doxygen/) > > gprof2dot analyses the output of the profiling that you get running the > code through the python profiler, > doing for example: > > python -m cProfile -o $STATS $FNAME $@ > $GPROF2DOT -f pstats $STATS | dot -T$TYPE -o $OUT > > doxygen is more useful for C++ but it's also able to infer a few things > (without running) from a python project.. +1 for doxygen. Combined with http://code.foosel.org/doxypy , it is a fully featured solution. I use it for all my projects, python and otherwise. ~Andrew From steve+comp.lang.python at pearwood.info Mon Jul 16 20:43:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 00:43:47 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> Message-ID: <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 16 Jul 2012 13:54:32 -0700, Ethan Furman wrote: > Andrew Berg wrote: >> On 7/15/2012 9:38 PM, Steven D'Aprano wrote: >>>> I would expect None to mean "doesn't exist" or "unknown" or something >>>> like that - e.g., a value of 0 means 0 jelly beans in the jar and >>>> None means there isn't a jar. > >> >>> How you interpret some_variable = None depends on what some_variable >>> represents. If some_variable represents "number of jelly beans in a >>> jar", then that should be 0 if there is no jar. > > >> What is None supposed to mean then, and what should I do when I have to >> make a distinction between "doesn't exist" and "empty"? Sure, if I need >> to count the total number of jelly beans in all my stores, the >> distinction is meaningless, but if I need to find out which stores sell >> jelly beans so I know which stores need to be restocked, the >> distinction is quite important. > > I'm not sure what Steven was trying to say there, but for me: > > jar with no jellybeans == 0 > > no jar == None The existence of a jar or no jar is irrelevant to the question of how many jellybeans there are. They are two different things, and therefore need two different values. There are many ways to implement this. # One way jar_exists = True # or possibly False jellybeans = 42 # or whatever the number is, possibly 0 # Another way jar = Jar(number_of_beans=jellybeans) if jar_exists else None jellybeans = jar.jellybeans if jar is not None else 0 If you have many jars, and you want to count the total number of jellybeans: total = sum(jar.jellybeans for jar in jars if jar is not None) Strictly speaking, the "is not None" is redundant, but it expresses the intent better than the alternative. Assuming that jar instances follow the standard Python API for containers, and is treated as falsey when it has a jellybean count of zero: total = sum(jar.jellybeans for jar in jars if jar) # relies on the fact that adding zero to a number makes # no difference, so you can safely leave zeroes out Here's a case where you *must* distinguish between empty jars and None: number_of_jars = sum(1 for jar in jars if jar is not None) and a case where you *shouldn't*: number_of_nonempty_jars = sum(1 for jar in jars if jar) Of course you can write this: number_of_nonempty_jars = sum( 1 for jar in jars if jar is not None and jar.jellybeans > 1 ) but that overwhelms the code with incidental implementation details about jellybean counts, which is prone to bugs. (Did you spot it?) Even jar.isempty() would be better, but better still is to *not* invent your own container API but to use the standard Python one instead and define an appropriate __nonzero__ (Python 2) or __bool__ (Python 3) method. If I insist on making a single object do duty for both the jar and the jellybean count, then I need a "null jar object", and I probably end up with something like this: Jar(number_of_beans=None) => null jar object with jar.jellybeans = 0 Jar(number_of_beans=0) => normal jar object with jar.jellybeans = 0 Jar(number_of_beans=42) => normal jar object with jar.jellybeans = 42 and then my code becomes even more complicated and less understandable, but hey, it's *my* code and I can do whatever damn-fool thing I like! -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 16 21:12:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 01:12:47 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5004bc0f$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 16 Jul 2012 13:28:14 -0400, Dennis Lee Bieber wrote: > On 16 Jul 2012 02:38:35 GMT, Steven D'Aprano > declaimed the following in > gmane.comp.python.general: > >> On Sun, 15 Jul 2012 12:02:37 -0500, Andrew Berg wrote: >> >> >> > Okay, I see the value in this, but I don't understand why None has a >> > truth value. >> >> And this is exactly the sort of mental confusion that Laura Crichton >> warned about (see the link I included earlier). >> >> > Would one rather have the behavior seen in SQL for Null? > http://www.firebirdsql.org/file/documentation/reference_manuals/ user_manuals/Firebird-Null-Guide.pdf That's a 51 page document. I'm not sure I know which behaviour you are referring to. Seems to me that the Firebird NULL object is closer to a float NaN than to Python's None, except that Firebird treats comparisons with NULL as returning a NULL, while Python treats comparisons with NaN as True or False. Both behaviours are reasonable, but the Firebird behaviour seems to be more error-prone. > Hey, let's turn the IF statement into tri-state logic... [...] I'm not sure if you're being sarcastic here or not. Ternary logic is perfectly reasonable, although I expect that it would be error-prone because programmers would forget the "unknown" clause all the time. It looks like Firebird implements the variety of ternary logical called "Keene logic". Of course, ternary logic can always be re-written in binary terms. Assuming that UNKNOWN evaluates as false: if flag: true-clause else: if flag is UNKNOWN: unknown-clause else: false-clause -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 16 21:13:39 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 01:13:39 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <5004bc0f$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5004bc42$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 17 Jul 2012 01:12:47 +0000, Steven D'Aprano wrote: > It > looks like Firebird implements the variety of ternary logical called > "Keene logic". Oops, I meant "Kleene". -- Steven From bahamutzero8825 at gmail.com Mon Jul 16 21:22:18 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 16 Jul 2012 20:22:18 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> Message-ID: <5004BE4A.1020506@gmail.com> On 7/15/2012 3:28 PM, Terry Reedy wrote: > Because everything does (or should). I can see how truth testing for empty values is convenient, but perhaps objects should only have a truth value if explicitly given one - particularly in cases where such a value wouldn't be obvious or the obvious value isn't the actual one: >>> c = types.SimpleNamespace() >>> if c: print('c') ... c >>> c.__dict__ {} Would it not be reasonable to expect an empty namespace to have a truth value of False since [] and friends do? It's a bit of a gray area for an object defined by "class C: pass", but this is *specifically intended* to be a namespace. Why should things like functions or exceptions have truth values? Note: For those who aren't aware, types.SimpleNamespace was added in 3.3.0b1. On a side note, I tend to do this: x = some_list try: y = x.pop() except IndexError: do_something_else() rather than: if x: y = x.pop() else: do_something_else() but of course that only applies to empty lists/sets/related and not 0/0.0/None and only when I want something from the list/set/whatever. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rustompmody at gmail.com Mon Jul 16 21:45:51 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 16 Jul 2012 18:45:51 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> Message-ID: On Jul 15, 9:50?pm, Rick Johnson wrote: > On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote: > > On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano > > wrote: > > > (For the record, I can only think of one trap for the unwary: time > > > objects are false at *exactly* midnight.) > > > Ugh, that's irritating. ?I can't think of any scenario where I would > > ever want the semantics "if timeval (is not midnight):". ?This > > reinforces the point that if you only want to test whether you have > > None, you should use "is not None" rather than relying on __bool__. > > I think this issue is not so much a "bool test" vs "type test", but more an ambiguous syntax > issue. If you know some English, its clear that if and while create bool contexts. [If you know English but have not studied logic the 'if/while' make sense whereas 'bool' is gobbledygook] The issue is not where the cast goes to -- this clearly is bool But where the cast comes from -- which requires tracing program-paths From bahamutzero8825 at gmail.com Mon Jul 16 21:57:43 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 16 Jul 2012 20:57:43 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5004C697.8020809@gmail.com> On 7/16/2012 7:43 PM, Steven D'Aprano wrote: > The existence of a jar or no jar is irrelevant to the question of how > many jellybeans there are. They are two different things, and therefore > need two different values. There are many ways to implement this. I have a better real example, but I opted not to use it before since it requires some explanation - IRC messages. A client-to-server message has the basic form of b'COMMAND arguments :message' (e.g. b'PRIVMSG #channel :hi guys!'). Some commands have no message part because there is no message associated with it (e.g. b'JOIN #channel') and there is at least one where there is a big difference between a blank message (b'') and no message - b'TOPIC #channel' is a request for the topic while b'TOPIC #channel :' clears the topic since the part after the b':' is b'' (b'TOPIC #channel :Welcome to #channel' sets the topic to "Welcome to #channel"). In my code, I would have an object representing a message rather than parsing it multiple times. If the message attribute is not None, I send b'{command} {args} :{message}', otherwise b'{command} {args}'. If I considered '' falsey, either I would require all messages to have ":" (which would not actually be part of the message) or have any request to view the topic as a channel op clear the topic. This would apply to the server parsing the message as well. A few other commands have messages optional as well, but they are not as serious as TOPIC. I could do: if has_message: send('{command} {args} :{message}') else: send('{command} {args}') but then I'd have to make sure has_message stays accurate since message won't necessarily be. Or maybe I could leave message undefined and catch the appropriate exception. However, using None is the cleanest and most obvious. I know Rick likes to troll, but I do agree with him that "if something:" for arbitrary objects can be ambiguous or confusing. I don't think if/while must have True or False, but not every object has an obvious truth value. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rosuav at gmail.com Mon Jul 16 22:13:48 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 17 Jul 2012 12:13:48 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5004C697.8020809@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004C697.8020809@gmail.com> Message-ID: On Tue, Jul 17, 2012 at 11:57 AM, Andrew Berg wrote: > I could do: > > if has_message: > send('{command} {args} :{message}') > else: > send('{command} {args}') > > but then I'd have to make sure has_message stays accurate since message > won't necessarily be. Or maybe I could leave message undefined and catch > the appropriate exception. However, using None is the cleanest and most > obvious. > > I know Rick likes to troll, but I do agree with him that "if something:" > for arbitrary objects can be ambiguous or confusing. I don't think > if/while must have True or False, but not every object has an obvious > truth value. Using None when '' is a valid token is the right thing to do (see also, for instance, SQL's NULL, which is often used the same way). And then you have gone away from the language's idea of whether a string is truthy or not, so you get explicit: if message is not None: send('{command} {args} :{message}') Easy! Or if the language went the other way ("all strings are true"), it would be the other way around, you'd use "if message!=''" for the other case. It's not a difficult problem. Carry on bikeshedding. :) ChrisA From steve+comp.lang.python at pearwood.info Tue Jul 17 00:11:04 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 04:11:04 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> Message-ID: <5004e5d7$0$11116$c3e8da3@news.astraweb.com> On Mon, 16 Jul 2012 20:22:18 -0500, Andrew Berg wrote: > On 7/15/2012 3:28 PM, Terry Reedy wrote: >> Because everything does (or should). > I can see how truth testing for empty values is convenient, but perhaps > objects should only have a truth value if explicitly given one - > particularly in cases where such a value wouldn't be obvious or the > obvious value isn't the actual one: You have run into Python's default behaviour: objects are treated as something by default. If you want them to represent nothing, you have to explicitly code that case. py> o = object() py> bool(o) True Yet again, thinking about something versus nothing instead of true/false makes the behaviour both obvious and correct: of course an object should be treated as something (true-like) rather than nothing (false-like) by default, it's an *object* is it not? If you want your type to implement non-default semantics, such as container semantics, then you need to code it. >>>> c = types.SimpleNamespace() >>>> if c: print('c') > ... > c >>>> c.__dict__ > {} > > Would it not be reasonable to expect an empty namespace to have a truth > value of False since [] and friends do? It's a bit of a gray area for an > object defined by "class C: pass", but this is *specifically intended* > to be a namespace. Why should things like functions or exceptions have > truth values? And this is a good life-lesson that any class called "SimpleFoo" will not stay simple for long. If you are right that SimpleNamespace should be treated as a container, then it should implement container semantics. Since it doesn't, that is either: 1) a bug; or 2) a triumph of laziness over correctness I imagine though that the Python dev's answer will basically be #2: "it isn't a container, it just behaves a little bit like a container, except when it doesn't" kinda thing. But feel free to report it as a bug and see what happens. (This is not *entirely* wrong, because SimpleNamespace certainly doesn't *claim* to be a container, nor does it expose the full container API. But it should, even if that means it is no longer quite so simple.) -- Steven From rantingrickjohnson at gmail.com Tue Jul 17 00:18:18 2012 From: rantingrickjohnson at gmail.com (Ranting Rick) Date: Mon, 16 Jul 2012 21:18:18 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> <5004e5d7$0$11116$c3e8da3@news.astraweb.com> Message-ID: <96117e8b-c605-43c4-a60a-053b29243513@t32g2000yqd.googlegroups.com> On Jul 16, 11:11?pm, Steven D'Aprano wrote: > I imagine though that the Python dev's answer will basically be #2: "it > isn't a container, it just behaves a little bit like a container, except > when it doesn't" kinda thing. The emperor has no clothes! From jeanpierreda at gmail.com Tue Jul 17 00:18:28 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 17 Jul 2012 00:18:28 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote: > >> For example, instead of "if stack:" or "if bool(stack):", we could use >> "if stack.isempty():". This line tells us explicitly that stack is a >> container. > > isempty is not a container method. Your entire reply is predicated on this idea that I was talking about writing classes with this extra "isempty" method. No. I was talking about having "isempty" be part of the collection interface, and eliminating polymorphic bool conversion. If you were confused, instead of assuming I meant something patently absurd, you should have asked for a clarification. -- Devin From rosuav at gmail.com Tue Jul 17 00:24:09 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 17 Jul 2012 14:24:09 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <96117e8b-c605-43c4-a60a-053b29243513@t32g2000yqd.googlegroups.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> <5004e5d7$0$11116$c3e8da3@news.astraweb.com> <96117e8b-c605-43c4-a60a-053b29243513@t32g2000yqd.googlegroups.com> Message-ID: On Tue, Jul 17, 2012 at 2:18 PM, Ranting Rick wrote: > On Jul 16, 11:11 pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> I imagine though that the Python dev's answer will basically be #2: "it >> isn't a container, it just behaves a little bit like a container, except >> when it doesn't" kinda thing. > > The emperor has no clothes! The Troll's New Point. ChrisA From steve+comp.lang.python at pearwood.info Tue Jul 17 00:39:33 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 04:39:33 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5004ec84$0$11116$c3e8da3@news.astraweb.com> On Mon, 16 Jul 2012 20:57:43 -0500, Andrew Berg wrote: > I have a better real example, but I opted not to use it before since it > requires some explanation - IRC messages. A client-to-server message has > the basic form of b'COMMAND arguments :message' (e.g. b'PRIVMSG #channel > :hi guys!'). Some commands have no message part because there is no > message associated with it (e.g. b'JOIN #channel') and there is at least > one where there is a big difference between a blank message (b'') and no > message - b'TOPIC #channel' is a request for the topic while b'TOPIC > #channel :' clears the topic since the part after the b':' is b'' > (b'TOPIC #channel :Welcome to #channel' sets the topic to "Welcome to > #channel"). Okay, so you have two distinct "nothing" states when considering the message part of an IRC command: the empty string, and missing. That's okay. Floats have two zeroes (+0.0 and -0.0); complex numbers have four. (Although they try hard to hide that distinction from you.) There's nothing that says that you can only have a single falsey value in a type, or that you might not sometimes wish to distinguish between different false-like states. You need to distinguish between the many different true-like messages, so you should not be surprised that you need to distinguish between two false-like messages. There are many ways to implement this. Here are just the most obvious: 1) a Command object where the message attribute is optional, but if present, it is always a string; 2) a Command object where the message attribute is always present, but can be a string or some non-string sentinel value (e.g. None); 3) a string, where the message attribute is determined by the location of the colon, if any 4) a tuple with either two or three fields: (command, channel [,message]) > In my code, I would have an object representing a message > rather than parsing it multiple times. If the message > attribute is not None, I send b'{command} {args} :{message}', otherwise > b'{command} {args}'. Clear and obvious. Nothing wrong with that. > I could do: > > if has_message: > send('{command} {args} :{message}') > else: > send('{command} {args}') > > but then I'd have to make sure has_message stays accurate since message > won't necessarily be. Yes, keeping a separate variable is a mug's game. Encapsulate it in the Command object, and have the Command object responsible for keeping it in sync (assuming it is mutable), or just make Command immutable and be done with it. > Or maybe I could leave message undefined and catch > the appropriate exception. However, using None is the cleanest and most > obvious. Yes it is. What's your point? You've discovered a real-world situation where you can't collapse the entire universe of valid values into just two, True and False, without losing information. Did you think that this would be surprising? Python developers often talk about interpreting objects "in a boolean context" -- that's a pretty big hint that the semantics are to collapse the value into two states. If you need three (or four, or fifty) distinguishable states, then obviously boolean context will not solve your problem. I never said it would. -- Steven From bahamutzero8825 at gmail.com Tue Jul 17 00:44:02 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 16 Jul 2012 23:44:02 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5004e5d7$0$11116$c3e8da3@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <5002F7AD.1000209@gmail.com> <5004e5d7$0$11116$c3e8da3@news.astraweb.com> Message-ID: <5004ED92.1030805@gmail.com> On 7/16/2012 11:11 PM, Steven D'Aprano wrote: > If you are right that SimpleNamespace should be treated as a container, > then it should implement container semantics. Since it doesn't, that is > either: > > 1) a bug; or > 2) a triumph of laziness over correctness > > I imagine though that the Python dev's answer will basically be #2: "it > isn't a container, it just behaves a little bit like a container, except > when it doesn't" kinda thing. But feel free to report it as a bug and see > what happens. I'm not saying it's necessarily wrong, but I do think it quacks a lot like a container, even though it isn't one, especially if you're listening for quacks instead of looking for ducks. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From steve+comp.lang.python at pearwood.info Tue Jul 17 00:47:45 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 04:47:45 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5004ee71$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 15 Jul 2012 10:56:57 +0000, Steven D'Aprano wrote: > On Sun, 15 Jul 2012 03:34:46 -0500, Andrew Berg wrote: > >> This has probably been discussed before, > > By the hoary hosts of Hoggoth, has it ever! Dammit this topic is a tar-baby. :( -- Steven From bahamutzero8825 at gmail.com Tue Jul 17 01:19:48 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 00:19:48 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5004ec84$0$11116$c3e8da3@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> Message-ID: <5004F5F4.5000601@gmail.com> On 7/16/2012 11:39 PM, Steven D'Aprano wrote: > If you need three (or four, or fifty) > distinguishable states, then obviously boolean context will not solve > your problem. I never said it would. That is the impression I got from this statement: > How you interpret some_variable = None depends on what some_variable > represents. If some_variable represents "number of jelly beans in a jar", > then that should be 0 if there is no jar. But I guess you misunderstood (or were just picking at) the example. Of course I can (and do) explicitly use "if x is not None" when testing for None, but I don't want a bug being obscured because "if x" accepts an erroneous value that it interprets as truthy or falsey. I could be explicit when testing for things other than None, but apparently that's un-Pythonic. To put it in duck-typing terms, why should everything have to quack like True or False? Sure, I can see why 1 quacks like True or [] quacks like False, but I don't see why say, a Logger or function should quack like either. Should a Thread object be True if it's been started and False otherwise? If it truly is about something vs. nothing, why is a NameError (or AttributeError) raised when testing with an undefined variable? Being undefined quacks like nothing, doesn't it? -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From wuwei23 at gmail.com Tue Jul 17 02:10:05 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 16 Jul 2012 23:10:05 -0700 (PDT) Subject: Style question: metaclass self vs cls? References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8f38a814-3c6c-42d3-8d7b-d7d8ae33d06e@x6g2000pbh.googlegroups.com> On Jul 17, 1:29?am, Steven D'Aprano wrote: > Here's a style question for you: in a metaclass, what should I call the > instance parameter of methods, "cls" or "self"? Maybe portmanteu it as "clasself"? :) From steve+comp.lang.python at pearwood.info Tue Jul 17 02:14:09 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 06:14:09 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <500378e4$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500502b1$0$30002$c3e8da3$5496439d@news.astraweb.com> On Mon, 16 Jul 2012 11:13:33 -0700, Ethan Furman wrote: > Steven D'Aprano wrote: >> On Sun, 15 Jul 2012 10:19:16 -0600, Ian Kelly wrote: >>> On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano wrote: >>>> (For the record, I can only think of one trap for the unwary: time >>>> objects are false at *exactly* midnight.) > >> >>> Ugh, that's irritating. I can't think of any scenario where I would >>> ever want the semantics "if timeval (is not midnight):". >> >> Yes, it is a genuine gotcha. Time values are numbers, and zero is >> falsey, so midnight is falsey even though it shouldn't be. >> >> There's no good solution here, since we have a conflict between >> treating time values as time values ("midnight is nothing special") and >> as numbers ("midnight == 0 which is falsey"). > > --> import datetime > --> mn = datetime.time(0) > --> mn > datetime.time(0, 0) > --> mn == 0 > False > > Apparently, midnight does not equal zero. My mistake. -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 17 02:25:43 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 06:25:43 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50050567$0$30002$c3e8da3$5496439d@news.astraweb.com> On Tue, 17 Jul 2012 00:18:28 -0400, Devin Jeanpierre wrote: > On Mon, Jul 16, 2012 at 12:03 AM, Steven D'Aprano > wrote: >> On Sun, 15 Jul 2012 22:15:13 -0400, Devin Jeanpierre wrote: >> >>> For example, instead of "if stack:" or "if bool(stack):", we could use >>> "if stack.isempty():". This line tells us explicitly that stack is a >>> container. >> >> isempty is not a container method. > > Your entire reply is predicated on this idea that I was talking about > writing classes with this extra "isempty" method. > > No. I was talking about having "isempty" be part of the collection > interface, and eliminating polymorphic bool conversion. It already is part of the collection interface: it is spelled __nonzero__ (Python 2) or __bool__ (Python 3), and like all dunder methods, it is called automatically for you when you use the right syntax: # do this x = n - len(y) if x and y: ... # don't do this x = n.__sub__(y.__len__()) if x.__nonzero__() and y.__nonzero__(): ... -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 17 03:08:33 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Jul 2012 07:08:33 GMT Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> Message-ID: <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> On Tue, 17 Jul 2012 00:19:48 -0500, Andrew Berg wrote: > To put it in duck-typing terms, why should everything have to quack like > True or False? Sure, I can see why 1 quacks like True or [] quacks like > False, but I don't see why say, a Logger or function should quack like > either. The default behaviour is that every object is something, hence true-like, unless explicitly coded to be treated as false-like. Since both loggers and functions are objects, they are true-like unless the default is overridden. If you don't like that simple, consistent model for truthiness, feel free to design your own language with a different model. Or you can use any one of the dozens of other existing languages which do what you want. > Should a Thread object be True if it's been started and False > otherwise? If you, the Thread class author, want it to be, you can make it so. > If it truly is about something vs. nothing, why is a NameError (or > AttributeError) raised when testing with an undefined variable? Being > undefined quacks like nothing, doesn't it? Not really. It doesn't quack like anything. Are you suggesting that if x doesn't exist, you want this behaviour? >>> del x # make sure x doesn't exist >>> if x: print('cheese') ... else: ... print('x is falsy') ... print(x) ... x is falsy Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined OH MAN, that would be SO AWESOME, we should like so do it!!! (I'm being sarcastic, in case it's not obvious.) -- Steven From nagle at animats.com Tue Jul 17 03:26:50 2012 From: nagle at animats.com (John Nagle) Date: Tue, 17 Jul 2012 00:26:50 -0700 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: References: Message-ID: On 7/15/2012 1:34 AM, Andrew Berg wrote: > This has probably been discussed before, but why is there an implicit > conversion to a boolean in if and while statements? > > if not None: > print('hi') > prints 'hi' since bool(None) is False. > > If this was discussed in a PEP, I would like a link to it. There are so > many PEPs, and I wouldn't know which ones to look through. > > Converting 0 and 1 to False and True seems reasonable, but I don't see > the point in converting other arbitrary values. Because Boolean types were an afterthought in Python. See PEP 285. If a language starts out with a Boolean type, it tends towards Pascal/Ada/Java semantics in this area. If a language backs into needing a Boolean type, as Python and C did, it tends to have the somewhat weird semantics of a language which can't quite decide what's a Boolean. C and C++ have the same problem, for exactly the same reason - boolean types were an afterthought there, too. John Nagle From jussij at zeusedit.com Tue Jul 17 03:55:19 2012 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: Tue, 17 Jul 2012 00:55:19 -0700 (PDT) Subject: No more Python support in NetBeans 7.0 In-Reply-To: <4a98.4d8b560e.5ebee@altium.nl> References: <4a98.4d8b560e.5ebee@altium.nl> Message-ID: <5f0a26ed-1ee9-41f1-8dbb-08ced535463b@googlegroups.com> On Thursday, March 24, 2011 7:32:44 AM UTC-7, Kees Bakker wrote: > Sad news (for me, at least), in the upcoming version 7.0 of NetBeans > there will be no Python plugin anymore. FWIW on the Windows platform the Zeus IDE has support for python: http://www.zeusedit.com/python.html Zeus is a lightweight IDE but it does have limited Python debugger support: http://youtu.be/aXNep2fcSsk Jussi Jumppanen Author: Zeus Editor From gaodexiaozheng at gmail.com Tue Jul 17 04:04:32 2012 From: gaodexiaozheng at gmail.com (gaodexiaozheng at gmail.com) Date: Tue, 17 Jul 2012 01:04:32 -0700 (PDT) Subject: PyXML 0.8.2 is released In-Reply-To: References: <3e33d36d$0$234$cc9e4d1f@news.dial.pipex.com> Message-ID: ? 2003?1?26????UTC+8??10?01?02??"Martin v. L?wis"??? > Tim C wrote: > > I've been trying pyxml from jython and fell into the problem when trying to > > create executables that pyxml's mechanisms for importing modules confound > > the compiler. > > What do you mean by "executable", and which compiler are you talking > about? How was it confound? > > Regards, > Martin Hi ,I just read your talks,I have a small question which needs your help. I am doing one project by Jython and want to use PyXML,but I am not sure if I can use the PyXML in Jython ,because it seems the PyXML is not supported by Jython ,is that right? Is there other way to resolve this? Thanks! From moogyd at yahoo.co.uk Tue Jul 17 04:20:58 2012 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Tue, 17 Jul 2012 01:20:58 -0700 (PDT) Subject: Simulation Results Managment In-Reply-To: <519ddc1b-4538-43a1-b925-325de59e8802@km7g2000pbc.googlegroups.com> References: <4834becc-783a-4af2-b94a-2b95c39d6be3@googlegroups.com> <16cb8524-63ad-4755-93e2-3f45e98c9af5@googlegroups.com> <519ddc1b-4538-43a1-b925-325de59e8802@km7g2000pbc.googlegroups.com> Message-ID: On Sunday, July 15, 2012 6:20:34 PM UTC+2, rusi wrote: > On Jul 15, 11:35?am, Dieter Maurer <die... at handshake.de> wrote: > > moo... at yahoo.co.uk writes: > > > ... > > > Does pickle have any advantages over json/yaml? > > > > It can store and retrieve almost any Python object with almost no effort. > > > > Up to you whether you see it as an advantage to be able to store > > objects rather than (almost) pure data with a rather limited type set. > > > > Of course, "pickle" is a proprietary Python format. Not so easy to > > decode it with something else than Python. In addition, when > > you store objects, the retrieving application must know the classes > > of those objects -- and its knowledge should not be too different > > from how those classes looked when the objects have been stored. > > > > I like very much to work with objects (rather than with pure data). > > Therefore, I use "pickle" when I know that the storing and retrieving > > applications all use Python. I use pure (and restricted) data formats > > when non Python applications come into play. > > Pickle -> JSON -> Yaml > are roughly in increasing order of human-friendliness and decreasing > order of machine friendliness (where machine means python 'machine') > > This means that > - Pickle is most efficient, Yaml least > - Pickle comes with python from as far back as I know > Json started coming somewhere round 2.5 (I think) > (py)yaml needs to be installed separately > - reading pickled data will spoil your eyes whereas yaml is pleasant > to read (just like python) Hi Everyone, Thanks for the feedback. For now, I store the data using Pickle. Steven From bahamutzero8825 at gmail.com Tue Jul 17 04:23:27 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 03:23:27 -0500 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500520FF.3010305@gmail.com> On 7/17/2012 2:08 AM, Steven D'Aprano wrote: > The default behaviour is that every object is something, hence true-like, > unless explicitly coded to be treated as false-like. Since both loggers > and functions are objects, they are true-like unless the default is > overridden. I am aware of the default behavior, but the reason for it still eludes me. > Are you suggesting that if x doesn't exist, you want this behaviour? I don't want that, but I am suggesting that it would be consistent with the idea of "something or nothing". -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rosuav at gmail.com Tue Jul 17 04:32:53 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 17 Jul 2012 18:32:53 +1000 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500520FF.3010305@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> <500520FF.3010305@gmail.com> Message-ID: On Tue, Jul 17, 2012 at 6:23 PM, Andrew Berg wrote: > On 7/17/2012 2:08 AM, Steven D'Aprano wrote: >> The default behaviour is that every object is something, hence true-like, >> unless explicitly coded to be treated as false-like. Since both loggers >> and functions are objects, they are true-like unless the default is >> overridden. > I am aware of the default behavior, but the reason for it still eludes me. There has to be something. This way, you can use None in place of any object, in the same way that a null pointer would be used in C; any object is true, None isn't. What other default makes more sense? ChrisA From gaodexiaozheng at gmail.com Tue Jul 17 04:35:11 2012 From: gaodexiaozheng at gmail.com (gaodexiaozheng at gmail.com) Date: Tue, 17 Jul 2012 01:35:11 -0700 (PDT) Subject: jython lacks working xml processing modules? In-Reply-To: <23891c90.0311240342.46419188@posting.google.com> References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: ? 2003?11?24????UTC+8??7?42?31??Paul Boddie??? > janeaustine50 at hotmail.com (Jane Austine) wrote in message news:<ba1e306f.0311201805.9df1d9 at posting.google.com>... > > I'm trying to parse an xml file with jython (not through java parsers > > like xerces). > > > > I tried minidom in jython 2.1 and 2.2a but all failed. > > > > What can I do? The last resort would be using java parsers. Then how > > can I use them like python xml parsers? It seems like javadom and > > javasax has something to do, but I don't know how. > > The Java parsers seem to work quite well with the xml.dom.javadom > package. First, update your CLASSPATH with references to the necessary > .jar files - this can be a frustrating process, but I found that > xercesImpl-2.5.0.jar and xml-apis.jar were a good combination: > > export CLASSPATH=.../xercesImpl-2.5.0.jar:.../xml-apis.jar > > Then, start jython and try the following: > > import xml.dom.javadom > impl = xml.dom.javadom.XercesDomImplementation() > # Use your own filename below! > doc = impl.buildDocumentFile("example.xml") > # Now, try some PyXML-style DOM properties and methods. > doc.childNodes > doc.childNodes[0].getAttribute("some-attr") > > I'd seen javadom lurking in PyXML before now, but it's a nice surprise > to see that it works rather well, especially since I've never seen any > evidence of anyone using it (as far as I remember). > > Paul hi,do you know the PyXML whether can be supported by Jython ? Looking forward to your reply! Thanks From lipska at lipskathekat.com Tue Jul 17 04:45:16 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 09:45:16 +0100 Subject: Encapsulation, inheritance and polymorphism Message-ID: Pythoners Python 2.7.3 Ubuntu Linux 12.04 LTS I've been taking a brief look at Python. From the tutorial documentation I get the following 'Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming'. I was expecting (hoping) to see in depth documentation relating to Class construction, extension mechanisms and runtime polymorphism. What I actually get is a confusion of Classes, modules, scripts and whatever else. Is Python truly OO or is it just one way to use the language. I see some documentation relating to classes but nothing on instantiation .. in fact the documentation appears to say that classes are used in a static way e.g ClassName.method(), and command line scripting is really outside the scope of other OO languages I have experienced. Is there a previous discussion in the group that I could read. Many thanks Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer. From andrea.crotti.0 at gmail.com Tue Jul 17 05:06:36 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Tue, 17 Jul 2012 10:06:36 +0100 Subject: assertraises behaviour In-Reply-To: References: Message-ID: 2012/7/16 Peter Otten <__peter__ at web.de>: > No, I don't see how the code you gave above can fail with an OSError. > > Can you give an example that produces the desired behaviour with nose? Maybe > we can help you translate it to basic unittest. > > -- > http://mail.python.org/mailman/listinfo/python-list Well this is what I meant: import unittest class TestWithRaises(unittest.TestCase): def test_first(self): assert False def test_second(self): print("also called") assert True if __name__ == '__main__': unittest.main() in this case also the second test is run even if the first fails.. But that's probably easy because we just need to catch exceptions for every method call, so it's not exactly the same thing.. From ulrich.eckhardt at dominolaser.com Tue Jul 17 05:30:42 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 17 Jul 2012 11:30:42 +0200 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: Message-ID: <3vnfd9-343.ln1@satorlaser.homedns.org> Welcome! Am 17.07.2012 10:45, schrieb Lipska the Kat: > I was expecting (hoping) to see in depth documentation relating to Class > construction, extension mechanisms and runtime polymorphism. In addition to this forum for direct help and discussion, two suggestions: Firstly, it could help if you mentioned what programming languages you are fluent in, in order to help traditional misconceptions and to draw parallels. Secondly, http://docs.python.org is the central hub to tutorials and documentation. > What I actually get is a confusion of Classes, modules, scripts and > whatever else. Due to the very dynamic nature of Python, types (classes), modules and functions are themselves objects that can be manipulated. > Is Python truly OO or is it just one way to use the language. Python supports OOP, but it doesn't enforce it. You can use other paradigms, too. > I see some documentation relating to classes but nothing on > instantiation .. in fact the documentation appears to say that classes > are used in a static way e.g ClassName.method(), and command line > scripting is really outside the scope of other OO languages I have > experienced. I think you are confused. For the documentation, it would help to know which documentation exactly seems to make such claims. For the thing about commandline scripting, I'm afraid you will have to adjust your expectations. BTW: In general, you instantiate a class by just calling the class' name like a function. If e.g. ClassName is a class, ClassName() instantiates this class. Good luck! Uli From stefan_ml at behnel.de Tue Jul 17 05:31:37 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 17 Jul 2012 11:31:37 +0200 Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: gaodexiaozheng at gmail.com, 17.07.2012 10:35: > hi,do you know the PyXML whether can be supported by Jython ? PyXML is a dead project, don't use it. You can use ElementTree in Jython, just as in Python. Stefan From tinnews at isbd.co.uk Tue Jul 17 05:34:18 2012 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Tue, 17 Jul 2012 10:34:18 +0100 Subject: PyQt QCalendarWidget events question References: Message-ID: John Posner wrote: > On 7/16/2012 12:28 PM, tinnews at isbd.co.uk wrote: > > tinnews at isbd.co.uk wrote: > >> I am trying to use the PyQt4 calendar widget to perform some different > >> actions on specific dates. There are three events available:- > >> > >> selectionChanged() > >> activated(QDate) > >> clicked(QDate) > >> > >> On trying all these out it would appear that the event handlers get > >> called as follows:- > >> > >> The clicked(QDate) event gets called if you click on an already > >> selected date. > >> > >> The selectionChanged() and then the clicked(QDate) events are > >> called when you click on a new date. > >> > >> The selectionChanged(), then the clicked(QDate) and then the > >> activated(QDate) events are called if you double-click on a new date. > >> > >> The clicked(QDate) and then the activated(QDate) events are called > >> if you double-click on an already selected date. > >> > >> > >> How can I get a single-click on a date to get 'Action1' and double-click > >> on a date to get 'Action2'? > > I'm sorry, this got sent a bit before I'd completed it. The trouble > > is that I want to run Action1 if I single-click on a date whether or > > not it's a changed date and I want to run Action2 if I double-click on > > a date whether or not it's a changed date. However I don't see how I > > can do this because of the order in which the event handlers are > > called. > > > > Is there any way to manipulate this so I can get the result I want? > > At the moment the only way I can see to do it is to wait a while after > > a click and then look at what actions occurred but this seems a real > > bodge. > > I suspect that the consensus would be "don't do that" -- having > single-click and double click perform unrelated actions. They're not actually unrelated, one will edit an existing entry in a file for the given date, the other will add a new entry in the file for that date. I.e. single-click means open file at specified date, double-click means open file at specified date and insert a new entry for that date. > But here's an > implementation based on the advice at > http://www.qtcentre.org/threads/7858-Double-Click-Capturing > > (use Ctrl-Break to break out of the event loop) > > import PyQt4.QtCore as C > import PyQt4.QtGui as G > > class Button(G.QPushButton): > def __init__(self, text): > G.QPushButton.__init__(self, text) > > # flag to suppress second mouseReleaseEvent > # in this double-click event sequence: > # 1. mousePressEvent > # 2. mouseReleaseEvent > # 3. mouseDoubleClickEvent > # 4. mouseReleaseEvent > self.double_clicked = False > > def mouseReleaseEvent(self, evt): > # executed for first mouseReleaseEvent > if not self.double_clicked: > self.first_click_timer = C.QTimer() > self.first_click_timer.setSingleShot(True) > # double-click must occur within 1/4 second of first-click > release > self.first_click_timer.setInterval(250) > self.first_click_timer.timeout.connect(self.single_click_action) > self.first_click_timer.start() > # executed for second mouseReleaseEvent > else: > # reset the flag > self.double_clicked = False > > def single_click_action(self): > print "Performing single-click action" > > def mouseDoubleClickEvent(self, evt): > # suppress the single-click action; perform double-click action > instead > self.first_click_timer.stop() > print "Performing double-click action" > > # prepare for second mouseReleaseEvent > self.double_clicked = True > > # main program > > app = G.QApplication([]) > button = Button("Click or double-click me") > button.show() > app.exec_() > > Yes, thanks, though it is basically the bodge using timing that I was trying to avoid. It's so fundamental to most GUIs that single-click and double-click allow one to do different things with the same object I'm surprised that pyqt makes it so difficult to implement. -- Chris Green From jeanpierreda at gmail.com Tue Jul 17 05:38:07 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 17 Jul 2012 05:38:07 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50050567$0$30002$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <7b027612-a07e-40f9-8ad2-3e95c5440482@googlegroups.com> <86872ad2-fda0-403b-9f18-d1cb18e41860@t32g2000yqd.googlegroups.com> <50039290$0$29978$c3e8da3$5496439d@news.astraweb.com> <50050567$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 17, 2012 at 2:25 AM, Steven D'Aprano wrote: > It already is part of the collection interface: it is spelled __nonzero__ > (Python 2) or __bool__ (Python 3), and like all dunder methods, it is > called automatically for you when you use the right syntax: You're still ignoring what I actually said. -- Devin From mcepl at redhat.com Tue Jul 17 05:39:50 2012 From: mcepl at redhat.com (Matej Cepl) Date: Tue, 17 Jul 2012 11:39:50 +0200 Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: On 17/07/12 10:35, gaodexiaozheng at gmail.com wrote: >> > I'm trying to parse an xml file with jython (not through java parsers >> > like xerces). https://code.google.com/p/jython-elementtree/ ??? From stefan_ml at behnel.de Tue Jul 17 06:02:31 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 17 Jul 2012 12:02:31 +0200 Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: Matej Cepl, 17.07.2012 11:39: > On 17/07/12 10:35, gaodexiaozheng at gmail.com wrote: >>> > I'm trying to parse an xml file with jython (not through java >>> parsers >>> > like xerces). > > https://code.google.com/p/jython-elementtree/ ??? Note that this ships with Jython 2.5. Stefan From jeanpierreda at gmail.com Tue Jul 17 06:03:48 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 17 Jul 2012 06:03:48 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: Message-ID: On Tue, Jul 17, 2012 at 4:45 AM, Lipska the Kat wrote: > Is Python truly OO or is it just one way to use the language. I see some > documentation relating to classes but nothing on instantiation .. in fact > the documentation appears to say that classes are used in a static way e.g > ClassName.method(), and command line scripting is really outside the scope > of other OO languages I have experienced. It doesn't look like you're reading the section on classes: http://docs.python.org/tutorial/classes.html You create a class like this: class MyClass(MySuperclass1, MySuperclass2): # class attributes and methods attr = 3 def method(self): print self.attr You can instantiate it by calling the class, as if it were a function: myinstance = MyClass() You call a method getting the method (myinstance.method), and then calling that as if it were a function. myinstance.method() Polymorphism is "duck typed" -- that is, it's based on the presence/absence of attributes and methods, not on declared interfaces (Python has no interfaces). So, for example, "foo.read()" works on any object bound to the name "foo", as long as it has a read method that takes no parameters. This could be a file-like object, but it could also be something completely different that just happens to have a method by the same name. > Is there a previous discussion in the group that I could read. Man, I dunno, the list archives are impossible to navigate. -- Devin From ulrich.eckhardt at dominolaser.com Tue Jul 17 06:34:29 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 17 Jul 2012 12:34:29 +0200 Subject: assertraises behaviour In-Reply-To: References: Message-ID: Am 17.07.2012 11:06, schrieb andrea crotti: > import unittest > > class TestWithRaises(unittest.TestCase): > def test_first(self): > assert False > > def test_second(self): > print("also called") > assert True > > if __name__ == '__main__': > unittest.main() > > in this case also the second test is run even if the first fails.. The reason for that is that the unit testing framework catches and handles the error. It calls both test functions in some unspecified order and logs the result. Calls to two separate test functions are thereby separated from each other. This is intentionally so, but I think you can also give the unit testing framework a flag that makes it abort after the first error. In no way will the exception escape from the unittest.main() call though, it is all caught and handled inside, also by intention. > But that's probably easy because we just need to catch exceptions for > every method call, so it's not exactly the same thing.. I don't understand what you want to say here. I also don't understand what your problem in general is. I guess there are some expectations which are not satisfied, but you haven't explained those explicitly yet. Uli From albert at spenarnc.xs4all.nl Tue Jul 17 06:54:25 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 17 Jul 2012 10:54:25 GMT Subject: code review References: <500038f5$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Duncan Booth wrote: >Steven D'Aprano wrote: > >> On Fri, 13 Jul 2012 12:30:47 +0000, Albert van der Horst wrote: >>> The worst of is, of course, = for assignment instead of := . This is >>> a convention that Python follows, to my dismay. >> >> *shrug* >> >> The worst is to use = for both equality and assignment, like some >> BASICs. At least Python does not allow assignment as an expression, so >> you can't make the typical C error of: >> >> if x = y: do_something() # oops meant x == y >> >Technically of course Python doesn't have assignment, it just binds names. > >Albert raised the subject of Algol 68 which if I remember correctly used := >for assignment and = to bind names (although unlike Python you couldn't >then re-bind the name to another object in the same scope). Algol 68 is very particular about this indeed. For instance they have a whole theory behind real x; x := 17.; This is considered an abbreviation of ref real x = loc real; x:= 17; So x is a reference bound to a freshly generated local real. You see = and that means you can't ever break that relationship. On the left side of a := it is required to have a ref something. Because that generates a pretty clear context, you have considerable leeway on the right side, that is cast into the something. real x= 18.; x := 15.; is right out. If you want to rebind something you need a ref which is really a ref ref. Then you can only switch bindings between different types. So it is totally different from Python. I never thought about = in python to mean binding to set it apart from the Pascal := , instead of being a c-ism. Still my mathematical mind is bothered about the sequence ( legal in FORTRAN , C Python ) X = 1 X = 2 Groetjes Albert >-- >Duncan Booth http://kupuguy.blogspot.com Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From lipska at lipskathekat.com Tue Jul 17 07:01:21 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 12:01:21 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <3vnfd9-343.ln1@satorlaser.homedns.org> References: <3vnfd9-343.ln1@satorlaser.homedns.org> Message-ID: <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> On 17/07/12 10:30, Ulrich Eckhardt wrote: > Welcome! > > Am 17.07.2012 10:45, schrieb Lipska the Kat: >> I was expecting (hoping) to see in depth documentation relating to Class >> construction, extension mechanisms and runtime polymorphism. > > In addition to this forum for direct help and discussion, two > suggestions: Firstly, it could help if you mentioned what programming > languages you are fluent in For the past 9 years I have been developing in Java, everything from device drivers (well firmware interfaces would be a better description) to serverside business logic implemented using POJOs and database interfaces along with some in depth work with earlier versions of J2EE including EJBs and of course the obligatory frameworks. There's more but you get the idea. My speciality if you like is the design of high availability real time business systems right from high level natural language specifications to detailed use cases and associated models in UML. I also do some implementation work although not so much these days. phew! my resume in a nutshell I suppose Earlier on in my career I did some fairly low level stuff in C and C++ although the mists of time and all that ... Anyway, I'm looking at Python as a rapid prototyping language. I have an idea and just want to get it down in basic outline code as quickly as possible before it departs my aging brain... I'm not used to using variables without declaring their type ... (well I used to do Visual Basic many years ago) It just seems so weird, and what's this obsession with 'correct' indentation of code ??? >in order to help traditional misconceptions > and to draw parallels. Secondly, http://docs.python.org is the central > hub to tutorials and documentation. > > >> What I actually get is a confusion of Classes, modules, scripts and >> whatever else. > > Due to the very dynamic nature of Python, types (classes), modules and > functions are themselves objects that can be manipulated. > > snip > >> I see some documentation relating to classes but nothing on >> instantiation .. in fact the documentation appears to say that classes > > are used in a static way e.g ClassName.method(), and command line > > scripting is really outside the scope of other OO languages I have > > experienced. > > I think you are confused. Highly likely > For the documentation, it would help to know > which documentation exactly seems to make such claims. For the thing > about commandline scripting, I'm afraid you will have to adjust your > expectations. I'll try to find it again > > BTW: In general, you instantiate a class by just calling the class' name > like a function. If e.g. ClassName is a class, ClassName() instantiates > this class. > > > Good luck! Thank you, and thank you for your kind response Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From d at davea.name Tue Jul 17 07:23:13 2012 From: d at davea.name (Dave Angel) Date: Tue, 17 Jul 2012 07:23:13 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <50054B21.3010206@davea.name> On 07/17/2012 07:01 AM, Lipska the Kat wrote: > > > Anyway, I'm looking at Python as a rapid prototyping language. > I have an idea and just want to get it down in basic outline code as > quickly as possible before it departs my aging brain... I'm not used > to using variables without declaring their type ... (well I used to do > Visual Basic many years ago) It just seems so weird, and what's this > obsession with 'correct' indentation of code ??? > Welcome to comp.lang.python. I hope you enjoy learning and using Python. Indentation isn't just custom in Python. It's part of the syntax. Other languages use braces, or keywords, to indicate scope, but Python uses indentation. Other than the occasional tab to confuse things, the rules are pretty simple. You must indent the body of a function, the scope of an if or else clause, or other similar language pieces (class, try, except, ...) Within such a scope, you cannot change indentation, except of course for a nested scope. At the end of such scope you must outdent to the previous state. The convention is to use 4 spaces per indentation, but the language will accept any amount, as long as it's consistent within any single scope. And although mixing tabs and space worked in Python 2.x, sort of, it's disallowed in Python 3. An expression may span multiple lines, but only if it's unambiguous to the compiler (eg. a pending left paren with no matching right paren yet). In that case. indentation of the subsequent lines is unrestricted. HTH -- DaveA From lipska at lipskathekat.com Tue Jul 17 07:24:52 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 12:24:52 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: Message-ID: <69-dnRfmT7kb1pjNnZ2dnUVZ8kSdnZ2d@bt.com> On 17/07/12 11:03, Devin Jeanpierre wrote: > On Tue, Jul 17, 2012 at 4:45 AM, Lipska the Kat wrote: >> Is Python truly OO or is it just one way to use the language. I see some >> documentation relating to classes but nothing on instantiation .. in fact >> the documentation appears to say that classes are used in a static way e.g >> ClassName.method(), and command line scripting is really outside the scope >> of other OO languages I have experienced. > > It doesn't look like you're reading the section on classes: > > http://docs.python.org/tutorial/classes.html Thanks, I wasn't, there is too much to do and not enough time to do it. So now I just need to chill out a bit and get into 'documentation reading mode' again > Polymorphism is "duck typed" -- Yes, I've been reading the wikipedia entry on this ... this type of polymorphism is not familiar to me ... I come from a Java background. more reading I guess. snip > -- Devin Thanks for your time and I'll try to do a bit better with the reading thing before asking more questions... not sure about this obsession with code indentation though :-| -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From bahamutzero8825 at gmail.com Tue Jul 17 07:37:07 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 06:37:07 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <50054E63.8080304@gmail.com> On 7/17/2012 6:01 AM, Lipska the Kat wrote: > Anyway, I'm looking at Python as a rapid prototyping language. > I have an idea and just want to get it down in basic outline code as > quickly as possible before it departs my aging brain... I'm not used to > using variables without declaring their type ... (well I used to do > Visual Basic many years ago) It just seems so weird, and what's this > obsession with 'correct' indentation of code ??? "Pythonic" is (or at least should be) a word you encounter frequently in discussions of Python code. Learn what is considered Pythonic and then write Python code that way if you want to work with the language rather than fight it. Duck-typing is very Pythonic and so is readable code. As Dave mentioned, indentation is part of the syntax - blocks must be indented with either tabs or spaces (choose one - if you mix them ambiguously, an IndentationError will be raised). Try "from __future__ import braces" and "import this" for some insight. ;) The official tutorial gives a great overview of the language and has links to reference material that goes into greater detail: http://docs.python.org/tutorial/ (Python 2.7) http://docs.python.org/py3k/tutorial/ (Python 3.2) On a side note, I would highly recommend learning Python 3 (3.2 is the latest stable version) unless you have an explicit need for Python 2 (some major 3rd-party libraries have not been ported yet). Python 2 won't get any new features; it will simply get bug fixes until its EOL in 2014 (15?). -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From lipska at lipskathekat.com Tue Jul 17 07:44:32 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 12:44:32 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/12 12:37, Andrew Berg wrote: > On 7/17/2012 6:01 AM, Lipska the Kat wrote: >> Anyway, I'm looking at Python as a rapid prototyping language. snip > "Pythonic" is (or at least should be) a word you encounter frequently in > discussions of Python code. Learn what is considered Pythonic and then > write Python code that way if you want to work with the language rather > than fight it. Duck-typing is very Pythonic You're not kidding, the 'duck' example at http://en.wikipedia.org/wiki/Duck_typing made me check I hadn't overdone the medication this morning. That is just plain ...weird. It will take me a while to form non knee jerk opinions of this for sure. snip > On a side note, I would highly recommend learning Python 3 (3.2 is the > latest stable version) unless you have an explicit need for Python 2 > (some major 3rd-party libraries have not been ported yet). Python 2 > won't get any new features; it will simply get bug fixes until its EOL > in 2014 (15?). I'll check it out, thanks. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From bahamutzero8825 at gmail.com Tue Jul 17 07:53:06 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 06:53:06 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <50055222.3010303@gmail.com> On 7/17/2012 6:44 AM, Lipska the Kat wrote: > I'll check it out, thanks. I forgot to add this: http://wiki.python.org/moin/Python2orPython3 It's a little outdated (there is more progress toward py3k by 3rd-party libraries every day), but still quite helpful. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From lipska at lipskathekat.com Tue Jul 17 08:01:12 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 13:01:12 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: Message-ID: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> On 17/07/12 09:45, Lipska the Kat wrote: > Pythoners > > Python 2.7.3 > Ubuntu Linux 12.04 LTS > > I've been taking a brief look at Python. > snip Well I've set myself a task. I have a text file containing a list of stock items each line contains the number in stock followed by a tab followed by the name of the item. I need to implement something that reads in the text file and outputs the stock list in ascending or descending order of quantity. Please note I am NOT asking for solutions. In bash this is laughably trivial sort -nr $1 | head -${2:-10} Java is easy but long winded and takes a while to set up C is ... well it's been a while but I'll get there Python, well that's my current task. It will be interesting to compare the solutions for speed and ease of development and more importantly re-usability. > > Lipska > -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From ulrich.eckhardt at dominolaser.com Tue Jul 17 08:18:20 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 17 Jul 2012 14:18:20 +0200 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: Am 17.07.2012 13:01, schrieb Lipska the Kat: > On 17/07/12 10:30, Ulrich Eckhardt wrote: >> Am 17.07.2012 10:45, schrieb Lipska the Kat: >>> I was expecting (hoping) to see in depth documentation relating to Class >>> construction, extension mechanisms and runtime polymorphism. >> >> In addition to this forum for direct help and discussion, two >> suggestions: Firstly, it could help if you mentioned what programming >> languages you are fluent in > > For the past 9 years I have been developing in Java [...] Java is usually called an OOP language, because everything you do there is put into a class. Free functions don't exist, the closest you get is class-static functions (correct me if I'm wrong, I'm not really fluent in that language). In Python, you have the choice to use OOP, but you can also use free functions or mix those. > I'm not used to using variables without declaring their type As a C++ programmer (roughly 80%C++, 15%Python, 5%C) I know that feeling. Having types declared in advance just helps by having the compiler check if the passed arguments are correct. Not having this gives both freedom but also bears dangers. > what's this obsession with 'correct' indentation of code ??? You'll get used to it and then start loving it. ;) Uli From michele.simionato at gmail.com Tue Jul 17 08:23:22 2012 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 17 Jul 2012 05:23:22 -0700 (PDT) Subject: Style question: metaclass self vs cls? In-Reply-To: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7566b8bc-929e-4f70-8e44-f0bda232ef85@googlegroups.com> The standard is to use `cls`. In the __new__ method you can use `mcl` or `meta`. From ethan at stoneleaf.us Tue Jul 17 08:35:52 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 05:35:52 -0700 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <5004F5F4.5000601@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <5004F5F4.5000601@gmail.com> Message-ID: <50055C28.40601@stoneleaf.us> Andrew Berg wrote: > To put it in duck-typing terms, why should everything have to quack like > True or False? Sure, I can see why 1 quacks like True or [] quacks like > False, but I don't see why say, a Logger or function should quack like > either. Should a Thread object be True if it's been started and False > otherwise? True and False are red herrings. It is more appropriate to think that True quacks like something and False like nothing than the other way 'round. Maybe some examples from my own code will help: DbfTable --> True if any records in table, False otherwise DbfIndex --> True if any records in index, False otherwise DbfList --> True if any records in list, False otherwise DbfDate --> True if a date, False otherwise (could be eight spaces instead of a real date) DbfDateTime --> True if a datetime, False otherwise DbfRecord --> True always DbfRecordTemplate --> True always DbfRecordVaporware --> False always While I could have DbfRecord be False if, for example, it had no data stored in it, I have no use case for that scenario so haven't bothered. Also, at this point I am using the distinction of True/False with regards to records to determine if I have a real record (True means a record/template I can read/write, False means I don't). > If it truly is about something vs. nothing, why is a NameError (or > AttributeError) raised when testing with an undefined variable? Being > undefined quacks like nothing, doesn't it? It's about /representing/ something vs. nothing. An undefined name isn't representing anything (except a bug, of course ;). ~Ethan~ From gandalf at shopzeus.com Tue Jul 17 08:43:11 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 17 Jul 2012 14:43:11 +0200 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500520FF.3010305@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> <500520FF.3010305@gmail.com> Message-ID: <50055DDF.20500@shopzeus.com> On 2012-07-17 10:23, Andrew Berg wrote: > I don't want that, but I am suggesting that it would be consistent with > the idea of "something or nothing". Don't confuse names and objects. You can only test the truth value of objects. If you don't have a name in a namespace, then it means you don't have a tool to have a reference to anything (including the False object). Using the same logic you could also say that not giving any condition to the "if" statement should be evaluated as False: if: print "This never gets executed" But it makes no sense. From gandalf at shopzeus.com Tue Jul 17 08:59:44 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 17 Jul 2012 14:59:44 +0200 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500561C0.5030308@shopzeus.com> > Not really. It doesn't quack like anything. Actually, there is no "it". So we cannot talk about how it quacks. :-D From breamoreboy at yahoo.co.uk Tue Jul 17 09:29:30 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 14:29:30 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/2012 12:01, Lipska the Kat wrote: > > Anyway, I'm looking at Python as a rapid prototyping language. > > Lipska > One of the huge advantages of Python here is that you can simply blast stuff into the interactive prompt and see what happens, no need to write a script. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Jul 17 09:35:20 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 14:35:20 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/2012 12:44, Lipska the Kat wrote: > > You're not kidding, the 'duck' example at > http://en.wikipedia.org/wiki/Duck_typing made me check I hadn't overdone > the medication this morning. That is just plain ...weird. It will take > me a while to form non knee jerk opinions of this for sure. > > Lipska > > It's difficult to get junkies off of their addictive substances but I'm sure that the qualities of Python will eventually overcome your Java habit :) -- Cheers. Mark Lawrence. From n.nikandish at gmail.com Tue Jul 17 09:47:05 2012 From: n.nikandish at gmail.com (Naser Nikandish) Date: Tue, 17 Jul 2012 06:47:05 -0700 (PDT) Subject: Python 2.6 on Mac 10.7 doesn't work Message-ID: <3b73f4f4-dc36-4b16-a3c3-66b52ef95654@googlegroups.com> Hi, I am trying to install Python 2.6 on Mac OS Lion. Here is what I did: 1- Download Mac Installer disk image (2.6) (sig) from http://www.python.org/getit/releases/2.6/ 2- Install it 3- Run Python Luncher, go to Python Luncher preferences, and change the interpreter to Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw Now that I want to open IDLE and open my old projects, it doesn't run! Is there anything that I am missing? oh btw, I used to use Python 2.6.7 that comes preinstalled on Mac OS. I really appreciate your help. From roy at panix.com Tue Jul 17 09:52:59 2012 From: roy at panix.com (Roy Smith) Date: Tue, 17 Jul 2012 09:52:59 -0400 Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: In article <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d at bt.com>, Lipska the Kat wrote: > I'm not used to using variables without declaring their type If you truly wanted to recreate this type-bondage style of programming in Python, it's easy enough to do. Where you would write in C++: // Type matching will get checked at compile-time void my_function(MassivelyParallelFrobinator& mpf, OtherThing& ot) { blah, blah, blah } you could write in Python: # Type matching will get checked at run-time def my_function(mpf, ot): assert isinstance(mpf, MassivelyParallelFrobinator) assert isinstance(ot, OtherThing) but that's just not the way people write code in Python. From sarbjit1987 at gmail.com Tue Jul 17 09:55:21 2012 From: sarbjit1987 at gmail.com (Sarbjit singh) Date: Tue, 17 Jul 2012 06:55:21 -0700 (PDT) Subject: How to configure Tkinter Listbox to disable state keeping selected item highlighted Message-ID: <92bf377d-05ea-42f8-98e4-3d76114aebc9@googlegroups.com> I am having a problem configuring a listbox widget such that the selection remains highlighted even while it is set (programmatically) to the DISABLED state. Below code shows the problem: from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "Text1") listbox.insert(END, "Text2") listbox.insert(END, "Text3") listbox.selection_set(first=0, last=None) listbox.configure(exportselection=False) listbox.configure(state=DISABLED) Now when I change state to NORMAL, selected item is being highlighted. Is there a way I could disable widget (i.e. No response on mouse clicks) but keep the selected object remain highlighted? Intent: I want to utilise this widget on wizard App that I am creating. I would like this widget to indicate the current page / wizard number which the user selected. Is there any other widget I could use instead of it? (Labels possibly?) From lipska at lipskathekat.com Tue Jul 17 10:01:02 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 15:01:02 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/12 12:37, Andrew Berg wrote: > On 7/17/2012 6:01 AM, Lipska the Kat wrote: snip > On a side note, I would highly recommend learning Python 3 (3.2 is the > latest stable version) unless you have an explicit need for Python 2 > (some major 3rd-party libraries have not been ported yet). Python 2 > won't get any new features; it will simply get bug fixes until its EOL > in 2014 (15?). Wow, that was a blast from the past Just downloaded, unzipped, untarred, configured, made and installed python 3.2.3 ... it's YEARS since I've done this, makes me feel young again. Lispka -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From dihedral88888 at googlemail.com Tue Jul 17 10:11:54 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 17 Jul 2012 07:11:54 -0700 (PDT) Subject: Diagramming code In-Reply-To: References: Message-ID: Chris Rebert? 2012?7?16????UTC+8??9?38?53???? > On Sun, Jul 15, 2012 at 6:26 PM, hamilton <hamilton at nothere.com> wrote: > > Subject: Diagramming code > > > > Is there any software to help understand python code ? > > What sort of diagrams? Control flow diagrams? Class diagrams? Sequence > diagrams? Module dependency diagrams? There are many different types > you could be referring to. Here's a relatively comprehensive list: > http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview > > Regards, > Chris > -- > UML: Kill it with fire! OK, I'll classify OOP by (1) properties of instances of declared classes must be fixed such as those in C++ (2) An interpreter could be embedded in the run time for an object to evolve through time to accquire properties. If the robot age was to be comming, what can we do now? I think learning python is the high school does help a lot for the United States in the future. From dihedral88888 at googlemail.com Tue Jul 17 10:11:54 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 17 Jul 2012 07:11:54 -0700 (PDT) Subject: Diagramming code In-Reply-To: References: Message-ID: Chris Rebert? 2012?7?16????UTC+8??9?38?53???? > On Sun, Jul 15, 2012 at 6:26 PM, hamilton <hamilton at nothere.com> wrote: > > Subject: Diagramming code > > > > Is there any software to help understand python code ? > > What sort of diagrams? Control flow diagrams? Class diagrams? Sequence > diagrams? Module dependency diagrams? There are many different types > you could be referring to. Here's a relatively comprehensive list: > http://en.wikipedia.org/wiki/Unified_Modeling_Language#Diagrams_overview > > Regards, > Chris > -- > UML: Kill it with fire! OK, I'll classify OOP by (1) properties of instances of declared classes must be fixed such as those in C++ (2) An interpreter could be embedded in the run time for an object to evolve through time to accquire properties. If the robot age was to be comming, what can we do now? I think learning python is the high school does help a lot for the United States in the future. From bahamutzero8825 at gmail.com Tue Jul 17 10:16:04 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 09:16:04 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <500573A4.2090306@gmail.com> On 7/17/2012 9:01 AM, Lipska the Kat wrote: > Wow, that was a blast from the past > Just downloaded, unzipped, untarred, configured, made and installed > python 3.2.3 ... it's YEARS since I've done this, makes me feel young again. Most Linux distributions should have a premade package for stable Python versions - apt-get install python3 or something like that. Python 2 is generally the default Python because of all the system scripts that haven't been ported to py3k. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From lipska at lipskathekat.com Tue Jul 17 10:23:30 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 15:23:30 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/12 14:52, Roy Smith wrote: > In article<-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d at bt.com>, > Lipska the Kat wrote: > >> I'm not used to using variables without declaring their type > > If you truly wanted to recreate this type-bondage style of programming > in Python, it's easy enough to do. snip Well 'type-bondage' is a strange way of thinking about compile time type checking and making code easier to read (and therefor debug) but I'm not about to get into some religious war about declaring a variables type. I'll just say that I prefer to devote testing efforts to the real danger area which in my experience is 'user' input. Clients look dimly on runtime errors however they occur and if I can leave it to the compiler to check as much as possible then I'll take that. I do understand however that compiling an intepreted language doesn't really make sense however i'm sure there are interpreted languages that allow pre-execution type checking ... aren't there ? Oh yes, there's one called Java :-) Still, I'm sure you're only kidding around with me :-) Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From lipska at lipskathekat.com Tue Jul 17 10:26:12 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 15:26:12 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/12 15:16, Andrew Berg wrote: > On 7/17/2012 9:01 AM, Lipska the Kat wrote: >> Wow, that was a blast from the past >> Just downloaded, unzipped, untarred, configured, made and installed >> python 3.2.3 ... it's YEARS since I've done this, makes me feel young again. > Most Linux distributions should have a premade package for stable Python > versions - apt-get install python3 or something like that. Not as much fun though is it :-) Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From inq1ltd at inqvista.com Tue Jul 17 11:27:16 2012 From: inq1ltd at inqvista.com (inq1ltd) Date: Tue, 17 Jul 2012 11:27:16 -0400 Subject: How to configure Tkinter Listbox to disable state keeping selected item highlighted In-Reply-To: <92bf377d-05ea-42f8-98e4-3d76114aebc9@googlegroups.com> References: <92bf377d-05ea-42f8-98e4-3d76114aebc9@googlegroups.com> Message-ID: <7343626.2v6gsTI0UE@mach-114-20> On Tuesday, July 17, 2012 06:55:21 AM Sarbjit singh wrote: > I am having a problem configuring a listbox widget such that the selection > remains highlighted even while it is set (programmatically) to the DISABLED > state. Below code shows the problem: > > from Tkinter import * > master = Tk() > listbox = Listbox(master) > listbox.pack() > listbox.insert(END, "Text1") > listbox.insert(END, "Text2") > listbox.insert(END, "Text3") > listbox.selection_set(first=0, last=None) > listbox.configure(exportselection=False) > listbox.configure(state=DISABLED) > > Now when I change state to NORMAL, selected item is being highlighted. Is > there a way I could disable widget (i.e. No response on mouse clicks) but > keep the selected object remain highlighted? Learn how to use radiobuttons. I think this is what you want. jd > > Intent: I want to utilise this widget on wizard App that I am creating. I > would like this widget to indicate the current page / wizard number which > the user selected. Is there any other widget I could use instead of it? > (Labels possibly?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Jul 17 12:26:28 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 17:26:28 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/2012 15:23, Lipska the Kat wrote: > On 17/07/12 14:52, Roy Smith wrote: >> In article<-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d at bt.com>, >> Lipska the Kat wrote: >> >>> I'm not used to using variables without declaring their type >> >> If you truly wanted to recreate this type-bondage style of programming >> in Python, it's easy enough to do. > > snip > > Well 'type-bondage' is a strange way of thinking about compile time type > checking and making code easier to read (and therefor debug) but > I'm not about to get into some religious war about declaring a variables > type. I'll just say that I prefer to devote testing efforts to the real > danger area which in my experience is 'user' input. Why waste time testing, I thought that the compiler looked after everything? :) But seriously you might want to look at the unittest module in the standard library. There's also a separate mailing list for Python testing and I'm sure there's a wiki that compares the available tesing tools. Google and ye shall find!!! > Clients look dimly on runtime errors however they occur and if I can > leave it to the compiler to check as much as possible then I'll take that. > > I do understand however that compiling an intepreted language doesn't > really make sense however i'm sure there are interpreted languages that > allow pre-execution type checking ... aren't there ? Oh yes, there's one > called Java :-) There are tools available to help here such as pylint, pychecker and pyflakes. For other modules check out pypi at http://pypi.python.org/pypi > > Still, I'm sure you're only kidding around with me :-) Kidding around on a Python mailing list, never, how dare you Sir, simply wouldn't be cricket :-) > > Lipska > -- Cheers. Mark Lawrence. From hansmu at xs4all.nl Tue Jul 17 12:27:37 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 17 Jul 2012 18:27:37 +0200 Subject: Python 2.6 on Mac 10.7 doesn't work In-Reply-To: <3b73f4f4-dc36-4b16-a3c3-66b52ef95654@googlegroups.com> References: <3b73f4f4-dc36-4b16-a3c3-66b52ef95654@googlegroups.com> Message-ID: <5005927a$0$6949$e4fe514c@news2.news.xs4all.nl> On 17/07/12 15:47:05, Naser Nikandish wrote: > Hi, > > I am trying to install Python 2.6 on Mac OS Lion. Here is what I did: > > 1- Download Mac Installer disk image (2.6) (sig) from > http://www.python.org/getit/releases/2.6/ > > 2- Install it > > 3- Run Python Luncher, go to Python Luncher preferences, and change the > interpreter to Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw > > Now that I want to open IDLE and open my old projects, it doesn't run! > Is there anything that I am missing? You may be missing a leading slash. The path to pythonw is /Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw > oh btw, I used to use Python 2.6.7 that comes preinstalled on Mac OS. That could also be the problem. You could try using the Python you've downloaded in step 1. > I really appreciate your help. You could try opening /Applications/Utilities/Terminal.app and running: /Library/Frameworks/Python.framework/Versions/2.6/bin/pyt\ hon /Applications/Python\ 2.6/IDLE.app/Contents/MacOS/IDLE (you can type it one two lines, as shown, or as a single rather long line, leaving out the backslash-newline). That should run Idle, or, if it doesn't, it should give you a useful error message. Hope this helps, -- HansM From manengstudent at gmail.com Tue Jul 17 12:32:18 2012 From: manengstudent at gmail.com (Shamefaced) Date: Tue, 17 Jul 2012 09:32:18 -0700 (PDT) Subject: Blank TK Window Message-ID: <250fc186-0fa9-481c-8b2b-44e77921e6d8@googlegroups.com> Hi, Any reason why a blank Tk() window opens up when I run my code: Code: for run in range(RUNS): waittime = Monitor2() checkouttime = Monitor2() totaltimeinshop = Monitor2() checkout_aisle = Simulation.Resource(AISLES) Simulation.initialize() cf = Customer_Market() Simulation.activate(cf, cf.run(), 0.0) Simulation.simulate(until=CLOSING) Histo = waittime.histogram(low=0.0, high=80, nbins=40) plt = SimPlot() plt.plotLine(Histo, xlab='Time (min)',ylab='Qty Customers', title="Wait Time", color="red", width=2, smooth='True') plt.mainloop() From ian.g.kelly at gmail.com Tue Jul 17 12:34:04 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 17 Jul 2012 10:34:04 -0600 Subject: Style question: metaclass self vs cls? In-Reply-To: <7566b8bc-929e-4f70-8e44-f0bda232ef85@googlegroups.com> References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> <7566b8bc-929e-4f70-8e44-f0bda232ef85@googlegroups.com> Message-ID: On Tue, Jul 17, 2012 at 6:23 AM, Michele Simionato wrote: > The standard is to use `cls`. In the __new__ method you can use `mcl` or `meta`. I've also seen `mcs` a fair amount. From ian.g.kelly at gmail.com Tue Jul 17 12:35:00 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 17 Jul 2012 10:35:00 -0600 Subject: Style question: metaclass self vs cls? In-Reply-To: <8f38a814-3c6c-42d3-8d7b-d7d8ae33d06e@x6g2000pbh.googlegroups.com> References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> <8f38a814-3c6c-42d3-8d7b-d7d8ae33d06e@x6g2000pbh.googlegroups.com> Message-ID: On Tue, Jul 17, 2012 at 12:10 AM, alex23 wrote: > On Jul 17, 1:29 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> Here's a style question for you: in a metaclass, what should I call the >> instance parameter of methods, "cls" or "self"? > > Maybe portmanteu it as "clasself"? :) What is this, 1st edition D&D? Elf is a race, not a class. From lipska at lipskathekat.com Tue Jul 17 12:46:23 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 17:46:23 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 17/07/12 17:26, Mark Lawrence wrote: > On 17/07/2012 15:23, Lipska the Kat wrote: >> On 17/07/12 14:52, Roy Smith wrote: snip >> >> Still, I'm sure you're only kidding around with me :-) > > Kidding around on a Python mailing list, never, how dare you Sir, simply > wouldn't be cricket :-) As in "The batsman of the Kalahari" no doubt :-) -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From woooee at gmail.com Tue Jul 17 12:47:15 2012 From: woooee at gmail.com (woooee) Date: Tue, 17 Jul 2012 09:47:15 -0700 (PDT) Subject: Blank TK Window References: <250fc186-0fa9-481c-8b2b-44e77921e6d8@googlegroups.com> Message-ID: On Jul 17, 9:32?am, Shamefaced wrote: > Hi, > Any reason why a blank Tk() window opens up when I run my code: > Code: > for run in range(RUNS): > ? ? waittime = Monitor2() > ? ? checkouttime = Monitor2() > ? ? totaltimeinshop = Monitor2() > ? ? checkout_aisle = Simulation.Resource(AISLES) > ? ? Simulation.initialize() > ? ? cf = Customer_Market() > ? ? Simulation.activate(cf, cf.run(), 0.0) > ? ? Simulation.simulate(until=CLOSING) > > ? ? Histo = waittime.histogram(low=0.0, high=80, nbins=40) > ? ? plt = SimPlot() > ? ? plt.plotLine(Histo, xlab='Time (min)',ylab='Qty Customers', > ? ? ? ? ? ? ? ? ? ? ? title="Wait Time", > ? ? ? ? ? ? ? ? ? ? ? color="red", width=2, > ? ? ? ? ? ? ? ? ? ? ? smooth='True') > plt.mainloop() 1. you no longer have a toplevel/root "plt" once you replace "plt" with ? ? plt = SimPlot() 2. the SimPlot widget in never placed in Tkinter. This is usually done with pack() or grid() So start out with a Tkinter tutorial so you understand the basics. From tjreedy at udel.edu Tue Jul 17 13:07:38 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Jul 2012 13:07:38 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 7/17/2012 10:23 AM, Lipska the Kat wrote: > Well 'type-bondage' is a strange way of thinking about compile time type > checking and making code easier to read (and therefor debug 'type-bondage' is the requirement to restrict function inputs and output to one declared type, where the type declaration mechanisms are usually quite limited. >>> def max(a, b): if a <= b: return a return b >>> max(1,3) 1 >>> max(3.3, 3.1) 3.1 >>> max('ab', 'aa') 'aa' >>> max([1,1], [1,0]) [1, 0] and so on, indefinitely. How easy is it to write the same in Java? Similarly, list.sort sorts any list as long as a < b works for all pairs of items in the list. Function max works for any two objects as long as 'a <= b' works. So the 'type' of a and b is 'mutually comparable with <='. How do you declare that in Java? How do you declare the type 'non-negative number'? In python, putting 'if input >= 0:' as the top effectively 'declares' that input must be a number and greater than 0. > but I'm not about to get into some religious war about declaring a variables > type. In Python, *all* data items have a class (type). Names in code do not have a type. When they become data items, they are strings. 'Variable' is a somewhat fuzzy term or concept in Python. Since every object is an instance of some class, every class is a subclass of class 'object', and an instance of a class is an instance of all its classess superclasses; every object is an instance of 'object'. So 'object' is the type of all inputs until further restricted. id(ob) produces an integer for all objects. str(ob) is intented to produce a string representation for all objects. The print functions calls str on all its inputs. > I'll just say that I prefer to devote testing efforts to the real > danger area which in my experience is 'user' input. > Clients look dimly on runtime errors however they occur and if I can > leave it to the compiler to check as much as possible then I'll take that. import ast a = ast.literal_eval(input('enter a value: ')) b = ast.literal_eval(input('enter a comparable value: ') try: print('the max of those two is ', max(a,b)) except TypeError: print(a, ' and ', b, ' are not comparable') I suppose > Still, I'm sure you're only kidding around with me :-) How easy was it to write max, or a universal sort in Java? -- Terry Jan Reedy From tjreedy at udel.edu Tue Jul 17 13:24:25 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Jul 2012 13:24:25 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> References: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> Message-ID: On 7/17/2012 8:01 AM, Lipska the Kat wrote: > On 17/07/12 09:45, Lipska the Kat wrote: >> Pythoners >> >> Python 2.7.3 >> Ubuntu Linux 12.04 LTS >> >> I've been taking a brief look at Python. >> > > snip > > Well I've set myself a task. > I have a text file containing a list of stock items > each line contains the number in stock followed by a tab followed by the > name of the item. I need to implement something that reads in the text > file and outputs the stock list in ascending or descending order of > quantity. Nice problem. Easy but non-trivial. > Please note I am NOT asking for solutions. Ok. With some inefficient redundancy, I believe it could be done in one line in Python. Better code would take a few more. > In bash this is laughably trivial > > sort -nr $1 | head -${2:-10} Won't sort work alphabetically and leave the following as is? 1\talpha 11\tbeta 2\tgamma -- Terry Jan Reedy From ethan at stoneleaf.us Tue Jul 17 13:29:39 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 10:29:39 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <5005A103.9050802@stoneleaf.us> Terry Reedy wrote: > On 7/17/2012 10:23 AM, Lipska the Kat wrote: > >> Well 'type-bondage' is a strange way of thinking about compile time type >> checking and making code easier to read (and therefor debug > > 'type-bondage' is the requirement to restrict function inputs and output > to one declared type, where the type declaration mechanisms are usually > quite limited. > > >>> def max(a, b): > if a <= b: return a > return b Surely you meant 'if a >= b: . . .' No worries, I'm sure your unittests would have caught it. ;) ~Ethan~ From tjreedy at udel.edu Tue Jul 17 13:30:44 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Jul 2012 13:30:44 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <500573A4.2090306@gmail.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <500573A4.2090306@gmail.com> Message-ID: On 7/17/2012 10:16 AM, Andrew Berg wrote: > On 7/17/2012 9:01 AM, Lipska the Kat wrote: >> Wow, that was a blast from the past >> Just downloaded, unzipped, untarred, configured, made and installed >> python 3.2.3 ... it's YEARS since I've done this, makes me feel young again. > Most Linux distributions should have a premade package for stable Python > versions - apt-get install python3 or something like that. I am just curious: how long will it take 'most Linux distributions' to premake the even better 3.3.0 (after it comes out) and change the default python3 to that? Do any of them have a premade 3.3.0b0 available? (In some ways, it is already better than 3.2.3.) -- Terry Jan Reedy From rosuav at gmail.com Tue Jul 17 13:41:35 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 18 Jul 2012 03:41:35 +1000 Subject: PyQt QCalendarWidget events question In-Reply-To: References: Message-ID: On Tue, Jul 17, 2012 at 7:34 PM, wrote: > It's so fundamental to most GUIs that single-click > and double-click allow one to do different things with the same object Kinda yes, kinda no. Most GUIs and GUI recommendations would either enforce or strongly suggest that the double-click action incorporate the click action; for instance, click to select, double-click to open. The series of events usually goes: Mouse down Mouse up Click Mouse down Mouse up Double-click They're fired as things happen and in that order. (Some systems insert another Click just before the Double-click, but that's generally unhelpful.) Please code your application so that this isn't a problem to it, because anything else causes untold confusion to the users. ChrisA From python at mrabarnett.plus.com Tue Jul 17 13:43:02 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 17 Jul 2012 18:43:02 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> Message-ID: <5005A426.6020906@mrabarnett.plus.com> On 17/07/2012 18:24, Terry Reedy wrote: > On 7/17/2012 8:01 AM, Lipska the Kat wrote: >> On 17/07/12 09:45, Lipska the Kat wrote: >>> Pythoners >>> >>> Python 2.7.3 >>> Ubuntu Linux 12.04 LTS >>> >>> I've been taking a brief look at Python. >>> >> >> snip >> >> Well I've set myself a task. >> I have a text file containing a list of stock items >> each line contains the number in stock followed by a tab followed by the >> name of the item. I need to implement something that reads in the text >> file and outputs the stock list in ascending or descending order of >> quantity. > > Nice problem. Easy but non-trivial. > >> Please note I am NOT asking for solutions. > > Ok. With some inefficient redundancy, I believe it could be done in one > line in Python. Better code would take a few more. > >> In bash this is laughably trivial >> >> sort -nr $1 | head -${2:-10} > > Won't sort work alphabetically and leave the following as is? > > 1\talpha > 11\tbeta > 2\tgamma > The commandline options are "-nr". "n" means compare numerically and "r" means reverse order. From ramit.prasad at jpmorgan.com Tue Jul 17 13:49:35 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 17 Jul 2012 17:49:35 +0000 Subject: assertraises behaviour In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> > > import unittest > > > > class TestWithRaises(unittest.TestCase): > > def test_first(self): > > assert False > > > > def test_second(self): > > print("also called") > > assert True > > > > if __name__ == '__main__': > > unittest.main() > > > > in this case also the second test is run even if the first fails.. > > The reason for that is that the unit testing framework catches and > handles the error. It calls both test functions in some unspecified > order and logs the result. Calls to two separate test functions are > thereby separated from each other. This is intentionally so, but I think > you can also give the unit testing framework a flag that makes it abort > after the first error. In no way will the exception escape from the > unittest.main() call though, it is all caught and handled inside, also > by intention. > > > > But that's probably easy because we just need to catch exceptions for > > every method call, so it's not exactly the same thing.. > > I don't understand what you want to say here. I also don't understand > what your problem in general is. I guess there are some expectations > which are not satisfied, but you haven't explained those explicitly yet. > I think Andrea wants to do the same thing but with nose and not unittest. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python.list at tim.thechases.com Tue Jul 17 13:51:39 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Jul 2012 12:51:39 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5005A103.9050802@stoneleaf.us> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: <5005A62B.6080704@tim.thechases.com> On 07/17/12 12:29, Ethan Furman wrote: > Terry Reedy wrote: >> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >> >>> Well 'type-bondage' is a strange way of thinking about compile time type >>> checking and making code easier to read (and therefor debug >> >> 'type-bondage' is the requirement to restrict function inputs and output >> to one declared type, where the type declaration mechanisms are usually >> quite limited. >> >> >>> def max(a, b): >> if a <= b: return a >> return b > > > Surely you meant 'if a >= b: . . .' > > No worries, I'm sure your unittests would have caught it. ;) Or he could have meant "min" instead of "max". Or he could have returned the wrong values: def max(a, b): if a <= b: return b return a :-) -tkc From python.list at tim.thechases.com Tue Jul 17 13:56:14 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Jul 2012 12:56:14 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> Message-ID: <5005A73E.5070606@tim.thechases.com> On 07/17/12 12:24, Terry Reedy wrote: > On 7/17/2012 8:01 AM, Lipska the Kat wrote: >> In bash this is laughably trivial >> >> sort -nr $1 | head -${2:-10} > > Won't sort work alphabetically and leave the following as is? > > 1\talpha > 11\tbeta > 2\tgamma Only if Lipska had omitted the "-n" which tells sort to treat numbers like numbers. For Lipska, you'd want to look into the "csv" module for parsing the file easily (specifying '\t' as the delimiter). You can then sort and crop as-is, or you can use heapq.nsmallest() -tkc From bahamutzero8825 at gmail.com Tue Jul 17 13:57:16 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 17 Jul 2012 12:57:16 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <500573A4.2090306@gmail.com> Message-ID: <5005A77C.9010601@gmail.com> On 7/17/2012 12:30 PM, Terry Reedy wrote: > (In some ways, it is already better than 3.2.3.) I certainly make heavy use of some of the new features. I'm not sure we can have enough separate exceptions for OS errors without exhausting every possibility and I might start looking for excuses to use the lzma module. :P -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From tjreedy at udel.edu Tue Jul 17 13:57:19 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Jul 2012 13:57:19 -0400 Subject: Implicit conversion to boolean in if and while statements In-Reply-To: <500520FF.3010305@gmail.com> References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> <500520FF.3010305@gmail.com> Message-ID: On 7/17/2012 4:23 AM, Andrew Berg wrote: > On 7/17/2012 2:08 AM, Steven D'Aprano wrote: >> The default behaviour is that every object is something, hence true-like, >> unless explicitly coded to be treated as false-like. Since both loggers >> and functions are objects, they are true-like unless the default is >> overridden. > I am aware of the default behavior, but the reason for it still eludes me. Ultimately, because Guido's intuition said that the current behavior is the best. I happen to agree on this one. Quoting from elsewhere: > If it truly is about something vs. nothing, why is a NameError (or > AttributeError) raised when testing with an undefined variable? Python does not have 'undefined variable' objects in the way that some other languages do. There is nothing to test 'with'. 'if undefined_name:' raises NameError because all uses of undefined_names other that assignments do. The actually execution order is expression first, then if. You can explicitly test "'some_name' in namespace" or "hasattr(obj, 'somename') by turning the possibly undefined name into a string object. -- Terry Jan Reedy From rosuav at gmail.com Tue Jul 17 14:01:02 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 18 Jul 2012 04:01:02 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On Wed, Jul 18, 2012 at 12:23 AM, Lipska the Kat wrote: > Well 'type-bondage' is a strange way of thinking about compile time type > checking and making code easier to read (and therefor debug) but > I'm not about to get into some religious war about declaring a variables > type. There are options for that, but they aren't Python. (I'd like to see a "from __future__ import variable_declarations", but it doesn't seem to work. Yet.) If you're interested, I could tell you about a language that has a lot of what you're looking for (including polymorphism and even the ability to declare a variable that can contain "non-negative integer" as a type), but it's off-topic for the forum. However, I can't email you, as lipskathekat.com doesn't seem to exist... Email me privately if you're interested, we can continue the discussion off-list. ChrisA From breamoreboy at yahoo.co.uk Tue Jul 17 14:03:19 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 19:03:19 +0100 Subject: assertraises behaviour In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> Message-ID: On 17/07/2012 18:49, Prasad, Ramit wrote: >>> import unittest >>> >>> class TestWithRaises(unittest.TestCase): >>> def test_first(self): >>> assert False >>> >>> def test_second(self): >>> print("also called") >>> assert True >>> >>> if __name__ == '__main__': >>> unittest.main() >>> >>> in this case also the second test is run even if the first fails.. >> >> The reason for that is that the unit testing framework catches and >> handles the error. It calls both test functions in some unspecified >> order and logs the result. Calls to two separate test functions are >> thereby separated from each other. This is intentionally so, but I think >> you can also give the unit testing framework a flag that makes it abort >> after the first error. In no way will the exception escape from the >> unittest.main() call though, it is all caught and handled inside, also >> by intention. >> >> >>> But that's probably easy because we just need to catch exceptions for >>> every method call, so it's not exactly the same thing.. >> >> I don't understand what you want to say here. I also don't understand >> what your problem in general is. I guess there are some expectations >> which are not satisfied, but you haven't explained those explicitly yet. >> > > I think Andrea wants to do the same thing but with nose and not > unittest. > > Ramit > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > Do what? Like Ulrich Eckhart I simply don't understand what she's getting at. Perhaps it's a problem with Englsh being a second language issue rather than Python itself. Thankfully I'm sure that everything will come out in the wash. -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Jul 17 14:18:21 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 19:18:21 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5005A103.9050802@stoneleaf.us> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: On 17/07/2012 18:29, Ethan Furman wrote: > Terry Reedy wrote: >> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >> >>> Well 'type-bondage' is a strange way of thinking about compile time type >>> checking and making code easier to read (and therefor debug >> >> 'type-bondage' is the requirement to restrict function inputs and >> output to one declared type, where the type declaration mechanisms are >> usually quite limited. >> >> >>> def max(a, b): >> if a <= b: return a >> return b > > > Surely you meant 'if a >= b: . . .' > > No worries, I'm sure your unittests would have caught it. ;) > > ~Ethan~ Wouldn't the compiler have caught it before the unittests? :-) -- Cheers. Mark Lawrence. From lipska at lipskathekat.com Tue Jul 17 14:21:43 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 19:21:43 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> Message-ID: On 17/07/12 18:24, Terry Reedy wrote: > On 7/17/2012 8:01 AM, Lipska the Kat wrote: >> On 17/07/12 09:45, Lipska the Kat wrote: >>> Pythoners >>> >>> Python 2.7.3 >>> Ubuntu Linux 12.04 LTS >>> >>> I've been taking a brief look at Python. >>> >> >> snip > >> >> Well I've set myself a task. >> I have a text file containing a list of stock items >> each line contains the number in stock followed by a tab followed by the >> name of the item. I need to implement something that reads in the text >> file and outputs the stock list in ascending or descending order of >> quantity. snip > >> In bash this is laughably trivial >> >> sort -nr $1 | head -${2:-10} > > Won't sort work alphabetically and leave the following as is? > > 1\talpha > 11\tbeta > 2\tgamma The -n option tells sort to interpret the first word on a line as a number r means sort in descending order. It works fine. I also added another feature not in the specification that allows the input of a number of lines to print ... well on the way to being bloatware I guess ;-) Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From lipska at lipskathekat.com Tue Jul 17 14:36:00 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 19:36:00 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: On 17/07/12 19:18, Mark Lawrence wrote: > On 17/07/2012 18:29, Ethan Furman wrote: >> Terry Reedy wrote: >>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>> >>>> Well 'type-bondage' is a strange way of thinking about compile time >>>> type >>>> checking and making code easier to read (and therefor debug >>> >>> 'type-bondage' is the requirement to restrict function inputs and >>> output to one declared type, where the type declaration mechanisms are >>> usually quite limited. >>> >>> >>> def max(a, b): >>> if a <= b: return a >>> return b >> >> >> Surely you meant 'if a >= b: . . .' >> >> No worries, I'm sure your unittests would have caught it. ;) >> >> ~Ethan~ > > Wouldn't the compiler have caught it before the unittests? :-) > Not unless the compiler could read your mind! The syntax looks fine it's the semantics that are suspect. Wrong is a word that I try not to use as it tends to upset people, let's call them "differently right" ;-) BTW having more than one return statement in a block is a little thing I know but it drives me nuts ... another "Pythonic" thing I'll have to get used to I suppose. -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From tjreedy at udel.edu Tue Jul 17 14:39:12 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Jul 2012 14:39:12 -0400 Subject: assertraises behaviour In-Reply-To: References: Message-ID: On 7/17/2012 5:06 AM, andrea crotti wrote: > Well this is what I meant: > > import unittest > > class TestWithRaises(unittest.TestCase): > def test_first(self): > assert False > > def test_second(self): > print("also called") > assert True > > if __name__ == '__main__': > unittest.main() > > in this case also the second test is run even if the first fails. Or test_first is run even if test_second fails. The point is that unittest runs separate test methods independently. They could theoretically be run simultaneously. Tests within a method are dependent unless you take steps to make them independent by not having them raise exceptions or by catching exception as you go until you are done. If you make a error_list of problems as you go, you could end the method with assertFalse(error_list). -- Terry Jan Reedy From ethan at stoneleaf.us Tue Jul 17 14:43:57 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 11:43:57 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: <5005B26D.1080704@stoneleaf.us> Mark Lawrence wrote: > On 17/07/2012 18:29, Ethan Furman wrote: >> Terry Reedy wrote: >>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>> >>>> Well 'type-bondage' is a strange way of thinking about compile time >>>> type >>>> checking and making code easier to read (and therefor debug >>> >>> 'type-bondage' is the requirement to restrict function inputs and >>> output to one declared type, where the type declaration mechanisms are >>> usually quite limited. >>> >>> >>> def max(a, b): >>> if a <= b: return a >>> return b >> >> >> Surely you meant 'if a >= b: . . .' >> >> No worries, I'm sure your unittests would have caught it. ;) >> >> ~Ethan~ > > Wouldn't the compiler have caught it before the unittests? :-) Silly me, the word processor would have caught it! ~Ethan~ From hobson42 at gmail.com Tue Jul 17 14:59:09 2012 From: hobson42 at gmail.com (Ian) Date: Tue, 17 Jul 2012 19:59:09 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5005B26D.1080704@stoneleaf.us> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5005B26D.1080704@stoneleaf.us> Message-ID: <5005B5FD.4060906@gmail.com> On 17/07/2012 19:43, Ethan Furman wrote: > Mark Lawrence wrote: >> On 17/07/2012 18:29, Ethan Furman wrote: >>> Terry Reedy wrote: >>>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>>> >>>>> Well 'type-bondage' is a strange way of thinking about compile >>>>> time type >>>>> checking and making code easier to read (and therefor debug >>>> >>>> 'type-bondage' is the requirement to restrict function inputs and >>>> output to one declared type, where the type declaration mechanisms are >>>> usually quite limited. >>>> >>>> >>> def max(a, b): >>>> if a <= b: return a >>>> return b >>> >>> >>> Surely you meant 'if a >= b: . . .' >>> >>> No worries, I'm sure your unittests would have caught it. ;) >>> >>> ~Ethan~ >> >> Wouldn't the compiler have caught it before the unittests? :-) > > Silly me, the word processor would have caught it! > > ~Ethan~ No compiler can find as many faults as publishing your code on a mailing list!!! :) Ian From jeanpierreda at gmail.com Tue Jul 17 15:05:26 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 17 Jul 2012 15:05:26 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On Tue, Jul 17, 2012 at 1:07 PM, Terry Reedy wrote: > 'type-bondage' is the requirement to restrict function inputs and output to > one declared type, where the type declaration mechanisms are usually quite > limited. This is interesting, I hadn't expected that sort of definition. So Haskell is not a type-bondage language? (i.e. it lets you write functions that accept any type via parametric polymorphism, or any type that supports an interface via type classes). > How easy was it to write max, or a universal sort in Java? You write obj.compareTo(other) < 0 instead of using obj < other, and your methods only work on objects (that support the comparable interface). Otherwise, no different than Python, I guess. Would Java not be a type-bondage language if everything was an object? -- Devin From lipska at lipskathekat.com Tue Jul 17 15:29:36 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 20:29:36 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <4YudnY5tG-6-IJjNnZ2dnUVZ8gidnZ2d@bt.com> On 17/07/12 18:07, Terry Reedy wrote: > On 7/17/2012 10:23 AM, Lipska the Kat wrote: > >> Well 'type-bondage' is a strange way of thinking about compile time type >> checking and making code easier to read (and therefor debug > snip > > How easy was it to write max, or a universal sort in Java? > Well java.lang.Math.max() (or min() depending on what you want) might do it and as for sorting ... java.utils.Collections.sort will sort anything that implements the java.util.Comparable interface. All the standard numerical classes implement Comparable by default so there is nothing to do really. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From breamoreboy at yahoo.co.uk Tue Jul 17 15:33:24 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 20:33:24 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5005B26D.1080704@stoneleaf.us> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5005B26D.1080704@stoneleaf.us> Message-ID: On 17/07/2012 19:43, Ethan Furman wrote: > Mark Lawrence wrote: >> On 17/07/2012 18:29, Ethan Furman wrote: >>> Terry Reedy wrote: >>>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>>> >>>>> Well 'type-bondage' is a strange way of thinking about compile time >>>>> type >>>>> checking and making code easier to read (and therefor debug >>>> >>>> 'type-bondage' is the requirement to restrict function inputs and >>>> output to one declared type, where the type declaration mechanisms are >>>> usually quite limited. >>>> >>>> >>> def max(a, b): >>>> if a <= b: return a >>>> return b >>> >>> >>> Surely you meant 'if a >= b: . . .' >>> >>> No worries, I'm sure your unittests would have caught it. ;) >>> >>> ~Ethan~ >> >> Wouldn't the compiler have caught it before the unittests? :-) > > Silly me, the word processor would have caught it! > > ~Ethan~ +1 laugh of the week -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Jul 17 15:39:53 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 17 Jul 2012 20:39:53 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <4YudnY5tG-6-IJjNnZ2dnUVZ8gidnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <4YudnY5tG-6-IJjNnZ2dnUVZ8gidnZ2d@bt.com> Message-ID: On 17/07/2012 20:29, Lipska the Kat wrote: > On 17/07/12 18:07, Terry Reedy wrote: >> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >> >>> Well 'type-bondage' is a strange way of thinking about compile time type >>> checking and making code easier to read (and therefor debug >> > > snip > >> >> How easy was it to write max, or a universal sort in Java? >> > Well java.lang.Math.max() (or min() depending on what you want) might do > it and as for sorting ... java.utils.Collections.sort will sort anything > that implements the java.util.Comparable interface. All the standard > numerical classes implement Comparable by default so there is nothing to > do really. > > Lipska > I would like to spend more time on this thread, but unfortunately the 44 ton artic carrying "Java in a Nutshell Volume 1 Part 1 Chapter 1 Paragraph 1 Sentence 1" has just arrived outside my abode and needs unloading :-) -- Cheers. Mark Lawrence. From lipska at lipskathekat.com Tue Jul 17 15:52:20 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Tue, 17 Jul 2012 20:52:20 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <4YudnY5tG-6-IJjNnZ2dnUVZ8gidnZ2d@bt.com> Message-ID: On 17/07/12 20:39, Mark Lawrence wrote: > On 17/07/2012 20:29, Lipska the Kat wrote: >> On 17/07/12 18:07, Terry Reedy wrote: >>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>> snip >>> How easy was it to write max, or a universal sort in Java? >>> >> Well java.lang.Math.max() (or min() depending on what you want) might do >> it and as for sorting ... java.utils.Collections.sort will sort anything >> that implements the java.util.Comparable interface. All the standard >> numerical classes implement Comparable by default so there is nothing to >> do really. >> >> Lipska >> > > I would like to spend more time on this thread, but unfortunately the 44 > ton artic carrying "Java in a Nutshell Volume 1 Part 1 Chapter 1 > Paragraph 1 Sentence 1" has just arrived outside my abode and needs > unloading :-) :-))))))) LOL (and I did) but the pay is FANTASTIC, particularly if you 'get' OO. -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From nad at acm.org Tue Jul 17 17:02:00 2012 From: nad at acm.org (Ned Deily) Date: Tue, 17 Jul 2012 14:02:00 -0700 Subject: Python 2.6 on Mac 10.7 doesn't work References: <3b73f4f4-dc36-4b16-a3c3-66b52ef95654@googlegroups.com> <5005927a$0$6949$e4fe514c@news2.news.xs4all.nl> Message-ID: In article <5005927a$0$6949$e4fe514c at news2.news.xs4all.nl>, Hans Mulder wrote: > On 17/07/12 15:47:05, Naser Nikandish wrote: > > I am trying to install Python 2.6 on Mac OS Lion. Here is what I did: > > > > 1- Download Mac Installer disk image (2.6) (sig) from > > http://www.python.org/getit/releases/2.6/ > > > > 2- Install it > > > > 3- Run Python Luncher, go to Python Luncher preferences, and change the > > interpreter to > > Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw > > > > Now that I want to open IDLE and open my old projects, it doesn't run! > > Is there anything that I am missing? > > You may be missing a leading slash. The path to pythonw is > /Library/Frameworks/Python.framework/Versions/2.6/bin/pythonw Also keep in mind that Python 2.6 has been moved to security-fix-only mode which, among other things, means that new binary installers for OS X are not being made. The most recent OS X binary installer was 2.6.6. The system Python in OS X 10.7 Lion is 2.6.7. There has been one additional security fix release for 2.6 (2.6.8) since then. If you need Python 2, you really should consider moving to Python 2.7, which is already at 2.7.3 and is fully maintained. (The most recent Python 3 release is 3.2.3, also fully maintained.) -- Ned Deily, nad at acm.org From ramit.prasad at jpmorgan.com Tue Jul 17 17:04:57 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 17 Jul 2012 21:04:57 +0000 Subject: assertraises behaviour In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741657ACAE@SCACMX008.exchad.jpmchase.net> > On 17/07/2012 18:49, Prasad, Ramit wrote: > >>> import unittest > >>> > >>> class TestWithRaises(unittest.TestCase): > >>> def test_first(self): > >>> assert False > >>> > >>> def test_second(self): > >>> print("also called") > >>> assert True > >>> > >>> if __name__ == '__main__': > >>> unittest.main() > >>> > >>> in this case also the second test is run even if the first fails.. > >> > >> The reason for that is that the unit testing framework catches and > >> handles the error. It calls both test functions in some unspecified > >> order and logs the result. Calls to two separate test functions are > >> thereby separated from each other. This is intentionally so, but I think > >> you can also give the unit testing framework a flag that makes it abort > >> after the first error. In no way will the exception escape from the > >> unittest.main() call though, it is all caught and handled inside, also > >> by intention. > >> > >> > >>> But that's probably easy because we just need to catch exceptions for > >>> every method call, so it's not exactly the same thing.. > >> > >> I don't understand what you want to say here. I also don't understand > >> what your problem in general is. I guess there are some expectations > >> which are not satisfied, but you haven't explained those explicitly yet. > >> > > > > I think Andrea wants to do the same thing but with nose and not > > unittest. > > > > Ramit > > > > Do what? Like Ulrich Eckhart I simply don't understand what she's > getting at. Perhaps it's a problem with Englsh being a second language > issue rather than Python itself. Thankfully I'm sure that everything > will come out in the wash. > > -- > Cheers. > > Mark Lawrence. I get the impression that nose stops running tests once any test fails instead of running all tests and listing all the tests and their pass/fail status (like unittest). Granted that is just what I get from the context as I read it as I have no knowledge of nose. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From panisson at di.unito.it Tue Jul 17 17:44:27 2012 From: panisson at di.unito.it (=?ISO-8859-1?Q?Andr=E9_Panisson?=) Date: Tue, 17 Jul 2012 23:44:27 +0200 Subject: multiprocessing: apply_async with different callbacks Message-ID: <5005DCBB.4080205@di.unito.it> Hi all, I'm having a strange behavior when executing the following script: --------------------------- import multiprocessing def f(i): return i p = multiprocessing.Pool() for i in range(20): def c(r): print r, i p.apply_async(f, (i,) , callback=c) p.close() p.join() --------------------------- Result: 0 6 1 11 2 13 3 15 4 15 5 19 etc.... It seems that the callbacks of all submitted tasks are being overridden with the last callback submitted by apply_async. Is this the right behaviour or I am stumbling in some issue? I'm using Python 2.7.3 @ Ubuntu 12.04 Regards, Andr? -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3878 bytes Desc: S/MIME Cryptographic Signature URL: From johnpote at jptechnical.co.uk Tue Jul 17 18:56:30 2012 From: johnpote at jptechnical.co.uk (John Pote) Date: Tue, 17 Jul 2012 23:56:30 +0100 Subject: help needed with subprocess, pipes and parameters In-Reply-To: References: Message-ID: nuffi, Have you tried running your piped commands c:\Programs\bob\bob.exe -x -y "C:\text\path\to some\file.txt" | c:\Programs\kate\kate.exe -A 2 --dc "Print Media Is Dead" --da "Author" --dt "Title" --hf "Times" --bb "14" --aa "" --font "Ariel" - "C:\rtf\path\to some\file.rtf" in a single instance of subprocess? Start it up and use the poll method to wait until the subprocess has terminated. Then open the output file to get the results. My recent (and single, hence limited, experience) of using subprocess indicated that the spawned process may take a little time to start up. Try bob = subprocess.Popen([bobPath, '-x', '-y', docpath], stdout = subprocess.PIPE,) time.sleep( 0.5 ) #experiment with the delay kate = subprocess.Popen([katePath, A, dc, da, dt, hf, fn, bb, path], stdin = bob.stdout, stdout = subprocess.PIPE,) Never looked under the subprocess hood but maybe there's a race condition with the kate subprocess starting before the bob subprocess has set up its stdout. It's unlikely but so easy to check with a sleep between the subprocesses it has to be worth a go. John On 13/07/2012 08:34, nuffi wrote: > > If I copy and paste the following command into a command window, it does what I need. > > c:\Programs\bob\bob.exe -x -y "C:\text\path\to some\file.txt" | c:\Programs\kate\kate.exe -A 2 --dc "Print Media Is Dead" --da "Author" --dt "Title" --hf "Times" --bb "14" --aa "" --font "Ariel" - "C:\rtf\path\to some\file.rtf" > > My mission is to recreate this command within a python script, so that I can pass a bunch of different parameters into it, and use it as a batch over a bunch of different papers. > > http://docs.python.org/library/subprocess.html seems to be the thing to use in python 2.7.3. I also checked out http://www.doughellmann.com/PyMOTW/subprocess/. > > My attempts run fine, create destination folders ok and prints done but don't actually seem to process the file. Is there some way to get subprocess to output the command it's generating so I can see what I'm doing wrong, rather than just the output of the command? > > How can I chekc that kate's opening the pipe left from bob? Bob may take some time to execute, will that matter? > > > The code I came up with looks like this: > > import os, glob, subprocess > > sourceDir = "c:\\text\\" > destDir = "c:\\rtf\\" > bobPath = "C:\\Programs\\bob\\bob.exe" > katePath = "C:\\Programs\\kate\\kate.exe" > > def get_new_path(doc): > blah = doc.replace(sourceDir, destDir) > if not os.path.isdir(blah): > os.makedirs(blah) > rtf = blah.replace('.txt', '.rtf') > pathString = '- "' + (os.path.join(rtf)) + '"' > return(pathString) > > > def convert_doc(doc): > dc = '--dc "Print Media Is Dead"' > da = '--da "Author"' > dt = '--dt "Title"' > hf = '--hf "Times"' > fn = '--font "Ariel"' > bb = '--bb "14"' > docpath = '"' + (os.path.join(doc)) + '"' > path = get_new_path(doc) > A = '-A 2' > bob = subprocess.Popen([bobPath, '-x', '-y', docpath], stdout = subprocess.PIPE,) > kate = subprocess.Popen([katePath, A, dc, da, dt, hf, fn, bb, path], stdin = bob.stdout, stdout = subprocess.PIPE,) > end_of_pipe = kate.stdout > #print kate > #subprocess.call(['echo', "Test peice of text", '>', 'D:\\output.txt']) > for line in end_of_pipe: > print '\t', blah.strip() > #raw_input() > return('done') > > > test = convert_doc("c:\\text\\path to\\some\\specific text file.txt") > print(blah) > > > == > > Thanks for looking :-) > --- Posted via news://freenews.netfront.net/ - Complaints to news at netfront.net --- From ethan at stoneleaf.us Tue Jul 17 18:57:04 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 15:57:04 -0700 Subject: Foxpro goto command and deleted records Message-ID: <5005EDC0.6050608@stoneleaf.us> In Foxpro if you do a GOTO 7 with deleted off and record 7 is deleted, the record pointer doesn't move (at least in version 6). I don't like that. I see four other options: 0) don't move the pointer (listed for completeness) 1) go to that record anyway 2) go to the next undeleted record 3) go to the seventh undeleted record (possibly the least practical) 4) raise an exception Any opinions? ~Ethan~ From panisson at di.unito.it Tue Jul 17 19:17:20 2012 From: panisson at di.unito.it (=?ISO-8859-1?Q?Andr=E9_Panisson?=) Date: Wed, 18 Jul 2012 01:17:20 +0200 Subject: multiprocessing: apply_async with different callbacks In-Reply-To: <5005DCBB.4080205@di.unito.it> References: <5005DCBB.4080205@di.unito.it> Message-ID: <5005F280.1060609@di.unito.it> On 07/17/2012 11:44 PM, Andr? Panisson wrote: > Hi all, > > I'm having a strange behavior when executing the following script: > --------------------------- > import multiprocessing > > def f(i): > return i > > p = multiprocessing.Pool() > for i in range(20): > def c(r): > print r, i > p.apply_async(f, (i,) , callback=c) > p.close() > p.join() > --------------------------- > > Result: > 0 6 > 1 11 > 2 13 > 3 15 > 4 15 > 5 19 > etc.... > > It seems that the callbacks of all submitted tasks are being > overridden with the last callback submitted by apply_async. > Is this the right behaviour or I am stumbling in some issue? I'm using > Python 2.7.3 @ Ubuntu 12.04 > > Regards, Sorry for taking the time, I just found the solution: ------------------- import multiprocessing def f(i): return i def cfactory(i): def c(r): print r, i return c p = multiprocessing.Pool() for i in range(20): p.apply_async(f, (i,) , callback=cfactory(i)) p.close() p.join() ------------------ Regards, Andr? -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3878 bytes Desc: S/MIME Cryptographic Signature URL: From andrea.crotti.0 at gmail.com Tue Jul 17 19:31:24 2012 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Wed, 18 Jul 2012 00:31:24 +0100 Subject: assertraises behaviour In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF4741657AA3F@SCACMX008.exchad.jpmchase.net> Message-ID: <5005F5CC.4010902@gmail.com> To clarify my "problem", I just thought that assertRaises if used as context manager should behave as following: - keep going if the exception declared is raised - re-raise an error even if catched after the declared exception was catched I was also confused by the doc a bit: "Test that an exception is raised when /callable/ is called with any positional or keyword arguments that are also passed to assertRaises() . The test passes if /exception/ is raised, is an error if another exception is raised, or fails if no exception is raised" which speaks about when it's not used as a context manager.. I understand why it's not possible and it's not a big issue though.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Jul 17 19:50:20 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 17 Jul 2012 17:50:20 -0600 Subject: Foxpro goto command and deleted records In-Reply-To: <5005EDC0.6050608@stoneleaf.us> References: <5005EDC0.6050608@stoneleaf.us> Message-ID: On Tue, Jul 17, 2012 at 4:57 PM, Ethan Furman wrote: > In Foxpro if you do a > > GOTO 7 > > with deleted off and record 7 is deleted, the record pointer doesn't > move (at least in version 6). > > I don't like that. > > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > Any opinions? Relevance to Python? From python at mrabarnett.plus.com Tue Jul 17 20:01:36 2012 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jul 2012 01:01:36 +0100 Subject: Foxpro goto command and deleted records In-Reply-To: <5005EDC0.6050608@stoneleaf.us> References: <5005EDC0.6050608@stoneleaf.us> Message-ID: <5005FCE0.5020204@mrabarnett.plus.com> On 17/07/2012 23:57, Ethan Furman wrote: > In Foxpro if you do a > > GOTO 7 > > with deleted off and record 7 is deleted, the record pointer doesn't > move (at least in version 6). > > I don't like that. > > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > Any opinions? > What happens when you 'delete' a record? Does it disappear immediately, or is it merely marked for deletion? If it is marked for deletion, can it be unmarked? Will a marked record be removed when the file is closed, or does the file need to be explicitly purged/compacted? If it is merely marked, then I think the best option is 1, or possibly 4 if the file is compacted when closed. From amc96 at cam.ac.uk Tue Jul 17 20:46:31 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Wed, 18 Jul 2012 01:46:31 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: On 17/07/2012 19:36, Lipska the Kat wrote: > On 17/07/12 19:18, Mark Lawrence wrote: >> On 17/07/2012 18:29, Ethan Furman wrote: >>> Terry Reedy wrote: >>>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>>> >>>>> Well 'type-bondage' is a strange way of thinking about compile time >>>>> type >>>>> checking and making code easier to read (and therefor debug >>>> >>>> 'type-bondage' is the requirement to restrict function inputs and >>>> output to one declared type, where the type declaration mechanisms are >>>> usually quite limited. >>>> >>>> >>> def max(a, b): >>>> if a <= b: return a >>>> return b >>> >>> >>> Surely you meant 'if a >= b: . . .' >>> >>> No worries, I'm sure your unittests would have caught it. ;) >>> >>> ~Ethan~ >> >> Wouldn't the compiler have caught it before the unittests? :-) >> > > Not unless the compiler could read your mind! > The syntax looks fine it's the semantics that are suspect. Wrong is a > word that I try not to use as it tends to upset people, let's call them > "differently right" ;-) > > BTW having more than one return statement in a block is a little thing I > know but it drives me nuts ... another "Pythonic" thing I'll have to get > used to I suppose. > Its not a pythonic thing. Its a common and very acceptable paradigm. Mainly, it avoids complicated breaks from nested control structures, and especially the 'style' of maintaining one boolean value called "should_continue" or something equally silly. My daily work involves C, x86 assembly, reading x86/PCI/ACPI/etc specifications and cursing violently at some of the stupidity, Python, Bash and C++, and this is one of the few styles which remains fairly constant throughout. Take for example a Linux system call handler. The general form looks a little like (substituting C for python style pseudocode) if not (you are permitted to do this): return -EPERM if not (you've given me some valid data): return -EFAULT if not (you've given me some sensible data): return -EINVAL return actually_try_to_do_something_with(data) How would you program this sort of logic with a single return statement? This is very common logic for all routines for which there is even the remotest possibility that some data has come from an untrusted source. ~Andrew P.S. like the sig. From wuwei23 at gmail.com Tue Jul 17 21:35:09 2012 From: wuwei23 at gmail.com (alex23) Date: Tue, 17 Jul 2012 18:35:09 -0700 (PDT) Subject: Implicit conversion to boolean in if and while statements References: <5002a1f9$0$29995$c3e8da3$5496439d@news.astraweb.com> <50037eab$0$29995$c3e8da3$5496439d@news.astraweb.com> <50047A84.6020208@gmail.com> <5004b543$0$29978$c3e8da3$5496439d@news.astraweb.com> <5004ec84$0$11116$c3e8da3@news.astraweb.com> <50050f70$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <21fcdb92-20e3-428b-b06b-057065a4ab25@oo8g2000pbc.googlegroups.com> On Jul 17, 6:23?pm, Andrew Berg wrote: > On 7/17/2012 2:08 AM, Steven D'Aprano wrote: > > The default behaviour is that every object is something, hence true-like, > > unless explicitly coded to be treated as false-like. Since both loggers > > and functions are objects, they are true-like unless the default is > > overridden. > > I am aware of the default behavior, but the reason for it still eludes me. Because it makes it simple to distinguish between having an object and not having one without having to explicitly test for it each time. db = connect("my:db") # or None if the connection failed if db: I find that usage to be incredibly intuitive. From mmdionisio1993 at yahoo.com.ph Tue Jul 17 21:44:58 2012 From: mmdionisio1993 at yahoo.com.ph (Maria Hanna Carmela Dionisio) Date: Wed, 18 Jul 2012 09:44:58 +0800 (SGT) Subject: my email In-Reply-To: References: Message-ID: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> mmdionisio1993 at yahoo.com.ph Just a newbhie here :> ________________________________ From: "python-list-request at python.org" To: mmdionisio1993 at yahoo.com.ph Sent: Saturday, July 7, 2012 7:41 PM Subject: Welcome to the "Python-list" mailing list Welcome to the Python-list at python.org mailing list! The purpose of this mailing list is to support general discussions about the Python programming language.? Please remember that this list is mirrored to the Usenet newsgroup comp.lang.python. For more information on the Python programming language see <http://www.python.org/> To post to this list, send your email to: ? python-list at python.org General information about the mailing list is at: ? http://mail.python.org/mailman/listinfo/python-list If you ever want to unsubscribe or change your options (eg, switch to or from digest mode, change your password, etc.), visit your subscription page at: ? http://mail.python.org/mailman/options/python-list/mmdionisio1993%40yahoo.com.ph You can also make such adjustments via email by sending a message to: ? Python-list-request at python.org with the word `help' in the subject or body (don't include the quotes), and you will get back a message with instructions. You must know your password to change your options (including changing the password, itself) or to unsubscribe.? It is: ? sweet103093 Normally, Mailman will remind you of your python.org mailing list passwords once every month, although you can disable this if you prefer.? This reminder will also include instructions on how to unsubscribe or change your account options.? There is also a button on your options page that will email your current password to you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mmdionisio1993 at yahoo.com.ph Tue Jul 17 21:58:55 2012 From: mmdionisio1993 at yahoo.com.ph (Maria Hanna Carmela Dionisio) Date: Wed, 18 Jul 2012 09:58:55 +0800 (SGT) Subject: Python Programming expert - adding user Message-ID: <1342576735.54186.YahooMailNeo@web193104.mail.sg3.yahoo.com> Im just a student :) Our prof gave as a task that we need to make a program using python (for redhat) and c++(for windows) Our objective is to make a program file and we will said it remotely to another computer via network ( its easy and i could do it lolz).. the hard part is the programming..that when the user click the file a box will prompt and ask for username and a password(even without a password) then the username that he inputted will add to the user account of his/her computer :DD HELP HELP EXPERTSSSSSSSSSSSSSS THANKS :D -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Jul 17 22:08:09 2012 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jul 2012 03:08:09 +0100 Subject: my email In-Reply-To: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> References: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> Message-ID: <50061A89.9090200@mrabarnett.plus.com> On 18/07/2012 02:44, Maria Hanna Carmela Dionisio wrote: > mmdionisio1993 at yahoo.com.ph > > Just a newbhie here :> > ...who has just revealed her password! [remainder snipped] From ethan at stoneleaf.us Tue Jul 17 22:16:27 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 19:16:27 -0700 Subject: Foxpro goto command and deleted records In-Reply-To: References: <5005EDC0.6050608@stoneleaf.us> Message-ID: <50061C7B.6050607@stoneleaf.us> Ian Kelly wrote: > On Tue, Jul 17, 2012 at 4:57 PM, Ethan Furman wrote: >> In Foxpro if you do a >> >> GOTO 7 >> >> with deleted off and record 7 is deleted, the record pointer doesn't >> move (at least in version 6). >> >> I don't like that. >> >> I see four other options: >> >> 0) don't move the pointer (listed for completeness) >> 1) go to that record anyway >> 2) go to the next undeleted record >> 3) go to the seventh undeleted record (possibly the least practical) >> 4) raise an exception >> >> Any opinions? > > Relevance to Python? I'm deciding how my python dbf module will handle this situation. http://python.org/pypi/dbf for the curious. ~Ethan~ From ethan at stoneleaf.us Tue Jul 17 22:19:26 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 19:19:26 -0700 Subject: Foxpro goto command and deleted records In-Reply-To: <5005FCE0.5020204@mrabarnett.plus.com> References: <5005EDC0.6050608@stoneleaf.us> <5005FCE0.5020204@mrabarnett.plus.com> Message-ID: <50061D2E.8080204@stoneleaf.us> MRAB wrote: > On 17/07/2012 23:57, Ethan Furman wrote: >> In Foxpro if you do a >> >> GOTO 7 >> >> with deleted off and record 7 is deleted, the record pointer doesn't >> move (at least in version 6). >> >> I don't like that. >> >> I see four other options: >> >> 0) don't move the pointer (listed for completeness) >> 1) go to that record anyway >> 2) go to the next undeleted record >> 3) go to the seventh undeleted record (possibly the least practical) >> 4) raise an exception >> >> Any opinions? >> > What happens when you 'delete' a record? Does it disappear immediately, > or is it merely marked for deletion? Marked for deletion. > If it is marked for deletion, can it be unmarked? Will a marked record > be removed when the file is closed, or does the file need to be > explicitly purged/compacted? Yes, it can be unmarked. No, the table must be explicitly packed. > If it is merely marked, then I think the best option is 1, or possibly > 4 if the file is compacted when closed. There is a use_deleted setting that controls whether deleted records are accessed or skipped. Skipping is fine when looping, not so fine when going directly to a particular record. ~Ethan~ From simoncropper at fossworkflowguides.com Tue Jul 17 22:34:33 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Wed, 18 Jul 2012 12:34:33 +1000 Subject: my email In-Reply-To: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> References: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> Message-ID: <500620B9.40100@fossworkflowguides.com> On 18/07/12 11:44, Maria Hanna Carmela Dionisio wrote: > mmdionisio1993 at yahoo.com.ph > > Just a newbhie here :> > [snip] > You must know your password to change your options (including changing > the password, itself) or to unsubscribe. It is: > > sweet103093 > I suggest you change you password now that you have told the world what it is. -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From steve+comp.lang.python at pearwood.info Tue Jul 17 22:50:25 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Jul 2012 02:50:25 GMT Subject: Style question: metaclass self vs cls? References: <50043377$0$29978$c3e8da3$5496439d@news.astraweb.com> <7566b8bc-929e-4f70-8e44-f0bda232ef85@googlegroups.com> Message-ID: <50062471$0$1542$c3e8da3$76491128@news.astraweb.com> On Tue, 17 Jul 2012 05:23:22 -0700, Michele Simionato wrote: > The standard is to use `cls`. In the __new__ method you can use `mcl` or > `meta`. Thanks to everyone who answered. I think I will stick with "meta" and "cls". -- Steven From python at mrabarnett.plus.com Tue Jul 17 22:57:33 2012 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jul 2012 03:57:33 +0100 Subject: Foxpro goto command and deleted records In-Reply-To: <50061D2E.8080204@stoneleaf.us> References: <5005EDC0.6050608@stoneleaf.us> <5005FCE0.5020204@mrabarnett.plus.com> <50061D2E.8080204@stoneleaf.us> Message-ID: <5006261D.5020609@mrabarnett.plus.com> On 18/07/2012 03:19, Ethan Furman wrote: > MRAB wrote: >> On 17/07/2012 23:57, Ethan Furman wrote: >>> In Foxpro if you do a >>> >>> GOTO 7 >>> >>> with deleted off and record 7 is deleted, the record pointer doesn't >>> move (at least in version 6). >>> >>> I don't like that. >>> >>> I see four other options: >>> >>> 0) don't move the pointer (listed for completeness) >>> 1) go to that record anyway >>> 2) go to the next undeleted record >>> 3) go to the seventh undeleted record (possibly the least practical) >>> 4) raise an exception >>> >>> Any opinions? >>> >> What happens when you 'delete' a record? Does it disappear immediately, >> or is it merely marked for deletion? > > Marked for deletion. > >> If it is marked for deletion, can it be unmarked? Will a marked record >> be removed when the file is closed, or does the file need to be >> explicitly purged/compacted? > > Yes, it can be unmarked. No, the table must be explicitly packed. > >> If it is merely marked, then I think the best option is 1, or possibly >> 4 if the file is compacted when closed. > > There is a use_deleted setting that controls whether deleted records are > accessed or skipped. Skipping is fine when looping, not so fine when > going directly to a particular record. > If use_deleted is false, does that mean that deleted records are hidden, or just that when iterating through the records the deleted ones aren't yielded? From ethan at stoneleaf.us Tue Jul 17 23:11:48 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 17 Jul 2012 20:11:48 -0700 Subject: Foxpro goto command and deleted records In-Reply-To: <5006261D.5020609@mrabarnett.plus.com> References: <5005EDC0.6050608@stoneleaf.us> <5005FCE0.5020204@mrabarnett.plus.com> <50061D2E.8080204@stoneleaf.us> <5006261D.5020609@mrabarnett.plus.com> Message-ID: <50062974.4050107@stoneleaf.us> MRAB wrote: > On 18/07/2012 03:19, Ethan Furman wrote: >> MRAB wrote: >>> On 17/07/2012 23:57, Ethan Furman wrote: >>>> In Foxpro if you do a >>>> >>>> GOTO 7 >>>> >>>> with deleted off and record 7 is deleted, the record pointer doesn't >>>> move (at least in version 6). >>>> >>>> I don't like that. >>>> >>>> I see four other options: >>>> >>>> 0) don't move the pointer (listed for completeness) >>>> 1) go to that record anyway >>>> 2) go to the next undeleted record >>>> 3) go to the seventh undeleted record (possibly the least practical) >>>> 4) raise an exception >>>> >>>> Any opinions? >>>> >>> What happens when you 'delete' a record? Does it disappear immediately, >>> or is it merely marked for deletion? >> >> Marked for deletion. >> >>> If it is marked for deletion, can it be unmarked? Will a marked record >>> be removed when the file is closed, or does the file need to be >>> explicitly purged/compacted? >> >> Yes, it can be unmarked. No, the table must be explicitly packed. >> >>> If it is merely marked, then I think the best option is 1, or possibly >>> 4 if the file is compacted when closed. >> >> There is a use_deleted setting that controls whether deleted records are >> accessed or skipped. Skipping is fine when looping, not so fine when >> going directly to a particular record. >> > If use_deleted is false, does that mean that deleted records are > hidden, or just that when iterating through the records the deleted > ones aren't yielded? Definitely the latter, but I'm starting to wonder if the former should also be the case. ~Ethan~ From gaodexiaozheng at gmail.com Tue Jul 17 23:12:14 2012 From: gaodexiaozheng at gmail.com (gaodexiaozheng at gmail.com) Date: Tue, 17 Jul 2012 20:12:14 -0700 (PDT) Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: ? 2012?7?17????UTC+8??6?02?31??Stefan Behnel??? > Matej Cepl, 17.07.2012 11:39: > > On 17/07/12 10:35, gaodexiaozheng at gmail.com wrote: > >>> &gt; I&#39;m trying to parse an xml file with jython (not through java > >>> parsers > >>> &gt; like xerces). > > > > https://code.google.com/p/jython-elementtree/ ??? > > Note that this ships with Jython 2.5. > > Stefan Got that,thanks! However,there is one project implemented by Python used PyXML and now my Jython project has to depend on it ,so I am afraid that if Jython doesn't support PyXML,then my jython project can not depend on the original Python project ,then my jython project maybe can not move on unless I find another project to take place of the original Python project. From gaodexiaozheng at gmail.com Tue Jul 17 23:12:14 2012 From: gaodexiaozheng at gmail.com (gaodexiaozheng at gmail.com) Date: Tue, 17 Jul 2012 20:12:14 -0700 (PDT) Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: ? 2012?7?17????UTC+8??6?02?31??Stefan Behnel??? > Matej Cepl, 17.07.2012 11:39: > > On 17/07/12 10:35, gaodexiaozheng at gmail.com wrote: > >>> &gt; I&#39;m trying to parse an xml file with jython (not through java > >>> parsers > >>> &gt; like xerces). > > > > https://code.google.com/p/jython-elementtree/ ??? > > Note that this ships with Jython 2.5. > > Stefan Got that,thanks! However,there is one project implemented by Python used PyXML and now my Jython project has to depend on it ,so I am afraid that if Jython doesn't support PyXML,then my jython project can not depend on the original Python project ,then my jython project maybe can not move on unless I find another project to take place of the original Python project. From rustompmody at gmail.com Tue Jul 17 23:54:06 2012 From: rustompmody at gmail.com (rusi) Date: Tue, 17 Jul 2012 20:54:06 -0700 (PDT) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: <088cf4de-2e5a-4ca8-8c56-e016cb6c692c@t1g2000pbl.googlegroups.com> On Jul 18, 5:46?am, Andrew Cooper wrote: > On 17/07/2012 19:36, Lipska the Kat wrote: > > > > > > > > > > > On 17/07/12 19:18, Mark Lawrence wrote: > >> On 17/07/2012 18:29, Ethan Furman wrote: > >>> Terry Reedy wrote: > >>>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: > > >>>>> Well 'type-bondage' is a strange way of thinking about compile time > >>>>> type > >>>>> checking and making code easier to read (and therefor debug > > >>>> 'type-bondage' is the requirement to restrict function inputs and > >>>> output to one declared type, where the type declaration mechanisms are > >>>> usually quite limited. > > >>>> >>> def max(a, b): > >>>> if a <= b: return a > >>>> return b > > >>> Surely you meant 'if a >= b: . . .' > > >>> No worries, I'm sure your unittests would have caught it. ;) > > >>> ~Ethan~ > > >> Wouldn't the compiler have caught it before the unittests? :-) > > > Not unless the compiler could read your mind! > > The syntax looks fine it's the semantics that are suspect. Wrong is a > > word that I try not to use as it tends to upset people, let's call them > > "differently right" ;-) > > > BTW having more than one return statement in a block is a little thing I > > know but it drives me nuts ... another "Pythonic" thing I'll have to get > > used to I suppose. > > Its not a pythonic thing. ?Its a common and very acceptable paradigm. > > Mainly, it avoids complicated breaks from nested control structures, and > especially the 'style' of maintaining one boolean value called > "should_continue" or something equally silly. > > My daily work involves C, x86 assembly, reading x86/PCI/ACPI/etc > specifications and cursing violently at some of the stupidity, Python, > Bash and C++, and this is one of the few styles which remains fairly > constant throughout. > > Take for example a Linux system call handler. ?The general form looks a > little like (substituting C for python style pseudocode) > > if not (you are permitted to do this): > ? ? return -EPERM > if not (you've given me some valid data): > ? ? return -EFAULT > if not (you've given me some sensible data): > ? ? return -EINVAL > return actually_try_to_do_something_with(data) > > How would you program this sort of logic with a single return statement? > ?This is very common logic for all routines for which there is even the > remotest possibility that some data has come from an untrusted source. return (-EPERM if not_permitted else -EFAULT if non_valid else -EINVAL if non_sensible else do_something) Not that I recommend *doing* this :-) [I recommend knowing about it] From kliateni at gmail.com Wed Jul 18 02:04:53 2012 From: kliateni at gmail.com (Karim) Date: Wed, 18 Jul 2012 08:04:53 +0200 Subject: my email In-Reply-To: <500620B9.40100@fossworkflowguides.com> References: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> <500620B9.40100@fossworkflowguides.com> Message-ID: <50065205.7070204@gmail.com> Le 18/07/2012 04:34, Simon Cropper a ?crit : > On 18/07/12 11:44, Maria Hanna Carmela Dionisio wrote: >> mmdionisio1993 at yahoo.com.ph >> >> Just a newbhie here :> >> > [snip] > >> You must know your password to change your options (including changing >> the password, itself) or to unsubscribe. It is: >> >> sweet103093 >> > > I suggest you change you password now that you have told the world > what it is. > ?????????????????? From orgnut at yahoo.com Wed Jul 18 03:10:47 2012 From: orgnut at yahoo.com (Larry Hudson) Date: Wed, 18 Jul 2012 00:10:47 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <69-dnRfmT7kb1pjNnZ2dnUVZ8kSdnZ2d@bt.com> References: <69-dnRfmT7kb1pjNnZ2dnUVZ8kSdnZ2d@bt.com> Message-ID: <3_-dnSE1NeHq_JvNnZ2dnUVZ_sadnZ2d@giganews.com> On 07/17/2012 04:24 AM, Lipska the Kat wrote: ... > Thanks for your time and I'll try to do a bit better with the reading thing before asking more > questions... not sure about this obsession with code indentation though :-| > I think it's inaccurate to call this indentation an obsession, it's part of Python's defined syntax. It's used INSTEAD OF punctuation or keywords (like {} or BEGIN END). If you're already used to indenting your code consistently, you'll be surprised at how quickly it becomes a non-issue when you start using Python. It's a bit dated, but you might find http://www.linuxjournal.com/article/3882 to be an interesting read. -=- Larry -=- From mcepl at redhat.com Wed Jul 18 04:09:13 2012 From: mcepl at redhat.com (Matej Cepl) Date: Wed, 18 Jul 2012 10:09:13 +0200 Subject: jython lacks working xml processing modules? In-Reply-To: References: <23891c90.0311240342.46419188@posting.google.com> Message-ID: On 18/07/12 05:12, gaodexiaozheng at gmail.com wrote: > However,there is one project implemented by Python used PyXML and now > my Jython project has to depend on it ,so I am afraid that if Jython > doesn't support PyXML,then my jython project can not depend on the > original Python project ,then my jython project maybe can not move on > unless I find another project to take place of the original Python > project. I think, if possible, such project should switch out of PyXML anyway. If you make them nice patch to port them to standard ElementTree (and as a side-effect make the project working with Jython), they will like you. I guess. Mat?j From lipska at lipskathekat.com Wed Jul 18 05:06:51 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Wed, 18 Jul 2012 10:06:51 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: On 18/07/12 01:46, Andrew Cooper wrote: > On 17/07/2012 19:36, Lipska the Kat wrote: >> On 17/07/12 19:18, Mark Lawrence wrote: >>> On 17/07/2012 18:29, Ethan Furman wrote: >>>> Terry Reedy wrote: >>>>> On 7/17/2012 10:23 AM, Lipska the Kat wrote: >>>>> snip > > Take for example a Linux system call handler. The general form looks a > little like (substituting C for python style pseudocode) > > if not (you are permitted to do this): > return -EPERM > if not (you've given me some valid data): > return -EFAULT > if not (you've given me some sensible data): > return -EINVAL > return actually_try_to_do_something_with(data) > > How would you program this sort of logic with a single return statement? > This is very common logic for all routines for which there is even the > remotest possibility that some data has come from an untrusted source. Eeek! well if you insist (type bound) someType -EPERM someType -EFAULT sometype -EINVAL someType -EDOSOMETHING //method someType checkSomething(data){ someType result = -EINVAL //or your most likely or 'safest' result if not (you are permitted to do this): result = -EPERM if not (you've given me some valid data): result = -EFAULT if not (you've given me some sensible data): result = -EINVAL else result = -EDSOMETHING return result } //cohesive, encapsulated, reusable and easy to read //later if(checkSomething(data) == EDOSOMETHING){ actually_try_to_do_something_with(data) } else{ //who knows } What do you think ? > > ~Andrew > > P.S. like the sig. thanks -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From arnodel at gmail.com Wed Jul 18 06:35:51 2012 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 18 Jul 2012 11:35:51 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> References: <3-WdnYTg0r6XyZjNnZ2dnUVZ7sidnZ2d@bt.com> Message-ID: On 17 July 2012 13:01, Lipska the Kat wrote: > Well I've set myself a task. > I have a text file containing a list of stock items > each line contains the number in stock followed by a tab followed by the > name of the item. I need to implement something that reads in the text file > and outputs the stock list in ascending or descending order of quantity. > > Please note I am NOT asking for solutions. > > In bash this is laughably trivial > sort -nr $1 | head -${2:-10} Here's a Python translation that won't help :) from sys import argv print ''.join(sorted(open(argv[1]), key=lambda l: -int(l.split('\t')[0]))[:10 if len(argv) < 3 else int(argv[2])]) Who said Python was readabl'y yours, -- Arnaud From sylvain.thenault at logilab.fr Wed Jul 18 07:49:38 2012 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Wed, 18 Jul 2012 13:49:38 +0200 Subject: [ANN] Pylint 0.25.2 / ASTNG 0.24 / logilab-common 0.58.1 released Message-ID: <20120718114938.GG2392@logilab.fr> Hi there, I've released this morning new versions of Pylint, ASTNG and logilab-common projects. For more information, read http://www.logilab.org/blogentry/100365 Enjoy! -- Sylvain Th?nault, LOGILAB, Paris (01.45.32.03.12) - Toulouse (09.54.03.55.76) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From ulrich.eckhardt at dominolaser.com Wed Jul 18 08:01:06 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Wed, 18 Jul 2012 14:01:06 +0200 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: <25lid9-q9a.ln1@satorlaser.homedns.org> Am 18.07.2012 11:06, schrieb Lipska the Kat: > On 18/07/12 01:46, Andrew Cooper wrote: >> Take for example a Linux system call handler. The general form looks a >> little like (substituting C for python style pseudocode) >> >> if not (you are permitted to do this): >> return -EPERM >> if not (you've given me some valid data): >> return -EFAULT >> if not (you've given me some sensible data): >> return -EINVAL >> return actually_try_to_do_something_with(data) >> >> How would you program this sort of logic with a single return statement? >> This is very common logic for all routines for which there is even the >> remotest possibility that some data has come from an untrusted source. > > Eeek! well if you insist (type bound) > > someType -EPERM > someType -EFAULT > sometype -EINVAL > someType -EDOSOMETHING > > //method > someType checkSomething(data){ > > someType result = -EINVAL //or your most likely or 'safest' result > > if not (you are permitted to do this): > result = -EPERM > if not (you've given me some valid data): > result = -EFAULT > if not (you've given me some sensible data): > result = -EINVAL > else > result = -EDSOMETHING > > return result > } > //cohesive, encapsulated, reusable and easy to read This is a classic discussion topic, whether single exit (SE) functions should be used or not. There are two things I consider as problematic with them: 1. In the presence of exceptions, every function has at least two possible paths that can be taken out, one returns a value (or None, in Python), the other throws an exception. For that reason, trying to achieve SE is a dangerous illusion. The syscall handler above is C, which doesn't have exceptions like Java, C++ or Python, so it doesn't suffer those two paths. 2. The biggest problem with SE functions is that you often need to skip over lots of code before you finally find out that the fault at the very beginning causes nothing else to happen inside the function before it is finally returned to the caller. A typical symptom is deeply nested if-else structures. Another symptom is result variables that are checked multiple times to skip over effectively the rest of the function, which "unrolls" the nested if-else structures. Yet another symptom is a very fine granularity of microscopic functions, which is effectively a distributed nest of if-else structures. Coming back to Python, this would look like this: if not /you are permitted to do this/: raise NotPermitted("go awai!") if not /you've given me valid data/: raise TypeError("unexpected input") if not /you're given me sensible data/: raise ValueError("invalid input") # do stuff here... If you shoehorn this into an SE function (which you can't do if something in between might throw), then it probably looks like this: error = None if not /you are permitted to do this/: error = NotPermitted("go awai!") elif not /you've given me valid data/: raise TypeError("unexpected input") elif not /you're given me sensible data/: raise ValueError("invalid input") else: # do stuff here... if error: raise error else: return result > //later > > if(checkSomething(data) == EDOSOMETHING){ > > actually_try_to_do_something_with(data) > } > else{ > //who knows > } Interestingly, you suggest to divide the original function into one that verifies some conditions and one that does the actual work. Using an early return is to me like drawing a big red line inside a function by which it can be split into two sections. This makes it IMHO equally clear, even clearer since I don't have to locate and read that other function. My bioware parses this so that if the first part succeeds, the second part can be read independently thereof, which reduces the amount of info to keep in mind at a time. Also, when changing code, I don't have to locate other places where the utility function (checkSomething) is called (Python allows local functions, which can be very(!!) useful). Since the code is inline, I know that only this one function is affected. Yes, this is in direct contrast to the reusability you mentioned. Neither ease of change nor reusability are goals in and of themselves though, so this is not a black-or-white question and a compromise can be good enough. It's a question of taste, experience, phase of the moon, coffeination levels etc. :) Uli From steve+comp.lang.python at pearwood.info Wed Jul 18 08:43:23 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Jul 2012 12:43:23 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <5006af6a$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 17 Jul 2012 12:01:21 +0100, Lipska the Kat wrote: > For the past 9 years I have been developing in Java [...] > Anyway, I'm looking at Python as a rapid prototyping language. I have an > idea and just want to get it down in basic outline code as quickly as > possible before it departs my aging brain... A couple of good resources for you to read, written by a top Python developer who also knows Java backwards: http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html You will occasionally (i.e. about sixteen times a day) read some Python programmer tossing out comments like "Flat is better than nested", often in quotes. P.J. Eby does this at least twice in the first link above. What the hell are they talking about? They're talking about the Zen of Python, a list of a dozen or so slightly tongue in cheek mottoes meant to encapsulate the (often deliberately contradictory) coding philosophy that Python developers should aspire too. At the interactive Python prompt, enter "import this" (without the quotes) and be enlightened. Keeping the Zen in mind as an ideal is incredibly useful. Arguing over whose opinion is more true to the Zen is a waste of time. > I'm not used to using > variables without declaring their type ... (well I used to do Visual > Basic many years ago) It just seems so weird, Compared to Java, or Haskell, or Ada, Python may seem like an incredibly sloppy language. A lot of that sloppiness comes from the lack of compile- time type-checking. And that's probably true: Haskell's type checker can detect infinite loops, by Jove! Python won't even warn you that you're about to blow away a built-in function. (Don't worry though, you can easily get it back again.) (But at least Python isn't Perl, or PHP.) While Python doesn't (can't!) check the type of data at compile-time, but it does check the type of data at run-time. This ain't assembly language, where there's only one type, bytes! I came from a Pascal background, and at first I found the lack of type declarations rather concerning. But soon I found it liberating. Especially once I started using Python interactively, at the REPL. Most arguments about which is better, compile-time type checking or run- time type checking, miss the point: both have advantages, and disadvantages. Which is "better" depends on what you want to do. Python is deliberately designed to be *fast to write*. It gives up a little bit of safety for that. But not as much as you might think. Type errors are less frequent than other errors (errors of logic, bad data, etc.). And so in the time it might take a Java programmer to satisfy the compiler's insistence on type correctness, a Python programmer has probably written the program *and* the unittests and given the customer the first iteration of the application. At least, that's the theory. But you probably already know that. After all, that's why Python is the rapid-application-development language, not Java. > and what's this obsession > with 'correct' indentation of code ??? Nearly everyone rights correctly indented code anyway. At least, those who don't, you don't want on your project. Python just takes it one step further, and makes correctly indented code mandatory rather than optional. The plus side is, no more style wars over where the braces go, no more hunting for lost braces. The downside is, if you paste code into a dumb application (like many email clients!) that strips whitespace, your code will break. So don't do that. http://stromberg.dnsalias.org/~strombrg/significant-whitespace.html -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 18 08:58:11 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Jul 2012 12:58:11 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 17 Jul 2012 09:52:59 -0400, Roy Smith wrote: > you could write in Python: > > # Type matching will get checked at run-time > def my_function(mpf, ot): > assert isinstance(mpf, MassivelyParallelFrobinator) > assert isinstance(ot, OtherThing) Keep in mind that assertions are not guaranteed to run. Code like the above is buggy, because if Python is run under the -O (optimize) flag, assertions will be stripped out. Assertions are mostly useful for two things: 1) "This cannot possibly happen, but just in case it does..." If you've ever written something like this: if x%2 == 0: do_spam() elif x%2 == 1: do_ham() else: # This can't happen! print("something unexpected happened") sys.exit() that is better written as: if x%2 == 0: do_spam() else: assert x%2 == 1, "something unexpected happened" do_ham() 2) To check your internal reasoning in a function or method. For example: def foo(something): n = len(something) x = math.sqrt(x) # We expect that x must be less than half of n. # E.g. n=100 gives 10 < 50, which is correct. assert x < n//2 process(n, x) Run with the -O flag, the (hopefully!) redundant test will be stripped out; without the flag, the test will check your logic for you and fail if the stated condition is not met. For bonus points, can you see the mistake? The stated condition is wrong. Without the assert, the process() code could go off and potentially silently do the wrong thing, but the assert guards against that possibility. And once I've had a bug report that my app raises an AssertionError, I will go back and think more carefully about the assertion that sqrt(n) is always less than half of n. > but that's just not the way people write code in Python. Better is to use explicit type checks and raise an exception yourself: if not isinstance(x, int): raise TypeError('expected an int, got %r' % x) Better still is to duck-type whenever you can. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 18 09:05:15 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Jul 2012 13:05:15 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 18 Jul 2012 01:46:31 +0100, Andrew Cooper wrote: > Take for example a Linux system call handler. The general form looks a > little like (substituting C for python style pseudocode) > > if not (you are permitted to do this): > return -EPERM > if not (you've given me some valid data): > return -EFAULT > if not (you've given me some sensible data): > return -EINVAL > return actually_try_to_do_something_with(data) > > How would you program this sort of logic with a single return statement? That's not terribly hard. if not (you are permitted to do this): result = -EPERM elif not (you've given me some valid data): result = -EFAULT elif not (you've given me some sensible data): result = -EINVAL else: result = actually_try_to_do_something_with(data) return result A better example would involve loops. I used to hate programming in some versions of Pascal without a break statement: I needed a guard variable to decide whether or not to do anything in the loop! # pseudo-code for i in 1 to 100: if not condition: do_something_useful() Even with a break, why bother continuing through the body of the function when you already have the result? When your calculation is done, it's done, just return for goodness sake. You wouldn't write a search that keeps going after you've found the value that you want, out of some misplaced sense that you have to look at every value. Why write code with unnecessary guard values and temporary variables out of a misplaced sense that functions must only have one exit? -- Steven From roy at panix.com Wed Jul 18 09:07:22 2012 From: roy at panix.com (Roy Smith) Date: Wed, 18 Jul 2012 09:07:22 -0400 Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <5006b2e2$0$29978$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Tue, 17 Jul 2012 09:52:59 -0400, Roy Smith wrote: > > > you could write in Python: > > > > # Type matching will get checked at run-time > > def my_function(mpf, ot): > > assert isinstance(mpf, MassivelyParallelFrobinator) > > assert isinstance(ot, OtherThing) > > Keep in mind that assertions are not guaranteed to run. Code like the > above is buggy, because if Python is run under the -O (optimize) flag, > assertions will be stripped out. One could equally say that "code like the above is efficient, because if Python is run under the -O (optimize) flag, assertions will be stripped out" :-) > Better is to use explicit type checks and raise an exception yourself: > > if not isinstance(x, int): > raise TypeError('expected an int, got %r' % x) Maybe, but that's two lines where one does just fine. If you're going to go for type-bondage, you might as well be efficient and succinct about it. From steve+comp.lang.python at pearwood.info Wed Jul 18 10:31:37 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Jul 2012 14:31:37 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5006c8c8$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 18 Jul 2012 09:07:22 -0400, Roy Smith wrote: >> Keep in mind that assertions are not guaranteed to run. Code like the >> above is buggy, because if Python is run under the -O (optimize) flag, >> assertions will be stripped out. > > One could equally say that "code like the above is efficient, because if > Python is run under the -O (optimize) flag, assertions will be stripped > out" :-) You seem to have missed my point. Asserts *should* be used for checks which are optional. In this case, the fact that assert is optimized away is a feature: you have the added safety of a guard against some programming errors, while still being able to optimize that code on request. This is what assert is for. You get no argument from me about that -- my code is bulging with assertions. But where you *need* an explicit check to run, assert is not suitable, because you cannot control whether or not it will run. The caller, not you, controls that, by passing -O to the python interpreter. If you have a public function or method that can be called by any other piece of code, and it has required pre-conditions that need to be checked (not necessarily a type-check), then DO NOT USE ASSERT. If you use assert, then sometimes that pre-condition will not happen, and the caller can pass garbage into your function. The pre-condition will be violated, and your function will silently go off and do the wrong thing without warning. If you're lucky, your program will fail somewhere else, probably far away from where the error actually occurs, and you will merely have to spend hours or days trying to debug it. If you're unlucky, your program won't fail, it will just calculate garbage, or otherwise do the wrong thing. Besides, there is another reason not to use assert: it gives the wrong exception. If the error is a type error, you should raise TypeError, not ValueError, or ZeroDivisionError, or IndexError, or AssertionError. Using assert because it saves a line of code is lazy, sloppy programming. >> Better is to use explicit type checks and raise an exception yourself: >> >> if not isinstance(x, int): >> raise TypeError('expected an int, got %r' % x) > > Maybe, but that's two lines where one does just fine. But one line (assert) does *not* do just fine under the conditions I am talking about. If you need the check to run, then assert is not suitable, because it is not guaranteed to run. It's as simple as that. -- Steven From invalid at invalid.invalid Wed Jul 18 10:34:30 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 18 Jul 2012 14:34:30 +0000 (UTC) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: On 2012-07-17, Lipska the Kat wrote: > and what's this obsession with 'correct' indentation of code ??? If you can explain to us Java's obsession with 'correct' placemnt of curly-braces, then you've explained indentation in python. Unless you're asking about the tabs vs. spaces argument. In that case, people who use 4 spaces per level are 'correct'; people who use a different number of spaces are a bit less correct; people who use tabs are wrong; and people who mix spaces and tabs -- well, we don't talk about them in polite company. -- Grant Edwards grant.b.edwards Yow! NEWARK has been at REZONED!! DES MOINES has gmail.com been REZONED!! From lipska at lipskathekat.com Wed Jul 18 10:40:00 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Wed, 18 Jul 2012 15:40:00 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 18/07/12 14:05, Steven D'Aprano wrote: > On Wed, 18 Jul 2012 01:46:31 +0100, Andrew Cooper wrote: > >> Take for example a Linux system call handler. The general form looks a >> little like (substituting C for python style pseudocode) >> >> if not (you are permitted to do this): >> return -EPERM >> if not (you've given me some valid data): >> return -EFAULT >> if not (you've given me some sensible data): >> return -EINVAL >> return actually_try_to_do_something_with(data) >>I?m feeling a bit fed uI?m feeling a bit fed uI?m feeling a bit fed u >> How would you program this sort of logic with a single return statement? > > That's not terribly hard. > > if not (you are permitted to do this): > result = -EPERM > elif not (you've given me some valid data): > result = -EFAULT > elif not (you've given me some sensible data): > result = -EINVAL > else: > result = actually_try_to_do_something_with(data) > return result > > > A better example would involve loops. I used to hate programming in some > versions of Pascal without a break statement: I needed a guard variable > to decide whether or not to do anything in the loop! > > # pseudo-code > for i in 1 to 100: > if not condition: > do_something_useful() > > > Even with a break, why bother continuing through the body of the function > when you already have the result? When your calculation is done, it's > done, just return for goodness sake. You wouldn't write a search that > keeps going after you've found the value that you want, out of some > misplaced sense that you have to look at every value. Why write code with > unnecessary guard values and temporary variables out of a misplaced sense > that functions must only have one exit? Object Oriented programming is all about encapsulating human concepts in a way that makes sense to human beings. Make no mistake, it is NEVER the case that a software system is written for any other reason than to serve human beings. OO is more than just the mechanics of writing code, it's a state of mind. OO was 'invented' to address the many problems that beset increasingly complex software systems. The main problem was maintainability. Encapsulating a concept in a clear and concise way makes the code easier to understand. Sometimes this means writing code that is not 'optimal' for the machine. Good code should be readable as well as efficient but I contend that it is better to write something that is clear, concise and well encapsulated than always go for the 'meanest dog in the scrapyard' approach where a developer is determined to write unreadable code that shows how jolly clever he is. More often than not he is forced to admit six months down the line that he has no idea what his code does as he 'forgot' to comment it. I speak from bitter experience. This approach works for me. I have thousands of lines of code operating every day 'in the wild', everything from flight booking systems to real time odds arbitrage. Any developer who 'gets' OO can read and modify my code and I am very proud of this fact ... and I have never been forced to admit that I don't know what I wrote six months ago. If you are writing embedded systems that must have a very limited memory footprint then there is a case for conciseness over readability but even then it has to be maintainable Python looks like an interesting language and I will certainly spend time getting to know it but at the moment it seems to me that calling it an Object Oriented language is just plain misleading. There, I've said it, trolls and flamers beware, I take no prisoners. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From invalid at invalid.invalid Wed Jul 18 10:40:58 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 18 Jul 2012 14:40:58 +0000 (UTC) Subject: Foxpro goto command and deleted records References: Message-ID: On 2012-07-17, Ethan Furman wrote: > In Foxpro if you do a Foxpro? -- Grant Edwards grant.b.edwards Yow! I am NOT a nut.... at gmail.com From lipska at lipskathekat.com Wed Jul 18 10:48:28 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Wed, 18 Jul 2012 15:48:28 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> On 18/07/12 15:34, Grant Edwards wrote: > On 2012-07-17, Lipska the Kat wrote: > >> and what's this obsession with 'correct' indentation of code ??? > > If you can explain to us Java's obsession with 'correct' placemnt of > curly-braces, then you've explained indentation in python. I'm not getting into the curly braces wars. Life is just too short. > Unless you're asking about the tabs vs. spaces argument. In that > case, people who use 4 spaces per level are 'correct'; people who use > a different number of spaces are a bit less correct; people who use > tabs are wrong; hmm, I've been using tabs ... still, why use one key press when you can use 4 ;-). Actually I quite like this aspect of Python, it's rapidly growing on me. Wonder if I could introduce this in a future release of Java ... nah, I'd be dead within a week %-( > and people who mix spaces and tabs -- well, we don't > talk about them in polite company. > -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From bahamutzero8825 at gmail.com Wed Jul 18 11:00:40 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 18 Jul 2012 10:00:40 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> Message-ID: <5006CF98.3060509@gmail.com> On 7/18/2012 9:34 AM, Grant Edwards wrote: > people who us tabs are wrong Don't make me get my flamethrower! > and people who mix spaces and tabs -- well, we don't > talk about them in polite company. Mixing can make sense, but not in Python. *hides* -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rosuav at gmail.com Wed Jul 18 11:04:50 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 19 Jul 2012 01:04:50 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Jul 19, 2012 at 12:40 AM, Lipska the Kat wrote: > Python looks like an interesting language and I will certainly spend time > getting to know it but at the moment it seems to me that calling it an > Object Oriented language is just plain misleading. Python isn't object oriented in the way Java is ("EVERYTHING has to be in a class! Look, it's all OO now!"). It simply says that, well, what's the difference? That integer you're holding. That's an object. Your function is an object. The module you're in, your "global scope", is an object too, and can be passed around. Python doesn't care about buzzwords, it cares about making code. Of course, the simplicity of Python's object model has its costs too. Every little integer has to be memory-managed and garbage-collected (eg in CPython, they're all refcounted). That has a performance hit. But not all that big a hit, and it is so handy when you want your function to be able to accept, and distinguish between, different types of object - you don't have to write one version that takes an integer and a different one that takes a heap object. ChrisA From rosuav at gmail.com Wed Jul 18 11:09:35 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 19 Jul 2012 01:09:35 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> Message-ID: On Thu, Jul 19, 2012 at 12:48 AM, Lipska the Kat wrote: > hmm, I've been using tabs ... still, why use one key press when you can use > 4 ;-). Actually I quite like this aspect of Python, it's rapidly growing on > me. Wonder if I could introduce this in a future release of Java ... nah, > I'd be dead within a week %-( First let's get Python working properly. The "from __future__ import braces" statement still doesn't work on any of the released versions. After that, we can consider fixing Java to do the converse. We must meet half way, you know. As to tab vs spaces: I'm a fan of tabs, myself. There was an argument over the matter last year at work, and we settled on tabs because the one guy who reckons 1-2 space indent is plenty was then able to just set his editor to two-space tabs, and the rest of us could use a more reasonable width. Using tab characters in the file gives this flexibility. It separates the lexical structure ("this is three blocks in") from the visual display ("draw these glyphs 35mm from the left margin"). ChrisA From ethan at stoneleaf.us Wed Jul 18 11:32:07 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 18 Jul 2012 08:32:07 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5006D6F7.2020905@stoneleaf.us> Lipska the Kat wrote: > On 18/07/12 14:05, Steven D'Aprano wrote: >> Even with a break, why bother continuing through the body of the function >> when you already have the result? When your calculation is done, it's >> done, just return for goodness sake. You wouldn't write a search that >> keeps going after you've found the value that you want, out of some >> misplaced sense that you have to look at every value. Why write code with >> unnecessary guard values and temporary variables out of a misplaced sense >> that functions must only have one exit? > > Object Oriented programming is all about encapsulating human concepts in > a way that makes sense to human beings. Make no mistake, it is NEVER the > case that a software system is written for any other reason than to > serve human beings. OO is more than just the mechanics of writing code, > it's a state of mind. I must admit I have no idea how we went from discussing Single Exit functions to the One True Purpose of Object Oriented Programming; are you saying that SE is one of the basic tenets of OO? > OO was 'invented' to address the many problems that beset increasingly > complex software systems. The main problem was maintainability. > Encapsulating a concept in a clear and concise way makes the code easier > to understand. Sometimes this means writing code that is not 'optimal' > for the machine. Good code should be readable as well as efficient but I > contend that it is better to write something that is clear, concise and > well encapsulated than always go for the 'meanest dog in the scrapyard' > approach where a developer is determined to write unreadable code that > shows how jolly clever he is. More often than not he is forced to admit > six months down the line that he has no idea what his code does as he > 'forgot' to comment it. And one of the many reasons I love Python is that it is so easy to write clear, readable, and sometimes concise code (nested list comps are still a challenge for me). . . . > Python looks like an interesting language and I will certainly spend > time getting to know it but at the moment it seems to me that calling it > an Object Oriented language is just plain misleading. Since *everything* in Python is an object, how can you /not/ call it an OO language? Sure, you don't have to use everything as an object -- plain functions exist -- kinda ;) Even functions live in some namespace: len() lives in __builtin__, any top level function lives in its module, etc. Oh, and namespaces are objects. It seems to me that Python is more about providing tools, and then staying out of your way. That works for me. Maybe it will work for you, too. ~Ethan~ From lipska at lipskathekat.com Wed Jul 18 11:36:20 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Wed, 18 Jul 2012 16:36:20 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> Message-ID: On 18/07/12 16:09, Chris Angelico wrote: > On Thu, Jul 19, 2012 at 12:48 AM, Lipska the Kat > wrote: >> hmm, I've been using tabs ... snip > We must meet half way, you know. Seems reasonable to me, I'll let you suggest it ;-) > As to tab vs spaces: I'm a fan of tabs, myself. There was an argument > over the matter last year at work, and we settled on tabs because the > one guy who reckons 1-2 space indent is plenty was then able to just > set his editor to two-space tabs, and the rest of us could use a more > reasonable width. Using tab characters in the file gives this > flexibility. It separates the lexical structure ("this is three blocks > in") from the visual display ("draw these glyphs 35mm from the left > margin"). OK, I'll set my tab to 4 spaces ... Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From lipska at lipskathekat.com Wed Jul 18 11:49:06 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Wed, 18 Jul 2012 16:49:06 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 18/07/12 16:32, Ethan Furman wrote: > Lipska the Kat wrote: >> On 18/07/12 14:05, Steven D'Aprano wrote: >>> Even with a break, why bother continuing through the body of the >>> function >>> when you already have the result? When your calculation is done, it's >>> done, just return for goodness sake. You wouldn't write a search that >>> keeps going after you've found the value that you want, out of some >>> misplaced sense that you have to look at every value. Why write code >>> with >>> unnecessary guard values and temporary variables out of a misplaced >>> sense >>> that functions must only have one exit? >> >> Object Oriented programming is all about encapsulating human concepts >> in a way that makes sense to human beings. Make no mistake, it is >> NEVER the case that a software system is written for any other reason >> than to serve human beings. OO is more than just the mechanics of >> writing code, it's a state of mind. > > I must admit I have no idea how we went from discussing Single Exit > functions to the One True Purpose of Object Oriented Programming; are > you saying that SE is one of the basic tenets of OO? It's my fault, I get carried away sometimes. Maintainable code is one of the basic tenets of OO, it all seems so clear to me and I get frustrated when I think that others don't see the 'beauty' ... but then I come to my senses and realise that there is always another way to do things. >> Python looks like an interesting language and I will certainly spend >> time getting to know it but at the moment it seems to me that calling >> it an Object Oriented language is just plain misleading. > > Since *everything* in Python is an object, how can you /not/ call it an > OO language? Obviously I can't. I can't make a call as I haven't studied the language yet. I just can't get my head around duck typing at the moment as it is just so ... different. > Sure, you don't have to use everything as an object -- > plain functions exist -- kinda ;) Even functions live in some namespace: > len() lives in __builtin__, any top level function lives in its module, > etc. Oh, and namespaces are objects. > > It seems to me that Python is more about providing tools, and then > staying out of your way. > > That works for me. Maybe it will work for you, too. I hope so and thank you for being so calm and reasonable in your response. > > ~Ethan~ Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From ian.g.kelly at gmail.com Wed Jul 18 12:26:12 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 18 Jul 2012 10:26:12 -0600 Subject: Foxpro goto command and deleted records In-Reply-To: References: Message-ID: On Wed, Jul 18, 2012 at 8:40 AM, Grant Edwards wrote: > On 2012-07-17, Ethan Furman wrote: > >> In Foxpro if you do a > > Foxpro? http://en.wikipedia.org/wiki/Visual_FoxPro From d at davea.name Wed Jul 18 12:33:01 2012 From: d at davea.name (Dave Angel) Date: Wed, 18 Jul 2012 12:33:01 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5006E53D.3000809@davea.name> On 07/18/2012 08:58 AM, Steven D'Aprano wrote: > > > > 2) To check your internal reasoning in a function or method. > > For example: > > def foo(something): > n = len(something) > x = math.sqrt(x) > # We expect that x must be less than half of n. > # E.g. n=100 gives 10 < 50, which is correct. > assert x < n//2 > process(n, x) > > > > For bonus points, can you see the mistake? The stated condition is wrong. > Without the assert, the process() code could go off and potentially > silently do the wrong thing, but the assert guards against that > possibility. And once I've had a bug report that my app raises an > AssertionError, I will go back and think more carefully about the > assertion that sqrt(n) is always less than half of n. > > There are actually two bugs in that function. One is in the assertion, but more importantly, there's a typo earlier. One that would give a traceback, so it would be caught quickly. UnboundLocalError: local variable 'x' referenced before assignment Once you change the argument of sqrt() to n, then you come to the problem you were expecting; if n has a value of 1, 2, or 3, 4, or 5 the assertion will fire. -- DaveA From ed at leafe.com Wed Jul 18 12:55:44 2012 From: ed at leafe.com (Ed Leafe) Date: Wed, 18 Jul 2012 11:55:44 -0500 Subject: Foxpro goto command and deleted records In-Reply-To: <5005EDC0.6050608@stoneleaf.us> References: <5005EDC0.6050608@stoneleaf.us> Message-ID: <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> On Jul 17, 2012, at 5:57 PM, Ethan Furman wrote: > In Foxpro if you do a > > GOTO 7 > > with deleted off and record 7 is deleted, the record pointer doesn't > move (at least in version 6). > > I don't like that. > > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > Any opinions? It's been many years since I fired up VFP, but the above doesn't sound correct. If you have SET DELETED OFF and the GOTO 7, the pointer should move to the 7th record, whether it is marked deleted or not. With SET DELETED ON, the pointer should not move, since 7 is not a valid record. -- Ed Leafe From ethan at stoneleaf.us Wed Jul 18 13:23:03 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 18 Jul 2012 10:23:03 -0700 Subject: Foxpro goto command and deleted records In-Reply-To: <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> References: <5005EDC0.6050608@stoneleaf.us> <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> Message-ID: <5006F0F7.8030004@stoneleaf.us> Ed Leafe wrote: > On Jul 17, 2012, at 5:57 PM, Ethan Furman wrote: > >> In Foxpro if you do a >> >> GOTO 7 >> >> with deleted off and record 7 is deleted, the record pointer doesn't >> move (at least in version 6). >> >> I don't like that. >> >> I see four other options: >> >> 0) don't move the pointer (listed for completeness) >> 1) go to that record anyway >> 2) go to the next undeleted record >> 3) go to the seventh undeleted record (possibly the least practical) >> 4) raise an exception >> >> Any opinions? > > It's been many years since I fired up VFP, but the above doesn't sound correct. If you have SET DELETED OFF and the GOTO 7, the pointer should move to the 7th record, whether it is marked deleted or not. With SET DELETED ON, the pointer should not move, since 7 is not a valid record. Your memory is good! I typed it in wrong. I still don't like it. Any opinion on the other four choices? I'm leaning towards 1, possibly with 4 as an option: def goto(self, recno, raise_if_deleted=True): if is_deleted(self[recno)) and raise_if_deleted: raise DbfError( "Record %d is deleted and use_deleted is False" % recno) self._index = recno Part of the reason I feel this is reasonable is that with my dbf module it is possible to create an index that does /not/ include certain records: def ignore_deleted(record): if dbf.deleted(record): return dbf.DoNotIndex return dbf.recno(record) ~Ethan~ From ed at leafe.com Wed Jul 18 13:28:58 2012 From: ed at leafe.com (Ed Leafe) Date: Wed, 18 Jul 2012 12:28:58 -0500 Subject: Foxpro goto command and deleted records In-Reply-To: <5006F0F7.8030004@stoneleaf.us> References: <5005EDC0.6050608@stoneleaf.us> <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> <5006F0F7.8030004@stoneleaf.us> Message-ID: <485D3051-777B-49DA-8FD9-383F5807F827@leafe.com> On Jul 18, 2012, at 12:16 PM, Ethan Furman wrote: > Your memory is good! I typed it in wrong. Well, I was an MVP for Visual Foxpro for 10 years, so... ;-) > I see four other options: > > 0) don't move the pointer (listed for completeness) > 1) go to that record anyway > 2) go to the next undeleted record > 3) go to the seventh undeleted record (possibly the least practical) > 4) raise an exception > > I still don't like it. Any opinion on the other four choices? I'm leaning towards 1, possibly with 4 as an option: #4 is probably the most Pythonic approach. The calling code can then decide how to react to attempting to access a deleted record. Even if you're accessing data stored in VFP tables, your module should be as Pythonic as possible. > Part of the reason I feel this is reasonable is that with my dbf module it is possible to create an index that does /not/ include certain records: Deleting a record in VFP doesn't remove it from the index; I believe it marks that index entry as deleted, too. I think that as long as you treat the deleted status as the same as any other boolean column you'll be good. -- Ed Leafe From python at mrabarnett.plus.com Wed Jul 18 13:57:49 2012 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 18 Jul 2012 18:57:49 +0100 Subject: Foxpro goto command and deleted records In-Reply-To: <485D3051-777B-49DA-8FD9-383F5807F827@leafe.com> References: <5005EDC0.6050608@stoneleaf.us> <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> <5006F0F7.8030004@stoneleaf.us> <485D3051-777B-49DA-8FD9-383F5807F827@leafe.com> Message-ID: <5006F91D.6030306@mrabarnett.plus.com> On 18/07/2012 18:28, Ed Leafe wrote: > On Jul 18, 2012, at 12:16 PM, Ethan Furman wrote: > >> Your memory is good! I typed it in wrong. > > Well, I was an MVP for Visual Foxpro for 10 years, so... > > ;-) > >> I see four other options: >> >> 0) don't move the pointer (listed for completeness) >> 1) go to that record anyway >> 2) go to the next undeleted record >> 3) go to the seventh undeleted record (possibly the least practical) >> 4) raise an exception >> >> I still don't like it. Any opinion on the other four choices? I'm leaning towards 1, possibly with 4 as an option: > > #4 is probably the most Pythonic approach. The calling code can then decide how to react to attempting to access a deleted record. Even if you're accessing data stored in VFP tables, your module should be as Pythonic as possible. > I disagree. I think that if you can see it should be able to go to it. I think that the closest analogue is a list, although maybe you should be able to hide any records which are marked for deletion. # Print all of the names. records.include_deleted = True print("There are {} names".format(len(records))) for r in records: if r.deleted: print("\t{} (deleted)".format(r["name"])) else: print("\t{}".format(r["name"])) # Print all but the deleted names. records.include_deleted = False print("There are {} names".format(len(records))) for r in records: print(r["name"]) >> Part of the reason I feel this is reasonable is that with my dbf module it is possible to create an index that does /not/ include certain records: > > Deleting a record in VFP doesn't remove it from the index; I believe it marks that index entry as deleted, too. I think that as long as you treat the deleted status as the same as any other boolean column you'll be good. > From ed at leafe.com Wed Jul 18 15:13:40 2012 From: ed at leafe.com (Ed Leafe) Date: Wed, 18 Jul 2012 14:13:40 -0500 Subject: Foxpro goto command and deleted records In-Reply-To: <5006F91D.6030306@mrabarnett.plus.com> References: <5005EDC0.6050608@stoneleaf.us> <8416AFAF-E201-4F89-B306-D89F920A00FE@leafe.com> <5006F0F7.8030004@stoneleaf.us> <485D3051-777B-49DA-8FD9-383F5807F827@leafe.com> <5006F91D.6030306@mrabarnett.plus.com> Message-ID: <94CB0124-825E-4510-AC38-55BB1EB23DF2@leafe.com> On Jul 18, 2012, at 12:57 PM, MRAB wrote: >> #4 is probably the most Pythonic approach. The calling code can then decide how to react to attempting to access a deleted record. Even if you're accessing data stored in VFP tables, your module should be as Pythonic as possible. >> > I disagree. I think that if you can see it should be able to go to it. The use case was a deleted record with SET DELETED ON, which means you shouldn't "see" it. -- Ed Leafe From recaialkan at gmail.com Wed Jul 18 18:05:24 2012 From: recaialkan at gmail.com (recaialkan at gmail.com) Date: Wed, 18 Jul 2012 15:05:24 -0700 (PDT) Subject: FORTH in Python (py4th.py) In-Reply-To: <3c3772$21u@typhoon.osg.saic.com> References: <3c3772$21u@typhoon.osg.saic.com> Message-ID: 7 Aral?k 1994 ?ar?amba 05:04:22 UTC+2 tarihinde Nick Seidenman yazd?: > Just for fun I sat down and started writing a forth interpreter in > python. I got as far as putting in control structs and decided I';d > better get back to my real job. It does make a nice little example of > many of the cooler features of the language. I hearby bequeath its > current incodation to the net. > > No arguments, now! ;) > > ---------------<cut here>------------- > #!/usr/Util/bin/python > # > # @(#)py4th.py 1.1 94/12/06 > # > # Forth in Python (py4th). > # > ## This module implements a postfix interpreter class that > ## can be instantiated as the inner interpreter or as a forth-ish > ## interactive interpreter. The inner interpreter has two methods > ## called p_compile and p_interp that are the core methods. Compile > ## takes a string argument and returns a list that is executable by > ## the p_interp method. > ## > ## As of this version (12/6/94) there are a few important features > ## that need to be added, namely if-else-then and do-loop structures. > ## Doing so may require that the "for" construct used in p_interp > ## be replaced by a while loop that iterates over the program with > ## a program counter instead of the nice, clean, pc-less way it's done > ## now. I had thought about implementing these as follows: > ## > ## for IF-ELSE-THEN: > ## > ## given -- IF wordlist1 ELSE wordlist2 THEN > ## wordlist1 and wordlist2 would be compiled as embedded > ## lists within the current list. For example: > ## > ## a @ if dup * else dup dup * * then > ## > ## would compile into > ## > ## ['a', '@', 'if', ['dup', '*'], 'else', [ 'dup', 'dup', > ## '*', '*']] > ## > ## so that p_interp could then treat the wordlists as single > ## words and pass then to recursive invocations of itself. > ## > ## I have a similar scheme in mind for DO-LOOPs. > ## > ## 10 0 do i . cr loop > ## > ## would become > ## > ## ['10', '0', 'do', ['i', '.', 'cr', 'loop']] > ## > ## One way to do it might be to have a prepass before > ## p_interp and after p_compile. Since these control structures > ## are only allowed inside definitions, perhaps p_semicolon > ## could be where this happens. It could then build the > ## sublists and add the code required for loop increments > ## and proper skipping (else over if) and handling of omitted > ## parts (if without else or then). > ## > ## Loops use the variable name 'I' for the reference count. > ## The prepass mentioned above would generate code to store > ## the current value of 'I' (if any) as some internally known > ## variable (e.g., '__I__2371') and restore it once the loop > ## was finished. > ## > ## I have already put the skeleton code in for doing this. It's a > ## bit of a hack at this point but you can get the gist of what I have > ## in mind from in. > ## > ## Author: Nick Seidenman > ## SAIC > ## nick at osg.saic.com > > import string > import math > import sys > import stack > > StackUnderflow = 'StackUnderflow' > ExitNonError = 'ExitNonError' > InnerInterpreterError = 'InnerInterpreterError' > > > # InnerInterpreter takes a postfix expression in the form of > # a python list object and 'executes it'. It has it's own > # dictionary, which is initialized with the py4thon primatives and a few > > # Operational modes. > Execution = 'Execution' > Definition = 'Definition' > Forgetting = 'Forgetting' > Comment = 'Comment' > Variable = 'Variable' > > class InnerInterpreter: > > def __init__(self): > # Create a new stack and dictionary for this interpreter instance. > self.__stack = stack.Stack() > self.__rstack = stack.Stack() > self.__vocabulary = {} > self.__ulist = [] > self.__vars = {} > self.__vlist = [] > self.__mode = Execution > self.__lastmode = Execution > self.__runlevel = 0 > > # Initialize the new dictionary with words for the primitive > # functions. > self.__vocabulary['.'] = self.p_dot > self.__vocabulary['cr'] = self.p_cr > self.__vocabulary['+'] = self.p_plus > self.__vocabulary['-'] = self.p_minus > self.__vocabulary['*'] = self.p_multiply > self.__vocabulary['/'] = self.p_divide > self.__vocabulary['uminus'] = self.p_uminus > self.__vocabulary['^'] = self.p_exponent > self.__vocabulary['variable'] = self.p_variable > self.__vocabulary['!'] = self.p_assign > self.__vocabulary['@'] = self.p_dereference > self.__vocabulary['dup'] = self.p_dup > self.__vocabulary['swap'] = self.p_swap > self.__vocabulary['bye'] = self.p_bye > self.__vocabulary['forget'] = self.p_forget > self.__vocabulary[':'] = self.p_colon > self.__vocabulary[';'] = self.p_semicolon > self.__vocabulary['('] = self.p_lparen > self.__vocabulary[')'] = self.p_rparen > self.__vocabulary['vlist'] = self.p_vlist > > # Initialize dictionary with control structures. > > self.__vocabulary['if'] = self.c_if > self.__vocabulary['else'] = self.c_else > self.__vocabulary['then'] = self.c_then > self.__vocabulary['do'] = self.c_do > self.__vocabulary['loop'] = self.c_loop > self.__vocabulary['+loop'] = self.c_plusloop > > # Initialize the control structures prepass table. > > self.__ctl_struct = {} > self.__ctl_struct['do'] = self.c_pp_do > self.__ctl_struct['loop'] = self.c_pp_loop > self.__ctl_struct['+loop'] = self.c_pp_plusloop > self.__ctl_struct['if'] = self.c_pp_if > self.__ctl_struct['else'] = self.c_pp_else > self.__ctl_struct['then'] = self.c_pp_then > > > # Primitive functions (all begin with 'p_'. Primitive > # is defined as a function that must directly manipulate > # the interpreter stack. Defined functions do not do this. > > def p_dot(self): > result = self.__stack.pop() > sys.stdout.write (result + ' ') > > def p_cr (self): > print > > def p_plus(self): > y = string.atof(self.__stack.pop()) > x = string.atof(self.__stack.pop()) > self.__stack.push (`y + x`) > > def p_minus (self): > y = string.atof(self.__stack.pop()) > x = string.atof(self.__stack.pop()) > self.__stack.push(`y - x`) > > def p_multiply (self): > y= string.atof(self.__stack.pop()) > x = string.atof(self.__stack.pop()) > self.__stack.push(`y * x`) > > def p_divide (self): > y = string.atof(self.__stack.pop()) > x = string.atof(self.__stack.pop()) > self.__stack.push( `b / a`) > > def p_exponent (self): > y = string.atof(self.__stack.pop()) > x = string.atof(self.__stack.pop()) > self.__stack.push( `math.pow(x, y)`) > > def p_uminus (self): > x = string.atof(self.__stack.pop()) > self.__stack.push (`- x`) > > def p_assign (self): > word = self.__stack.pop() > value = self.__stack.pop() > if self.__vars.has_key (word): > self.__vars[word] = value > else: > raise InnerInterpreterError, word > > def p_dereference (self): > word = self.__stack.pop() > try: > self.__stack.push(self.__vars[word]) > except KeyError, x: > raise InnerInterpreterError, word > > def p_dup(self): > val = self.__stack.pop() > self.__stack.push(val) > self.__stack.push(val) > > def p_swap(self): > a = self.__stack.pop() > b = self.__stack.pop() > self.__stack.push(a) > self.__stack.push(b) > > def p_def (self): > word = self.__stack.pop() > prog = self.__stack.pop() > ## print 'defining', word, 'as', prog > self.__vocabulary[word] = prog > self.__ulist.append(word) > > def p_colon (self): > if self.__mode == Execution: > self.__mode = Definition > self.__colon = [] > else: > raise InnerInterpreterError, 'nested colon' > > def p_semicolon (self): > if self.__mode == Definition: > # Perhaps put prepass in here to scan for > # IF-ELSE-THEN and DO-LOOP and create sublists > # from these? > prog = self.__colon[1:] > self.__stack.push(prog) > self.__stack.push(self.__colon[0]) > del self.__colon > self.p_def() > self.__mode = Execution > else: > raise InnerInterpreterError, 'nested semicolon' > > def p_forget (self): > self.__mode = Forgetting > > def p_bye (self): > raise ExitNonError > > def p_compile (self, text): > return string.split(text) > > def p_lparen (self): > if self.__mode != Comment: > self.__lastmode = self.__mode > self.__mode = Comment > > def p_rparen (self): > if self.__mode == Comment: > self.__mode = self.__lastmode > else: > raise InnerInterpreterError, ')' > > def do_forget (self, word): > if self.__vocabulary.has_key(word) or self.__vars.has_key(word): > i = self.__ulist.index(word) ## Should be in here. > ul = len(self.__ulist) > for j in range (i, ul): > if self.__vocabulary.has_key(self.__ulist[i]): > del self.__vocabulary[self.__ulist[i]] > elif self.__vars.has_key(self.__ulist[i]): > del self.__vars[self.__ulist[i]] > else: > raise InnerInterpreterError, 'system error' > del self.__ulist[i] > else: > raise InnerInterpreterError, 'system error' > > self.__mode = Execution > > def p_variable (self): > self.__lastmode = self.__mode > self.__mode = Variable > > def do_variable (self, varName): > self.__vars[varName] = self.__stack.pop() > self.__ulist.append(varName) > self.__mode = self.__lastmode > > def p_vlist (self): > vlist = self.__vocabulary.keys() > vlist.sort() > for k in vlist: > sys.stdout.write (k + ' ') > > ### > ### Control structures (if then else, do loop, etc). > ### > > def c_if (self): > if self.__runlevel == 0: > raise InnerInterpreterError, 'if' > > def c_else (self): > if self.__runlevel == 0: > raise InnerInterpreterError, 'else' > > def c_then (self): > if self.__runlevel == 0: > raise InnerInterpreterError, 'then' > > def c_do (self): > if self.__runlevel == 0: > raise InnerInterpreterError, 'do' > > def c_pp_do (self, scan): > self.__rstack.push(scan[0:]) > scan = [] > scan.append ('do') > return scan > > def c_pp_if (self, scan): > self.__rstack.push(scan[0:]) > scan = [] > scan.append ('if') > return scan > > def c_loop (self): > if self.__runlevel == 0: > raise InnerInterpreterError, 'loop' > > def c_pp_loop (self, scan): > scan.append('loop') > result = self.__rstack.pop() > result.append(scan) > return result > > def c_pp_plusloop (self, scan): > scan.append('+loop') > result = self.__rstack.pop() > result.append(scan) > return result > > def c_pp_else (self, scan): > scan.append('else') > result = self.__rstack.pop() > result.append(scan) > return result > > def c_pp_then (self, scan): > scan.append('then') > result = self.__rstack.pop() > result.append(scan) > return result > > def c_plusloop (self): > if self.__runlevel == 0: > raise InnerInterpreterError, '+loop' > > def c_prepass (self, prog): > self.__rstack.flush() > scan = [] > for word in prog: > if self.__ctl_struct.has_key(word): > scan = self.__ctl_struct[word](scan) > else: > scan.append(word) > > return scan > > # This is the inner interpreter itself. It will execute the > # code body passed in the form of a python list as 'prog'. > def p_interp (self, prog): > for word in prog: > # Are we in comment mode? > if self.__mode == Comment: > if word == ')': > self.p_rparen() > continue > > # Are we in execution mode or definition mode? > elif self.__mode == Definition: > if word == ';': > self.p_semicolon() > else: > self.__colon.append(word) > continue > > elif self.__mode == Variable: > self.do_variable (word) > continue > > # See if this is a word we are supposed to forget. > elif self.__mode == Forgetting: > self.do_forget (word) > continue > > # If it isn't in the dictionary to begin with, then it must > # be a constant: push it on the stack > if type(word) != type([]) and not self.__vocabulary.has_key(word): > self.__stack.push(word) > continue > > # It is in the dictionary, but it may be a defined word > # rather than a primitive. Chase it down to either a > # primitive, a constant, or another code body. In the > # latter case, recurse with the new code body. > else: > current_word = word > try: > while self.__vocabulary.has_key (self.__vocabulary[current_word]): > current_word = self.__vocabulary[current_word] > except TypeError, x: > pass # Ok, since this is probably because the > # it's a list, or a primative. > > # If what we have is another program (non-primative word) > # then we run interp recursively to execute the word's text. > if type(current_word) == type([]): > self.__runlevel = self.__runlevel + 1 > self.p_interp(current_word) > self.__runlevel = self.__runlevel - 1 > > elif type(self.__vocabulary[current_word]) == type([]): > self.__runlevel = self.__runlevel + 1 > self.p_interp(self.__vocabulary[current_word]) > self.__runlevel = self.__runlevel - 1 > > elif type(self.__vocabulary[current_word]) == type (self.p_def): > self.__vocabulary[current_word]() > > # Whatever it is at this point just gets pushed onto > # the stack. It should be some sort of constant. > else: > self.__stack.push(self.__vocabulary[current_word]) > > # Simple outter interpreter for Py4th. I envision this as being > # augmented with thread support to allow multiple instances of > # the interpreter to provide a multitasking "forth" environment. > > class Py4th: > def __init__(self, input=sys.stdin): > self.input = input > self.interpreter = InnerInterpreter () > > def go (self): > try: > while 1: > try: > input = self.input.readline () > code = self.interpreter.p_compile (input) > self.interpreter.p_interp (code) > if self.input.isatty () and self.interpreter.__mode == Execution: > print 'OK' > except InnerInterpreterError, err_str: > if err_str != 'stack underflow': > print err_str, '?' > else: > print err_str > self.interpreter.__stack.flush() > > except ExitNonError: > if self.input.isatty (): > print 'goodbye' > pass > > # ---------------------------------------------------------- > # Test driver. Add to this as functionality is augmented. > # ---------------------------------------------------------- > def test (): > ## # Compile and run a simple program. > ## > ## print '***** Testing simple postfix program' > ## s = '2 3 + . 3 4 ^ .' > f = InnerInterpreter() > ## t = f.p_compile (s) > ## print s, '->', t > ## f.p_interp (t) > ## > #### This section predated the implementation of ':-;' and is no longer > #### needed. > #### ------------------------------ > #### # Now add program as a new word to the dictionary, then invoke it. > #### > #### f.__stack.push(t) > #### f.__stack.push('junk') > #### f.p_def() > #### f.p_interp (['junk']) > ## > ## # Test assignment (!) word. > ## > ## print '***** Testing VARIABLE ! and @' > ## s = '19 variable a 3 a @ * . cr' > ## t = f.p_compile(s) > ## print s, '->', t > ## f.p_interp(t) > ## > ## try: > ## s = 'b @ . cr' > ## t = f.p_compile(s) > ## f.p_interp(t) > ## except InnerInterpreterError, x: > ## print 'This should fail' > ## > ## # Test dup and swap > ## > ## print '***** Testing dup and swap' > ## s = '20 dup . cr . cr' > ## t = f.p_compile(s) > ## print s, '->', t > ## print 'should see 20\\n20\\n' > ## f.p_interp(t) > ## > ## s = '5 10 swap . cr . cr' > ## t = f.p_compile(s) > ## print s, '->', t > ## print 'should see \\n5\\n10\\n' > ## f.p_interp(t) > ## > ## # Test : , ;, and forget > ## > ## print '***** Testing colon definitions and FORGET' > ## s = ': sq dup * ; 2 sq 3 sq 100 sq . cr . cr . cr' > ## t = f.p_compile(s) > ## print s, '->', t > ## print 'Should see 10000\\n9\\n4\\n' > ## f.p_interp(t) > ## > ## print 'forgetting sq' > ## f.p_interp(f.p_compile('4 variable d 5 variable e')) > ## f.p_interp(f.p_compile('d @ e @ . cr . cr')) > ## f.p_interp(f.p_compile('forget sq')) > ## try: > ## print f.__vocabulary['sq'] # It better not find this. > ## except KeyError, k: > ## print 'sq forgotten' # Exception is ok. > ## > ## try: > ## print f.__vars['d'] # It better not find this. > ## except KeyError, k: > ## pass # Exception is ok. > ## > ## try: > ## print f.__vars['e'] # It better not find this. > ## except KeyError, k: > ## print 'FORGET works' # Exception is ok. > ## > ## # Everything defined since sq is also forgotten - good! > > s = ': nestor 10 variable i 10 0 do i @ if . cr else dup 2 * loop 1 2 3 10 5 do . cr 2 +loop + + . cr ;' > t = f.p_compile (s) > print t > u = f.c_prepass (t) > print u > f.p_interp(u) > > ## print f.__vocabulary > > f.p_interp(f.c_prepass(f.p_compile('nestor'))) > > # Run the test program when called as a script > if __name__ == '__main__': > test() Thank you for the code. How can i import stack? Where is the code for it? From larry.martell at gmail.com Wed Jul 18 18:20:51 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Wed, 18 Jul 2012 15:20:51 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path Message-ID: I have an interesting problem I'm trying to solve. I have a solution almost working, but it's super ugly, and know there has to be a better, cleaner way to do it. I have a list of path names that have this form: /dir0/dir1/dir2/dir3/dir4/dir5/dir6/file I need to find all the file names (basenames) in the list that are duplicates, and for each one that is a dup, prepend dir4 to the filename as long as the dir4/file pair is unique. If there are multiple dir4/files in the list, then I also need to add a sequence number based on the sorted value of dir5 (which is a date in ddMONyy format). For example, if my list contains: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3 Then I want to end up with: /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/qwer_01_file3 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/abcd_file1 /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/xyz_file1 /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/qwer_00_file3 My solution involves multiple maps and multiple iterations through the data. How would you folks do this? From ian.g.kelly at gmail.com Wed Jul 18 18:43:20 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 18 Jul 2012 16:43:20 -0600 Subject: FORTH in Python (py4th.py) In-Reply-To: References: <3c3772$21u@typhoon.osg.saic.com> Message-ID: On Wed, Jul 18, 2012 at 4:05 PM, wrote: > 7 Aral?k 1994 ?ar?amba 05:04:22 UTC+2 tarihinde Nick Seidenman yazd?: You realize that you're replying to a post from 1994? This code was written for Python 1.0. I'll be pretty impressed if it still works in 2.7. > Thank you for the code. How can i import stack? Where is the code for it? Google turns up this post, also from 1994: https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/5qBmi7K-mo4 Cheers, Ian From no.email at nospam.invalid Wed Jul 18 18:49:14 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Wed, 18 Jul 2012 15:49:14 -0700 Subject: Finding duplicate file names and modifying them based on elements of the path References: Message-ID: <7xipdkwuqd.fsf@ruckus.brouhaha.com> "Larry.Martell at gmail.com" writes: > I have an interesting problem I'm trying to solve. I have a solution > almost working, but it's super ugly, and know there has to be a > better, cleaner way to do it. ... > > My solution involves multiple maps and multiple iterations through the > data. How would you folks do this? You could post your code and ask for suggestions how to improve it. There are a lot of not-so-natural constraints in that problem, so it stands to reason that the code will be a bit messy. The whole specification seems like an antipattern though. You should just give a sensible encoding for the filename regardless of whether other fields are duplicated or not. You also don't seem to address the case where basename, dir4, and dir5 are all duplicated. The approach I'd take for the spec as you wrote it is: 1. Sort the list on the (basename, dir4, dir5) triple, saving original location (numeric index) of each item 2. Use itertools.groupby to group together duplicate basenames. 3. Within the groups, use groupby again to gather duplicate dir4's, 4. Within -those- groups, group by dir5 and assign sequence numbers in groups where there's more than one file 5. Unsort to get the rewritten items back into the original order. Actual code is left as an exercise. From bruce.sherwood at gmail.com Wed Jul 18 19:03:52 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Wed, 18 Jul 2012 17:03:52 -0600 Subject: A thread import problem Message-ID: I'm trying to do something rather tricky, in which a program imports a module that starts a thread that exec's a (possibly altered) copy of the source in the original program, and the module doesn't return. This has to do with an attempt to run VPython in the Mac Cocoa context, in which Cocoa is required to be the primary thread, making it necessary to turn the environment inside out, as currently VPython invokes the Carbon context as a secondary thread. I've created a simple test case, displayed below, that illustrates something I don't understand. The module reads the source of the program that imported it, comments out the import statement in that source, and performs an exec of the modified source. The module then enters an infinite loop, so that there is no return to the original program; only the exec-ed program runs, and it runs in a secondary thread. The puzzle is that if there is any later import statement in the exec source, the exec program halts on that import statement, with no error message. I saw a discussion that suggested a need for the statement "global math" to make the math import work, but that doesn't fix the problem. I've tried with no success various versions of the exec statement, with respect to its global and local environment. Can anyone explain why the math import statement causes a problem? Thanks for any advice you can give. Bruce Sherwood --------------------------- The main program: from import_test import * print('exec this file') global math from math import sin print(sin(3.14159/6)) ----------------------------- Contents of import_test: from threading import Thread from time import sleep import sys prog = open(sys.argv[0]).read() prog = '#'+prog # comment out the import statement print(prog) class worker(Thread): def run(self): print('start thread') exec(prog) w = worker() w.start() while True: sleep(1) From python at mrabarnett.plus.com Wed Jul 18 19:22:11 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jul 2012 00:22:11 +0100 Subject: FORTH in Python (py4th.py) In-Reply-To: References: <3c3772$21u@typhoon.osg.saic.com> Message-ID: <50074523.4070106@mrabarnett.plus.com> On 18/07/2012 23:43, Ian Kelly wrote: > On Wed, Jul 18, 2012 at 4:05 PM, wrote: >> 7 Aral?k 1994 ?ar?amba 05:04:22 UTC+2 tarihinde Nick Seidenman yazd?: > > You realize that you're replying to a post from 1994? This code was > written for Python 1.0. I'll be pretty impressed if it still works in > 2.7. > You'll need to create a Stack class and replace the string exceptions, but once those are fixed, it appears to work OK in Python 2.7. From rantingrickjohnson at gmail.com Wed Jul 18 19:47:55 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Wed, 18 Jul 2012 16:47:55 -0700 (PDT) Subject: How to configure Tkinter Listbox to disable state keeping selected item highlighted In-Reply-To: <92bf377d-05ea-42f8-98e4-3d76114aebc9@googlegroups.com> References: <92bf377d-05ea-42f8-98e4-3d76114aebc9@googlegroups.com> Message-ID: <19fa8023-baba-446f-93ae-08e99cdadf50@googlegroups.com> On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote: > I am having a problem configuring a listbox widget such that the selection remains highlighted even while it is set (programmatically) to the DISABLED state. Below code shows the problem: > > from Tkinter import * > master = Tk() > listbox = Listbox(master) > listbox.pack() > listbox.insert(END, "Text1") > listbox.insert(END, "Text2") > listbox.insert(END, "Text3") > listbox.selection_set(first=0, last=None) > listbox.configure(exportselection=False) > listbox.configure(state=DISABLED) > > Now when I change state to NORMAL, selected item is being highlighted. Is there a way I could disable widget (i.e. No response on mouse clicks) but keep the selected object remain highlighted? > > Intent: I want to utilise this widget on wizard App that I am creating. I would like this widget to indicate the current page / wizard number which the user selected. Is there any other widget I could use instead of it? (Labels possibly?) On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote: > I am having a problem configuring a listbox widget such that the selection remains highlighted even while it is set (programmatically) to the DISABLED state. Below code shows the problem: > > from Tkinter import * > master = Tk() > listbox = Listbox(master) > listbox.pack() > listbox.insert(END, "Text1") > listbox.insert(END, "Text2") > listbox.insert(END, "Text3") > listbox.selection_set(first=0, last=None) > listbox.configure(exportselection=False) > listbox.configure(state=DISABLED) > > Now when I change state to NORMAL, selected item is being highlighted. Is there a way I could disable widget (i.e. No response on mouse clicks) but keep the selected object remain highlighted? > > Intent: I want to utilise this widget on wizard App that I am creating. I would like this widget to indicate the current page / wizard number which the user selected. Is there any other widget I could use instead of it? (Labels possibly?) What's wrong with a page number displayed on a label? Why must you insist on displaying every page number in a Listbox? That seems like a waste of resources to me. You could even say: "Showing page I of N". From simoncropper at fossworkflowguides.com Wed Jul 18 20:36:27 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Thu, 19 Jul 2012 10:36:27 +1000 Subject: Finding duplicate file names and modifying them based on elements of the path In-Reply-To: References: Message-ID: <5007568B.2060706@fossworkflowguides.com> On 19/07/12 08:20, Larry.Martell at gmail.com wrote: > I have an interesting problem I'm trying to solve. I have a solution > almost working, but it's super ugly, and know there has to be a > better, cleaner way to do it. > > I have a list of path names that have this form: > > /dir0/dir1/dir2/dir3/dir4/dir5/dir6/file > > I need to find all the file names (basenames) in the list that are > duplicates, and for each one that is a dup, prepend dir4 to the > filename as long as the dir4/file pair is unique. If there are > multiple dir4/files in the list, then I also need to add a sequence > number based on the sorted value of dir5 (which is a date in ddMONyy > format). > > For example, if my list contains: > > /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3 > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1 > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 > /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1 > /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3 > > Then I want to end up with: > > /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/qwer_01_file3 > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/abcd_file1 > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 > /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/xyz_file1 > /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/qwer_00_file3 > > My solution involves multiple maps and multiple iterations through the > data. How would you folks do this? > Hi Larry, I am making the assumption that you intend to collapse the directory tree and store each file in the same directory, otherwise I can't think of why you need to do this. If this is the case, then I would... 1. import all the files into an array 2. parse path to extract forth level directory name and base name. 3. reiterate through the array 3.1 check if base filename exists in recipient directory 3.2 if not, copy to recipient directory 3.3 if present, append the directory path then save 3.4 create log of success or failure Personally, I would not have some files with abcd_file1 and others as file2 because if it is important enough to store a file in a separate directory you should also note where file2 came from as well. When looking at your results at a later date you are going to have to open file2 (which I presume must record where it relates to) to figure out where it came from. If it is in the name it is easier to review. In short, consistency is the name of the game; if you are going to do it for some then do it for all; and finally it will be easier for others later to work out what you have done. -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From bc at freeuk.com Wed Jul 18 20:41:38 2012 From: bc at freeuk.com (BartC) Date: Thu, 19 Jul 2012 01:41:38 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> Message-ID: "Lipska the Kat" wrote in message news:c76dnV778_sw4ZvNnZ2dnUVZ8uKdnZ2d at bt.com... > On 18/07/12 01:46, Andrew Cooper wrote: >> if not (you are permitted to do this): >> return -EPERM >> if not (you've given me some valid data): >> return -EFAULT >> if not (you've given me some sensible data): >> return -EINVAL >> return actually_try_to_do_something_with(data) >> >> How would you program this sort of logic with a single return statement? >> This is very common logic for all routines for which there is even the >> remotest possibility that some data has come from an untrusted source. > someType result = -EINVAL //or your most likely or 'safest' result > > if not (you are permitted to do this): > result = -EPERM > if not (you've given me some valid data): > result = -EFAULT > if not (you've given me some sensible data): > result = -EINVAL > else > result = -EDSOMETHING > > return result > } > //cohesive, encapsulated, reusable and easy to read But, it works differently from the above. Perhaps replace some of those "if" statements with "elif". The "return" version is handy because it provides a quick escape mechanism without cluttering up the rest of code with extra variables. -- Bartc From steve+comp.lang.python at pearwood.info Wed Jul 18 21:14:35 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 01:14:35 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> Message-ID: <50075f7b$0$1756$c3e8da3$76491128@news.astraweb.com> On Wed, 18 Jul 2012 15:48:28 +0100, Lipska the Kat wrote: > On 18/07/12 15:34, Grant Edwards wrote: >> Unless you're asking about the tabs vs. spaces argument. In that case, >> people who use 4 spaces per level are 'correct'; people who use a >> different number of spaces are a bit less correct; people who use tabs >> are wrong; > > hmm, I've been using tabs ... still, why use one key press when you can > use 4 ;-). My editor lets me add four spaces with a single key press, and delete them again with another single key press. Personally, I think tabs make more sense for indents than spaces, but for compatibility with others who are not as enlightened and insist on using broken tools that cannot deal with tabs, I have reluctantly standardised on spaces for indentation. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 18 21:22:35 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 01:22:35 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5007615b$0$1756$c3e8da3$76491128@news.astraweb.com> On Thu, 19 Jul 2012 01:04:50 +1000, Chris Angelico wrote: > Python isn't object oriented in the way Java is ("EVERYTHING has to be > in a class! Look, it's all OO now!"). Actually, Python is more object-oriented than Java. In Python, everything is an object. We have no distinction between boxed and unboxed integers, for example -- all integers are boxed, always. (Of course, data structures written in C, for example the array type, can encapsulate unboxed native ints. But the array itself is still an object.) On the other hand, Python doesn't force you to program using an object- oriented style. If you want to write functional code like Haskell, you can. If you want to write Pascal-style procedural code, you can. If you prefer an imperative style closer to shell scripting, go right ahead. The only one of the major paradigms that Python doesn't naturally support is logic programming. So Python is simultaneously more *and* less object-oriented than Java. -- Steven From steve+comp.lang.python at pearwood.info Wed Jul 18 21:23:59 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 01:23:59 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5006b2e2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500761ae$0$1756$c3e8da3$76491128@news.astraweb.com> On Wed, 18 Jul 2012 12:33:01 -0400, Dave Angel wrote: > On 07/18/2012 08:58 AM, Steven D'Aprano wrote: >> >> For bonus points, can you see the mistake? [...] >> > There are actually two bugs in that function. One is in the assertion, > but more importantly, there's a typo earlier. One that would give a > traceback, so it would be caught quickly. > > UnboundLocalError: local variable 'x' referenced before assignment Good catch :) -- Steven From python at mrabarnett.plus.com Wed Jul 18 21:28:30 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jul 2012 02:28:30 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <50075f7b$0$1756$c3e8da3$76491128@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> <50075f7b$0$1756$c3e8da3$76491128@news.astraweb.com> Message-ID: <500762BE.4020300@mrabarnett.plus.com> On 19/07/2012 02:14, Steven D'Aprano wrote: > On Wed, 18 Jul 2012 15:48:28 +0100, Lipska the Kat wrote: > >> On 18/07/12 15:34, Grant Edwards wrote: > >>> Unless you're asking about the tabs vs. spaces argument. In that case, >>> people who use 4 spaces per level are 'correct'; people who use a >>> different number of spaces are a bit less correct; people who use tabs >>> are wrong; >> >> hmm, I've been using tabs ... still, why use one key press when you can >> use 4 ;-). > > My editor lets me add four spaces with a single key press, and delete > them again with another single key press. > > Personally, I think tabs make more sense for indents than spaces, but for > compatibility with others who are not as enlightened and insist on using > broken tools that cannot deal with tabs, I have reluctantly standardised > on spaces for indentation. > """Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.""" -- Georg Brandl From steve+comp.lang.python at pearwood.info Wed Jul 18 21:34:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 01:34:47 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> On Wed, 18 Jul 2012 15:40:00 +0100, Lipska the Kat wrote: [...] >> Even with a break, why bother continuing through the body of the >> function when you already have the result? When your calculation is >> done, it's done, just return for goodness sake. You wouldn't write a >> search that keeps going after you've found the value that you want, out >> of some misplaced sense that you have to look at every value. Why write >> code with unnecessary guard values and temporary variables out of a >> misplaced sense that functions must only have one exit? > > Object Oriented programming is all about encapsulating human concepts in > a way that makes sense to human beings. Make no mistake, it is NEVER the > case that a software system is written for any other reason than to > serve human beings. OO is more than just the mechanics of writing code, > it's a state of mind. Um, yes? I'm no sure what this has to do with single-exit functions/methods. You can just as easily write multi-exit methods in an OO language as in a non- OO language. So long as your language has a return statement which exits the function, you can have more than one. I am aware that some languages enforce a single exit point, but that seems to be an unnecessary restriction to me. Of course it does require discipline and/or sense to not write crap code: if you have a 300 line function or method, whether it has dozens of exits or just one, that is crap code in any language. But if the choice is to write a 20 line function with three exits, or a 30 line function with a single exit, there would have to be a good reason to prefer the single- exit version. -- Steven From thecocacolakid at gmail.com Wed Jul 18 21:36:11 2012 From: thecocacolakid at gmail.com (The Coca Cola Kid) Date: Wed, 18 Jul 2012 20:36:11 -0500 Subject: Need help connecting via a remote VPN Message-ID: I need to connect to a site/server that's only accessible after logging into a remote VPN, then scan a directory for a file pattern and then copy those files. I know how to do the latter using glob, and I think I figured out how to connect to the VPN using win32ras and got a response that said "302 Found" but I'm not sure what to do after that. Some people recommended using SSH or fabric.api modules, but I couldn't find any examples that applied to what I'm trying to do. From d at davea.name Wed Jul 18 21:59:51 2012 From: d at davea.name (Dave Angel) Date: Wed, 18 Jul 2012 21:59:51 -0400 Subject: Need help connecting via a remote VPN In-Reply-To: References: Message-ID: <50076A17.3080303@davea.name> On 07/18/2012 09:36 PM, The Coca Cola Kid wrote: > I need to connect to a site/server that's only accessible after > logging into a remote VPN, then scan a directory for a file pattern > and then copy those files. I know how to do the latter using glob, > and I think I figured out how to connect to the VPN using win32ras and > got a response that said "302 Found" but I'm not sure what to do after > that. Some people recommended using SSH or fabric.api modules, but I > couldn't find any examples that applied to what I'm trying to do. Starting a VPN simply makes it possible for IP packets to get to the specified machine. You still need to match some protocol that the particular remote machine can handle. SSH is probably the most common, but there are lots of other possibilities, some standard and some custom. So the question is what does the remote machine (server) support for file access? glob will work if the server supports mounting the remote partition as a file system. But there are no guarantees that that's possible. You haven't even said what the two operating systems involved are, though I can guess that the local machine is some version of Windows. -- DaveA From sddsdsddd at gmail.com Wed Jul 18 23:47:58 2012 From: sddsdsddd at gmail.com (Nicky dsdsdsds) Date: Wed, 18 Jul 2012 20:47:58 -0700 (PDT) Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! Message-ID: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! After Jews created Israel illegally, Israel became the main base of criminal operations for the most insane type of Jews called Zionists. Israeli Jews murdered JFK in 1963 because JFK did not allow them to have atomic bombs. Read the book "Final Judgment" by Michael Piper, available online in pdf, also google for video presentation by author. Since Americans let the Jews get away with JFK murder, just four years later in 1967, Israeli Jews murdered 34 servicemen of American Navy, and seriously wounded 174, when Jews tried repeatedly to sink the USS Liberty and blame Egypt for it. Watch online the video interviews with the actual survivors, then compare the facts to the lies spread by Jews through their propaganda outlets like wikipedia. One interview with a survivor should have been enough to turn all responsible Jews and American Traitors into fertilizer within 24 hours. Since Americans let Jews get away with JFK and USS Liberty murders, Israeli Jews murdered 3000 Americans in 9/11, this time to make USA invade Afghanistan/Iraq for Jews, and to enable Jews to impose their Jew Laws (Jaws) like "Patriot Act". Watch online the video "9/11 Missing Links" made in cooperation with contacts inside FBI, CIA, National Security Agency, US Military, who are still loyal to USA. All Jews covered up for Israeli Zionists, with the help from Traitors in Washington DC, because all Jews always protect themselves as single Jew Tribe. Jews are not the sweet/smart/suffering individuals as they present themselves using their own Jew propaganda machines. Jews are full of hate and suffer from a whole range of genetic mental diseases like schizophrenia, paranoia, psychopathy, homicidal behavior, sexual perversions like pedophilia/homosexuality/etc, and many others, that make them prone to criminal/parasitic/corruptive behavior. Banking Jews started their corruption of USA in 1913 with creation of the Fed. The Great Depression of 1930's was the direct result of Jew corruption. Jews used Great Depression as an opportunity to corrupt/ expand the federal government because parasites like Jews exploit host organisms through central systems. After Hitler came to power in 1933 and removed Jews from all important positions, Germany experienced unprecedented economic growth while the rest of the world controlled by Jews suffered through Great Depression. Jews did not like this precedent and immediately in 1933 Jews declared economic war on Germany. Hitler invaded Poland in 1939 only because Poland was infested with five million Jews who constantly were harassing Germany. Jews used their media power to brainwash White Americans to fight White Germans for Jews. All the official "history" has been written by lying Jews and it should be called Jewstory instead of History. Jews are not Whites but insane mongrels who hate Whites. Jews started all the jokes about Whites like Dumb Blondes, Rednecks, Polish Jokes. The sheeple merely parroted after the Jew media. Jews are the ones who promote all those Blacks you see in the media, sports, schools, or business. Jews constantly stir up conflicts between Whites and Blacks by propagandizing the shootings of Blacks in order to take your attention away from all Jew scams. Since 9/11 Jews intensified their "Racism" tactics and their famous "Holocaust" tactics because more Americans learn every day that Jews did 9/11. Jews know they are the biggest Criminals on Earth, and that is why Jews manufactured the "Holocaust" Scam where Jews masquerade as the biggest Victims on Earth. Jews are Masters of biggest Lies and Deceptions. Without their control of brainwashing media, Jews would be nothing more than insane rats. Only Jew scams enabled many Jews to masquerade with Ivy League diplomas, Nobel Prizes, Oscars. Jews run their college/ Awards scams like Wall Street or elections scams. Independent investigations of all Ivy League colleges would show that most Jew students are frauds with standardized tests taken by somebody else or their test results falsified by corrupt admissions offices. The biggest Jew Nobel Prize winner Einstein was a fraud and plagiarist. All you know about famous Jew "scientists" is what Jews told you, the same Jews who made you believe the "Manned Moon Landings" or "Man-Made Global Warming". Jews never invented anything but Scams and Hoaxes. Jews in Israel rank well below average in IQ scores among all nations. Basically, Israel is a hellhole where tens of billions of dollars of American taxpayers' money are wasted on worthless Jews each year. Jews control the US Government illegally. The American democracy is a myth. Most of "US Presidents" since 1913 were crypto Jews (FDR, Eisenhower, LBJ, Obama with Jew mother) or Jew puppets. Recently, Jews in US Congress imposed on Americans yet another Jew Law (Jaw) called "National Defense Authorization Act" that threatens any American who tries to defend The US Constitution with its Bill of Rights. All the Jaws out of Washington DC are meant to protect Jews and only Jews. However, the ultimate power lies in the economies, now all mortally wounded by Jews. Jews were too greedy by exporting all real American jobs and forcing Americans to live on debt for too long. Once enough good Americans reach poverty levels, the game will be over for Jews, especially if their psychotic relatives in Israel pull another USS Liberty or 9/11. How can Jews control the US Government with such a small Jew population? How can Jews amass so much wealth if Jews are not very intelligent? In order to answer such questions you have to look at the Big Picture painted for you by Mother Nature a long time ago. For thousands of years, each society had a small parasitic ruling class and a large working class needed to sustain the society. Mother Nature created such a social order to facilitate the evolutionary process because living conditions for humans were very tough. Mother Nature knew that a ruling class does not have to be very intelligent because any substantial intellect leads automatically to creativity needed only by working class. Instead, Mother Nature developed our human psychology in such a way that a ruling class could rule merely by displaying symbols of power like ornamental clothes, big buildings, rituals, propaganda, and so on. For this to work, a ruling class had to be filled with psychopaths only smart enough to band together for this scam to go on, and a working class had to be filled with intelligent people busy with doing all the creative work. At least the ruling and working classes were ethnically related until around 18th century when the biggest parasitic psychopaths called Jews learned enough about the game played by ruling classes. At that time, Jews decided to have a piece of the ruling action for themselves by creating central banks or starting revolutions. Jews were around for thousands of years. Clearly, Mother Nature created Jews on her bad hair day because Jews hated all non-Jews including her best creations. This hatred made Jews the perfect tool to exploit the weaknesses of both ruling and working classes of all normal societies. By destroying the old social orders, Jews acted like maggots decomposing dead animals. Mother Nature kept Jews around for thousands of years because she needed them to change slowly the old social orders. Otherwise, Mother Nature would abort Jews a long time ago because Jews lack the intellect to create anything. Decomposition of the old social orders was largely completed by Jews in early 20th century, at least in the Western World. Since then, Jews have been trying to become the ruling class for the whole world. Apparently, Mother Nature now uses Jews to internationalize all societies in order to speed up the evolution process because there are clear benefits in global cooperation. However, Mother Nature is well aware that Jews are useless beyond this point. Jews corrupted politics, media, economies, military, sciences, business, medicine and healthcare, education, agriculture, and others. Through their insanity, Jews started two world wars and are about to start the third one, Jews killed millions with their invention of communism, Jews committed the biggest terrorist acts in history and always blamed others, Jews polluted the whole world with nuclear technologies, Jews destroyed agriculture and food supplies with GMO crops and other poisons, Jews killed millions with the poisons produced by their pharmaceutical companies, Jews imposed on societies their sexual perversions like pedophilia and homosexuality, Jews run all organized crime including illegal drugs and prostitution, Jews own most of the pornography business, and on and on. The old ruling classes would not be able to do so much harm to the working classes because there were many different societies with different ruling classes and the classes within each society were ethnically related. This means that fraudulent ruling classes could last forever without the working classes ever waking up. However, Mother Nature wants to make all psychopathic rulers extinct once they served their purpose in Nature. Mankind cannot live forever while locked in the old psychology addicted to psychopathic rulers, Jews or non-Jews. That is why Mother Nature used the biggest parasitic psychopaths Jews to force out the old parasitic ruling classes first, and now Mother Nature is using the same Jews to exploit/harm the working classes in order to initiate the next evolutionary step. Many people are already ready to deal with the Jew problem. However, most people still refuse to deal with it because they are still locked in the old psychology developed by Mother Nature thousands of years ago. The latter group of people will wake up at the latest when the economies collapse. Realize that Mother Nature made Jews screw up the attack on USS Liberty so that the survivors could tell you the truth about the US Government controlled by Jews. Mother Nature created the Internet for you so that you can research all Scams and Hoaxes done by Jews. In other words, Mother Nature realizes that it is time for you to change and Jews have to go before Jews do too much damage. Mother Nature keeps Jews around so that you can see for yourself with your own eyes that something is wrong with you. Just put yourself in the shoes of Mother Nature. How would you make your own children abandon their old bad habits? You would let the bad habits hurt your own children just enough to teach them a lesson. This is exactly what Mother Nature is doing to you except Mother Nature is willing to get many of her children killed in order for other children to live better in the future. If you have any doubts about Jews then ask the USS Liberty survivors, or watch the videos of people jumping from the WTC Towers on 9/11. Help Mother Nature by not watching any Jew brainwashing media that makes you lose your own common sense! Otherwise, Mother Nature will bring the change violently! From wrw at mac.com Thu Jul 19 00:10:42 2012 From: wrw at mac.com (William Ray Wing) Date: Thu, 19 Jul 2012 00:10:42 -0400 Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! In-Reply-To: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> Message-ID: <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> On Jul 18, 2012, at 11:47 PM, Nicky dsdsdsds wrote: > COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! > > Sometimes I wish this list was moderated... -Bill From rosuav at gmail.com Thu Jul 19 01:09:43 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 19 Jul 2012 15:09:43 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5007615b$0$1756$c3e8da3$76491128@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <5007615b$0$1756$c3e8da3$76491128@news.astraweb.com> Message-ID: On Thu, Jul 19, 2012 at 11:22 AM, Steven D'Aprano wrote: > On Thu, 19 Jul 2012 01:04:50 +1000, Chris Angelico wrote: > >> Python isn't object oriented in the way Java is ("EVERYTHING has to be >> in a class! Look, it's all OO now!"). > > Actually, Python is more object-oriented than Java. In Python, everything > is an object. We have no distinction between boxed and unboxed integers, > for example -- all integers are boxed, always. That was my point. Less hype about OO but everything really is an object. ChrisA From breamoreboy at yahoo.co.uk Thu Jul 19 01:29:05 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 19 Jul 2012 06:29:05 +0100 Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! In-Reply-To: <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> Message-ID: On 19/07/2012 05:10, William Ray Wing wrote: > On Jul 18, 2012, at 11:47 PM, Nicky dsdsdsds wrote: > >> COPY THIS MESSAGE FAST BECAUSE JEWS AND TRAITORS DELETE IT FAST! >> >> > Sometimes I wish this list was moderated... > > -Bill > I do that, unofficially of course :) I routinely flag crap like this on gmane.org and google groups, and for any other Python list that I happen to read. -- Cheers. Mark Lawrence. From rustompmody at gmail.com Thu Jul 19 02:09:13 2012 From: rustompmody at gmail.com (rusi) Date: Wed, 18 Jul 2012 23:09:13 -0700 (PDT) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> Message-ID: <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> On Jul 19, 6:34?am, Steven D'Aprano wrote: > On Wed, 18 Jul 2012 15:40:00 +0100, Lipska the Kat wrote: > > Object Oriented programming is all about encapsulating human concepts in > > a way that makes sense to human beings. Make no mistake, it is NEVER the > > case that a software system is written for any other reason than to > > serve human beings. OO is more than just the mechanics of writing code, > > it's a state of mind. > > Um, yes? Its not so much a question of language as in programming as language as in layman-speak. One characteristic with our field is that we take ordinary words and then distort them so much the original meaning is completely lost. Take 'computer' for example. For Turing a computer was a mathematician doing a computation with a pen and paper. He then showed how to de-skill the mathematician so much that a machine could do what he was doing. In trying that he also hit upon the limits of such 'de-skilling' -- human-computers routinely detect infinite loops, whereas machine-computers can never do so (in full generality). Ironically the important lesson is lost and today 'computer' is synonymous with machine. Here is Dijkstra on similar distortions with 'user' and 'intelligent': http://www.cs.utexas.edu/~EWD/transcriptions/EWD06xx/EWD618.html 'Object' (and OO) are similar messes. In layman-speak and object is well, a thing. - subject to space-laws like can only exist at one place at a time, there cannot be two objects at the same place and time etc. - subject to time-laws like coming into existence at some time and going out at some other - connotes inanimateness unlike other 'creatures' or 'beings'. When this metaphor works (for example as in guis and simulation) then we have success-stories like smalltalk and simula. When it doesn't the success is poorer. eg a programmer writing math software in/on a OO system may for example 'clone' a matrix. This may be good science-fiction; its bad math. And one of the most pervasive (and stupidist) metaphors is the parent- child relation of classes. Just for the record, in the normal world 'creatures/beings' reproduce and therefore inherit. Objects dont. From tjreedy at udel.edu Thu Jul 19 02:11:23 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Jul 2012 02:11:23 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 7/18/2012 10:40 AM, Lipska the Kat wrote: > fact ... and I have never been forced to admit that I don't know what I > wrote six months ago. That is an explicit objective of Python's design. > Python looks like an interesting language and I will certainly spend > time getting to know it but at the moment it seems to me that calling it > an Object Oriented language is just plain misleading. I just call it object-based and let be done with it, as I have no interest in arguing 'Object Oriented'. What perhaps *you* need to know, given your background, is that nearly all syntax and most builtin callables wrap special method calls that can be defined on user classes. 'a + b' is executed as something like try: return a.__add__(b) # or the C type slot equivalent except: # not sure what is actually caught try: return b.__radd__(a) # r(everse)add except: # ditto raise TypeError("unsupported operand type(s) for +: {} and {}".format(a, b)) [Syntax exceptions: =, and, or] 'len(x)' calls x.__len__ and checks that the return value can be interpreted as an integer (I believe that means that it is an int or has an __index__ method, so that it can be used as a sequence index) and that its value is >= 0. -- Terry Jan Reedy From dieter at handshake.de Thu Jul 19 04:31:11 2012 From: dieter at handshake.de (Dieter Maurer) Date: Thu, 19 Jul 2012 10:31:11 +0200 Subject: A thread import problem References: Message-ID: <87k3y0ywxc.fsf@handshake.de> Bruce Sherwood writes: > I'm trying to do something rather tricky, in which a program imports a > module that starts a thread that exec's a (possibly altered) copy of > the source in the original program, and the module doesn't return. > This has to do with an attempt to run VPython in the Mac Cocoa > context, in which Cocoa is required to be the primary thread, making > it necessary to turn the environment inside out, as currently VPython > invokes the Carbon context as a secondary thread. > > I've created a simple test case, displayed below, that illustrates > something I don't understand. The module reads the source of the > program that imported it, comments out the import statement in that > source, and performs an exec of the modified source. The module then > enters an infinite loop, so that there is no return to the original > program; only the exec-ed program runs, and it runs in a secondary > thread. > > The puzzle is that if there is any later import statement in the exec > source, the exec program halts on that import statement, with no error > message. I saw a discussion that suggested a need for the statement > "global math" to make the math import work, but that doesn't fix the > problem. I've tried with no success various versions of the exec > statement, with respect to its global and local environment. In a recent discussion in this list someone mentioned that on module import, you should not start a thread. The reason: apparently, Python uses some kind of locking during import which can interfere with "import"s in the started thread. You can (in principle) easily avoid starting the thread on module import. Instead of starting the thread as a side effect of the import, put the start in a function, import the module and then call the thread starting function. From lipska at lipskathekat.com Thu Jul 19 04:56:30 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Thu, 19 Jul 2012 09:56:30 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> Message-ID: On 19/07/12 07:09, rusi wrote: > On Jul 19, 6:34 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> On Wed, 18 Jul 2012 15:40:00 +0100, Lipska the Kat wrote: >>> Object Oriented programming is all about encapsulating human concepts in >>> a way that makes sense to human beings. Make no mistake, it is NEVER the >>> case that a software system is written for any other reason than to >>> serve human beings. OO is more than just the mechanics of writing code, >>> it's a state of mind. >> >> Um, yes? > Its not so much a question of language as in programming as language > as in layman-speak. > One characteristic with our field is that we take ordinary words and > then distort them so much the original meaning is completely lost. > > Take 'computer' for example. For Turing a computer was a > mathematician doing a computation with a pen and paper. He then > showed how to de-skill the mathematician so much that a machine could > do what he was doing. In trying that he also hit upon the limits of > such 'de-skilling' -- human-computers routinely detect infinite loops, > whereas machine-computers can never do so (in full generality). > > Ironically the important lesson is lost and today 'computer' is > synonymous with machine. > > Here is Dijkstra on similar distortions with 'user' and > 'intelligent': > http://www.cs.utexas.edu/~EWD/transcriptions/EWD06xx/EWD618.html > > 'Object' (and OO) are similar messes. Well this is all very interesting. The terminology is quite concise if you allow it to be Take "An Object is an instance of a Class" A Class describes a human concept (be it concrete like a 'Parrot' or more abstract like a 'Session') an Object is an actual representation of that concept that exists in the memory of a computer (what else should we call it). Objects don't exist in the mind of a human, concepts do. A class is a way of representing that concept so that other humans can understand it. That's it, really, there is no more, anything else is implementation. > In layman-speak and object is well, a thing. But we are not talking in 'layman-speak' we are discussing concepts that are familiar to us in the 'language of the domain' at least I though we were. Academic twiddling with the distorted meaning of words spun by vested interests is all very interesting I'm sure but doesn't really advance the discussion does it? > - subject to space-laws like can only exist at one place at a time, > there cannot be two objects at the same place and time etc. > - subject to time-laws like coming into existence at some time and > going out at some other > - connotes inanimateness unlike other 'creatures' or 'beings'. Well here I have to agree with you. Anyone who invents a 'Person' Class should be dismissed forthwith. Parrots are OK though. > When this metaphor works (for example as in guis and simulation) then > we have success-stories like smalltalk and simula. > > When it doesn't the success is poorer. eg a programmer writing math > software in/on a OO system may for example 'clone' a matrix. This may > be good science-fiction; its bad math. > > And one of the most pervasive (and stupidist) metaphors is the parent- > child relation of classes. > Just for the record, in the normal world 'creatures/beings' reproduce > and therefore inherit. But we are not talking about the 'real world' are we, we are talking about representing complex interacting human concepts in a way that can be understood by humans and translated into a form that can be executed on a binary machine > Objects dont. Well they do, it's a fact, you can call a method on a sub class that only exists in the super class. What else would you call it. Well it's been fun but I have bills to pay so I suppose I'd better do some work. TTFN -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From dickie.moseley at virgin.net Thu Jul 19 05:03:40 2012 From: dickie.moseley at virgin.net (RICHARD MOSELEY) Date: Thu, 19 Jul 2012 10:03:40 +0100 Subject: Incorrect detection of futimesns/futimes in 3.3.0b1 Message-ID: I have recently been compiling the source for 3.3.0 beta1 and have discovered that even though the functions futimens, futimes and lutimes are found by the configure script, since they exist as entry points in libc, their actually only stub functions that simply return ENOSYS (Not Implemented) when called. This causes the installation stage to fail with a fatal error, 'Error: Function Not Implemented', during the installation of the libraries into the lib-dynload directory, leading me to initially think that there was a problem with the distutils module (fairly unlikely I know). The platform I am compiling on, is an ASUS Eee PC 1000 running the original Xandros operating system. I can make the installation complete, by modifying the pyconfig.h and undefining the erroneous defines: HAVE_FUNC_FUTIMENS, HAVE_FUNC_FUTIMES and HAVE_FUNC_LUTIMES. I am now considering providing a general patch to the configure.ac file which will more correctly detect all the various flavours of utimes (futimens, futimes, lutimes, futimesat, utimensat and utimes) using a different check other than AC_CHECK_FUNCS. Or would it be better simply to keep it private and apply the fix each time I upgrade the source code to the latest version? Richard Moseley -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Thu Jul 19 05:22:40 2012 From: lists at cheimes.de (Christian Heimes) Date: Thu, 19 Jul 2012 11:22:40 +0200 Subject: Incorrect detection of futimesns/futimes in 3.3.0b1 In-Reply-To: References: Message-ID: Am 19.07.2012 11:03, schrieb RICHARD MOSELEY: > I am now considering providing a general patch to the configure.ac > file which will more correctly detect all the > various flavours of utimes (futimens, futimes, lutimes, futimesat, > utimensat and utimes) using a different check other than AC_CHECK_FUNCS. > Or would it be better simply to keep it private and apply the fix each > time I upgrade the source code to the latest version? Please create a bug report http://bugs.python.org/ and attach your patch when it's ready. Other people will find your fix useful, too. The issue should be fixed in the official distribution. Thanks Christian From esbatmop at gmail.com Thu Jul 19 05:51:15 2012 From: esbatmop at gmail.com (esbatmop at gmail.com) Date: Thu, 19 Jul 2012 02:51:15 -0700 (PDT) Subject: Which lib can diff two dict tree? Message-ID: Q1? dict a?{'a1': 'b1', 'a2': {'b2': 'c2'}, 'a3': 'b3'} dict b?{'a1': 'b1', 'a2': {'b2': 'c3'}} which lib can diff two dict tree? like? print struct_diff(a?b) >>tree 'a3' print value_diff(a,b) >>c3 Q2 How can I diff two json file?How can I get struct_diff and value_diff? Q3 How can I diff two xml file? How can I get struct_diff and value_diff? From andrea.crotti.0 at gmail.com Thu Jul 19 06:15:11 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Thu, 19 Jul 2012 11:15:11 +0100 Subject: reloading code and multiprocessing Message-ID: We need to be able to reload code on a live system. This live system has a daemon process always running but it runs many subprocesses with multiprocessing, and the subprocesses might have a short life... Now I found a way to reload the code successfully, as you can see from this testcase: def func(): from . import a print(a.ret()) class TestMultiProc(unittest.TestCase): def setUp(self): open(path.join(cur_dir, 'a.py'), 'w').write(old_a) def tearDown(self): remove(path.join(cur_dir, 'a.py')) def test_reloading(self): """Starting a new process gives a different result """ p1 = Process(target=func) p2 = Process(target=func) p1.start() res = p1.join() open(path.join(cur_dir, 'a.py'), 'w').write(new_a) remove(path.join(cur_dir, 'a.pyc')) p2.start() res = p2.join() As long as I import the code in the function and make sure to remove the "pyc" files everything seems to work.. Are there any possible problems which I'm not seeing in this approach or it's safe? Any other better ways otherwise? From python.list at tim.thechases.com Thu Jul 19 07:21:58 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 06:21:58 -0500 Subject: Odd csv column-name truncation with only one column Message-ID: <5007EDD6.5020903@tim.thechases.com> tim at laptop:~/tmp$ python Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import csv >>> from cStringIO import StringIO >>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') >>> s.seek(0) >>> d = csv.Sniffer().sniff(s.read()) >>> s.seek(0) >>> r = csv.DictReader(s, dialect=d) >>> r.fieldnames ['Emai', ''] I get the same results using Python 3.1.3 (also readily available on Debian Stable), as well as working directly on a file rather than a StringIO. Any reason I'm getting ['Emai', ''] (note the missing ell) instead of ['Email'] as my resulting fieldnames? Did I miss something in the docs? -tkc From __peter__ at web.de Thu Jul 19 07:49:53 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Jul 2012 13:49:53 +0200 Subject: Odd csv column-name truncation with only one column References: <5007EDD6.5020903@tim.thechases.com> Message-ID: Tim Chase wrote: > tim at laptop:~/tmp$ python > Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import csv >>>> from cStringIO import StringIO >>>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') >>>> s.seek(0) >>>> d = csv.Sniffer().sniff(s.read()) >>>> s.seek(0) >>>> r = csv.DictReader(s, dialect=d) >>>> r.fieldnames > ['Emai', ''] > > I get the same results using Python 3.1.3 (also readily available on > Debian Stable), as well as working directly on a file rather than a > StringIO. > > Any reason I'm getting ['Emai', ''] (note the missing ell) instead > of ['Email'] as my resulting fieldnames? Did I miss something in > the docs? Judging from >>> import csv >>> sniffer = csv.Sniffer() >>> sniffer.sniff("abc").delimiter 'c' >>> sniffer.sniff("abc\naba").delimiter 'b' >>> sniffer.sniff("abc\naba\nxyz").delimiter Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/csv.py", line 184, in sniff raise Error, "Could not determine delimiter" _csv.Error: Could not determine delimiter >>> sniffer.sniff("abc\n"*10 + "xyz").delimiter 'c' >>> sniffer.sniff("abc\n"*9 + "xyz").delimiter Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/csv.py", line 184, in sniff raise Error, "Could not determine delimiter" _csv.Error: Could not determine delimiter the Sniffer heuristics determines a character that occurs on all of the first 10 lines to be the delimiter. There are of course examples where that doesn't make sense to a human observer... From steve+comp.lang.python at pearwood.info Thu Jul 19 08:08:48 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 12:08:48 GMT Subject: Odd csv column-name truncation with only one column References: Message-ID: <5007f8d0$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 19 Jul 2012 06:21:58 -0500, Tim Chase wrote: > tim at laptop:~/tmp$ python > Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import csv >>>> from cStringIO import StringIO >>>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') s.seek(0) >>>> d = csv.Sniffer().sniff(s.read()) >>>> s.seek(0) >>>> r = csv.DictReader(s, dialect=d) >>>> r.fieldnames > ['Emai', ''] I get the same results for Python 2.6 and 2.7. Curiously, 2.5 returns fieldnames as None. I'm not entirely sure that a single column is legitimate for CSV -- if there's only one column, it is hardly comma-separated, or any other separated for that matter. But perhaps the csv module should raise an exception in that case. I think you've found a weird corner case where the sniffer goes nuts. You should probably report it as a bug: py> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') py> s.seek(0) py> d = csv.Sniffer().sniff(s.read()) py> d.delimiter 'l' py> s = StringIO('Spam\nfoo at example.com\nbar at example.org\n') py> s.seek(0) py> d = csv.Sniffer().sniff(s.read()) py> d.delimiter 'p' py> s = StringIO('Spam\nham\ncheese\n') py> s.seek(0) py> d = csv.Sniffer().sniff(s.read()) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/csv.py", line 184, in sniff raise Error, "Could not determine delimiter" _csv.Error: Could not determine delimiter -- Steven From wrw at mac.com Thu Jul 19 08:22:17 2012 From: wrw at mac.com (William R. Wing (Bill Wing)) Date: Thu, 19 Jul 2012 08:22:17 -0400 Subject: Python Programming expert - adding user In-Reply-To: <1342576735.54186.YahooMailNeo@web193104.mail.sg3.yahoo.com> References: <1342576735.54186.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: On Jul 17, 2012, at 9:58 PM, Maria Hanna Carmela Dionisio wrote: > Im just a student :) > > Our prof gave as a task that we need to make a program using python (for redhat) and c++(for windows) > > Our objective is to make a program file and we will said it remotely to another computer via network ( its easy and i could do it lolz).. > > the hard part is the programming..that when the user click the file a box will prompt and ask for username and a password(even without a password) then the username that he inputted will add to the user account of his/her computer :DD > > HELP HELP EXPERTSSSSSSSSSSSSSS > > THANKS :D > -- > http://mail.python.org/mailman/listinfo/python-list I'm sorry if I'm not understanding exactly what your professor wants, I think he is asking you to add a new user to the list of possible users of the computer - that is, add a new user account. If so, then the answer is pretty simple, since Linux (Red Hat) has a "useradd" command that you just have to supply inputs to. Your python program will start by importing "subprocess" and then using it to spawn a child process in which the useradd command will run. Read the subprocess documentation here: http://docs.python.org/library/subprocess.html?highlight=subprocess#subprocess and see if this, plus the man page for useradd, doesn't get you going. -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Jul 19 08:59:56 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Jul 2012 12:59:56 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> Message-ID: <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 18 Jul 2012 23:09:13 -0700, rusi wrote: > Its not so much a question of language as in programming as language as > in layman-speak. > One characteristic with our field is that we take ordinary words and > then distort them so much the original meaning is completely lost. All technical fields have jargon. Those jargon terms are often more precise than the ordinary terms they are derived from, or have a slightly different meaning, or both. This is not unique to programming, nor is it anything to be disturbed by. Words change. What matters is whether the new meanings cause confusion or clarity. > Take 'computer' for example. For Turing a computer was a mathematician > doing a computation with a pen and paper. He then showed how to > de-skill the mathematician so much that a machine could do what he was > doing. In trying that he also hit upon the limits of such 'de-skilling' > -- human-computers routinely detect infinite loops, whereas > machine-computers can never do so (in full generality). Do they really? I doubt that. Human-computers *sometimes* detect infinite loops, but there's no evidence that they can detect ?-loops in full generality, or even that they are better at it than electrical computers. In fact, the sheer number of accidental ?-loops programmed by human beings suggests that people *cannot* routinely detect them, at least not without special training, and even then not *routinely*. Generally people detect ?-loops with an extremely simple-minded heuristic: "if the loop hasn't finished by now, it will never finish". The fact that we don't, as a general rule, program our computers to detect ?-loops does not mean that they cannot do so at least as well as humans, and probably better, when we bother to program them to. For example, both ML and Haskell can, under some circumstances, report a type-error for an infinite loop, *at compile time*. http://static.usenix.org/publications/library/proceedings/vhll/full_papers/koenig.a If you think that people can routinely detect infinite loops, then perhaps you would care to tell me whether this is an infinite loop or not: i = 1 while not is_perfect(i): i += 2 print "odd perfect number discovered" where is_perfect() returns True if the integer argument is perfect, and False otherwise. http://mathworld.wolfram.com/PerfectNumber.html http://mathworld.wolfram.com/OddPerfectNumber.html [...] > 'Object' (and OO) are similar messes. > > In layman-speak and object is well, a thing. Define "thing". Is a cloud a thing? What about a fog bank? An ocean? A desert? The atmosphere? Is the paint on your car a thing? I have an axe that has been passed down for generations through my family, from my father, his father before him, and his father, and his father before him. Occasionally we replace the handle, or put on a new head, but that axe is almost as good as the day my great-great- grandfather made it. Is that axe a thing? Just because laymen toss around a word, doesn't mean that it is a well- defined, meaningful word. > When it doesn't the success is poorer. eg a programmer writing math > software in/on a OO system may for example 'clone' a matrix. This may > be good science-fiction; its bad math. In what way is it bad maths? > And one of the most pervasive (and stupidist) metaphors is the parent- > child relation of classes. > Just for the record, in the normal world 'creatures/beings' reproduce > and therefore inherit. Incorrect. In the normal world, "inherit" is used for at least four senses: 1) to inherit wealth, property, a title, debts etc. from an ancestor upon their death; 2) to receive or take by birth, to have by nature, physical or mental qualities, e.g. "he inherited his tendency to melancholy from his father"; 3) to come into possession of, e.g. "the meek shall inherit the earth"; 4) to receive from a predecessor, e.g. "the Prime Minister has inherited an economy in dire straits". It is clear that the sense of inheritance used in OO programming is sense #2, to have by nature. > Objects dont. Irrelevant. -- Steven From python.list at tim.thechases.com Thu Jul 19 09:04:55 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 08:04:55 -0500 Subject: Odd csv column-name truncation with only one column In-Reply-To: <5007EDD6.5020903@tim.thechases.com> References: <5007EDD6.5020903@tim.thechases.com> Message-ID: <500805F7.3060406@tim.thechases.com> On 07/19/12 06:21, Tim Chase wrote: > tim at laptop:~/tmp$ python > Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import csv >>>> from cStringIO import StringIO >>>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') >>>> s.seek(0) >>>> d = csv.Sniffer().sniff(s.read()) >>>> s.seek(0) >>>> r = csv.DictReader(s, dialect=d) >>>> r.fieldnames > ['Emai', ''] I think I may have stumbled across the "what the heck is happening" factor: >>> import csv >>> from cStringIO import StringIO >>> s = StringIO('Email\nfoo at example.org\nbar at test.test\n') >>> d = csv.Sniffer().sniff(s.read()) >>> s.seek(0) >>> r = csv.DictReader(s, dialect=d) >>> r.fieldnames ['Em', 'il'] It appears that it's finding something repeated [ed: Peter's & Steven's replies came in as I finished typing this]. In my first, it was the "l" appearing on each line, and in the 2nd example here, it's the "a" on each line, so the csv module thinks that's the delimiter. The source file comes from an Excel-dialect generation: >>> s = StringIO() >>> w = csv.writer(s) >>> w.writerows([["email"], ["foo at example.com"], ["bar at example.org"]]) >>> s.seek(0) >>> d = csv.Sniffer().sniff(s.read()) >>> d.delimiter 'l' >>> s.seek(0) >>> r = csv.DictReader(s, dialect=d) >>> r.fieldnames ['emai', ''] I guess it then takes the Python community to make the call on whether the csv module is doing the right thing in the degenerate case. I.e., you can't get back out what you put in when you try to sniff. -tkc From roy at panix.com Thu Jul 19 09:06:45 2012 From: roy at panix.com (Roy Smith) Date: Thu, 19 Jul 2012 09:06:45 -0400 Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <500804cc$0$29978$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Wed, 18 Jul 2012 23:09:13 -0700, rusi wrote: > > > Its not so much a question of language as in programming as language as > > in layman-speak. > > One characteristic with our field is that we take ordinary words and > > then distort them so much the original meaning is completely lost. > > All technical fields have jargon. Those jargon terms are often more > precise than the ordinary terms they are derived from, or have a slightly > different meaning, or both. Heh. This reminds me of one of my current pet peeves. I've run across documentation for more than one Python project (django is the one that comes to mind, but I'm sure there's others) which misuse words like "set" and "list". They're often used in the generic sense of "a collection of things", but they're also the names of specific Python data types. It can sometimes get confusing trying to figure out which meaning they intended. From hansmu at xs4all.nl Thu Jul 19 09:52:12 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 19 Jul 2012 15:52:12 +0200 Subject: Odd csv column-name truncation with only one column In-Reply-To: References: Message-ID: <5008110d$0$6865$e4fe514c@news2.news.xs4all.nl> On 19/07/12 13:21:58, Tim Chase wrote: > tim at laptop:~/tmp$ python > Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) > [GCC 4.4.5] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import csv >>>> from cStringIO import StringIO >>>> s = StringIO('Email\nfoo at example.com\nbar at example.org\n') >>>> s.seek(0) >>>> d = csv.Sniffer().sniff(s.read()) >>>> s.seek(0) >>>> r = csv.DictReader(s, dialect=d) >>>> r.fieldnames > ['Emai', ''] > > I get the same results using Python 3.1.3 (also readily available on > Debian Stable), as well as working directly on a file rather than a > StringIO. > > Any reason I'm getting ['Emai', ''] (note the missing ell) instead > of ['Email'] as my resulting fieldnames? Did I miss something in > the docs? The sniffer tries to guess the column separator. If none of the usual suspects seems to work, it tries to find a character that occurs with the same frequency in every row. In your sample, the letter 'l' occurs exactly once on each line, so it is the most plausible separator, or so the Sniffer thinks. Perhaps it should be documented that the Sniffer doesn't work on single-column data. If you really need to read a one-column csv file, you'll have to find some other way to produce a Dialect object. Perhaps the predefined 'cvs.excel' dialect matches your data. If not, the easiest way might be to manually define a csv.Dialect subclass. Hope this helps, -- HansM From ndbecker2 at gmail.com Thu Jul 19 10:22:12 2012 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 19 Jul 2012 10:22:12 -0400 Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> Message-ID: Google the video "Go fuck yourself" From steveo at syslang.net Thu Jul 19 10:22:35 2012 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 19 Jul 2012 10:22:35 -0400 Subject: Use of compile flags in regular expressions. Message-ID: <5008182B.9030007@syslang.net> I have a problem that I'm solving using a regex. (Yeah, I know, now I have two problems...) ;-)> Anyways, the regex is about a couple of pages long and it works just peachy. There's just one thing I'd like to do to make it more elegant. I need to compile the regex with MULTILINE and DOTALL. But there are a few sections where I wish it was *not* compiled with DOTALL. For those cases, I use (something like) [^\n]* instead of .* I see that I can use the (?MS) construct but I also see that it applies globally and not to the subgroup that I'm using it in. * Is there a way to make it apply locally to a subgroup? * If not, is there another way? * Also, is this an incredible stroke of genius that I came up with this idea of applying flags to a subgroup, or have others thought of this too and found out that it's not really a good idea? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From msarro at gmail.com Thu Jul 19 10:27:02 2012 From: msarro at gmail.com (Matty Sarro) Date: Thu, 19 Jul 2012 10:27:02 -0400 Subject: Google the video "9/11 Missing Links". 9/11 was a Jew Job! In-Reply-To: References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> Message-ID: I must be a Jew or a traitor as I keep deleting this email. Seriously guys, don't reply to it, it's not worth the time. On Thu, Jul 19, 2012 at 10:22 AM, Neal Becker wrote: > Google the video "Go fuck yourself" > > -- > http://mail.python.org/mailman/listinfo/python-list From dihedral88888 at googlemail.com Thu Jul 19 11:08:49 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 19 Jul 2012 08:08:49 -0700 (PDT) Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: <49ac83ef-9d3d-4410-9dde-37496c467bcf@googlegroups.com> andrea crotti? 2012?7?19????UTC+8??6?15?11???? > We need to be able to reload code on a live system. This live system > has a daemon process always running but it runs many subprocesses with > multiprocessing, and the subprocesses might have a short life... > > Now I found a way to reload the code successfully, as you can see from > this testcase: > > > def func(): > from . import a > print(a.ret()) > > > class TestMultiProc(unittest.TestCase): > def setUp(self): > open(path.join(cur_dir, 'a.py'), 'w').write(old_a) > > def tearDown(self): > remove(path.join(cur_dir, 'a.py')) > > def test_reloading(self): > """Starting a new process gives a different result > """ > p1 = Process(target=func) > p2 = Process(target=func) > p1.start() > res = p1.join() > open(path.join(cur_dir, 'a.py'), 'w').write(new_a) > remove(path.join(cur_dir, 'a.pyc')) > > p2.start() > res = p2.join() > > > As long as I import the code in the function and make sure to remove the > "pyc" files everything seems to work.. > Are there any possible problems which I'm not seeing in this approach or > it's safe? > > Any other better ways otherwise? If a byte code interpreter is embedded in the executable, then the program can obtain or reload code objects in the run time. In C/C++, unless one can swap some DLL safely or spawn in another process with new executables obtained from other places, or a script interpreter is embedded, otherwise it's not easy for an instance in C/C++ to get new methods dynamically. or From dihedral88888 at googlemail.com Thu Jul 19 11:08:49 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 19 Jul 2012 08:08:49 -0700 (PDT) Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: <49ac83ef-9d3d-4410-9dde-37496c467bcf@googlegroups.com> andrea crotti? 2012?7?19????UTC+8??6?15?11???? > We need to be able to reload code on a live system. This live system > has a daemon process always running but it runs many subprocesses with > multiprocessing, and the subprocesses might have a short life... > > Now I found a way to reload the code successfully, as you can see from > this testcase: > > > def func(): > from . import a > print(a.ret()) > > > class TestMultiProc(unittest.TestCase): > def setUp(self): > open(path.join(cur_dir, 'a.py'), 'w').write(old_a) > > def tearDown(self): > remove(path.join(cur_dir, 'a.py')) > > def test_reloading(self): > """Starting a new process gives a different result > """ > p1 = Process(target=func) > p2 = Process(target=func) > p1.start() > res = p1.join() > open(path.join(cur_dir, 'a.py'), 'w').write(new_a) > remove(path.join(cur_dir, 'a.pyc')) > > p2.start() > res = p2.join() > > > As long as I import the code in the function and make sure to remove the > "pyc" files everything seems to work.. > Are there any possible problems which I'm not seeing in this approach or > it's safe? > > Any other better ways otherwise? If a byte code interpreter is embedded in the executable, then the program can obtain or reload code objects in the run time. In C/C++, unless one can swap some DLL safely or spawn in another process with new executables obtained from other places, or a script interpreter is embedded, otherwise it's not easy for an instance in C/C++ to get new methods dynamically. or From python at mrabarnett.plus.com Thu Jul 19 11:15:33 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jul 2012 16:15:33 +0100 Subject: Use of compile flags in regular expressions. In-Reply-To: <5008182B.9030007@syslang.net> References: <5008182B.9030007@syslang.net> Message-ID: <50082495.5080100@mrabarnett.plus.com> On 19/07/2012 15:22, Steven W. Orr wrote: > I have a problem that I'm solving using a regex. (Yeah, I know, now I have two > problems...) ;-)> > > Anyways, the regex is about a couple of pages long and it works just peachy. > There's just one thing I'd like to do to make it more elegant. > > I need to compile the regex with MULTILINE and DOTALL. But there are a few > sections where I wish it was *not* compiled with DOTALL. For those cases, I > use (something like) > > [^\n]* > > instead of > > .* > > I see that I can use the (?MS) construct but I also see that it applies > globally and not to the subgroup that I'm using it in. > > * Is there a way to make it apply locally to a subgroup? It with the re module. > * If not, is there another way? The DOTALL . could be replaced with, say, [\d\D]. > * Also, is this an incredible stroke of genius that I came up with this idea > of applying flags to a subgroup, or have others thought of this too and found > out that it's not really a good idea? > Many other regex implementations do support scoped flags, including the one here: http://pypi.python.org/pypi/regex which is designed to be backwards-compatible with the re module. From rustompmody at gmail.com Thu Jul 19 11:58:07 2012 From: rustompmody at gmail.com (rusi) Date: Thu, 19 Jul 2012 08:58:07 -0700 (PDT) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> Message-ID: On Jul 19, 1:56?pm, Lipska the Kat wrote: > Academic twiddling with the distorted meaning of words spun by > vested interests is all very interesting I'm sure but doesn't really > advance the discussion does it? Well lets back up the discussion a bit. You coming from a Java background have one view of what OO means. Others coming from a python background have a different view. In particular you said: > Python looks like an interesting language and I will certainly spend > time getting to know it but at the moment it seems to me that calling it > an Object Oriented language is just plain misleading. > On 19/07/12 07:09, rusi wrote: > > In layman-speak and object is well, a thing. > > But we are not talking in 'layman-speak' we are discussing concepts that > are familiar to us in the 'language of the domain' at least I though we > were. > > And one of the most pervasive (and stupidist) metaphors is the parent- > > child relation of classes. > > Just for the record, in the normal world 'creatures/beings' reproduce > > and therefore inherit. > > But we are not talking about the 'real world' are we, we are talking > about representing complex interacting human concepts in a way that can > be understood by humans and translated into a form that can be executed > on a binary machine So when multiple technical understandings are in conflict it seems reasonable to find a frame in which the different viewpoints could resolve. The ultimate such frame is the completely de-jargonized frame ie laymanspeak. [How far one can/should go toward that ultimate is another quesion] From zdoor at xs4all.nl Thu Jul 19 12:43:27 2012 From: zdoor at xs4all.nl (Alex van der Spek) Date: Thu, 19 Jul 2012 18:43:27 +0200 Subject: shutil ignore fails on passing a tuple? Message-ID: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> This beats me: ++++++++++++++++++++ >>> ipatterns ('*.txt', '*.hdf', '*.pdf', '*.png') >>> igf = shutil.ignore_patterns(ipatterns) >>> ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) Traceback (most recent call last): File "", line 1, in ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) File "C:\Python27\lib\shutil.py", line 138, in _ignore_patterns ignored_names.extend(fnmatch.filter(names, pattern)) File "C:\Python27\lib\fnmatch.py", line 49, in filter pat=os.path.normcase(pat) File "C:\Python27\lib\ntpath.py", line 46, in normcase return s.replace("/", "\\").lower() AttributeError: 'tuple' object has no attribute 'replace' >>> igg = shutil.ignore_patterns('*.txt', '*.hdf', '*.pdf', '*.png') >>> ignorethat = igg(ddftopdir, os.listdir(ddftopdir)) >>> ignorethat set(['Chi2.png', 'DTSdata.hdf', 'TST.hdf', 'BullNoseDiffs.png', 'DTSall.hdf', 'Symmetry.pdf']) >>> ++++++++++++++++++++++++++++ Why does it fail on passing in a tuple of ignore strings? I thought the , (comma) is pretty much the tuple constructor (if that is the right word). How can I solve this? Is there a way to convert a tuple of strings in a form that will be accepted? Thank you in advance, Alex van der Spek From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Jul 19 12:52:44 2012 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 19 Jul 2012 16:52:44 +0000 (UTC) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <-OKdnclIyZIjUZvNnZ2dnUVZ8k-dnZ2d@bt.com> <50075f7b$0$1756$c3e8da3$76491128@news.astraweb.com> Message-ID: MRAB wrote: > """Thus spake the Lord: Thou shalt indent with four spaces. No > more, no less. > Four shall be the number of spaces thou shalt indent, and the > number of thy indenting shall be four. Eight shalt thou not indent, > nor either indent thou > two, excepting that thou then proceed to four. Tabs are right > out.""" > -- Georg Brandl Yes, and the Lord was Wrong. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From ramit.prasad at jpmorgan.com Thu Jul 19 12:52:54 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 19 Jul 2012 16:52:54 +0000 Subject: shutil ignore fails on passing a tuple? In-Reply-To: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> References: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416581425@SCACMX008.exchad.jpmchase.net> > >>> ipatterns > ('*.txt', '*.hdf', '*.pdf', '*.png') > >>> igf = shutil.ignore_patterns(ipatterns) > >>> ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) > > Traceback (most recent call last): > File "", line 1, in > ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) > File "C:\Python27\lib\shutil.py", line 138, in _ignore_patterns > ignored_names.extend(fnmatch.filter(names, pattern)) > File "C:\Python27\lib\fnmatch.py", line 49, in filter > pat=os.path.normcase(pat) > File "C:\Python27\lib\ntpath.py", line 46, in normcase > return s.replace("/", "\\").lower() > AttributeError: 'tuple' object has no attribute 'replace' > > >>> igg = shutil.ignore_patterns('*.txt', '*.hdf', '*.pdf', '*.png') > >>> ignorethat = igg(ddftopdir, os.listdir(ddftopdir)) > >>> ignorethat > set(['Chi2.png', 'DTSdata.hdf', 'TST.hdf', 'BullNoseDiffs.png', > 'DTSall.hdf', 'Symmetry.pdf']) > >>> > ++++++++++++++++++++++++++++ > Why does it fail on passing in a tuple of ignore strings? I thought the , > (comma) is pretty much the tuple constructor (if that is the right word). > > How can I solve this? Is there a way to convert a tuple of strings in a form > that will be accepted? > Untested, but I think it should work. igf = shutil.ignore_patterns(*ipatterns) Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From joel.goldstick at gmail.com Thu Jul 19 12:55:17 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 19 Jul 2012 12:55:17 -0400 Subject: shutil ignore fails on passing a tuple? In-Reply-To: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> References: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> Message-ID: On Thu, Jul 19, 2012 at 12:43 PM, Alex van der Spek wrote: > This beats me: > ++++++++++++++++++++ >>>> >>>> ipatterns > > ('*.txt', '*.hdf', '*.pdf', '*.png') >>>> >>>> igf = shutil.ignore_patterns(ipatterns) >>>> ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) > > > Traceback (most recent call last): > File "", line 1, in > ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) > File "C:\Python27\lib\shutil.py", line 138, in _ignore_patterns > ignored_names.extend(fnmatch.filter(names, pattern)) > File "C:\Python27\lib\fnmatch.py", line 49, in filter > pat=os.path.normcase(pat) > File "C:\Python27\lib\ntpath.py", line 46, in normcase > return s.replace("/", "\\").lower() > AttributeError: 'tuple' object has no attribute 'replace' What is s? It needs to be a string. If s is a tuple with string values, you will have to iterate over each to replace. Or I believe you could use map. > >>>> igg = shutil.ignore_patterns('*.txt', '*.hdf', '*.pdf', '*.png') >>>> ignorethat = igg(ddftopdir, os.listdir(ddftopdir)) >>>> ignorethat > > set(['Chi2.png', 'DTSdata.hdf', 'TST.hdf', 'BullNoseDiffs.png', > 'DTSall.hdf', 'Symmetry.pdf']) >>>> >>>> > ++++++++++++++++++++++++++++ > Why does it fail on passing in a tuple of ignore strings? I thought the , > (comma) is pretty much the tuple constructor (if that is the right word). > > How can I solve this? Is there a way to convert a tuple of strings in a form > that will be accepted? > > Thank you in advance, > Alex van der Spek > > > -- > http://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick From paul.nospam at rudin.co.uk Thu Jul 19 13:22:15 2012 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 19 Jul 2012 18:22:15 +0100 Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <871uk7acoo.fsf@no-fixed-abode.cable.virginmedia.net> Steven D'Aprano writes: > For example, both ML and Haskell can, under some circumstances, report a > type-error for an infinite loop, *at compile time*. ... and in Charity all programs are guaranteed to terminate. Of course it's not Turing complete. From python.list at tim.thechases.com Thu Jul 19 14:01:37 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 13:01:37 -0500 Subject: Odd csv column-name truncation with only one column In-Reply-To: <5008110d$0$6865$e4fe514c@news2.news.xs4all.nl> References: <5008110d$0$6865$e4fe514c@news2.news.xs4all.nl> Message-ID: <50084B81.50909@tim.thechases.com> On 07/19/12 08:52, Hans Mulder wrote: > Perhaps it should be documented that the Sniffer doesn't work > on single-column data. I think this would involve the least change in existing code, and go a long way towards removing my surprise. :-) > If you really need to read a one-column csv file, you'll have > to find some other way to produce a Dialect object. Perhaps the > predefined 'cvs.excel' dialect matches your data. If not, the > easiest way might be to manually define a csv.Dialect subclass. The problem I'm trying to solve is "here's a filename that might be comma/pipe/tab delimited, it has an 'email' column at minimum, and perhaps a couple others of interest if they were included" It's improbable that it's ONLY an email column, but my tests happened to snag this edge case. I can likely do my own sniffing by reading the first line, checking for tabs then pipes then commas (perhaps biasing the order based on the file-extension of .csv vs. .txt), and then building my own dialect information to pass to csv.DictReader It just seems unfortunate that the sniffer would ever consider [a-zA-Z0-9] as a valid delimiter. -tkc From python.list at tim.thechases.com Thu Jul 19 14:20:28 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 13:20:28 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50084FEC.7040806@tim.thechases.com> > If you think that people can routinely detect infinite loops, then > perhaps you would care to tell me whether this is an infinite loop or not: > > i = 1 > while not is_perfect(i): > i += 2 > print "odd perfect number discovered" > > > where is_perfect() returns True if the integer argument is perfect, and > False otherwise. Sure it terminates...If you don't run out of RAM to represent the number "i" in question, there's also this "heat death of the universe" limit I keep hearing about ;-) -tkc From rosuav at gmail.com Thu Jul 19 14:28:50 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 20 Jul 2012 04:28:50 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <50084FEC.7040806@tim.thechases.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: On Fri, Jul 20, 2012 at 4:20 AM, Tim Chase wrote: > Sure it terminates...If you don't run out of RAM to represent the > number "i" in question, there's also this "heat death of the > universe" limit I keep hearing about ;-) I'd be more worried about the heat death of your computer, it's likely to be sooner. How many people have access to a computer that'll still be running in ten years, much less a thousand? And while a thousand years is extremely large, it still falls pitifully short of infinity[1], or even the heat death of the universe. ChrisA [1] http://tools.ietf.org/html/rfc2795 From python.list at tim.thechases.com Thu Jul 19 14:50:36 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 13:50:36 -0500 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: <500856FC.9010806@tim.thechases.com> On 07/19/12 13:28, Chris Angelico wrote: > On Fri, Jul 20, 2012 at 4:20 AM, Tim Chase > wrote: >> Sure it terminates...If you don't run out of RAM to represent the >> number "i" in question, there's also this "heat death of the >> universe" limit I keep hearing about ;-) > > I'd be more worried about the heat death of your computer, it's likely > to be sooner. How many people have access to a computer that'll still > be running in ten years, much less a thousand? Just putting a maximum bound on the problem, providing a time-frame in which I can be fairly certain that the program will have terminated. :-) -tkc From larry.martell at gmail.com Thu Jul 19 14:52:09 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 11:52:09 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> Message-ID: <8d08181d-316d-4fdc-8f03-1d9b90929d89@e7g2000yqh.googlegroups.com> On Jul 18, 4:49?pm, Paul Rubin wrote: > "Larry.Mart... at gmail.com" writes: > > I have an interesting problem I'm trying to solve. I have a solution > > almost working, but it's super ugly, and know there has to be a > > better, cleaner way to do it. ... > > > My solution involves multiple maps and multiple iterations through the > > data. How would you folks do this? > > You could post your code and ask for suggestions how to improve it. > There are a lot of not-so-natural constraints in that problem, so it > stands to reason that the code will be a bit messy. ?The whole > specification seems like an antipattern though. ?You should just give a > sensible encoding for the filename regardless of whether other fields > are duplicated or not. ?You also don't seem to address the case where > basename, dir4, and dir5 are all duplicated. > > The approach I'd take for the spec as you wrote it is: > > 1. Sort the list on the (basename, dir4, dir5) triple, saving original > ? ?location (numeric index) of each item > 2. Use itertools.groupby to group together duplicate basenames. > 3. Within the groups, use groupby again to gather duplicate dir4's, > 4. Within -those- groups, group by dir5 and assign sequence numbers in > ? ?groups where there's more than one file > 5. Unsort to get the rewritten items back into the original order. > > Actual code is left as an exercise. Thanks very much for the reply Paul. I did not know about itertools. This seems like it will be perfect for me. But I'm having 1 issue, how do I know how many of a given basename (and similarly how many basename/dir4s) there are? I don't know that I have to modify a file until I've passed it, so I have to do all kinds of contortions to save the previous one, and deal with the last one after I fall out of the loop, and it's getting very nasty. reports_list is the list sorted on basename, dir4, dir5 (tool is dir4, file_date is dir5): for file, file_group in groupby(reports_list, lambda x: x[0]): # if file is unique in file_group do nothing, but how can I tell if file is unique? for tool, tool_group in groupby(file_group, lambda x: x[1]): # if tool is unique for file, change file to tool_file, but how can I tell if tool is unique for file? for file_date, file_date_group in groupby(tool_group, lambda x: x[2]): You can't do a len on the iterator that is returned from groupby, and I've tried to do something with imap or defaultdict, but I'm not getting anywhere. I guess I can just make 2 passes through the data, the first time getting counts. Or am I missing something about how groupby works? Thanks! -larry From larry.martell at gmail.com Thu Jul 19 14:54:56 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 11:54:56 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: Message-ID: On Jul 18, 6:36?pm, Simon Cropper wrote: > On 19/07/12 08:20, Larry.Mart... at gmail.com wrote: > > > > > > > > > > > I have an interesting problem I'm trying to solve. I have a solution > > almost working, but it's super ugly, and know there has to be a > > better, cleaner way to do it. > > > I have a list of path names that have this form: > > > /dir0/dir1/dir2/dir3/dir4/dir5/dir6/file > > > I need to find all the file names (basenames) in the list that are > > duplicates, and for each one that is a dup, prepend dir4 to the > > filename as long as the dir4/file pair is unique. If there are > > multiple dir4/files in the list, then I also need to add a sequence > > number based on the sorted value of dir5 (which is a date in ddMONyy > > format). > > > For example, if my list contains: > > > /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3 > > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1 > > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 > > /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1 > > /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3 > > > Then I want to end up with: > > > /dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/qwer_01_file3 > > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/abcd_file1 > > /dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2 > > /dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/xyz_file1 > > /dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/qwer_00_file3 > > > My solution involves multiple maps and multiple iterations through the > > data. How would you folks do this? > > Hi Larry, > > I am making the assumption that you intend to collapse the directory > tree and store each file in the same directory, otherwise I can't think > of why you need to do this. Hi Simon, thanks for the reply. It's not quite this - what I am doing is creating a zip file with relative path names, and if there are duplicate files the parts of the path that are not be carried over need to get prepended to the file names to make then unique, > > If this is the case, then I would... > > 1. import all the files into an array > 2. parse path to extract forth level directory name and base name. > 3. reiterate through the array > ? ? 3.1 check if base filename exists in recipient directory > ? ? 3.2 if not, copy to recipient directory > ? ? 3.3 if present, append the directory path then save > ? ? 3.4 create log of success or failure > > Personally, I would not have some files with abcd_file1 and others as > file2 because if it is important enough to store a file in a separate > directory you should also note where file2 came from as well. When > looking at your results at a later date you are going to have to open > file2 (which I presume must record where it relates to) to figure out > where it came from. If it is in the name it is easier to review. > > In short, consistency is the name of the game; if you are going to do it > for some then do it for all; and finally it will be easier for others > later to work out what you have done. Yeah, I know, but this is for a client, and this is what they want. From larry.martell at gmail.com Thu Jul 19 15:00:46 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 12:00:46 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> Message-ID: <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> On Jul 18, 4:49?pm, Paul Rubin wrote: > "Larry.Mart... at gmail.com" writes: > > I have an interesting problem I'm trying to solve. I have a solution > > almost working, but it's super ugly, and know there has to be a > > better, cleaner way to do it. ... > > > My solution involves multiple maps and multiple iterations through the > > data. How would you folks do this? > > You could post your code and ask for suggestions how to improve it. > There are a lot of not-so-natural constraints in that problem, so it > stands to reason that the code will be a bit messy. ?The whole > specification seems like an antipattern though. ?You should just give a > sensible encoding for the filename regardless of whether other fields > are duplicated or not. ?You also don't seem to address the case where > basename, dir4, and dir5 are all duplicated. > > The approach I'd take for the spec as you wrote it is: > > 1. Sort the list on the (basename, dir4, dir5) triple, saving original > ? ?location (numeric index) of each item > 2. Use itertools.groupby to group together duplicate basenames. > 3. Within the groups, use groupby again to gather duplicate dir4's, > 4. Within -those- groups, group by dir5 and assign sequence numbers in > ? ?groups where there's more than one file > 5. Unsort to get the rewritten items back into the original order. > > Actual code is left as an exercise. I replied to this before, but I don't see, so if this is a duplicate, sorry. Thanks for the reply Paul. I had not heard of itertools. It sounds like just what I need for this. But I am having 1 issue - how do you know how many items are in each group? Without knowing that I have to either make 2 passes through the data, or else work on the previous item (when I'm in an iteration after the first then I know I have dups). But that very quickly gets crazy with trying to keep the previous values. From ramit.prasad at jpmorgan.com Thu Jul 19 15:02:37 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 19 Jul 2012 19:02:37 +0000 Subject: Finding duplicate file names and modifying them based on elements of the path In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47416582964@SCACMX008.exchad.jpmchase.net> > > I am making the assumption that you intend to collapse the directory > > tree and store each file in the same directory, otherwise I can't think > > of why you need to do this. > > Hi Simon, thanks for the reply. It's not quite this - what I am doing > is creating a zip file with relative path names, and if there are > duplicate files the parts of the path that are not be carried over > need to get prepended to the file names to make then unique, Depending on the file system of the client, you can hit file name length limits. I would think it would be better to just create the full structure in the zip. Just something to keep in mind, especially if you see funky behavior. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From larry.martell at gmail.com Thu Jul 19 15:06:20 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 12:06:20 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: Message-ID: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> On Jul 19, 1:02?pm, "Prasad, Ramit" wrote: > > > I am making the assumption that you intend to collapse the directory > > > tree and store each file in the same directory, otherwise I can't think > > > of why you need to do this. > > > Hi Simon, thanks for the reply. It's not quite this - what I am doing > > is creating a zip file with relative path names, and if there are > > duplicate files the parts of the path that are not be carried over > > need to get prepended to the file names to make then unique, > > Depending on the file system of the client, you can hit file name > length limits. I would think it would be better to just create > the full structure in the zip. > > Just something to keep in mind, especially if you see funky behavior. Thanks, but it's not what the client wants. From d at davea.name Thu Jul 19 15:20:35 2012 From: d at davea.name (Dave Angel) Date: Thu, 19 Jul 2012 15:20:35 -0400 Subject: shutil ignore fails on passing a tuple? In-Reply-To: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> References: <50083935$0$6851$e4fe514c@news2.news.xs4all.nl> Message-ID: <50085E03.8090901@davea.name> On 07/19/2012 12:43 PM, Alex van der Spek wrote: > This beats me: > ++++++++++++++++++++ >>>> ipatterns > ('*.txt', '*.hdf', '*.pdf', '*.png') >>>> igf = shutil.ignore_patterns(ipatterns) >>>> ignorethis = igf(ddftopdir,os.listdir(ddftopdir)) > > > Why does it fail on passing in a tuple of ignore strings? I thought > the , (comma) is pretty much the tuple constructor (if that is the > right word). > ignore_patterns() is not looking for a tuple, it's looking for one or more strings, as separate arguments. If you already have the tuple, you can expand it by using the asterisk, as Prasad ha pointed out. igf = shutil.ignore_patterns(*ipatterns) -- DaveA From no.email at nospam.invalid Thu Jul 19 15:43:03 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 19 Jul 2012 12:43:03 -0700 Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> Message-ID: <7xipdjilko.fsf@ruckus.brouhaha.com> "Larry.Martell at gmail.com" writes: > Thanks for the reply Paul. I had not heard of itertools. It sounds > like just what I need for this. But I am having 1 issue - how do you > know how many items are in each group? Simplest is: for key, group in groupby(xs, lambda x:(x[-1],x[4],x[5])): gs = list(group) # convert iterator to a list n = len(gs) # this is the number of elements there is some theoretical inelegance in that it requires each group to fit in memory, but you weren't really going to have billions of files with the same basename. If you're not used to iterators and itertools, note there are some subtleties to using groupby to iterate over files, because an iterator actually has state. It bumps a pointer and maybe consumes some input every time you advance it. In a situation like the above, you've got some nexted iterators (the groupby iterator generating groups, and the individual group iterators that come out of the groupby) that wrap the same file handle, so bad confusion can result if you advance both iterators without being careful (one can consume file input that you thought would go to another). This isn't as bad as it sounds once you get used to it, but it can be a source of frustration at first. BTW, if you just want to count the elements of an iterator (while consuming it), n = sum(1 for x in xs) counts the elements of xs without having to expand it into an in-memory list. Itertools really makes Python feel a lot more expressive and clean, despite little kinks like the above. From eric.frederich at gmail.com Thu Jul 19 15:51:33 2012 From: eric.frederich at gmail.com (Eric Frederich) Date: Thu, 19 Jul 2012 15:51:33 -0400 Subject: properly catch SIGTERM Message-ID: So I wrote a script which acts like a daemon. And it starts with something like this.... ########### Begin Code import signal STOPIT = False def my_SIGTERM_handler(signum, frame): global STOPIT print '\n--- Caught SIGTERM; Attempting to quit gracefully ---' STOPIT = True signal.signal(signal.SIGTERM, my_SIGTERM_handler) signal.signal(signal.SIGINT , my_SIGTERM_handler) ########### End Code My main loop looks something like this... login() while not STOPIT: foo1() foo2() foo3() if STOPIT: break bar1() bar2() bar3() print 'bye' logout() This seems to work okay but just now I got this while hitting ctrl-c It seems to have caught the signal at or in the middle of a call to sys.stdout.flush() --- Caught SIGTERM; Attempting to quit gracefully --- Traceback (most recent call last): File "/home/user/test.py", line 125, in sys.stdout.flush() IOError: [Errno 4] Interrupted system call How should I fix this? Am I doing this completely wrong? Thanks, ~Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at nospam.invalid Thu Jul 19 15:56:32 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Thu, 19 Jul 2012 12:56:32 -0700 Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <8d08181d-316d-4fdc-8f03-1d9b90929d89@e7g2000yqh.googlegroups.com> Message-ID: <7xipdjbk3z.fsf@ruckus.brouhaha.com> "Larry.Martell at gmail.com" writes: > You can't do a len on the iterator that is returned from groupby, and > I've tried to do something with imap or defaultdict, but I'm not > getting anywhere. I guess I can just make 2 passes through the data, > the first time getting counts. Or am I missing something about how > groupby works? I posted another reply to your other message, which reached me earlier. If you're still stuck, post again, though I probably won't be able to reply til tomorrow or the next day. From zdoor at xs4all.nl Thu Jul 19 16:06:32 2012 From: zdoor at xs4all.nl (Alex van der Spek) Date: Thu, 19 Jul 2012 22:06:32 +0200 Subject: logging time format millisecond precision Message-ID: <500868cd$0$6864$e4fe514c@news2.news.xs4all.nl> I use this formatter in logging: formatter = logging.Formatter(fmt='%(asctime)s \t %(name)s \t %(levelname)s \t %(message)s') Sample output: 2012-07-19 21:34:58,382 root INFO Removed - C:\Users\ZDoor\Documents The time stamp has millisecond precision but the decimal separator is a comma. Can I change the comma (,) into a period (.) and if so how? Thanks in advance, Alex van der Spek From gokoproject at gmail.com Thu Jul 19 16:34:31 2012 From: gokoproject at gmail.com (John Wong) Date: Thu, 19 Jul 2012 16:34:31 -0400 Subject: Let child process to run while parent is out (multiprocessing) Message-ID: def main(...): build_id = create_build_id(...) build_stuff return build_id Suppose build_stuff compiles a C program. It could take days to finish, and notify users their builds are ready. I was thinking about using mutliprocessing to handle the build_stuff. So here is a sample: #!/usr/bin/python import multiprocessing as mp import time def build(): print 'I am building HUGE things' time.sleep(10) def main(): build_p = mp.Process(name='build process', target=build) build_p.start() return 'abcd12345' if __name__ == '__main__': v = main() print v print 'done' Here is output: yeukhon at fermat:~$ python c2.py abcd12345 done [now hangs for 10 seconds] I build things When I looked at `ps -elf|grep python`, I can see two processes running, and one of the python c2.py process is `wait`. But this is not ideal, especially this is a web app. I can't implement any advanced queue / event system right now (I use Pylon, I believe I have gevent installed). But just with multiprocessing, is it possible to send the id first, while running child in the backgroud? Right now it hangs there as long as the child process is alive. Any solutions? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gordon at panix.com Thu Jul 19 17:01:10 2012 From: gordon at panix.com (John Gordon) Date: Thu, 19 Jul 2012 21:01:10 +0000 (UTC) Subject: Encapsulation, inheritance and polymorphism References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: In Dennis Lee Bieber writes: > > Sure it terminates...If you don't run out of RAM to represent the > > number "i" in question, there's also this "heat death of the > > universe" limit I keep hearing about ;-) > > > Since the current evidence indicates the universe will just keep > expanding, it's more of a "deep freeze death..." Heat death means *lack* of heat. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From ian.g.kelly at gmail.com Thu Jul 19 17:13:37 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 19 Jul 2012 15:13:37 -0600 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: On Thu, Jul 19, 2012 at 3:01 PM, John Gordon wrote: > In Dennis Lee Bieber writes: > >> > Sure it terminates...If you don't run out of RAM to represent the >> > number "i" in question, there's also this "heat death of the >> > universe" limit I keep hearing about ;-) >> > >> Since the current evidence indicates the universe will just keep >> expanding, it's more of a "deep freeze death..." > > Heat death means *lack* of heat. Actually actually it means *uniformity* of heat, i.e. that the entire universe is in thermodynamic equilibrium and so it is impossible to perform work. So heat death is expected regardless of whether the universe ultimately collapses or expands indefinitely. From jeanpierreda at gmail.com Thu Jul 19 17:30:52 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 19 Jul 2012 17:30:52 -0400 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: On Thu, Jul 19, 2012 at 5:01 PM, John Gordon wrote: >> Since the current evidence indicates the universe will just keep >> expanding, it's more of a "deep freeze death..." > > Heat death means *lack* of heat. But it doesn't mean low temperature! The term is agnostic as to what the temperature of the universe will be. -- Devin From python at mrabarnett.plus.com Thu Jul 19 17:32:46 2012 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 19 Jul 2012 22:32:46 +0100 Subject: Finding duplicate file names and modifying them based on elements of the path In-Reply-To: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> References: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> Message-ID: <50087CFE.4050608@mrabarnett.plus.com> On 19/07/2012 20:06, Larry.Martell at gmail.com wrote: > On Jul 19, 1:02 pm, "Prasad, Ramit" wrote: >> > > I am making the assumption that you intend to collapse the directory >> > > tree and store each file in the same directory, otherwise I can't think >> > > of why you need to do this. >> >> > Hi Simon, thanks for the reply. It's not quite this - what I am doing >> > is creating a zip file with relative path names, and if there are >> > duplicate files the parts of the path that are not be carried over >> > need to get prepended to the file names to make then unique, >> >> Depending on the file system of the client, you can hit file name >> length limits. I would think it would be better to just create >> the full structure in the zip. >> >> Just something to keep in mind, especially if you see funky behavior. > > Thanks, but it's not what the client wants. > Here's another solution, not using itertools: from collections import defaultdict from os.path import basename, dirname from time import strftime, strptime # Starting with the original paths paths = [ "/dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3", "/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1", "/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2", "/dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1", "/dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3", ] def make_dir5_key(path): date = strptime(path.split("/")[6], "%d%b%y") return strftime("%y%b%d", date) # Collect the paths into a dict keyed by the basename files = defaultdict(list) for path in paths: files[basename(path)].append(path) # Process a list of paths if there's more than one entry renaming = [] for name, entries in files.items(): if len(entries) > 1: # Collect the paths in each subgroup into a dict keyed by dir4 subgroup = defaultdict(list) for path in entries: subgroup[path.split("/")[5]].append(path) for dir4, subentries in subgroup.items(): # Sort the subentries by dir5 (date) subentries.sort(key=make_dir5_key) if len(subentries) > 1: for index, path in enumerate(subentries): renaming.append((path, "{}/{}_{:02}_{}".format(dirname(path), dir4, index, name))) else: path = subentries[0] renaming.append((path, "{}/{}_{}".format(dirname(path), dir4, name))) else: path = entries[0] for old_path, new_path in renaming: print("Rename {!r} to {!r}".format(old_path, new_path)) From rosuav at gmail.com Thu Jul 19 18:20:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 20 Jul 2012 08:20:57 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: On Fri, Jul 20, 2012 at 7:01 AM, John Gordon wrote: > In Dennis Lee Bieber writes: > >> > Sure it terminates...If you don't run out of RAM to represent the >> > number "i" in question, there's also this "heat death of the >> > universe" limit I keep hearing about ;-) >> > >> Since the current evidence indicates the universe will just keep >> expanding, it's more of a "deep freeze death..." > > Heat death means *lack* of heat. The second law of thermodynamics states that energy tends to go from higher states to lower, with heat being the very lowest. It's possible to do work using (say) kinetic energy, and in the process, some of that energy becomes heat. It's also possible to do work with any difference in temperature (eg Stirling engines), so the state of the universe in which it's no longer possible to do any work will be one in which all energy is heat and everything's at the same temperature. That doesn't mean a lack of heat; in fact, it implies that there'll be rather more heat than there now is, because we currently have a whole lot of chemical energy available to be used. But in any case, that's a looooooooong way off... ChrisA From gordon at panix.com Thu Jul 19 18:23:11 2012 From: gordon at panix.com (John Gordon) Date: Thu, 19 Jul 2012 22:23:11 +0000 (UTC) Subject: Encapsulation, inheritance and polymorphism References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: In Chris Angelico writes: > The second law of thermodynamics states that energy tends to go from > higher states to lower, with heat being the very lowest. It's possible > to do work using (say) kinetic energy, and in the process, some of > that energy becomes heat. It's also possible to do work with any > difference in temperature (eg Stirling engines), so the state of the > universe in which it's no longer possible to do any work will be one > in which all energy is heat and everything's at the same temperature. > That doesn't mean a lack of heat; in fact, it implies that there'll be > rather more heat than there now is, because we currently have a whole > lot of chemical energy available to be used. *mind blown* -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From miriam.gomezrs at udlap.mx Thu Jul 19 18:31:57 2012 From: miriam.gomezrs at udlap.mx (Miriam Gomez Rios) Date: Thu, 19 Jul 2012 22:31:57 +0000 Subject: help Message-ID: Hello, sorry for bothering you, but I have a doubt, Is there a way to turn this string into a tuplelist??????, I need it for gurobi ('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),('per1','persona1.1','pro4'),('per1','persona1.1','pro5'),('per2','persona2.1','pro1'),('per2','persona2.1','pro2'),('per2','persona2.1','pro3'),('per2','persona2.1','pro4'),('per2','persona2.1','pro5'),('per2','persona2.2','pro1'),('per2','persona2.2','pro2'),('per2','persona2.2','pro3'),('per2','persona2.2','pro4'),('per2','persona2.2','pro5'),('per2','persona2.3','pro1'),('per2','persona2.3','pro2'),('per2','persona2.3','pro3'),('per2','persona2.3','pro4'),('per2','persona2.3','pro5'),('per2','persona2.4','pro1'),('per2','persona2.4','pro2'),('per2','persona2.4','pro3' the string is made with fors, using data from another file, and I need it as a tuplelist Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Jul 19 19:05:11 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 20 Jul 2012 09:05:11 +1000 Subject: Let child process to run while parent is out (multiprocessing) In-Reply-To: References: Message-ID: On Fri, Jul 20, 2012 at 6:34 AM, John Wong wrote: > Here is output: > yeukhon at fermat:~$ python c2.py > abcd12345 > done [now hangs for 10 seconds] > I build things Side point: I just tried your code on Python 2.6 on Windows, and it produced all three lines of output before waiting the ten seconds. Same in Python 3.3 on Linux (after putting parentheses around the prints, the only 2->3 change needed). Your experience of it delaying the "building" message probably has something to do with output buffering. As to the fundamental, though: I don't know that Python truly supports what you're trying to do. A skim of the docs doesn't show up anything obvious, so I'm hoping that someone else has already tried this and can give an authoritative or empirical answer. ChrisA From benjamin.kaplan at case.edu Thu Jul 19 19:09:03 2012 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 19 Jul 2012 16:09:03 -0700 Subject: help In-Reply-To: References: Message-ID: On Jul 19, 2012 4:04 PM, "Miriam Gomez Rios" wrote: > > Hello, sorry for bothering you, but I have a doubt, > > Is there a way to turn this string into a tuplelist??????, I need it for gurobi > > ('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),('per1','persona1.1','pro4'),('per1','persona1.1','pro5'),('per2','persona2.1','pro1'),('per2','persona2.1','pro2'),('per2','persona2.1','pro3'),('per2','persona2.1','pro4'),('per2','persona2.1','pro5'),('per2','persona2.2','pro1'),('per2','persona2.2','pro2'),('per2','persona2.2','pro3'),('per2','persona2.2','pro4'),('per2','persona2.2','pro5'),('per2','persona2.3','pro1'),('per2','persona2.3','pro2'),('per2','persona2.3','pro3'),('per2','persona2.3','pro4'),('per2','persona2.3','pro5'),('per2','persona2.4','pro1'),('per2','persona2.4','pro2'),('per2','persona2.4','pro3' > > the string is made with fors, using data from another file, and I need it as a tuplelist > > Thank you > > > -- It looks like you can just put brackets around it and call ast.literal_eval. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Thu Jul 19 19:14:33 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 18:14:33 -0500 Subject: help In-Reply-To: References: Message-ID: <500894D9.9020106@tim.thechases.com> On 07/19/12 17:31, Miriam Gomez Rios wrote: > Hello, sorry for bothering you, but I have a doubt, > > Is there a way to turn this string into a tuplelist??????, I > need it for gurobi > > ('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),...,('per2','persona2.4','pro3' Assuming a closing paren, you can safely use ast.literal_eval on the raw string: import ast s = "('per1','persona1.1','pro1'),('per1','persona1.1','pro2')" resulting_tuple_of_tuples = ast.literal_eval(s) -tkc From ramit.prasad at jpmorgan.com Thu Jul 19 19:26:09 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 19 Jul 2012 23:26:09 +0000 Subject: help In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47416582D8D@SCACMX008.exchad.jpmchase.net> >('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),('per1','persona1.1','pro4'),('per1','persona1.1','pro5'),('per2','persona2.1','pro1'),('per2','persona2.1','pro2'),('per2','persona2.1','pro3'),('per2','persona2.1','pro4'),('per2','persona2.1','pro5'),('per2','persona2.2','pro1'),('per2','persona2.2','pro2'),('per2','persona2.2','pro3'),('per2','persona2.2','pro4'),('per2','persona2.2','pro5'),('per2','persona2.3','pro1'),('per2','persona2.3','pro2'),('per2','persona2.3','pro3'),('per2','persona2.3','pro4'),('per2','persona2.3','pro5'),('per2','persona2.4','pro1'),('per2','persona2.4','pro2'),('per2','persona2.4','pro3' You can use ast.literal_eval if you add an enclosing () or [] in the string (and add a finishing paren for the last tuple). >the string is made with fors, using data from another file, and I need it as a tuplelist If you are transferring this data (network/file) you may want to take a look at pickle/json. If you are doing this to convert to/from a CSV then look at the csv module. If you say what are you trying to do and why, someone on the list might be able to recommend a better way to do this. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python.list at tim.thechases.com Thu Jul 19 19:43:31 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 18:43:31 -0500 Subject: help In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47416582D8D@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47416582D8D@SCACMX008.exchad.jpmchase.net> Message-ID: <50089BA3.4020200@tim.thechases.com> On 07/19/12 18:26, Prasad, Ramit wrote: >> ('per1','persona1.1','pro1'),('per1','persona1.1','pro2'),('per1','persona1.1','pro3'),('per1','persona1.1','pro4'),('per1','persona1.1','pro5'),('per2','persona2.1','pro1'),('per2','persona2.1','pro2'),('per2','persona2.1','pro3'),('per2','persona2.1','pro4'),('per2','persona2.1','pro5'),('per2','persona2.2','pro1'),('per2','persona2.2','pro2'),('per2','persona2.2','pro3'),('per2','persona2.2','pro4'),('per2','persona2.2','pro5'),('per2','persona2.3','pro1'),('per2','persona2.3','pro2'),('per2','persona2.3','pro3'),('per2','persona2.3','pro4'),('per2','persona2.3','pro5'),('per2','persona2.4','pro1'),('per2','persona2.4','pro2'),('per2','persona2.4','pro3' > > You can use ast.literal_eval if you add an enclosing () or [] in the string > (and add a finishing paren for the last tuple). If you want a resulting tuple-of-tuple and you have at least one comma after the first tuple, you don't even have to include the () around it. -tkc From rmorgan466 at gmail.com Thu Jul 19 19:51:30 2012 From: rmorgan466 at gmail.com (Rita) Date: Thu, 19 Jul 2012 19:51:30 -0400 Subject: best way to handle this in Python Message-ID: Hello, I have data in many files (/data/year/month/day/) which are named like YearMonthDayHourMinute.gz. I would like to build a data structure which can easily handle querying the data. So for example, if I want to query data from 3 weeks ago till today, i can do it rather quickly. each YearMonthDayHourMinute.gz file look like this and they are about 4to 6kb red 34 green 44 blue 88 orange 4 black 3 while 153 I would like to query them so I can generate a plot rather quickly but not sure what is the best way to do this. -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Thu Jul 19 20:17:43 2012 From: wuwei23 at gmail.com (alex23) Date: Thu, 19 Jul 2012 17:17:43 -0700 (PDT) Subject: Which lib can diff two dict tree? References: Message-ID: On Jul 19, 7:51?pm, esbat... at gmail.com wrote: > Q1? > which lib can diff two dict tree? > Q2 > How can I diff two json file?How can I get struct_diff and value_diff? > Q3 > How can I diff two xml file? How can I get struct_diff and value_diff? Rather than trying to come up with a method for finding the diffs of three different data structures, it might be easier to transform all the structures into the same form and then just use one mechanism for diffs. There's a 3rd-party python library for producing diffs of XML documents: http://www.logilab.org/projects/xmldiff Python dicts can be converted to XML using one of the suggestions here: http://stackoverflow.com/questions/1019895/serialize-python-dictionary-to-xml JSON can be transformed into dicts by using the standard library's json module. From python.list at tim.thechases.com Thu Jul 19 20:46:36 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Jul 2012 19:46:36 -0500 Subject: help In-Reply-To: References: , <500894D9.9020106@tim.thechases.com> Message-ID: <5008AA6C.4000805@tim.thechases.com> On 07/19/12 19:32, Miriam Gomez Rios wrote: >>>> s = "('per1','persona1.1','pro1'),('per1','persona1.1','pro2')" >> resulting_tuple_of_tuples = ast.literal_eval(s) > > Traceback (most recent call last): > File "C:\Users\Miriam\scripts\prueba_datos", line 124, in > print resulting_tuple.select('perf1','*','*') > AttributeError: 'tuple' object has no attribute 'select' [copying the list, trimming your reply and changing to inline quoting for easier reading] I'm not sure why you expect there to be a .select method on the resulting object. Neither a list-of-tuples or a tuple-of-tuples has a .select method. It *sounds* like what you want to do is then to do something like d = ast.literal_eval(s) # data as a tuple-of-tuples filtered = [t for t in d where t[0] == "perf1"] or you can do filtered = [(v1,v2,v3) for (v1,v2,v3) in d where v1=="perf1"] which allows you to assign more meaningful names to the bits, as well as rearrange/select the contents: filtered = [(v3,v2) for (v1,v2,v3) in d where v1=="perf1"] or you can even do further work like instantiating objects: filtered = [MyCls(v3,v2) for (v1,v2,v3) in d where v1=="perf1"] Espero q' eso le ayuda a usted. -tkc From d at davea.name Thu Jul 19 20:52:37 2012 From: d at davea.name (Dave Angel) Date: Thu, 19 Jul 2012 20:52:37 -0400 Subject: best way to handle this in Python In-Reply-To: References: Message-ID: <5008ABD5.8020407@davea.name> On 07/19/2012 07:51 PM, Rita wrote: > Hello, > > I have data in many files (/data/year/month/day/) which are named like > YearMonthDayHourMinute.gz. > > I would like to build a data structure which can easily handle querying the > data. So for example, if I want to query data from 3 weeks ago till today, > i can do it rather quickly. > > each YearMonthDayHourMinute.gz file look like this and they are about 4to > 6kb > red 34 > green 44 > blue 88 > orange 4 > black 3 > while 153 > > I would like to query them so I can generate a plot rather quickly but not > sure what is the best way to do this. > > > What part of your code is giving you difficulty? You didn't post any code. You don't specify the OS, nor version of your Python, nor what other programs you expect to use along with Python. -- DaveA From larry.martell at gmail.com Thu Jul 19 20:58:13 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 17:58:13 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <8d08181d-316d-4fdc-8f03-1d9b90929d89@e7g2000yqh.googlegroups.com> <7xipdjbk3z.fsf@ruckus.brouhaha.com> Message-ID: <51ef259b-f7fd-49ae-975e-cb09d65fdd5d@cu1g2000vbb.googlegroups.com> On Jul 19, 1:56?pm, Paul Rubin wrote: > "Larry.Mart... at gmail.com" writes: > > You can't do a len on the iterator that is returned from groupby, and > > I've tried to do something with imap or ? ? ?defaultdict, but I'm not > > getting anywhere. I guess I can just make 2 passes through the data, > > the first time getting counts. Or am I missing something about how > > groupby works? > > I posted another reply to your other message, which reached me earlier. > If you're still stuck, post again, though I probably won't be able to > reply til tomorrow or the next day. I really appreciate the offer, but I'm going to go with MRAB's solution. It works, and I understand it ;-) From larry.martell at gmail.com Thu Jul 19 21:01:26 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 18:01:26 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> Message-ID: On Jul 19, 3:32?pm, MRAB wrote: > On 19/07/2012 20:06, Larry.Mart... at gmail.com wrote: > > > > > > > > > On Jul 19, 1:02 pm, "Prasad, Ramit" wrote: > >> > > I am making the assumption that you intend to collapse the directory > >> > > tree and store each file in the same directory, otherwise I can't think > >> > > of why you need to do this. > > >> > Hi Simon, thanks for the reply. It's not quite this - what I am doing > >> > is creating a zip file with relative path names, and if there are > >> > duplicate files the parts of the path that are not be carried over > >> > need to get prepended to the file names to make then unique, > > >> Depending on the file system of the client, you can hit file name > >> length limits. I would think it would be better to just create > >> the full structure in the zip. > > >> Just something to keep in mind, especially if you see funky behavior. > > > Thanks, but it's not what the client wants. > > Here's another solution, not using itertools: > > from collections import defaultdict > from os.path import basename, dirname > from time import strftime, strptime > > # Starting with the original paths > > paths = [ > ? ? ?"/dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3", > ? ? ?"/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1", > ? ? ?"/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2", > ? ? ?"/dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1", > ? ? ?"/dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3", > ] > > def make_dir5_key(path): > ? ? ?date = strptime(path.split("/")[6], "%d%b%y") > ? ? ?return strftime("%y%b%d", date) > > # Collect the paths into a dict keyed by the basename > > files = defaultdict(list) > for path in paths: > ? ? ?files[basename(path)].append(path) > > # Process a list of paths if there's more than one entry > > renaming = [] > > for name, entries in files.items(): > ? ? ?if len(entries) > 1: > ? ? ? ? ?# Collect the paths in each subgroup into a dict keyed by dir4 > > ? ? ? ? ?subgroup = defaultdict(list) > ? ? ? ? ?for path in entries: > ? ? ? ? ? ? ?subgroup[path.split("/")[5]].append(path) > > ? ? ? ? ?for dir4, subentries in subgroup.items(): > ? ? ? ? ? ? ?# Sort the subentries by dir5 (date) > ? ? ? ? ? ? ?subentries.sort(key=make_dir5_key) > > ? ? ? ? ? ? ?if len(subentries) > 1: > ? ? ? ? ? ? ? ? ?for index, path in enumerate(subentries): > ? ? ? ? ? ? ? ? ? ? ?renaming.append((path, > "{}/{}_{:02}_{}".format(dirname(path), dir4, index, name))) > ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ?path = subentries[0] > ? ? ? ? ? ? ? ? ?renaming.append((path, "{}/{}_{}".format(dirname(path), > dir4, name))) > ? ? ?else: > ? ? ? ? ?path = entries[0] > > for old_path, new_path in renaming: > ? ? ?print("Rename {!r} to {!r}".format(old_path, new_path)) Thanks a million MRAB. I really like this solution. It's very understandable and it works! I had never seen .format before. I had to add the index of the positional args to them to make it work. From larry.martell at gmail.com Thu Jul 19 21:01:36 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 18:01:36 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> <7xipdjilko.fsf@ruckus.brouhaha.com> Message-ID: <2862aea5-9d5c-4979-8ca2-0bb01f9db32c@m3g2000vbl.googlegroups.com> On Jul 19, 1:43?pm, Paul Rubin wrote: > "Larry.Mart... at gmail.com" writes: > > Thanks for the reply Paul. I had not heard of itertools. It sounds > > like just what I need for this. But I am having 1 issue - how do you > > know how many items are in each group? > > Simplest is: > > ? for key, group in groupby(xs, lambda x:(x[-1],x[4],x[5])): > ? ? ?gs = list(group) ?# convert iterator to a list > ? ? ?n = len(gs) ? ? ? # this is the number of elements > > there is some theoretical inelegance in that it requires each group to > fit in memory, but you weren't really going to have billions of files > with the same basename. > > If you're not used to iterators and itertools, note there are some > subtleties to using groupby to iterate over files, because an iterator > actually has state. ?It bumps a pointer and maybe consumes some input > every time you advance it. ?In a situation like the above, you've got > some nexted iterators (the groupby iterator generating groups, and the > individual group iterators that come out of the groupby) that wrap the > same file handle, so bad confusion can result if you advance both > iterators without being careful (one can consume file input that you > thought would go to another). It seems that if you do a list(group) you have consumed the list. This screwed me up for a while, and seems very counter-intuitive. > This isn't as bad as it sounds once you get used to it, but it can be > a source of frustration at first. > > BTW, if you just want to count the elements of an iterator (while > consuming it), > > ? ? ?n = sum(1 for x in xs) > > counts the elements of xs without having to expand it into an in-memory > list. > > Itertools really makes Python feel a lot more expressive and clean, > despite little kinks like the above. From rmorgan466 at gmail.com Thu Jul 19 21:28:12 2012 From: rmorgan466 at gmail.com (Rita) Date: Thu, 19 Jul 2012 21:28:12 -0400 Subject: best way to handle this in Python In-Reply-To: <5008ABD5.8020407@davea.name> References: <5008ABD5.8020407@davea.name> Message-ID: Using linux 2.6.31; Python 2.7.3. I am not necessary looking for code just a pythonic way of doing it. Eventually, I would like to graph the data using matplotlib On Thu, Jul 19, 2012 at 8:52 PM, Dave Angel wrote: > On 07/19/2012 07:51 PM, Rita wrote: > > Hello, > > > > I have data in many files (/data/year/month/day/) which are named like > > YearMonthDayHourMinute.gz. > > > > I would like to build a data structure which can easily handle querying > the > > data. So for example, if I want to query data from 3 weeks ago till > today, > > i can do it rather quickly. > > > > each YearMonthDayHourMinute.gz file look like this and they are about 4to > > 6kb > > red 34 > > green 44 > > blue 88 > > orange 4 > > black 3 > > while 153 > > > > I would like to query them so I can generate a plot rather quickly but > not > > sure what is the best way to do this. > > > > > > > > What part of your code is giving you difficulty? You didn't post any > code. You don't specify the OS, nor version of your Python, nor what > other programs you expect to use along with Python. > > > > -- > > DaveA > > -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From thecocacolakid at gmail.com Thu Jul 19 21:41:47 2012 From: thecocacolakid at gmail.com (The Coca Cola Kid) Date: Thu, 19 Jul 2012 20:41:47 -0500 Subject: Need help connecting via a remote VPN References: Message-ID: "Dave Angel" wrote in message news:mailman.2284.1342663213.4697.python-list at python.org... >Starting a VPN simply makes it possible for IP packets to get to the >specified machine. You still need to match some protocol that the >particular remote machine can handle. SSH is probably the most common, >but there are lots of other possibilities, some standard and some >custom. So the question is what does the remote machine (server) >support for file access? > >glob will work if the server supports mounting the remote partition as a >file system. But there are no guarantees that that's possible. You >haven't even said what the two operating systems involved are, though I >can guess that the local machine is some version of Windows. The local machine is running Windows 7. I'm not sure what the other machine is running on, but I assume it can handle ssh. If it helps, I usually connect to it manually via an https web link, and then after entering my user name and password in a Firepass session manager it runs an active-x cache cleaner program and will then let me navigate to server B which is behind the firewall. From d at davea.name Thu Jul 19 21:58:11 2012 From: d at davea.name (Dave Angel) Date: Thu, 19 Jul 2012 21:58:11 -0400 Subject: Need help connecting via a remote VPN In-Reply-To: References: Message-ID: <5008BB33.5010902@davea.name> On 07/19/2012 09:41 PM, The Coca Cola Kid wrote: > "Dave Angel" wrote in message > news:mailman.2284.1342663213.4697.python-list at python.org... > >> Starting a VPN simply makes it possible for IP packets to get to the >> specified machine. You still need to match some protocol that the >> particular remote machine can handle. SSH is probably the most common, >> but there are lots of other possibilities, some standard and some >> custom. So the question is what does the remote machine (server) >> support for file access? >> >> glob will work if the server supports mounting the remote partition as a >> file system. But there are no guarantees that that's possible. You >> haven't even said what the two operating systems involved are, though I >> can guess that the local machine is some version of Windows. > > The local machine is running Windows 7. I'm not sure what the other > machine is running on, but I assume it can handle ssh. If it helps, I > usually connect to it manually via an https web link, and then after > entering my user name and password in a Firepass session manager it > runs an active-x cache cleaner program and will then let me navigate > to server B which is behind the firewall. If the remote machine is Linux, running sshd, and if you have an account there, then use scp to copy the file. And if you want to automate it, run scp from within python, using the subprocess module. But make sure it works manually before bothering to automate it. To get ssh on Windows, one approach is to install cygwin. If you want more control than subprocess, there are a whole bunch of 3rd party ssh libraries for Python. Just google python ssh library to get at least 6 on the first page. -- DaveA From larry.martell at gmail.com Thu Jul 19 23:07:23 2012 From: larry.martell at gmail.com (Larry.Martell@gmail.com) Date: Thu, 19 Jul 2012 20:07:23 -0700 (PDT) Subject: Finding duplicate file names and modifying them based on elements of the path References: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> Message-ID: <68fe8c14-bb90-4505-8732-801154f508ac@tu6g2000pbc.googlegroups.com> On Jul 19, 7:01?pm, "Larry.Mart... at gmail.com" wrote: > On Jul 19, 3:32?pm, MRAB wrote: > > > > > > > > > > > On 19/07/2012 20:06, Larry.Mart... at gmail.com wrote: > > > > On Jul 19, 1:02 pm, "Prasad, Ramit" wrote: > > >> > > I am making the assumption that you intend to collapse the directory > > >> > > tree and store each file in the same directory, otherwise I can't think > > >> > > of why you need to do this. > > > >> > Hi Simon, thanks for the reply. It's not quite this - what I am doing > > >> > is creating a zip file with relative path names, and if there are > > >> > duplicate files the parts of the path that are not be carried over > > >> > need to get prepended to the file names to make then unique, > > > >> Depending on the file system of the client, you can hit file name > > >> length limits. I would think it would be better to just create > > >> the full structure in the zip. > > > >> Just something to keep in mind, especially if you see funky behavior. > > > > Thanks, but it's not what the client wants. > > > Here's another solution, not using itertools: > > > from collections import defaultdict > > from os.path import basename, dirname > > from time import strftime, strptime > > > # Starting with the original paths > > > paths = [ > > ? ? ?"/dir0/dir1/dir2/dir3/qwer/09Jan12/dir6/file3", > > ? ? ?"/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file1", > > ? ? ?"/dir0/dir1/dir2/dir3/abcd/08Jan12/dir6/file2", > > ? ? ?"/dir0/dir1/dir2/dir3/xyz/08Jan12/dir6/file1", > > ? ? ?"/dir0/dir1/dir2/dir3/qwer/07Jan12/dir6/file3", > > ] > > > def make_dir5_key(path): > > ? ? ?date = strptime(path.split("/")[6], "%d%b%y") > > ? ? ?return strftime("%y%b%d", date) > > > # Collect the paths into a dict keyed by the basename > > > files = defaultdict(list) > > for path in paths: > > ? ? ?files[basename(path)].append(path) > > > # Process a list of paths if there's more than one entry > > > renaming = [] > > > for name, entries in files.items(): > > ? ? ?if len(entries) > 1: > > ? ? ? ? ?# Collect the paths in each subgroup into a dict keyed by dir4 > > > ? ? ? ? ?subgroup = defaultdict(list) > > ? ? ? ? ?for path in entries: > > ? ? ? ? ? ? ?subgroup[path.split("/")[5]].append(path) > > > ? ? ? ? ?for dir4, subentries in subgroup.items(): > > ? ? ? ? ? ? ?# Sort the subentries by dir5 (date) > > ? ? ? ? ? ? ?subentries.sort(key=make_dir5_key) > > > ? ? ? ? ? ? ?if len(subentries) > 1: > > ? ? ? ? ? ? ? ? ?for index, path in enumerate(subentries): > > ? ? ? ? ? ? ? ? ? ? ?renaming.append((path, > > "{}/{}_{:02}_{}".format(dirname(path), dir4, index, name))) > > ? ? ? ? ? ? ?else: > > ? ? ? ? ? ? ? ? ?path = subentries[0] > > ? ? ? ? ? ? ? ? ?renaming.append((path, "{}/{}_{}".format(dirname(path), > > dir4, name))) > > ? ? ?else: > > ? ? ? ? ?path = entries[0] > > > for old_path, new_path in renaming: > > ? ? ?print("Rename {!r} to {!r}".format(old_path, new_path)) > > Thanks a million MRAB. I really like this solution. It's very > understandable and it works! I had never seen .format before. I had to > add the index of the positional args to them to make it work. Also, in make_dir5_key the format specifier for strftime should be %y%m %d so they sort properly. From dieter at handshake.de Fri Jul 20 02:09:38 2012 From: dieter at handshake.de (Dieter Maurer) Date: Fri, 20 Jul 2012 08:09:38 +0200 Subject: properly catch SIGTERM References: Message-ID: <87mx2vrmjh.fsf@handshake.de> Eric Frederich writes: > ... > This seems to work okay but just now I got this while hitting ctrl-c > It seems to have caught the signal at or in the middle of a call to > sys.stdout.flush() > --- Caught SIGTERM; Attempting to quit gracefully --- > Traceback (most recent call last): > ? File "/home/user/test.py", line 125, in > ??? sys.stdout.flush() > IOError: [Errno 4] Interrupted system call > How should I fix this? This is normal *nix behavior. Any signal, even if caught by a signal handler, can interrupt system calls. Modern *nix versions might allow to control whether a signal interrupts a system call or not. Check the signal documentation for your operating system for the control you have over signal handling. Likely, you cannot directly control the feature via Python, but the "ctypes" module allows you to call C functions directly. From steve+comp.lang.python at pearwood.info Fri Jul 20 03:24:23 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Jul 2012 07:24:23 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500907a7$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 19 Jul 2012 09:06:45 -0400, Roy Smith wrote: > Heh. This reminds me of one of my current pet peeves. I've run across > documentation for more than one Python project (django is the one that > comes to mind, but I'm sure there's others) which misuse words like > "set" and "list". They're often used in the generic sense of "a > collection of things", but they're also the names of specific Python > data types. It can sometimes get confusing trying to figure out which > meaning they intended. Now that is confusing! Writing good documentation is *hard*. I often end up writing more documentation than code, sometimes by a factor of two. Fortunately I love to write. As may be obvious. -- Steven From __peter__ at web.de Fri Jul 20 03:35:02 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Jul 2012 09:35:02 +0200 Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> <7xipdjilko.fsf@ruckus.brouhaha.com> <2862aea5-9d5c-4979-8ca2-0bb01f9db32c@m3g2000vbl.googlegroups.com> Message-ID: Larry.Martell at gmail.com wrote: > It seems that if you do a list(group) you have consumed the list. This > screwed me up for a while, and seems very counter-intuitive. Many itertools functions work that way. It allows you to iterate over the items even if there is more data than fits into memory. If you need to keep all items and are sure that your computer can cope with them at once you can always throw in a group = list(group) From no.email at nospam.invalid Fri Jul 20 03:51:21 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 20 Jul 2012 00:51:21 -0700 Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> <7xipdjilko.fsf@ruckus.brouhaha.com> <2862aea5-9d5c-4979-8ca2-0bb01f9db32c@m3g2000vbl.googlegroups.com> Message-ID: <7xk3xyswee.fsf@ruckus.brouhaha.com> "Larry.Martell at gmail.com" writes: > It seems that if you do a list(group) you have consumed the list. This > screwed me up for a while, and seems very counter-intuitive. Yes, that is correct, you have to carefully watch where the stuff in the iterators is getting consumed, including when there are nested iterators. That's what I was mentioning earlier--it got me confused at first, but I use that style all the time now and it is pretty natural. From levinie001 at gmail.com Fri Jul 20 03:56:06 2012 From: levinie001 at gmail.com (levi nie) Date: Fri, 20 Jul 2012 15:56:06 +0800 Subject: =?windows-1252?B?dGhlIG1lYW5pbmcgb2YgcpIuLi4uLi4ukQ==?= Message-ID: the meaning of r?.......?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Jul 20 04:11:39 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Jul 2012 08:11:39 GMT Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: <500912bb$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 19 Jul 2012 13:50:36 -0500, Tim Chase wrote: > On 07/19/12 13:28, Chris Angelico wrote: >> On Fri, Jul 20, 2012 at 4:20 AM, Tim Chase >> wrote: >>> Sure it terminates...If you don't run out of RAM to represent the >>> number "i" in question, there's also this "heat death of the universe" >>> limit I keep hearing about ;-) >> >> I'd be more worried about the heat death of your computer, it's likely >> to be sooner. How many people have access to a computer that'll still >> be running in ten years, much less a thousand? > > Just putting a maximum bound on the problem, providing a time-frame in > which I can be fairly certain that the program will have terminated. :-) I'm reminded of Graham's Number, which is so large that there aren't enough molecules in the universe to write it out as a power tower a^b^c^d^..., or even in a tower of hyperpowers a^^b^^c^^d^^... It was the provable upper bound to a question to which experts in the field thought the most likely answer was ... six. (The bounds have since been reduced: the lower bound is now 13, and the upper bound is *much* smaller than Graham's Number but still inconceivably ginormous.) http://en.wikipedia.org/wiki/Graham%27s_number -- Steven From rosuav at gmail.com Fri Jul 20 04:17:47 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 20 Jul 2012 18:17:47 +1000 Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: On Thu, Jul 19, 2012 at 8:15 PM, andrea crotti wrote: > We need to be able to reload code on a live system. This live system > has a daemon process always running but it runs many subprocesses with > multiprocessing, and the subprocesses might have a short life... > ... > As long as I import the code in the function and make sure to remove the > "pyc" files everything seems to work.. > Are there any possible problems which I'm not seeing in this approach or > it's safe? Python never promises reloading reliability, but from my understanding of what you've done here, it's probably safe. However, you may find that you're using the wrong language for the job; it depends on how expensive it is to spin off all those processes and ship their work to them. But if that's not an issue, I'd say you have something safe there. (Caveat: I've given this only a fairly cursory examination, and I'm not an expert. Others may have more to say. I just didn't want the resident Markov chainer to be the only one to respond!!) ChrisA From rustompmody at gmail.com Fri Jul 20 04:21:43 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 20 Jul 2012 01:21:43 -0700 (PDT) Subject: Encapsulation, inheritance and polymorphism References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <500907a7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8f328a79-eecb-4f81-9f6e-fd97c5c739e1@qk10g2000pbc.googlegroups.com> On Jul 20, 12:24?pm, Steven D'Aprano wrote: > I often end up writing more > documentation than code, sometimes by a factor of two. Fortunately I love > to write. As may be obvious. Now, now! Really?? From steve+comp.lang.python at pearwood.info Fri Jul 20 04:27:26 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Jul 2012 08:27:26 GMT Subject: Encapsulation, inheritance and polymorphism References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: <5009166e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Fri, 20 Jul 2012 08:20:57 +1000, Chris Angelico wrote: >>> Since the current evidence indicates the universe will just keep >>> expanding, it's more of a "deep freeze death..." >> >> Heat death means *lack* of heat. > > The second law of thermodynamics states that energy tends to go from > higher states to lower, with heat being the very lowest. It's possible > to do work using (say) kinetic energy, and in the process, some of that > energy becomes heat. It's also possible to do work with any difference > in temperature (eg Stirling engines), so the state of the universe in > which it's no longer possible to do any work will be one in which all > energy is heat and everything's at the same temperature. That doesn't > mean a lack of heat; in fact, it implies that there'll be rather more > heat than there now is, because we currently have a whole lot of > chemical energy available to be used. Yes, but the point is, that heat will be *incredibly* diffuse, essentially spread over the entire universe, which will be MUCH bigger than it is now, and hence the temperature will be low even though the total amount of heat will be high. The average temperature of the universe now is about 2.7 degrees above absolute zero (i.e. 2.7 K, -270.45 C or -454.81 F), with individual hotspots reaching into millions of degrees or higher. By the time the last of the stars burn out, the average temperature will be a minuscule fraction of a degree above absolute zero, and the only hotspots will be the slowly cooling neutron stars. > But in any case, that's a looooooooong way off... I once went to an astronomy lecture where the lecturer was talking about the eventual death of the sun. He said, "In about 10 billion years, the sun will consume almost all of its fuel. It will cool and expand into a red giant, and the earth will be engulfed by the expanded sun and destroyed." This fellow sitting next to me got all agitated, stood up and cried out, "Does the government know about this? We have to do something!" The lecturer said "Don't worry sir, there's no need to panic, this won't happen for billions of years." The fellow looked relived and said "Oh thank god, I thought you said *million*!" -- Steven From steve+comp.lang.python at pearwood.info Fri Jul 20 04:30:44 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Jul 2012 08:30:44 GMT Subject: Google the video blah blah jews blah blah 9/11 blah blah conspiracy blah cia blah blah blah zionist blah blah brainwashing blah blah blah References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> Message-ID: <50091734$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 19 Jul 2012 10:27:02 -0400, Matty Sarro wrote: > I must be a Jew or a traitor as I keep deleting this email. You might be both. -- Steven From steve+comp.lang.python at pearwood.info Fri Jul 20 04:31:29 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Jul 2012 08:31:29 GMT Subject: Odd csv column-name truncation with only one column References: <5008110d$0$6865$e4fe514c@news2.news.xs4all.nl> Message-ID: <50091761$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 19 Jul 2012 15:52:12 +0200, Hans Mulder wrote: > Perhaps it should be documented that the Sniffer doesn't work on > single-column data. > > If you really need to read a one-column csv file, you'll have to find > some other way to produce a Dialect object. Perhaps the predefined > 'cvs.excel' dialect matches your data. If not, the easiest way might be > to manually define a csv.Dialect subclass. Perhaps the csv module could do with a pre-defined "one column" dialect. If anyone comes up with one, do consider proposing it as a patch on the bug tracker. -- Steven From paul.nospam at rudin.co.uk Fri Jul 20 04:37:42 2012 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 20 Jul 2012 09:37:42 +0100 Subject: Finding duplicate file names and modifying them based on elements of the path References: <7xipdkwuqd.fsf@ruckus.brouhaha.com> <14831ee0-fd74-4906-852c-764ba2d8b1d5@h20g2000yqe.googlegroups.com> <7xipdjilko.fsf@ruckus.brouhaha.com> <2862aea5-9d5c-4979-8ca2-0bb01f9db32c@m3g2000vbl.googlegroups.com> Message-ID: <87r4s696ax.fsf@no-fixed-abode.cable.virginmedia.net> "Larry.Martell at gmail.com" writes: > It seems that if you do a list(group) you have consumed the list. This > screwed me up for a while, and seems very counter-intuitive. You've consumed the *group* which is an iterator, in order to construct a list from its elements. Sorry if this is excessively nit-picking, but it generally helps to keep these things very clear in your own mind. From kushal.kumaran+python at gmail.com Fri Jul 20 04:48:51 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Fri, 20 Jul 2012 14:18:51 +0530 Subject: Let child process to run while parent is out (multiprocessing) In-Reply-To: References: Message-ID: On Fri, Jul 20, 2012 at 2:04 AM, John Wong wrote: > def main(...): > build_id = create_build_id(...) > build_stuff > return build_id > > Suppose build_stuff compiles a C program. It could take days to finish, and > notify users their builds are ready. I was thinking about using > mutliprocessing to handle the build_stuff. > > So here is a sample: > > #!/usr/bin/python > > import multiprocessing as mp > import time > > def build(): > print 'I am building HUGE things' > time.sleep(10) > > def main(): > build_p = mp.Process(name='build process', target=build) > build_p.start() > return 'abcd12345' > > if __name__ == '__main__': > > v = main() > print v > print 'done' > > Here is output: > yeukhon at fermat:~$ python c2.py > abcd12345 > done [now hangs for 10 seconds] > I build things > > When I looked at `ps -elf|grep python`, I can see two processes running, and > one of the python c2.py process is `wait`. But this is not ideal, > especially this is a web app. I can't implement any advanced queue / event > system right now (I use Pylon, I believe I have gevent installed). But just > with multiprocessing, is it possible to send the id first, while running > child in the backgroud? > > Right now it hangs there as long as the child process is alive. Any > solutions? > >From the documentation, there does not seem to be any way of "detaching" a multiprocessing Process. But it is doable by using the underlying os.fork directly (CAUTION: not ready for being invoked from a web app): #!/usr/bin/python import os import time def build_and_send_email(): print 'I am building HUGE things' time.sleep(10) def main(): child_pid = os.fork() if child_pid == 0: build_and_send_email() os._exit(0) return 'abcd12345' if __name__ == '__main__': v = main() print v print 'done' To make it work correctly with web app will require a bit more work. At the least, you will have to close all file descriptors to make sure the request processing finishes. You can turn it into a proper background process (a daemon) using the python-daemon library with very little code, I think. -- regards, kushal From kushal.kumaran+python at gmail.com Fri Jul 20 04:52:59 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Fri, 20 Jul 2012 14:22:59 +0530 Subject: properly catch SIGTERM In-Reply-To: <87mx2vrmjh.fsf@handshake.de> References: <87mx2vrmjh.fsf@handshake.de> Message-ID: On Fri, Jul 20, 2012 at 11:39 AM, Dieter Maurer wrote: > Eric Frederich writes: >> ... >> This seems to work okay but just now I got this while hitting ctrl-c >> It seems to have caught the signal at or in the middle of a call to >> sys.stdout.flush() >> --- Caught SIGTERM; Attempting to quit gracefully --- >> Traceback (most recent call last): >> File "/home/user/test.py", line 125, in >> sys.stdout.flush() >> IOError: [Errno 4] Interrupted system call >> How should I fix this? > > This is normal *nix behavior. Any signal, even if caught by a signal > handler, can interrupt system calls. > > Modern *nix versions might allow to control whether a signal interrupts > a system call or not. Check the signal documentation for your operating > system for the control you have over signal handling. Likely, > you cannot directly control the feature via Python, but the > "ctypes" module allows you to call C functions directly. > The signal.siginterrupt function has been added in python 2.6 to do this. -- regards, kushal From breamoreboy at yahoo.co.uk Fri Jul 20 05:00:59 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 20 Jul 2012 10:00:59 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> Message-ID: On 19/07/2012 22:13, Ian Kelly wrote: > On Thu, Jul 19, 2012 at 3:01 PM, John Gordon wrote: >> In Dennis Lee Bieber writes: >> >>>> Sure it terminates...If you don't run out of RAM to represent the >>>> number "i" in question, there's also this "heat death of the >>>> universe" limit I keep hearing about ;-) >>>> >>> Since the current evidence indicates the universe will just keep >>> expanding, it's more of a "deep freeze death..." >> >> Heat death means *lack* of heat. > > Actually actually it means *uniformity* of heat, i.e. that the entire > universe is in thermodynamic equilibrium and so it is impossible to > perform work. So heat death is expected regardless of whether the > universe ultimately collapses or expands indefinitely. > All of this will pale into complete insignificance provided that England beat South Africa in the current cricket test match series and retain their world no.1 ranking. Of course if they lose the universe will collapse immediately or expand so far that it tears itself to tiny little pieces. Even The Ashes won't survive, something I should perhaps take up with the MCC. -- Cheers. Mark Lawrence. From vs at it.uu.se Fri Jul 20 05:05:09 2012 From: vs at it.uu.se (Virgil Stokes) Date: Fri, 20 Jul 2012 11:05:09 +0200 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <5009166e$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <5009166e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50091F45.4010208@it.uu.se> On 20-Jul-2012 10:27, Steven D'Aprano wrote: > On Fri, 20 Jul 2012 08:20:57 +1000, Chris Angelico wrote: > >>>> Since the current evidence indicates the universe will just keep >>>> expanding, it's more of a "deep freeze death..." >>> Heat death means *lack* of heat. >> The second law of thermodynamics states that energy tends to go from >> higher states to lower, with heat being the very lowest. It's possible >> to do work using (say) kinetic energy, and in the process, some of that >> energy becomes heat. It's also possible to do work with any difference >> in temperature (eg Stirling engines), so the state of the universe in >> which it's no longer possible to do any work will be one in which all >> energy is heat and everything's at the same temperature. That doesn't >> mean a lack of heat; in fact, it implies that there'll be rather more >> heat than there now is, because we currently have a whole lot of >> chemical energy available to be used. > Yes, but the point is, that heat will be *incredibly* diffuse, > essentially spread over the entire universe, which will be MUCH bigger > than it is now, and hence the temperature will be low even though the > total amount of heat will be high. > > The average temperature of the universe now is about 2.7 degrees above > absolute zero (i.e. 2.7 K, -270.45 C or -454.81 F), with individual > hotspots reaching into millions of degrees or higher. By the time the > last of the stars burn out, the average temperature will be a minuscule > fraction of a degree above absolute zero, and the only hotspots will be > the slowly cooling neutron stars. > > >> But in any case, that's a looooooooong way off... > I once went to an astronomy lecture where the lecturer was talking about > the eventual death of the sun. He said, "In about 10 billion years, the > sun will consume almost all of its fuel. It will cool and expand into a > red giant, and the earth will be engulfed by the expanded sun and > destroyed." > > This fellow sitting next to me got all agitated, stood up and cried out, > "Does the government know about this? We have to do something!" > > The lecturer said "Don't worry sir, there's no need to panic, this won't > happen for billions of years." > > The fellow looked relived and said "Oh thank god, I thought you said > *million*!" > > > How does this relate to the python list? "This mailing list is a general discussion list for the Python programming language." --- from http://mail.python.org/mailman/listinfo/python-list/ From max at alcyone.com Fri Jul 20 05:08:35 2012 From: max at alcyone.com (Erik Max Francis) Date: Fri, 20 Jul 2012 02:08:35 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: <500912bb$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <500912bb$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 07/20/2012 01:11 AM, Steven D'Aprano wrote: > On Thu, 19 Jul 2012 13:50:36 -0500, Tim Chase wrote: > >> On 07/19/12 13:28, Chris Angelico wrote: >>> On Fri, Jul 20, 2012 at 4:20 AM, Tim Chase >>> wrote: >>>> Sure it terminates...If you don't run out of RAM to represent the >>>> number "i" in question, there's also this "heat death of the universe" >>>> limit I keep hearing about ;-) >>> >>> I'd be more worried about the heat death of your computer, it's likely >>> to be sooner. How many people have access to a computer that'll still >>> be running in ten years, much less a thousand? >> >> Just putting a maximum bound on the problem, providing a time-frame in >> which I can be fairly certain that the program will have terminated. :-) > > I'm reminded of Graham's Number, which is so large that there aren't > enough molecules in the universe to write it out as a power tower > a^b^c^d^..., or even in a tower of hyperpowers a^^b^^c^^d^^... It was the > provable upper bound to a question to which experts in the field thought > the most likely answer was ... six. > > (The bounds have since been reduced: the lower bound is now 13, and the > upper bound is *much* smaller than Graham's Number but still > inconceivably ginormous.) You don't even need to go that high. Even a run-of-the-mill googol (10^100) is far larger than the total number of elementary particles in the observable Universe. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis I think it is safe to say that no one understands quantum mechanics. -- Richard P. Feynman From wolfgang at rohdewald.de Fri Jul 20 05:50:01 2012 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Fri, 20 Jul 2012 11:50:01 +0200 Subject: QVariant.toPyObject() Message-ID: <2216595.B494Yup0xz@i5> toPyObject() is mentioned but undocumented at http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qvariant.html#toPyObject without it being documented, I find it a bit surprising that toPyObject() can return a QString. Of course QString is a python object but then QVariant is too. -- Wolfgang From vincent.vandevyvre at swing.be Fri Jul 20 06:15:30 2012 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Fri, 20 Jul 2012 12:15:30 +0200 Subject: QVariant.toPyObject() In-Reply-To: <2216595.B494Yup0xz@i5> References: <2216595.B494Yup0xz@i5> Message-ID: <50092FC2.4030307@swing.be> On 20/07/12 11:50, Wolfgang Rohdewald wrote: > toPyObject() is mentioned but undocumented at > http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qvariant.html#toPyObject > > without it being documented, I find it a bit surprising that toPyObject() > can return a QString. > > Of course QString is a python object but then QVariant is too. > > I think you post on the bad mailing list. -- Vincent V.V. Oqapy . Qarte . PaQager From bc at freeuk.com Fri Jul 20 06:28:44 2012 From: bc at freeuk.com (BartC) Date: Fri, 20 Jul 2012 11:28:44 +0100 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <500912bb$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: "Erik Max Francis" wrote in message news:GsKdnWOQPKOOvZTNnZ2dnUVZ5s2dnZ2d at giganews.com... > On 07/20/2012 01:11 AM, Steven D'Aprano wrote: >> On Thu, 19 Jul 2012 13:50:36 -0500, Tim Chase wrote: >> I'm reminded of Graham's Number, which is so large that there aren't >> enough molecules in the universe to write it out as a power tower >> a^b^c^d^..., or even in a tower of hyperpowers a^^b^^c^^d^^... It was the >> provable upper bound to a question to which experts in the field thought >> the most likely answer was ... six. >> >> (The bounds have since been reduced: the lower bound is now 13, and the >> upper bound is *much* smaller than Graham's Number but still >> inconceivably ginormous.) > > You don't even need to go that high. Even a run-of-the-mill googol > (10^100) is far larger than the total number of elementary particles in > the observable Universe. But you can write it down, even as a straightforward number, without any problem. Perhaps a googolplex (10^10^100 iirc) would be difficult to write it down in full, but I have just represented it as an exponent with little difficulty. These bigger numbers can't be written down, because there will never be enough material, even using multiple systems of exponents. (A few years ago the biggest number I'd heard of was Skewes' Number (something like 10^10^10^34), but even that is trivial to write using conventional exponents as I've just shown. Graham's Number is in a different class altogether.) -- Bartc From rmorgan466 at gmail.com Fri Jul 20 06:34:47 2012 From: rmorgan466 at gmail.com (Rita) Date: Fri, 20 Jul 2012 06:34:47 -0400 Subject: best way to handle this in Python In-Reply-To: <6emh0859cren5ond0k5n2f58mh36bnp9jc@invalid.netcom.com> References: <5008ABD5.8020407@davea.name> <6emh0859cren5ond0k5n2f58mh36bnp9jc@invalid.netcom.com> Message-ID: Thats an interesting data structure Dennis. I will actually be running this type of query many times preferable in an ad-hoc environment. That makes it tough for sqlite3 since there will be several hundred thousand tuples. On Fri, Jul 20, 2012 at 12:18 AM, Dennis Lee Bieber wrote: > {NOTE: preferences for comp.lang.python are to follow the RFC on > "netiquette" -- that is, post comments /under/ quoted material, trimming > what is not relevant... I've restructured this reply to match} > > On Thu, 19 Jul 2012 21:28:12 -0400, Rita > declaimed the following in gmane.comp.python.general: > > > > > > > On Thu, Jul 19, 2012 at 8:52 PM, Dave Angel wrote: > > > > > On 07/19/2012 07:51 PM, Rita wrote: > > > > Hello, > > > > > > > > I have data in many files (/data/year/month/day/) which are named > like > > > > YearMonthDayHourMinute.gz. > > > > > > > > I would like to build a data structure which can easily handle > querying > > > the > > > > data. So for example, if I want to query data from 3 weeks ago till > > > today, > > > > i can do it rather quickly. > > > > > > > > each YearMonthDayHourMinute.gz file look like this and they are > about 4to > > > > 6kb > > > > red 34 > > > > green 44 > > > > blue 88 > > > > orange 4 > > > > black 3 > > > > while 153 > > > > > > > > I would like to query them so I can generate a plot rather quickly > but > > > not > > > > sure what is the best way to do this. > > > > > > > > > > > > > > > > > > What part of your code is giving you difficulty? You didn't post any > > > code. You don't specify the OS, nor version of your Python, nor what > > > other programs you expect to use along with Python. > > > > > Using linux 2.6.31; Python 2.7.3. > > I am not necessary looking for code just a pythonic way of doing it. > > Eventually, I would like to graph the data using matplotlib > > > > > Which doesn't really answer the question. After all, since the > source data is already in date/time-stamped files, a simple, sorted, > "glob" of files within a desired span would answer the requirement. > > But -- it would mean that you reparse the files for each processing > run. > > An alternative would be to run a pre-processor that parses the > files > into, say, an SQLite3 database (and which can determine, from the > highest datetime entry in the database, which /new/ files need to be > parsed on subsequent runs). Then do the query/plotting from a second > program which retrieves data from the database. > > But if this is a process that only needs to be run once, or at rare > intervals, maybe you only need to parse the files into an in-memory data > structure... Say a list of tuples of the form: > > [ (datetime, {color: value, color2: value2, ...}), > (datetime2, > ...) ] > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From zdoor at xs4all.nl Fri Jul 20 09:00:46 2012 From: zdoor at xs4all.nl (Alex van der Spek) Date: Fri, 20 Jul 2012 15:00:46 +0200 Subject: logging time format millisecond precision decimalsign Message-ID: <50095684$0$6957$e4fe514c@news2.news.xs4all.nl> I use this formatter in logging: formatter = logging.Formatter(fmt='%(asctime)s \t %(name)s \t %(levelname)s \t %(message)s') Sample output: 2012-07-19 21:34:58,382 root INFO Removed - C:\Users\ZDoor\Documents The time stamp has millisecond precision but the decimal separator is a comma. Can I change the comma (,) into a period (.) and if so how? Thanks in advance, Alex van der Spek From ben+python at benfinney.id.au Fri Jul 20 09:58:56 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 20 Jul 2012 23:58:56 +1000 Subject: Google the video blah blah jews blah blah 9/11 blah blah conspiracy blah cia blah blah blah zionist blah blah brainwashing blah blah blah References: <04e6ccdc-4f6f-4351-800f-5a40ce3879f3@t32g2000yqd.googlegroups.com> <1207AC9C-A0B5-41BE-A5D9-446D15BBB689@mac.com> <50091734$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87fw8mtty7.fsf@benfinney.id.au> Steven D'Aprano writes: > On Thu, 19 Jul 2012 10:27:02 -0400, Matty Sarro wrote: > > > I must be a Jew or a traitor as I keep deleting this email. > > You might be both. -- \ ?My business is to teach my aspirations to conform themselves | `\ to fact, not to try and make facts harmonise with my | _o__) aspirations.? ?Thomas Henry Huxley, 1860-09-23 | Ben Finney From eric.frederich at gmail.com Fri Jul 20 10:27:01 2012 From: eric.frederich at gmail.com (Eric Frederich) Date: Fri, 20 Jul 2012 10:27:01 -0400 Subject: properly catch SIGTERM In-Reply-To: References: Message-ID: On Fri, Jul 20, 2012 at 1:51 AM, Jason Friedman wrote: > > This seems to work okay but just now I got this while hitting ctrl-c > > It seems to have caught the signal at or in the middle of a call to > > sys.stdout.flush() > > > > > > --- Caught SIGTERM; Attempting to quit gracefully --- > > Traceback (most recent call last): > > File "/home/user/test.py", line 125, in > > sys.stdout.flush() > > IOError: [Errno 4] Interrupted system call > > > > > > How should I fix this? > > Am I doing this completely wrong? > > Instead of rolling your own others have written Python code to > implement daemons. Try a search on "Python daemon". > I found a stackoverflow question that linked to this... http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ ... I'm not sure how that would help. They don't attempt to exit gracefully. I don't think my problem is the daemon part, it is the handling the SIGTERM signal where I'm having trouble. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jul 20 10:31:52 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Jul 2012 16:31:52 +0200 Subject: logging time format millisecond precision decimalsign References: <50095684$0$6957$e4fe514c@news2.news.xs4all.nl> Message-ID: Alex van der Spek wrote: > I use this formatter in logging: > > formatter = logging.Formatter(fmt='%(asctime)s \t %(name)s \t > %(levelname)s \t %(message)s') > > Sample output: > > 2012-07-19 21:34:58,382 root INFO Removed - C:\Users\ZDoor\Documents > > The time stamp has millisecond precision but the decimal separator is a > comma. > > Can I change the comma (,) into a period (.) and if so how? I think you have to subclass Formatter.formatTime(). Here's a monkey- patching session to get you started: >>> import logging >>> logging.basicConfig(format="%(asctime)s") >>> logging.getLogger().error("foo") 2012-07-20 16:17:39,364 >>> _formatTime = logging.Formatter.formatTime >>> def formatTime(*args): ... return _formatTime(*args).replace(",", ".") ... >>> logging.Formatter.formatTime = formatTime >>> logging.getLogger().error("foo") 2012-07-20 16:20:20.838 See also http://docs.python.org/dev/py3k/library/logging.html#logging.Formatter.formatTime """ Changed in version 3.3: Previously, the default ISO 8601 format was hard- coded as in this example: 2010-09-06 22:38:15,292 where the part before the comma is handled by a strptime format string ('%Y-%m-%d %H:%M:%S'), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, '%s,%03d' ? and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are default_time_format (for the strptime format string) and default_msec_format (for appending the millisecond value). """ From python at mrabarnett.plus.com Fri Jul 20 11:45:06 2012 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 20 Jul 2012 16:45:06 +0100 Subject: Finding duplicate file names and modifying them based on elements of the path In-Reply-To: <68fe8c14-bb90-4505-8732-801154f508ac@tu6g2000pbc.googlegroups.com> References: <3a201907-c6dd-4c1f-b921-6f508d0af6e8@r3g2000yqh.googlegroups.com> <68fe8c14-bb90-4505-8732-801154f508ac@tu6g2000pbc.googlegroups.com> Message-ID: <50097D02.30507@mrabarnett.plus.com> On 20/07/2012 04:07, Larry.Martell at gmail.com wrote: [snip] > Also, in make_dir5_key the format specifier for strftime should be %y%m > %d so they sort properly. > Correct. I realised that only some time later, after I'd turned off my computer for the night. :-( From hansmu at xs4all.nl Fri Jul 20 12:59:24 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 20 Jul 2012 18:59:24 +0200 Subject: Odd csv column-name truncation with only one column In-Reply-To: References: <5008110d$0$6865$e4fe514c@news2.news.xs4all.nl> <50084B81.50909@tim.thechases.com> Message-ID: <50098e6c$0$6880$e4fe514c@news2.news.xs4all.nl> On 19/07/12 23:10:04, Dennis Lee Bieber wrote: > On Thu, 19 Jul 2012 13:01:37 -0500, Tim Chase > declaimed the following in > gmane.comp.python.general: > >> It just seems unfortunate that the sniffer would ever consider >> [a-zA-Z0-9] as a valid delimiter. +1 > I'd suspect the sniffer logic does not do any special casing > -- any /byte value/ is a candidate for the delimiter. The sniffer prefers [',', '\t', ';', ' ', ':'] (in that order). If none of those is found, it goes to the other extreme and considers all characters equally likely. > This would allow for usage of some old ASCII control characters -- > things like x1F (unit separator) If the Sniffer excludes [a-zA-Z0-9] (or all alphanumerics) as potential delimiters, than control characters such as "\x1F" are still possible. > {Next is to rig the sniffer to identify x1F for fields, and x1E > for records } The sniffer will always guess '\r\n' as the line terminator. That should not stop you from creating a dialect with '\x1E' as the line terminator. Just don't expect the sniffer to recognize that dialect. -- HansM From oscar.benjamin at bristol.ac.uk Fri Jul 20 13:18:52 2012 From: oscar.benjamin at bristol.ac.uk (Oscar Benjamin) Date: Fri, 20 Jul 2012 18:18:52 +0100 Subject: properly catch SIGTERM In-Reply-To: References: Message-ID: What about Kushal's suggestion above? Does the following work for you? signal.signal(signal.SIGTERM, my_SIGTERM_handler) signal.siginterrupt(signal.SIGTERM, flag=False) According to the siginterrupt docs ( http://docs.python.org/library/signal.html) """ Change system call restart behaviour: if flag is False, system calls will be restarted when interrupted by signal signalnum, otherwise system calls will be interrupted. Returns nothing. Availability: Unix '""" Cheers, Oscar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hansmu at xs4all.nl Fri Jul 20 13:45:44 2012 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 20 Jul 2012 19:45:44 +0200 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <5009166e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50099948$0$6987$e4fe514c@news2.news.xs4all.nl> On 20/07/12 11:05:09, Virgil Stokes wrote: > On 20-Jul-2012 10:27, Steven D'Aprano wrote: >> On Fri, 20 Jul 2012 08:20:57 +1000, Chris Angelico wrote: >> >>>>> Since the current evidence indicates the universe will just >>>>> keep >>>>> expanding, it's more of a "deep freeze death..." >>>> Heat death means *lack* of heat. >>> The second law of thermodynamics states that energy tends to go from >>> higher states to lower, with heat being the very lowest. It's possible >>> to do work using (say) kinetic energy, and in the process, some of that >>> energy becomes heat. It's also possible to do work with any difference >>> in temperature (eg Stirling engines), so the state of the universe in >>> which it's no longer possible to do any work will be one in which all >>> energy is heat and everything's at the same temperature. That doesn't >>> mean a lack of heat; in fact, it implies that there'll be rather more >>> heat than there now is, because we currently have a whole lot of >>> chemical energy available to be used. >> Yes, but the point is, that heat will be *incredibly* diffuse, >> essentially spread over the entire universe, which will be MUCH bigger >> than it is now, and hence the temperature will be low even though the >> total amount of heat will be high. >> >> The average temperature of the universe now is about 2.7 degrees above >> absolute zero (i.e. 2.7 K, -270.45 C or -454.81 F), with individual >> hotspots reaching into millions of degrees or higher. By the time the >> last of the stars burn out, the average temperature will be a minuscule >> fraction of a degree above absolute zero, and the only hotspots will be >> the slowly cooling neutron stars. >> >> >>> But in any case, that's a looooooooong way off... >> I once went to an astronomy lecture where the lecturer was talking about >> the eventual death of the sun. He said, "In about 10 billion years, the >> sun will consume almost all of its fuel. It will cool and expand into a >> red giant, and the earth will be engulfed by the expanded sun and >> destroyed." >> >> This fellow sitting next to me got all agitated, stood up and cried out, >> "Does the government know about this? We have to do something!" >> >> The lecturer said "Don't worry sir, there's no need to panic, this won't >> happen for billions of years." >> >> The fellow looked relived and said "Oh thank god, I thought you said >> *million*!" >> > How does this relate to the python list? This thread is as coherent as a typical episode of Monty Python's Flying Circus :-) -- HansM From ian.g.kelly at gmail.com Fri Jul 20 14:14:30 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 20 Jul 2012 12:14:30 -0600 Subject: best way to handle this in Python In-Reply-To: References: <5008ABD5.8020407@davea.name> <6emh0859cren5ond0k5n2f58mh36bnp9jc@invalid.netcom.com> Message-ID: On Fri, Jul 20, 2012 at 4:34 AM, Rita wrote: > Thats an interesting data structure Dennis. I will actually be running this > type of query many times preferable in an ad-hoc environment. That makes it > tough for sqlite3 since there will be several hundred thousand tuples. Several hundred thousand is not an enormous number. I think you're underestimating sqlite3. I just tried a test with one million tuples, six colors per tuple (six million rows altogether). Each row contains a primary key, a timestamp, a color, and a count, with an index on the timestamp column. Building the database from scratch took about a minute; adding the index took about another minute. Incremental updates would of course be much faster. Queries like "select * from data where timestamp between 500000 and 600000" return instantly (from a user perspective). Cheers, Ian From bruce.sherwood at gmail.com Fri Jul 20 14:44:59 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Fri, 20 Jul 2012 12:44:59 -0600 Subject: A thread import problem In-Reply-To: References: Message-ID: Dieter Maurer commented the following on my question about a thread import problem: ---------------------- In a recent discussion in this list someone mentioned that on module import, you should not start a thread. The reason: apparently, Python uses some kind of locking during import which can interfere with "import"s in the started thread. You can (in principle) easily avoid starting the thread on module import. Instead of starting the thread as a side effect of the import, put the start in a function, import the module and then call the thread starting function. ----------------------- Thanks for the helpful information. I tried the experiment of altering the source code to be exec-ed to import a different module and then call a function from that module to start a thread, but that didn't help, perhaps because in this chain of events, which necessarily involve exec's in a thread, it's the equivalent of the problem you identify. I actually do have a solution but it's inelegant. In the module imported by the user's program, I find all import statements in that user's program and execute them (then comment them out), thereby adding their symbols to the module's globals, and I pass the module's globals to the exec statement. I'll state the problem in a more general way in the hopes that someone will see a solution I've missed. The VPython API permits the following short program, which displays a 3D cube moving to the right, and you can rotate and zoom the camera with the mouse: from visual import box, rate b = box() while True: rate(100) # no more than 100 iterations per second b.pos.x += .01 This works because a GUI environment is invoked by the visual module in a secondary thread (written mainly in C++, connected to Python by Boost). The OpenGL rendering of the box in its current position is driven by a 30-millisecond timer. This works fine with any environment other than Mac Cocoa. However, the Mac Cocoa GUI environment and interact loop are required to be the primary thread, so the challenge is to have the visual module set up the Cocoa environment, with the user's program running in a secondary thread. Any ideas? Bruce Sherwood On Wed, Jul 18, 2012 at 5:03 PM, Bruce Sherwood wrote: > I'm trying to do something rather tricky, in which a program imports a > module that starts a thread that exec's a (possibly altered) copy of > the source in the original program, and the module doesn't return. > This has to do with an attempt to run VPython in the Mac Cocoa > context, in which Cocoa is required to be the primary thread, making > it necessary to turn the environment inside out, as currently VPython > invokes the Carbon context as a secondary thread. > > I've created a simple test case, displayed below, that illustrates > something I don't understand. The module reads the source of the > program that imported it, comments out the import statement in that > source, and performs an exec of the modified source. The module then > enters an infinite loop, so that there is no return to the original > program; only the exec-ed program runs, and it runs in a secondary > thread. > > The puzzle is that if there is any later import statement in the exec > source, the exec program halts on that import statement, with no error > message. I saw a discussion that suggested a need for the statement > "global math" to make the math import work, but that doesn't fix the > problem. I've tried with no success various versions of the exec > statement, with respect to its global and local environment. > > Can anyone explain why the math import statement causes a problem? > Thanks for any advice you can give. > > Bruce Sherwood > > --------------------------- > The main program: > > from import_test import * > print('exec this file') > global math > from math import sin > print(sin(3.14159/6)) > > ----------------------------- > Contents of import_test: > > from threading import Thread > from time import sleep > import sys > > prog = open(sys.argv[0]).read() > prog = '#'+prog # comment out the import statement > print(prog) > > class worker(Thread): > def run(self): > print('start thread') > exec(prog) > > w = worker() > w.start() > > while True: > sleep(1) From db3l.net at gmail.com Fri Jul 20 14:50:28 2012 From: db3l.net at gmail.com (David Bolen) Date: Fri, 20 Jul 2012 14:50:28 -0400 Subject: logging time format millisecond precision decimalsign References: <50095684$0$6957$e4fe514c@news2.news.xs4all.nl> Message-ID: "Alex van der Spek" writes: > I use this formatter in logging: > > formatter = logging.Formatter(fmt='%(asctime)s \t %(name)s \t %(levelname)s > \t %(message)s') > > Sample output: > > 2012-07-19 21:34:58,382 root INFO Removed - C:\Users\ZDoor\Documents > > The time stamp has millisecond precision but the decimal separator is a > comma. > > Can I change the comma (,) into a period (.) and if so how? I do it by: 1. Replacing the default date format string to exclude ms. 2. Including %(msecs)03d in the format string where appropriate. Using 'd' instead of s truncates rather than shows the full float value. So in your case, I believe that changing your formatter creation to: formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d \t %(name)s \t %(levelname)s \t %(message)s', '%Y-%m-%d %H:%M:%S') should work. This uses the same date format as the default, but without ms, though of course you could also opt to make any other date format you prefer. -- David From uccoord at microsoft.com Fri Jul 20 19:06:48 2012 From: uccoord at microsoft.com (uccoord at microsoft.com) Date: Fri, 20 Jul 2012 16:06:48 -0700 (PDT) Subject: Microsoft: Seeking Devs with All Levels of Experience for NATIONWIDE Remote Research Study Message-ID: <001303fc-a390-4d13-9f77-467b5cbad02e@googlegroups.com> 'm with Microsoft User Research and we're looking nationally for developers with all levels of experience (from college graduate to senior developer) for an upcoming remote research study. This is a great opportunity to share feedback with Microsoft User Researchers and have a direct impact on the future of Microsoft products and technology. These two hour studies will take place remotely via online meetings starting Tuesday, August 7th. Each participant will be offered their choice of technical software, hardware or games from a list of our most popular products. If this is something you are interested in, you can reply back to me Gina at uccoord at microsoft.com with ?dev" in the subject line with the following information: 1. Name/Phone: 2. Job Title/ Company: 3. How many years of experience do you have developing? 4. How many years have you been with your current employer? 5. Do you use Agile methods? 6. What languages do you develop in? 7. Do you use any non-Microsoft tools? 8. Do you develop mobile applications? Thanks for your time!! Gina Microsoft User Research uccoord at microsoft.com From purplewelshy at googlemail.com Fri Jul 20 19:38:53 2012 From: purplewelshy at googlemail.com (Chris Williams) Date: Sat, 21 Jul 2012 00:38:53 +0100 Subject: Newbie question on python programming Message-ID: Hello I hope this is the right newsgroup for this post. I am just starting to learn python programming and it seems very straightforward so far. It seems, however, geared toward doing the sort of programming for terminal output. Is it possible to write the sort of applications you can create in something like c-sharp or visual c++, or should I be looking at some other programming language? I am using ubuntu 12.04. Thanks, Chris. --- Posted via news://freenews.netfront.net/ - Complaints to news at netfront.net --- From ethan at stoneleaf.us Fri Jul 20 19:59:21 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 20 Jul 2012 16:59:21 -0700 Subject: ANN: dbf.py 0.94 Message-ID: <5009F0D9.1050900@stoneleaf.us> Getting closer to a stable release. Latest version has a simpler, cleaner API, and works on PyPy (and hopefully the other implementations as well ;), as well as CPython. Get your copy at http://python.org/pypi/dbf. Bug reports, comments, and kudos welcome! ;) ~Ethan~ From ian.g.kelly at gmail.com Fri Jul 20 20:30:25 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 20 Jul 2012 18:30:25 -0600 Subject: Newbie question on python programming In-Reply-To: References: Message-ID: On Fri, Jul 20, 2012 at 5:38 PM, Chris Williams wrote: > Hello > > I hope this is the right newsgroup for this post. > > I am just starting to learn python programming and it seems very > straightforward so far. It seems, however, geared toward doing the sort of > programming for terminal output. > > Is it possible to write the sort of applications you can create in something > like c-sharp or visual c++, or should I be looking at some other programming > language? I am using ubuntu 12.04. There are plenty of options for GUI programming in Python. Among the most popular are Tkinter, wxPython, PyGTK, and PyQT, all of which are cross-platform and free. Also, since you specifically mention the .NET languages, IronPython runs on .NET and so is able to make full use of the .NET APIs including Windows Forms and WPF. A more comprehensive list can be found at: http://wiki.python.org/moin/GuiProgramming From steve+comp.lang.python at pearwood.info Fri Jul 20 20:43:58 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 00:43:58 GMT Subject: best way to handle this in Python References: <5008ABD5.8020407@davea.name> <6emh0859cren5ond0k5n2f58mh36bnp9jc@invalid.netcom.com> Message-ID: <5009fb4e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Fri, 20 Jul 2012 12:14:30 -0600, Ian Kelly wrote: > On Fri, Jul 20, 2012 at 4:34 AM, Rita wrote: >> Thats an interesting data structure Dennis. I will actually be running >> this type of query many times preferable in an ad-hoc environment. That >> makes it tough for sqlite3 since there will be several hundred thousand >> tuples. > > Several hundred thousand is not an enormous number. I think you're > underestimating sqlite3. A common trap, and not just for sqlite. I frequently have to remind people -- including myself -- that what is a lot of data for you may not be a lot of data for your computer. -- Steven From steve+comp.lang.python at pearwood.info Fri Jul 20 20:50:13 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 00:50:13 GMT Subject: ANN: dbf.py 0.94 References: Message-ID: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> On Fri, 20 Jul 2012 16:59:21 -0700, Ethan Furman wrote: > Getting closer to a stable release. Excellent! That's fantastic news! I've been waiting for a stable release of dbf for months! I just have one question. What is dbf? > Latest version has a simpler, cleaner API, and works on PyPy (and > hopefully the other implementations as well ;), as well as CPython. > > Get your copy at http://python.org/pypi/dbf. I don't generally click on arbitrary links to find out whether or not the link is something that interests me enough to click on it. -- Steven From menghsiu.lee at gmail.com Fri Jul 20 22:09:08 2012 From: menghsiu.lee at gmail.com (Menghsiu Lee) Date: Fri, 20 Jul 2012 19:09:08 -0700 (PDT) Subject: can someone teach me this? Message-ID: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Hi, I have tried 1000 times to compile this python file to be an exe file by using py2exe and gui2exe But, it does not work out. I am thinking if there can be some genius teaching me how to make this happen. The link in below is the complete code with all sources. Everything is open to everyone since I change this from another expert. http://dl.dropbox.com/u/63928380/blackjack.rar Thanks for your help and instructions. Best regards, menghsiu From rustompmody at gmail.com Fri Jul 20 22:22:16 2012 From: rustompmody at gmail.com (rusi) Date: Fri, 20 Jul 2012 19:22:16 -0700 (PDT) Subject: can someone teach me this? References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On Jul 21, 7:09?am, Menghsiu Lee wrote: "can someone teach me this?" Lesson 1: Use an informational subject line Lesson 2: Post what you did and what happened From lamialily at cleverpun.com Fri Jul 20 22:56:59 2012 From: lamialily at cleverpun.com (Temia Eszteri) Date: Fri, 20 Jul 2012 19:56:59 -0700 Subject: ANN: dbf.py 0.94 References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21 Jul 2012 00:50:13 GMT, Steven D'Aprano wrote: >> Latest version has a simpler, cleaner API, and works on PyPy (and >> hopefully the other implementations as well ;), as well as CPython. >> >> Get your copy at http://python.org/pypi/dbf. > >I don't generally click on arbitrary links to find out whether or not the >link is something that interests me enough to click on it. Can't really call a cheese shop link arbitrary. It's in the best place it could be for providing info about the package. ~Temia -- Invective! Verb your expletive nouns! From rosuav at gmail.com Fri Jul 20 23:02:55 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 21 Jul 2012 13:02:55 +1000 Subject: ANN: dbf.py 0.94 In-Reply-To: References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jul 21, 2012 at 12:56 PM, Temia Eszteri wrote: > On 21 Jul 2012 00:50:13 GMT, Steven D'Aprano > wrote: > >>> Latest version has a simpler, cleaner API, and works on PyPy (and >>> hopefully the other implementations as well ;), as well as CPython. >>> >>> Get your copy at http://python.org/pypi/dbf. >> >>I don't generally click on arbitrary links to find out whether or not the >>link is something that interests me enough to click on it. > > Can't really call a cheese shop link arbitrary. It's in the best place > it could be for providing info about the package. True, but Steven's point still stands, that announcements of this nature are far more readable when they open with a one-sentence statement of what the package _is_. ChrisA From hamilton at nothere.com Fri Jul 20 23:15:35 2012 From: hamilton at nothere.com (hamilton) Date: Fri, 20 Jul 2012 21:15:35 -0600 Subject: can someone teach me this? In-Reply-To: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On 7/20/2012 8:09 PM, Menghsiu Lee wrote: > Hi, > I have tried 1000 times to compile this python file to be an exe file by using py2exe and gui2exe > But, it does not work out. > I am thinking if there can be some genius teaching me how to make this happen. > The link in below is the complete code with all sources. Everything is open to everyone since I change this from another expert. > > http://dl.dropbox.com/u/63928380/blackjack.rar Oh yea, let me download a rar file without an explanation. You are an idiot, or a scammer. > > Thanks for your help and instructions. > > Best regards, > > menghsiu > From ethan at stoneleaf.us Fri Jul 20 23:26:25 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 20 Jul 2012 20:26:25 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500A2161.7090708@stoneleaf.us> Steven D'Aprano wrote: > On Fri, 20 Jul 2012 16:59:21 -0700, Ethan Furman wrote: > >> Getting closer to a stable release. > > Excellent! That's fantastic news! I've been waiting for a stable release > of dbf for months! I just have one question. > > What is dbf? :) dbf (also known as python dbase) is a module for reading/writing dBase III, FP, VFP, and soon Clipper, .dbf database files. It's an ancient format that still finds lots of use. It even reads and writes memo fields -- something which none of the other modules do (which is why I wrote this one -- I needed that! ;). It supports unicode, and returns all fields as native Python types: Character --> unicode Date --> datetime.date Logical --> bool/None Memo --> unicode Numeric --> int/float depending on field definition If a field is uninitialized (Date, Logical, Numeric) then None is returned for the value. Tables are accessible as lists; Records are accessible as lists, dicts, and objects ( attribute access ). Enjoy your weekend! From simoncropper at fossworkflowguides.com Fri Jul 20 23:30:40 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Sat, 21 Jul 2012 13:30:40 +1000 Subject: ANN: dbf.py 0.94 In-Reply-To: <5009F0D9.1050900@stoneleaf.us> References: <5009F0D9.1050900@stoneleaf.us> Message-ID: <500A2260.20806@fossworkflowguides.com> On 21/07/12 09:59, Ethan Furman wrote: > Getting closer to a stable release. > > Latest version has a simpler, cleaner API, and works on PyPy (and > hopefully the other implementations as well ;), as well as CPython. > > Get your copy at http://python.org/pypi/dbf. > > Bug reports, comments, and kudos welcome! ;) > > ~Ethan~ Question 1 - What version of VFP will dbf work with? Is VFP9 OK? Question 2 - You statement of compatibility is unclear. Works with PyPy, OK. Hopefully works with other implementations, Hm, what does this mean? Works or hopefully works with CPython -- which is it? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From lamialily at cleverpun.com Fri Jul 20 23:33:28 2012 From: lamialily at cleverpun.com (Temia Eszteri) Date: Fri, 20 Jul 2012 20:33:28 -0700 Subject: ANN: dbf.py 0.94 References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, 21 Jul 2012 13:02:55 +1000, Chris Angelico wrote: >On Sat, Jul 21, 2012 at 12:56 PM, Temia Eszteri wrote: >> On 21 Jul 2012 00:50:13 GMT, Steven D'Aprano >> wrote: >> >>>> Latest version has a simpler, cleaner API, and works on PyPy (and >>>> hopefully the other implementations as well ;), as well as CPython. >>>> >>>> Get your copy at http://python.org/pypi/dbf. >>> >>>I don't generally click on arbitrary links to find out whether or not the >>>link is something that interests me enough to click on it. >> >> Can't really call a cheese shop link arbitrary. It's in the best place >> it could be for providing info about the package. > >True, but Steven's point still stands, that announcements of this >nature are far more readable when they open with a one-sentence >statement of what the package _is_. > >ChrisA If I wanted to counter his whole point, I would've quoted his whole post. ;P Yes, the post to the newsgroup is rather oblique, but the cheese shop is hardly arbitrary. ~Temia -- Invective! Verb your expletive nouns! From steve+comp.lang.python at pearwood.info Fri Jul 20 23:34:44 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 03:34:44 GMT Subject: ANN: dbf.py 0.94 References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> On Fri, 20 Jul 2012 19:56:59 -0700, Temia Eszteri wrote: >>I don't generally click on arbitrary links to find out whether or not >>the link is something that interests me enough to click on it. > > Can't really call a cheese shop link arbitrary. It's in the best place > it could be for providing info about the package. You've missed the point. Why should I bother to click on it at all, PyPI or not, if I'm going to find it is a library for something I don't care about? If the developer of the library doesn't write a few words to tell people what his library does when making an announcement, or what improvements there are from the previous release, he's going to struggle to attract even those users who *would* be interested, if only they knew about it. This mailing list is about helping our fellow Python developers improve their skills and solve problems. That doesn't just mean *coding* problems, it also means helping them to write better documentation and promote their software better. For every person like me who takes the time out to gently remind the developer that we aren't mind-readers and don't know WTF he's talking about, there are a thousand who just move on, and he's just lost 99% of his potential user-base. Since he's taken the time out to make a public announcement, I assume he would like people to use his software. If not, why bother making the announcement at all? Unless the software is so well-known that everybody knows what it is, failure to mention what the software does gives the impression that: 1) the software is so niche, or so ill-thought out, that the developer *can't* describe it succinctly; 2) the developer has such poor communication skills that trying to get support will be a nightmare; 3) that he just doesn't give a monkey's toss for anyone else's time or all three. Ethan is a good, helpful member of this community, and so I'm pretty sure that neither 2) nor 3) are true, but others may get the wrong impression. Here are a few randomly selected examples of good release announcements: http://mail.python.org/pipermail/python-announce-list/2012-June/009528.html http://mail.python.org/pipermail/python-announce-list/2012-June/009509.html http://mail.python.org/pipermail/python-announce-list/2012-June/009524.html -- Steven From simoncropper at fossworkflowguides.com Fri Jul 20 23:35:21 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Sat, 21 Jul 2012 13:35:21 +1000 Subject: PyPy, is it a 1:1 replacement for CPython? Message-ID: <500A2379.5050404@fossworkflowguides.com> Hi, Can you use PyPy as a direct replacement for the normal python or is it a specialized compiler that can only work with libraries that are manipulated to operate within its constraints (if it has any). Are there any issues with using PyPy? For example, if programs are created under PyPy are they subtle different from normal code that would make the program incompatible with the normal compiler? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From steve+comp.lang.python at pearwood.info Fri Jul 20 23:38:11 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 03:38:11 GMT Subject: ANN: dbf.py 0.94 References: <5009F0D9.1050900@stoneleaf.us> Message-ID: <500a2423$0$29997$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 13:30:40 +1000, Simon Cropper wrote: > Works with PyPy, OK. > > Hopefully works with other implementations, Hm, what does this mean? I guess that Ethan means that his library definitely works with PyPy and CPython, because he has tested it on those, and that he expects that it will work with Stackless, Jython, IronPython, and any other compliant Python interpreter, but hasn't tested on them. > Works or hopefully works with CPython -- which is it? I agree that the sentence is unclear, but my reading of it is that it works on CPython. -- Steven From lamialily at cleverpun.com Fri Jul 20 23:38:35 2012 From: lamialily at cleverpun.com (Temia Eszteri) Date: Fri, 20 Jul 2012 20:38:35 -0700 Subject: ANN: dbf.py 0.94 References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21 Jul 2012 03:34:44 GMT, Steven D'Aprano wrote: >tl;dr Easy there, tiger. No need to get riled up over a single nitpick over phrasing. ~Temia -- Invective! Verb your expletive nouns! From rosuav at gmail.com Fri Jul 20 23:43:27 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 21 Jul 2012 13:43:27 +1000 Subject: ANN: dbf.py 0.94 In-Reply-To: <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jul 21, 2012 at 1:34 PM, Steven D'Aprano wrote: > Unless the software is so well-known that everybody knows what it is... I've yet to meet ANY piece of software that's like that. Even with releases of CPython (arguably the primary point of this list) it wouldn't hurt to give an explanation, and certainly with other Pythons, it'd help a lot (PyPy and Jython are probably guessable, but I wouldn't bet on anyone knowing what "IronPython" is without a summary). > Here are a few randomly selected examples of good release announcements: > > http://mail.python.org/pipermail/python-announce-list/2012-June/009528.html > > http://mail.python.org/pipermail/python-announce-list/2012-June/009509.html > > http://mail.python.org/pipermail/python-announce-list/2012-June/009524.html Agreed, those are worth imitating. ChrisA From alec.taylor6 at gmail.com Fri Jul 20 23:52:23 2012 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 21 Jul 2012 13:52:23 +1000 Subject: PyPy, is it a 1:1 replacement for CPython? In-Reply-To: <500A2379.5050404@fossworkflowguides.com> References: <500A2379.5050404@fossworkflowguides.com> Message-ID: ask on PyPy's list But yes, it is designed as a 1:1 replacement of CPython On Sat, Jul 21, 2012 at 1:35 PM, Simon Cropper wrote: > Hi, > > Can you use PyPy as a direct replacement for the normal python or is it a > specialized compiler that can only work with libraries that are manipulated > to operate within its constraints (if it has any). > > Are there any issues with using PyPy? For example, if programs are created > under PyPy are they subtle different from normal code that would make the > program incompatible with the normal compiler? > > -- > Cheers Simon > > Simon Cropper - Open Content Creator > > Free and Open Source Software Workflow Guides > ------------------------------------------------------------ > Introduction http://www.fossworkflowguides.com > GIS Packages http://www.fossworkflowguides.com/gis > bash / Python http://www.fossworkflowguides.com/scripting > -- > http://mail.python.org/mailman/listinfo/python-list From steve+comp.lang.python at pearwood.info Fri Jul 20 23:59:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 03:59:47 GMT Subject: PyPy, is it a 1:1 replacement for CPython? References: Message-ID: <500a2933$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 13:35:21 +1000, Simon Cropper wrote: > Hi, > > Can you use PyPy as a direct replacement for the normal python or is it > a specialized compiler that can only work with libraries that are > manipulated to operate within its constraints (if it has any). PyPy should work perfectly with pure-Python software. I don't know if it is compatible with extension libraries written in C or Fortran. > Are there any issues with using PyPy? For example, if programs are > created under PyPy are they subtle different from normal code that would > make the program incompatible with the normal compiler? I don't expect so. There may be special PyPy functions that other Python's won't have, but I don't know of any. If you stick to standard library and language features as described in the normal Python docs, you should be fine. -- Steven From drsalists at gmail.com Sat Jul 21 00:21:33 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Fri, 20 Jul 2012 21:21:33 -0700 Subject: PyPy, is it a 1:1 replacement for CPython? In-Reply-To: <500a2933$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500a2933$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Jul 20, 2012 at 8:59 PM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > On Sat, 21 Jul 2012 13:35:21 +1000, Simon Cropper wrote: > > > Hi, > > > > Can you use PyPy as a direct replacement for the normal python or is it > > a specialized compiler that can only work with libraries that are > > manipulated to operate within its constraints (if it has any). > > PyPy should work perfectly with pure-Python software. I don't know if it > is compatible with extension libraries written in C or Fortran. > PyPy generally does great with pure python that doesn't depend on any C extension modules. Sometimes Pypy will have Pure Python equivalents, sometimes it won't. Sometimes when it doesn't, it does the job with ctypes interfaces, but you generally don't need to know that. Pypy can run some C extension modules, but the PyPy-C boundary is a bit of a slowish hack called cpyext. They're working on a new CFFI module/library that hopes to work nicely with tailor-made modules, which, curiously enough, requires a C compiler at runtime. I gather they've got it running on CPython now, with plans for making it run on PyPY before long. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From janpeterr at freenet.de Sat Jul 21 03:33:27 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 21 Jul 2012 10:33:27 +0300 Subject: Basic question about speed/coding style/memory Message-ID: <500A5B47.1060805@freenet.de> Hello Pythonlist, I have one very basic question about speed,memory friendly coding, and coding style of the following easy "if"-statement in Python 2.7, but Im sure its also the same in Python 3.x Block #---------------------------------- if statemente_true: doSomething() else: doSomethingElseInstead() #---------------------------------- versus this block: #---------------------------------- if statement_true: doSomething() return doSomethingElseInstead() #---------------------------------- I understand the first pattern that I tell the interpreter to do: Check if the conditional is true, run "doSomething()" else go inside the else block and "doSomethingElseInstead()". while the 2nd does only checks: doSomething() if statement_true, if not, just go directly to "doSomethingElseInstead() Now, very briefly, what is the better way to proceed in terms of execution speed, readability, coding style? Letting out the fact that, in order to prevent "doSomethingElseInstead"-Block to execute, a return has to provided. Thank you for reading and hope someone brings light into that. Your fellow python programmer Jan From ethan at stoneleaf.us Sat Jul 21 03:58:17 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 21 Jul 2012 00:58:17 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> <500a2353$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500A6119.4050006@stoneleaf.us> Steven D'Aprano wrote: > This mailing list is about helping our fellow Python developers improve > their skills and solve problems. That doesn't just mean *coding* > problems, it also means helping them to write better documentation and > promote their software better. Indeed it is, and your reminder is appreciated. Hopefully my followup-post was more explanatory. > Unless the software is so well-known that everybody knows what it is, > failure to mention what the software does gives the impression that: > > 1) the software is so niche, or so ill-thought out, that the developer > *can't* describe it succinctly; Nah -- just the end of a long week, needed to go get my daughter, and wanted it out there for those few who actually need the bug fixes (which I neglected to mention). > 2) the developer has such poor communication skills that trying to get > support will be a nightmare; My support is pretty good. :) > 3) that he just doesn't give a monkey's toss for anyone else's time See point one. > or all three. Ethan is a good, helpful member of this community, and > so I'm pretty sure that neither 2) nor 3) are true, but others may get > the wrong impression. Thank you. The project is kinda niche, but very useful if you happen to be in that niche. > Here are a few randomly selected examples of good release announcements: > > http://mail.python.org/pipermail/python-announce-list/2012-June/009528.html > > http://mail.python.org/pipermail/python-announce-list/2012-June/009509.html > > http://mail.python.org/pipermail/python-announce-list/2012-June/009524.html Those are good. My announcement will be better next time. ~Ethan~ From ethan at stoneleaf.us Sat Jul 21 04:02:03 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 21 Jul 2012 01:02:03 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: <500A2260.20806@fossworkflowguides.com> References: <5009F0D9.1050900@stoneleaf.us> <500A2260.20806@fossworkflowguides.com> Message-ID: <500A61FB.7060600@stoneleaf.us> Simon Cropper wrote: > Question 1 - What version of VFP will dbf work with? Is VFP9 OK? As long as you don't use auto-incrementing fields nor varchar fields you'll be fine. > Question 2 - You statement of compatibility is unclear. Works with CPython 2.4 - 2.7. (Tested) Works with PyPy 1.8. (Tested) Should work with the others. (Not tested) ~Ethan~ From bahamutzero8825 at gmail.com Sat Jul 21 04:02:29 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sat, 21 Jul 2012 03:02:29 -0500 Subject: Basic question about speed/coding style/memory In-Reply-To: <500A5B47.1060805@freenet.de> References: <500A5B47.1060805@freenet.de> Message-ID: <500A6215.8070703@gmail.com> On 7/21/2012 2:33 AM, Jan Riechers wrote: > Block > ... > versus this block: > ... > Now, very briefly, what is the better way to proceed in terms of > execution speed, readability, coding style? Using if/else is the most readable in the general sense. Using return (or break or continue as applicable) in this manner would indicate (at least to me) that it's an exceptional or otherwise special case and that the function can't do what it's supposed to. In that case, I would try to catch an exception rather than use if/else whenever possible. I highly doubt there is a significant performance difference between them. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From janpeterr at freenet.de Sat Jul 21 04:13:02 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 21 Jul 2012 11:13:02 +0300 Subject: Basic question about speed/coding style/memory In-Reply-To: <500A6215.8070703@gmail.com> References: <500A5B47.1060805@freenet.de> <500A6215.8070703@gmail.com> Message-ID: <500A648E.3030807@freenet.de> On 21.07.2012 11:02, Andrew Berg wrote: > On 7/21/2012 2:33 AM, Jan Riechers wrote: >> Block >> ... >> versus this block: >> ... >> Now, very briefly, what is the better way to proceed in terms of >> execution speed, readability, coding style? > Using if/else is the most readable in the general sense. Using return > (or break or continue as applicable) in this manner would indicate (at > least to me) that it's an exceptional or otherwise special case and that > the function can't do what it's supposed to. In that case, I would try > to catch an exception rather than use if/else whenever possible. I > highly doubt there is a significant performance difference between them. > Hello Andrew, Your answer is right, in other circumstances I also would stick to try/except, break-statements in loops and so forth. But the question was a bit more elementary. Cause, as I understand the interpreter chooses either the "else" (1st block) or just proceeds with following code outside the if. So if there is some overhead in some fashion in case we don't offer the else, assuming the interpreter has to exit the evaluation of the "if"-statement clause and return to a "normal parsing code"-state outside the if statement itself. I hope this explanation makes more sense in what I want to ask ;) Jan From dieter at handshake.de Sat Jul 21 04:32:09 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sat, 21 Jul 2012 10:32:09 +0200 Subject: A thread import problem References: Message-ID: <87a9yt7bw6.fsf@handshake.de> Bruce Sherwood writes: > ... > from visual import box, rate > b = box() > while True: > rate(100) # no more than 100 iterations per second > b.pos.x += .01 > > This works because a GUI environment is invoked by the visual module > in a secondary thread (written mainly in C++, connected to Python by > Boost). The OpenGL rendering of the box in its current position is > driven by a 30-millisecond timer. This works fine with any environment > other than Mac Cocoa. > > However, the Mac Cocoa GUI environment and interact loop are required > to be the primary thread, so the challenge is to have the visual > module set up the Cocoa environment, with the user's program running > in a secondary thread. Any ideas? The usual approach to this situation is to invoke the user code via a callback from the UI main loop or invoke it explicitely after the UI system has been set up immediately before its main loop is called. Might look somehow like this: main thread: from thread import start_new_thread from visual import setup_gui, start_main_loop setup_gui() # sets up the GUI subsystem start_new_thread(lambda: __import__(), ()) start_main_loop() From rosuav at gmail.com Sat Jul 21 05:04:12 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 21 Jul 2012 19:04:12 +1000 Subject: Basic question about speed/coding style/memory In-Reply-To: <500A5B47.1060805@freenet.de> References: <500A5B47.1060805@freenet.de> Message-ID: On Sat, Jul 21, 2012 at 5:33 PM, Jan Riechers wrote: > Block > #---------------------------------- > if statemente_true: > doSomething() > else: > doSomethingElseInstead() > > #---------------------------------- This means, to me, that the two options are peers - you do this or you do that. > versus this block: > #---------------------------------- > if statement_true: > doSomething() > return > > doSomethingElseInstead() > > #---------------------------------- This would be for an early abort. Don't bother doing most of this function's work, just doSomething. Might be an error condition, or perhaps an optimized path. Definitely for error conditions, I would use the second option. The "fail and bail" notation keeps the entire error handling in one place: def func(x,y,z): if x<0: y+=5 return if y<0: raise PEBKAC("There's an idiot here somewhere") # ... do the rest of the work Note the similarity between the control structures. Raising an exception immediately terminates processing, without polluting the rest of the function with an unnecessary indentation level. Early aborting through normal function return can do the same thing. But this is purely a matter of style. I don't think there's any significance in terms of processing time or memory usage, and even if there is, it would be dwarfed by considerations of readability. Make your code look like what it's doing, and let the execution take care of itself. ChrisA From bahamutzero8825 at gmail.com Sat Jul 21 05:05:27 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sat, 21 Jul 2012 04:05:27 -0500 Subject: Basic question about speed/coding style/memory In-Reply-To: <500A648E.3030807@freenet.de> References: <500A5B47.1060805@freenet.de> <500A6215.8070703@gmail.com> <500A648E.3030807@freenet.de> Message-ID: <500A70D7.3060702@gmail.com> On 7/21/2012 3:13 AM, Jan Riechers wrote: > Cause, as I understand the interpreter chooses either the "else" (1st > block) or just proceeds with following code outside the if. If none of the if/elif statements evaluate to something true, the else block is executed. > So if there is some overhead in some fashion in case we don't offer the > else, assuming the interpreter has to exit the evaluation of the > "if"-statement clause and return to a "normal parsing code"-state > outside the if statement itself. I really don't understand. You can look into the dis module if you want to look at how CPython bytecode is executed and the timeit module to measure speed. In any case, I don't see how there would be any significant difference. http://docs.python.org/py3k/library/dis.html http://docs.python.org/py3k/library/timeit.html -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From rosuav at gmail.com Sat Jul 21 05:06:09 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 21 Jul 2012 19:06:09 +1000 Subject: ANN: dbf.py 0.94 In-Reply-To: <500A61FB.7060600@stoneleaf.us> References: <5009F0D9.1050900@stoneleaf.us> <500A2260.20806@fossworkflowguides.com> <500A61FB.7060600@stoneleaf.us> Message-ID: On Sat, Jul 21, 2012 at 6:02 PM, Ethan Furman wrote: > Works with CPython 2.4 - 2.7. (Tested) Have you considered supporting 3.2/3.3 at all? It's often not difficult to make your code compatible with both. Or is there some dependency that is locked to 2.X? ChrisA From steve+comp.lang.python at pearwood.info Sat Jul 21 05:06:40 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Jul 2012 09:06:40 GMT Subject: Basic question about speed/coding style/memory References: Message-ID: <500a711f$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 10:33:27 +0300, Jan Riechers wrote: > Hello Pythonlist, > > I have one very basic question about speed,memory friendly coding, and > coding style of the following easy "if"-statement in Python 2.7, but Im > sure its also the same in Python 3.x I assume that the following is meant to be inside a function, otherwise the return in the second example is illegal. But in general, you're worrying too much about trivia. One way or the other, any speed difference will be trivial. Write whatever style reads and writes most naturally, and only worry about what's faster where it actually counts. To give it an analogy that might be clear, this question is not too far from worrying about whether your car will be faster with the radio aerial up or down. Yes, technically the car will be slower with the aerial up, due to air resistance, but you'd have a job measuring it, and it makes no difference whether you are zooming down the highway at 120mph or stuck in traffic crawling along at 5mph. Here's a minimal example: def with_else(x): if x: a = x else: a = x+1 return a def without_else(x): if x: a = x return a a = x+1 return a Notice that I try to make each function do the same amount of work, so that we're seeing only the difference between "else" vs "no else". Now let's test the speed difference with Python 2.7. Because this is timing small code snippets, we should use the timeit module to time the code: from timeit import Timer setup = "from __main__ import with_else, without_else" t1 = Timer("for i in (0, 1): result = with_else(i)", setup) t2 = Timer("for i in (0, 1): result = without_else(i)", setup) Each snippet calls the function twice, once to take the if branch, then to take the else branch. Now we time how long it takes to run each code snippet 1000000 times. We do that six times each, and print the best (lowest) speed: py> min(t1.repeat(repeat=6)) 0.9761919975280762 py> min(t2.repeat(repeat=6)) 0.9494419097900391 So there is approximately 0.03 second difference per TWO MILLION if...else blocks, or about 15 nanoseconds each. This is highly unlikely to be the bottleneck in your code. Assuming the difference is real, and not just measurement error, the difference is insignificant. So, don't worry about which is faster. Write whichever is more natural, easier to read and write. > Block > #---------------------------------- > if statemente_true: > doSomething() > else: > doSomethingElseInstead() This style is especially recommended when the two clauses are equal in importance. > versus this block: > #---------------------------------- > if statement_true: > doSomething() > return > doSomethingElseInstead() This style is especially recommended when the doSomethingElseInstead() block is the "normal" procedure, and the doSomething() block is a special case. Not necessarily rare, but nevertheless special in some sense. Of course, the decision as to which is the "special" case and which is the "normal" case is often entirely arbitrary. -- Steven From janpeterr at freenet.de Sat Jul 21 05:32:53 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 21 Jul 2012 12:32:53 +0300 Subject: Basic question about speed/coding style/memory In-Reply-To: <500a711f$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500a711f$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500A7745.9000607@freenet.de> On 21.07.2012 12:06, Steven D'Aprano wrote: > > But in general, you're worrying too much about trivia. One way or the > other, any speed difference will be trivial. Write whatever style reads > and writes most naturally, and only worry about what's faster where it > actually counts. > > > Notice that I try to make each function do the same amount of work, so > that we're seeing only the difference between "else" vs "no else". > > Now let's test the speed difference with Python 2.7. Because this is > timing small code snippets, we should use the timeit module to time the > code: > > from timeit import Timer > setup = "from __main__ import with_else, without_else" > t1 = Timer("for i in (0, 1): result = with_else(i)", setup) > t2 = Timer("for i in (0, 1): result = without_else(i)", setup) > > Each snippet calls the function twice, once to take the if branch, then > to take the else branch. > > Now we time how long it takes to run each code snippet 1000000 times. We > do that six times each, and print the best (lowest) speed: > > py> min(t1.repeat(repeat=6)) > 0.9761919975280762 > py> min(t2.repeat(repeat=6)) > 0.9494419097900391 > > So there is approximately 0.03 second difference per TWO MILLION > if...else blocks, or about 15 nanoseconds each. This is highly unlikely > to be the bottleneck in your code. Assuming the difference is real, and > not just measurement error, the difference is insignificant. > > So, don't worry about which is faster. Write whichever is more natural, > easier to read and write. > > Hello Steven, very nice example and thank you very much for also for the Timeit test! Actually it confirms my assumption in some way: [SNIP myself] So if there is some overhead in some fashion in case we don't offer the else, assuming the interpreter has to exit the evaluation of the "if"-statement clause and return to a "normal parsing code"-state outside the if statement itself. [SNAP] Without having looked at Andrew's bytecode excecution hint, using the dis module, to see how the interpreter handles the task on lower level. But fare enough for me :) But I agree, the return in my example is misleading and it would be illegal outside of a function call. I just added it to make clear that the fellow code below the return should not be executed in comparison to the 2nd example. Thank you very much Jan From mmdionisio1993 at yahoo.com.ph Sat Jul 21 06:36:19 2012 From: mmdionisio1993 at yahoo.com.ph (Maria Hanna Carmela Dionisio) Date: Sat, 21 Jul 2012 18:36:19 +0800 (SGT) Subject: my email In-Reply-To: <50061A89.9090200@mrabarnett.plus.com> References: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> <50061A89.9090200@mrabarnett.plus.com> Message-ID: <1342866979.8152.YahooMailNeo@web193102.mail.sg3.yahoo.com> lolz sorry i already change it..just a newbhie, that's why :Dv ________________________________ From: MRAB To: python-list at python.org Sent: Wednesday, July 18, 2012 10:08 AM Subject: Re: my email On 18/07/2012 02:44, Maria Hanna Carmela Dionisio wrote: > mmdionisio1993 at yahoo.com.ph > > Just a newbhie here :> > ...who has just revealed her password! [remainder snipped] -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Jul 21 06:41:14 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Jul 2012 06:41:14 -0400 Subject: PyPy, is it a 1:1 replacement for CPython? In-Reply-To: References: <500A2379.5050404@fossworkflowguides.com> Message-ID: On 7/20/2012 11:52 PM, Alec Taylor wrote: > ask on PyPy's list > > But yes, it is designed as a 1:1 replacement of CPython It is a replacement for some late 2.x versions but not, at present, for Python 3. -- Terry Jan Reedy From d at davea.name Sat Jul 21 06:48:29 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 06:48:29 -0400 Subject: Sudden doubling of nearly all messages Message-ID: <500A88FD.40504@davea.name> Has anybody else noticed the sudden double-posting of nearly all messages in the python mailing list? Previously, I've seen some messages double posted, and it was nearly always a newbie, presumably posting via some low-end gateway. But now i'm noticing nearly every message appears twice, identical datestamps, and usually one message considered a reply to the other. Deleting these locally is not only a pain, but if I get the wrong one, it messes up the threading. I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for non-digest mode. I read the messages in threaded mode. Probably related, I've had a serious spate of messages are obvious Re: types, but not threaded to the original set. I'm guessing because it's because I earlier deleted one of a pair. -- DaveA From bahamutzero8825 at gmail.com Sat Jul 21 07:05:14 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sat, 21 Jul 2012 06:05:14 -0500 Subject: Sudden doubling of nearly all messages In-Reply-To: <500A88FD.40504@davea.name> References: <500A88FD.40504@davea.name> Message-ID: <500A8CEA.8030307@gmail.com> On 7/21/2012 5:48 AM, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? I am also using the mailing list, but I haven't experienced this. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From breamoreboy at yahoo.co.uk Sat Jul 21 07:18:09 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 21 Jul 2012 12:18:09 +0100 Subject: Sudden doubling of nearly all messages In-Reply-To: <500A88FD.40504@davea.name> References: <500A88FD.40504@davea.name> Message-ID: On 21/07/2012 11:48, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? No. > > Previously, I've seen some messages double posted, and it was nearly > always a newbie, presumably posting via some low-end gateway. But now > i'm noticing nearly every message appears twice, identical datestamps, > and usually one message considered a reply to the other. > > Deleting these locally is not only a pain, but if I get the wrong one, > it messes up the threading. I have noticed some problems with threading. > > I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for > non-digest mode. I read the messages in threaded mode. Windows Vista, rest the same. > > Probably related, I've had a serious spate of messages are obvious Re: > types, but not threaded to the original set. I'm guessing because it's > because I earlier deleted one of a pair. > Could well be. Just sorry I can't be of more help. :( -- Cheers. Mark Lawrence. From d at davea.name Sat Jul 21 07:25:08 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 07:25:08 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: <500A8CEA.8030307@gmail.com> References: <500A88FD.40504@davea.name> <500A8CEA.8030307@gmail.com> Message-ID: <500A9194.7050901@davea.name> On 07/21/2012 07:05 AM, Andrew Berg wrote: > On 7/21/2012 5:48 AM, Dave Angel wrote: >> Has anybody else noticed the sudden double-posting of nearly all >> messages in the python mailing list? > I am also using the mailing list, but I haven't experienced this. Well, my own message was doubled, but not your reply. When I look at the message sources, they definitely are different. The one looks to me like an ordinary email. The other is much longer, but I don't claim to know what all the fields mean. One pair of fields that looks interesting is: ... X-Original-To: python-list at python.org ... Delivered-To: python-list at mail.python.org I sent to python-list at python.org, and when I do a reply-all that's what gets filled in. But what about the other address? The pervasive doubling just started in the last day or two; I saw 50 new messages overnight, between about 10pm and 4am, EDT. I haven't changed any settings on purpose, and the only new software is whatever the Linux update manager changes. -- DaveA From cjw at ncf.ca Sat Jul 21 07:27:04 2012 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 21 Jul 2012 07:27:04 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On 21/07/2012 6:48 AM, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? > No. Colin W. From jasonveldicott at gmail.com Sat Jul 21 07:35:41 2012 From: jasonveldicott at gmail.com (Jason Veldicott) Date: Sat, 21 Jul 2012 04:35:41 -0700 Subject: Calling Java jar class with parameter from Python Message-ID: Hi, I have read a number of posts on how this can be done, but I have not been able to replicate success with the particular command I'm wishing to execute. I am wanting to execute the following Java command from Python in Windows: java -cp c:\antlr\antlr-3.4-complete.jar org.antlr.Tool "C:\Users\Jason\Documents\antlr\java grammar\Java.g" This command works outside of Python at the command prompt. So I do the same using Python's os.system: os.system("C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe -cp c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool 'C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g'") The return value is 1, which presumably indicates error. Another variation using subprocess.call, one of many tried, gives the same result: subprocess.call(["C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool", "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"] ) This variation using subprocess.Popen, gives a result, but it's ('', None). subprocess.Popen(["C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool", "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], stdout=subprocess.PIPE, shell=True ).communicate() Obviously, some trick is being missed. Could anyone shed light on what it may be? Thanks Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Jul 21 08:20:48 2012 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Jul 2012 14:20:48 +0200 Subject: Calling Java jar class with parameter from Python References: Message-ID: Jason Veldicott wrote: > subprocess.Popen(["C:\\Program Files > (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp > c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool", > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > stdout=subprocess.PIPE, shell=True ).communicate() > > > Obviously, some trick is being missed. Could anyone shed light on what it > may be? File names with spaces can be tricky. Try thoroughly separating the individual arguments and let subprocess do the necessary escaping. I think it should be subprocess.Popen([ "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp", "C:\\antlr\\antlr-3.4-complete.jar", "org.antlr.Tool", "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], stdout=subprocess.PIPE).communicate() From roy at panix.com Sat Jul 21 09:57:48 2012 From: roy at panix.com (Roy Smith) Date: Sat, 21 Jul 2012 09:57:48 -0400 Subject: Calling Java jar class with parameter from Python References: Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > subprocess.Popen([ > "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", > "-cp", > "C:\\antlr\\antlr-3.4-complete.jar", > "org.antlr.Tool", > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > stdout=subprocess.PIPE).communicate() You might also want to try raw strings. This should be identical to Peter's version, but easier to read: subprocess.Popen([ r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe", r"-cp", r"C:\antlr\antlr-3.4-complete.jar", r"org.antlr.Tool", r"C:\Users\Jason\Documents\antlr\java grammar\Java.g"], stdout=subprocess.PIPE).communicate() although I would probably refactor it like: args = [r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe", r"-cp", r"C:\antlr\antlr-3.4-complete.jar", r"org.antlr.Tool", r"C:\Users\Jason\Documents\antlr\java grammar\Java.g", ] proc = subprocess.Popen(args, stdout=subprocess.PIPE) proc.communicate() From bruce.sherwood at gmail.com Sat Jul 21 10:54:53 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sat, 21 Jul 2012 08:54:53 -0600 Subject: A thread import problem In-Reply-To: <87a9yt7bw6.fsf@handshake.de> References: <87a9yt7bw6.fsf@handshake.de> Message-ID: Thanks much for this suggestion. I'm not sure I've correctly understood the operation "start_new_thread(lambda: __import__(), ())". By "your module" do you mean the user program which imported the module that will execute start_new_thread? It hadn't occurred to me to have A import B and B import A, though now that you describe this (if that's indeed what you mean) it makes sense. The original instance of A won't get past its initial import statement because the main loop won't return to it. Bruce Sherwood On Sat, Jul 21, 2012 at 2:32 AM, Dieter Maurer wrote: > Bruce Sherwood writes: >> ... >> from visual import box, rate >> b = box() >> while True: >> rate(100) # no more than 100 iterations per second >> b.pos.x += .01 >> >> This works because a GUI environment is invoked by the visual module >> in a secondary thread (written mainly in C++, connected to Python by >> Boost). The OpenGL rendering of the box in its current position is >> driven by a 30-millisecond timer. This works fine with any environment >> other than Mac Cocoa. >> >> However, the Mac Cocoa GUI environment and interact loop are required >> to be the primary thread, so the challenge is to have the visual >> module set up the Cocoa environment, with the user's program running >> in a secondary thread. Any ideas? > > The usual approach to this situation is to invoke the user code via > a callback from the UI main loop or invoke it explicitely > after the UI system has been set up immediately before its main loop > is called. Might look somehow like this: > > main thread: > > from thread import start_new_thread > from visual import setup_gui, start_main_loop > setup_gui() # sets up the GUI subsystem > start_new_thread(lambda: __import__(), ()) > start_main_loop() From jeanpierreda at gmail.com Sat Jul 21 11:06:27 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 21 Jul 2012 11:06:27 -0400 Subject: can someone teach me this? In-Reply-To: References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On Fri, Jul 20, 2012 at 11:15 PM, hamilton wrote: > You are an idiot, or a scammer. Please be nice. -- Devin From jasonveldicott at gmail.com Sat Jul 21 12:03:57 2012 From: jasonveldicott at gmail.com (jasonveldicott at gmail.com) Date: Sat, 21 Jul 2012 09:03:57 -0700 (PDT) Subject: Calling Java jar class with parameter from Python In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 5:20:48 AM UTC-7, Peter Otten wrote: > Jason Veldicott wrote: > > > subprocess.Popen(["C:\\Program Files > > (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp > > c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool", > > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > > stdout=subprocess.PIPE, shell=True ).communicate() > > > > > > Obviously, some trick is being missed. Could anyone shed light on what it > > may be? > > File names with spaces can be tricky. Try thoroughly separating the > individual arguments and let subprocess do the necessary escaping. > I think it should be > > subprocess.Popen([ > "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", > "-cp", > "C:\\antlr\\antlr-3.4-complete.jar", > "org.antlr.Tool", > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > stdout=subprocess.PIPE).communicate() That did the trick, thanks. I had the impression from another post that the breaking up of command strings into subprocess arguments could be done arbitrarily as needed to deal with nested inverted commas. Obviously as you've shown, this is not the case, at least for Popen. From jasonveldicott at gmail.com Sat Jul 21 12:03:57 2012 From: jasonveldicott at gmail.com (jasonveldicott at gmail.com) Date: Sat, 21 Jul 2012 09:03:57 -0700 (PDT) Subject: Calling Java jar class with parameter from Python In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 5:20:48 AM UTC-7, Peter Otten wrote: > Jason Veldicott wrote: > > > subprocess.Popen(["C:\\Program Files > > (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", "-cp > > c:\\antlr\\antlr-3.4-complete.jar org.antlr.Tool", > > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > > stdout=subprocess.PIPE, shell=True ).communicate() > > > > > > Obviously, some trick is being missed. Could anyone shed light on what it > > may be? > > File names with spaces can be tricky. Try thoroughly separating the > individual arguments and let subprocess do the necessary escaping. > I think it should be > > subprocess.Popen([ > "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", > "-cp", > "C:\\antlr\\antlr-3.4-complete.jar", > "org.antlr.Tool", > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > stdout=subprocess.PIPE).communicate() That did the trick, thanks. I had the impression from another post that the breaking up of command strings into subprocess arguments could be done arbitrarily as needed to deal with nested inverted commas. Obviously as you've shown, this is not the case, at least for Popen. From jasonveldicott at gmail.com Sat Jul 21 12:11:18 2012 From: jasonveldicott at gmail.com (jasonveldicott at gmail.com) Date: Sat, 21 Jul 2012 09:11:18 -0700 (PDT) Subject: Calling Java jar class with parameter from Python In-Reply-To: References: Message-ID: <1d773886-2cd0-4f72-b061-1490db6567e8@googlegroups.com> On Saturday, July 21, 2012 6:57:48 AM UTC-7, Roy Smith wrote: > In article <mailman.2380.1342873263.4697.python-list at python.org>, > Peter Otten <__peter__ at web.de> wrote: > > > subprocess.Popen([ > > "C:\\Program Files (x86)\\Java\\jdk1.7.0_05\\bin\\java.exe", > > "-cp", > > "C:\\antlr\\antlr-3.4-complete.jar", > > "org.antlr.Tool", > > "C:\\Users\\Jason\\Documents\\antlr\\java grammar\\Java.g"], > > stdout=subprocess.PIPE).communicate() > > You might also want to try raw strings. This should be identical to > Peter's version, but easier to read: > > subprocess.Popen([ > r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe", > r"-cp", > r"C:\antlr\antlr-3.4-complete.jar", > r"org.antlr.Tool", > r"C:\Users\Jason\Documents\antlr\java grammar\Java.g"], > stdout=subprocess.PIPE).communicate() > > although I would probably refactor it like: > > args = [r"C:\Program Files (x86)\Java\jdk1.7.0_05\bin\java.exe", > r"-cp", > r"C:\antlr\antlr-3.4-complete.jar", > r"org.antlr.Tool", > r"C:\Users\Jason\Documents\antlr\java grammar\Java.g", > ] > proc = subprocess.Popen(args, stdout=subprocess.PIPE) > proc.communicate() The r string notation at least saves having to double type a bunch of backslashes, although the appearance prepended to the string takes a little getting used to. Visually the separate array to handle arguments is perhaps cleaner, having more resemblance to the original command. Thanks for the tips. From bruce.sherwood at gmail.com Sat Jul 21 12:11:30 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sat, 21 Jul 2012 10:11:30 -0600 Subject: A thread import problem In-Reply-To: <87a9yt7bw6.fsf@handshake.de> References: <87a9yt7bw6.fsf@handshake.de> Message-ID: I couldn't get a simple test case to work. I append a listing of the little test files, all in the same folder. The diagnostic statement print('after start_new_thread\n') works, but then nothing. Originally I tried importing testABA.py but was worried that the circular importing (A imports B which imports A) would be a problem, hence the test of importing a version of the test program without the import. The failure of this test case suggests that one cannot do imports inside secondary threads started in imported modules, something I keep tripping over. But I hope you'll be able to tell me that I'm doing something wrong! Incidentally, a simple test is to execute the file ABA.py, in which case everything works. Bruce Sherwood --------------------------- testABA.py -- execute this file from ABA import * print('exec testABA') from math import sin print(sin(3.14159/6)) ---------------------------- testABA_noimport.py -- a version of testABA.py without the import of ABA print('exec testABA_noimport') from math import sin print(sin(3.14159/6)) ----------------------------- ABA.py from thread import start_new_thread from time import sleep import sys user = 'testABA_noimport' start_new_thread(lambda: __import__(user), ()) print('after start_new_thread\n') while True: sleep(1) On Sat, Jul 21, 2012 at 2:32 AM, Dieter Maurer wrote: > The usual approach to this situation is to invoke the user code via > a callback from the UI main loop or invoke it explicitely > after the UI system has been set up immediately before its main loop > is called. Might look somehow like this: > > main thread: > > from thread import start_new_thread > from visual import setup_gui, start_main_loop > setup_gui() # sets up the GUI subsystem > start_new_thread(lambda: __import__(), ()) > start_main_loop() From werotizy at freent.dd Sat Jul 21 12:13:31 2012 From: werotizy at freent.dd (Tom P) Date: Sat, 21 Jul 2012 18:13:31 +0200 Subject: Newbie question on python programming In-Reply-To: References: Message-ID: On 07/21/2012 02:30 AM, Ian Kelly wrote: > On Fri, Jul 20, 2012 at 5:38 PM, Chris Williams > wrote: >> Hello >> >> I hope this is the right newsgroup for this post. >> >> I am just starting to learn python programming and it seems very >> straightforward so far. It seems, however, geared toward doing the sort of >> programming for terminal output. >> >> Is it possible to write the sort of applications you can create in something >> like c-sharp or visual c++, or should I be looking at some other programming >> language? I am using ubuntu 12.04. > > There are plenty of options for GUI programming in Python. Among the > most popular are Tkinter, wxPython, PyGTK, and PyQT, all of which are > cross-platform and free. Also, since you specifically mention the > .NET languages, IronPython runs on .NET and so is able to make full > use of the .NET APIs including Windows Forms and WPF. A more > comprehensive list can be found at: > > http://wiki.python.org/moin/GuiProgramming > Another platform independent approach is to write the program as a web server something like this- def application(environ, start_response): start_response("200 OK", [("Content-type", "text/plain")]) return ["Hello World!"] if __name__ == '__main__': from wsgiref.simple_server import make_server server = make_server('localhost', 8080, application) server.serve_forever() Run this and then use your browser to connect to localhost:8080 You can then use html features such as forms for input/output. From d at davea.name Sat Jul 21 12:26:35 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 12:26:35 -0400 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> Message-ID: <500AD83B.1090403@davea.name> On 07/21/2012 10:54 AM, Bruce Sherwood wrote: > Thanks much for this suggestion. I'm not sure I've correctly > understood the operation "start_new_thread(lambda: __import__( module>), ())". By "your module" do you mean the user program which > imported the module that will execute start_new_thread? It hadn't > occurred to me to have A import B and B import A, though now that you > describe this (if that's indeed what you mean) it makes sense. The > original instance of A won't get past its initial import statement > because the main loop won't return to it. > > Bruce Sherwood > Two of the things you mustn't do during an import: 1) start or end any threads 2) import something that's already in the chain of pending imports. (otherwise known as recursive imports, or import loop). And there's a special whammy reserved for those who import the script as though it were a module. Like any rule, there are possible exceptions. But you're much better off factoring your code better. I haven't managed to understand your software description, so i'm not making a specific suggestion. But I know others have pointed out that you should do as little as possible in top-level code of an imported module. Make the work happen in a function, and call that function from the original script, not from inside some import. An imported module's top-level code should do nothing more complex than initialize module constants. -- DaveA From hamilton at nothere.com Sat Jul 21 12:53:47 2012 From: hamilton at nothere.com (hamilton) Date: Sat, 21 Jul 2012 10:53:47 -0600 Subject: can someone teach me this? In-Reply-To: References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On 7/21/2012 9:06 AM, Devin Jeanpierre wrote: > On Fri, Jul 20, 2012 at 11:15 PM, hamilton wrote: >> You are an idiot, or a scammer. > > Please be nice. > > -- Devin > Devin, When someone asks me to download a compressed file, its just like the SCAM junk email I get all too often. If the OP would learn how to post on usenet, I would have been happy to help out. I apologize to the group, but the OP needs to learn how to post. hamilton From d at davea.name Sat Jul 21 13:08:03 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 13:08:03 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: <500A88FD.40504@davea.name> References: <500A88FD.40504@davea.name> Message-ID: <500AE1F3.6010803@davea.name> On 07/21/2012 06:48 AM, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? > > Previously, I've seen some messages double posted, and it was nearly > always a newbie, presumably posting via some low-end gateway. But now > i'm noticing nearly every message appears twice, identical datestamps, > and usually one message considered a reply to the other. > > Deleting these locally is not only a pain, but if I get the wrong one, > it messes up the threading. > > I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for > non-digest mode. I read the messages in threaded mode. > > Probably related, I've had a serious spate of messages are obvious Re: > types, but not threaded to the original set. I'm guessing because it's > because I earlier deleted one of a pair. > Well, since nobody else (so far) saw it, and I don't see it any more (except for messages from a relatively few individuals), I'll drop it. Sorry for the noise. -- DaveA From s.pasoev at gmail.com Sat Jul 21 13:24:40 2012 From: s.pasoev at gmail.com (Sergi Pasoev) Date: Sat, 21 Jul 2012 21:24:40 +0400 Subject: Sudden doubling of nearly all messages Message-ID: <877gtxni1z.fsf@gmail.com> > I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for > non-digest mode. I read the messages in threaded mode. I wonder how many decades should pass for linux to reach its 11.04 version. OK, I know you mean Ubuntu. There is already a lot of wrong use of names connected to Gnu, Linux, POSIX, etc. Don't make it worse, please. From ethan at stoneleaf.us Sat Jul 21 14:15:09 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 21 Jul 2012 11:15:09 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: References: <5009F0D9.1050900@stoneleaf.us> <500A2260.20806@fossworkflowguides.com> <500A61FB.7060600@stoneleaf.us> Message-ID: <500AF1AD.5080106@stoneleaf.us> Chris Angelico wrote: > On Sat, Jul 21, 2012 at 6:02 PM, Ethan Furman wrote: >> Works with CPython 2.4 - 2.7. (Tested) > > Have you considered supporting 3.2/3.3 at all? It's often not > difficult to make your code compatible with both. Or is there some > dependency that is locked to 2.X? I'll support 3.3+, but not with the same code base: I want to use all the cool features that 3.3 has! :) ~Ethan~ From rantingrickjohnson at gmail.com Sat Jul 21 14:16:03 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sat, 21 Jul 2012 11:16:03 -0700 (PDT) Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 5:48:29 AM UTC-5, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? > > Previously, I've seen some messages double posted, and it was nearly > always a newbie, presumably posting via some low-end gateway. But now > i'm noticing nearly every message appears twice, identical datestamps, > and usually one message considered a reply to the other. It's due to the new Google Groups interface. They started forcing everyone to use the new buggy version about a week ago EVEN THOUGH the old interface is just fine. Another bug: If you look at the text i quoted you will see HTML character references. Usually i clean the text before posting but sometimes i forget. Google is starting to SUCK! You know, i really went out of my way to support Google for many years even though i knew they were spying on me. But since they were giving me "interesting software" for free, i did not mind so much. But now they have dropped great software and refuse to maintain the software they do have. Their online docs were a great idea, but have you ever tried to use the docs interface for anything serious? S-U-C-K-S! Seriously, i can see Google going the way of yahoo soon. Heck, i even use Bing as my search engine now. I MUST be a disgruntled customer if i am using the search engine of the evil empire! It was a nice run Google. We had good times and bad times. A few smiles and cries. LMBTFY From rantingrickjohnson at gmail.com Sat Jul 21 14:16:03 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sat, 21 Jul 2012 11:16:03 -0700 (PDT) Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 5:48:29 AM UTC-5, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? > > Previously, I've seen some messages double posted, and it was nearly > always a newbie, presumably posting via some low-end gateway. But now > i'm noticing nearly every message appears twice, identical datestamps, > and usually one message considered a reply to the other. It's due to the new Google Groups interface. They started forcing everyone to use the new buggy version about a week ago EVEN THOUGH the old interface is just fine. Another bug: If you look at the text i quoted you will see HTML character references. Usually i clean the text before posting but sometimes i forget. Google is starting to SUCK! You know, i really went out of my way to support Google for many years even though i knew they were spying on me. But since they were giving me "interesting software" for free, i did not mind so much. But now they have dropped great software and refuse to maintain the software they do have. Their online docs were a great idea, but have you ever tried to use the docs interface for anything serious? S-U-C-K-S! Seriously, i can see Google going the way of yahoo soon. Heck, i even use Bing as my search engine now. I MUST be a disgruntled customer if i am using the search engine of the evil empire! It was a nice run Google. We had good times and bad times. A few smiles and cries. LMBTFY From rosuav at gmail.com Sat Jul 21 14:25:21 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 04:25:21 +1000 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Sun, Jul 22, 2012 at 4:16 AM, Rick Johnson wrote: > It was a nice run Google. We had good times and bad times. A few smiles and cries. > > LMBTFY So, what... you reckon Microsoft is going to be the paragon of righteousness against the squalor of Google's information-grubbing tactics? Fascinating. Oh, and make sure you get yourself a new email address Rick, can't have you connected with *Google* mail now can we. Use whichever service you like, but don't seriously expect anything that you don't pay money for to be perfectly featured AND not spy on you. ChrisA From rosuav at gmail.com Sat Jul 21 14:28:36 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 04:28:36 +1000 Subject: ANN: dbf.py 0.94 In-Reply-To: <500AF1AD.5080106@stoneleaf.us> References: <5009F0D9.1050900@stoneleaf.us> <500A2260.20806@fossworkflowguides.com> <500A61FB.7060600@stoneleaf.us> <500AF1AD.5080106@stoneleaf.us> Message-ID: On Sun, Jul 22, 2012 at 4:15 AM, Ethan Furman wrote: > I'll support 3.3+, but not with the same code base: I want to use all the > cool features that 3.3 has! :) The trouble with double-codebasing is that you have double maintenance. But sure. So long as your time isn't under great pressure, it can be quite effective. Recommendation: Figure out a way to minimize double-handling of things. One way might be to have source control manage it for you - apply a patch to your 3.3+ source tree, then merge it into your 2.4+ tree and see if it applies cleanly. I dunno how successful that'd be, but I really dread the idea of maintaining, unassisted, two identical projects in two dialects of the same language. Recipe for burnout I'd predict. ChrisA From mcepl at redhat.com Sat Jul 21 14:33:46 2012 From: mcepl at redhat.com (Matej Cepl) Date: Sat, 21 Jul 2012 20:33:46 +0200 Subject: ANN: dbf.py 0.94 In-Reply-To: References: <5009fcc5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 21/07/12 05:26, Ethan Furman wrote: > dbf (also known as python dbase) is a module for reading/writing > dBase III, FP, VFP, and soon Clipper, .dbf database files. It's > an ancient format that still finds lots of use. Other than the caring for the ancient legacy data, it is still widely used in GIS, because shapefiles (http://en.wikipedia.org/wiki/Shapefile) are based on it. Mat?j From lipska at lipskathekat.com Sat Jul 21 15:08:07 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sat, 21 Jul 2012 20:08:07 +0100 Subject: My first ever Python program, comments welcome Message-ID: Greetings Pythoners A short while back I posted a message that described a task I had set myself. I wanted to implement the following bash shell script in Python Here's the script sort -nr $1 | head -${2:-10} this script takes a filename and an optional number of lines to display and sorts the lines in numerical order, printing them to standard out. if no optional number of lines are input the script prints 10 lines Here's the file. 50 Parrots 12 Storage Jars 6 Lemon Currys 2 Pythons 14 Spam Fritters 23 Flying Circuses 1 Meaning Of Life 123 Holy Grails 76 Secret Policemans Balls 8 Something Completely Differents 12 Lives of Brian 49 Spatulas ... and here's my very first attempt at a Python program I'd be interested to know what you think, you can't hurt my feelings just be brutal (but fair). There is very little error checking as you can see and I'm sure you can crash the program easily. 'Better' implementations most welcome #! /usr/bin/env python3.2 import fileinput from sys import argv from operator import itemgetter l=[] t = tuple filename=argv[1] lineCount=10 with fileinput.input(files=(filename)) as f: for line in f: t=(line.split('\t')) t[0]=int(t[0]) l.append(t) l=sorted(l, key=itemgetter(0)) try: inCount = int(argv[2]) lineCount = inCount except IndexError: #just catch the error and continue None for c in range(lineCount): t=l[c] print(t[0], t[1], sep='\t', end='') Thanks Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From PointedEars at web.de Sat Jul 21 15:19:42 2012 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sat, 21 Jul 2012 21:19:42 +0200 Subject: Basic question about speed/coding style/memory References: Message-ID: <10519940.DbTeoADQlL@PointedEars.de> Jan Riechers wrote: > I have one very basic question about speed,memory friendly coding, and > coding style of the following easy "if"-statement in Python 2.7, but Im > sure its also the same in Python 3.x > > Block > #---------------------------------- > if statemente_true: > doSomething() > else: > doSomethingElseInstead() > > #---------------------------------- > > versus this block: > #---------------------------------- > if statement_true: > doSomething() > return > > doSomethingElseInstead() > > #---------------------------------- > > > I understand the first pattern that I tell the interpreter to do: A common misconception. As a writer of Python source code, (usually) you never tell the (CPython) interpreter anything (but to start working on the source code). Python source code is automatically *compiled* into bytecode by the (CPython) interpreter, and that bytecode is executed by a virtual machine.? So at most, you are telling that virtual machine to do something, through the bytecode created from your source code. > Check if the conditional is true, run "doSomething()" else go inside the > else block and "doSomethingElseInstead()". > > while the 2nd does only checks: > doSomething() if statement_true, if not, just go directly to > "doSomethingElseInstead() > > > Now, very briefly, what is the better way to proceed in terms of > execution speed, readability, coding style? Since this is comp.lang.python, you just need to check against the Zen of Python to know what you should do ;-) For me, this boils down in this case to the common recommendation "return early, return often" as "explicit is better than implicit" and "readability counts". If there is nothing else than the `else' block in the function, there is no use for you to continue in the function, so you should return explicitly at this point. On the other hand, if you can *avoid repeating code* in each branch by _not_ returning in the first branch, you should do that instead ("practicality beats purity"). HTH _____ ? This is not unlike in other so-called "scripting languages"; although for reasons that escape me, the software that compiles the source code ? the compiler ? is called the (C)Python *interpreter*, even in . -- PointedEars Please do not Cc: me. / Bitte keine Kopien per E-Mail. From ian at feete.org Sat Jul 21 15:34:48 2012 From: ian at feete.org (Ian Foote) Date: Sat, 21 Jul 2012 20:34:48 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: <500B0458.5040503@feete.org> On 21/07/12 20:08, Lipska the Kat wrote: > Greetings Pythoners > > A short while back I posted a message that described a task I had set > myself. I wanted to implement the following bash shell script in Python > > Here's the script > > sort -nr $1 | head -${2:-10} > > this script takes a filename and an optional number of lines to display > and sorts the lines in numerical order, printing them to standard out. > if no optional number of lines are input the script prints 10 lines > > Here's the file. > > 50 Parrots > 12 Storage Jars > 6 Lemon Currys > 2 Pythons > 14 Spam Fritters > 23 Flying Circuses > 1 Meaning Of Life > 123 Holy Grails > 76 Secret Policemans Balls > 8 Something Completely Differents > 12 Lives of Brian > 49 Spatulas > > > ... and here's my very first attempt at a Python program > I'd be interested to know what you think, you can't hurt my feelings > just be brutal (but fair). There is very little error checking as you > can see and I'm sure you can crash the program easily. > 'Better' implementations most welcome > > #! /usr/bin/env python3.2 > > import fileinput > from sys import argv > from operator import itemgetter > > l=[] > t = tuple What is this line supposed to do? If you're trying to make an empty tuple, you can write: t = () But I don't think this is needed at all. > filename=argv[1] > lineCount=10 > > with fileinput.input(files=(filename)) as f: > for line in f: > t=(line.split('\t')) > t[0]=int(t[0]) > l.append(t) > l=sorted(l, key=itemgetter(0)) > > try: > inCount = int(argv[2]) > lineCount = inCount I don't think you need to split this into two lines here. try: lineCount = int(argv[2]) should work. > except IndexError: > #just catch the error and continue > None I would use pass instead of None here - I want to "do nothing" rather than create a None object. > for c in range(lineCount): > t=l[c] > print(t[0], t[1], sep='\t', end='') > > Thanks > > Lipska > My only other point is that you might find it helpful to use slightly more verbose names than l or t - its not immediately obvious to the reader what these are intended to represent. Regards, Ian From python at mrabarnett.plus.com Sat Jul 21 15:40:46 2012 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 21 Jul 2012 20:40:46 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: <500B05BE.10908@mrabarnett.plus.com> On 21/07/2012 20:08, Lipska the Kat wrote: > Greetings Pythoners > > A short while back I posted a message that described a task I had set > myself. I wanted to implement the following bash shell script in Python > > Here's the script > > sort -nr $1 | head -${2:-10} > > this script takes a filename and an optional number of lines to display > and sorts the lines in numerical order, printing them to standard out. > if no optional number of lines are input the script prints 10 lines > > Here's the file. > > 50 Parrots > 12 Storage Jars > 6 Lemon Currys > 2 Pythons > 14 Spam Fritters > 23 Flying Circuses > 1 Meaning Of Life > 123 Holy Grails > 76 Secret Policemans Balls > 8 Something Completely Differents > 12 Lives of Brian > 49 Spatulas > > > ... and here's my very first attempt at a Python program > I'd be interested to know what you think, you can't hurt my feelings > just be brutal (but fair). There is very little error checking as you > can see and I'm sure you can crash the program easily. > 'Better' implementations most welcome > > #! /usr/bin/env python3.2 > > import fileinput > from sys import argv > from operator import itemgetter > > l=[] > t = tuple What's the purpose of this line? > filename=argv[1] > lineCount=10 > > with fileinput.input(files=(filename)) as f: > for line in f: > t=(line.split('\t')) > t[0]=int(t[0]) > l.append(t) > l=sorted(l, key=itemgetter(0)) Short is: l.sort(key=itemgetter(0)) > > try: > inCount = int(argv[2]) > lineCount = inCount You may as well say: lineCount = int(argv[2]) > except IndexError: > #just catch the error and continue > None The do-nothing statement is: pass > > for c in range(lineCount): > t=l[c] If there are fewer than 'lineCount' lines, this will raise IndexError. You could do this instead: for t in l[ : lineCount]: > print(t[0], t[1], sep='\t', end='') > From d at davea.name Sat Jul 21 16:10:51 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 16:10:51 -0400 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: <500B0CCB.5010306@davea.name> On 07/21/2012 03:08 PM, Lipska the Kat wrote: > Greetings Pythoners > > A short while back I posted a message that described a task I had set > myself. I wanted to implement the following bash shell script in Python > You already have comments from Ian and MRAB, and I'll try to point out only things that they did not. Congratulations on getting your first program running. And when reading the following, remember that getting it right is more important than getting it pretty. > Here's the script > > sort -nr $1 | head -${2:-10} > > this script takes a filename and an optional number of lines to display > and sorts the lines in numerical order, printing them to standard out. > if no optional number of lines are input the script prints 10 lines > > Here's the file. > > 50 Parrots > 12 Storage Jars > 6 Lemon Currys > 2 Pythons > 14 Spam Fritters > 23 Flying Circuses > 1 Meaning Of Life > 123 Holy Grails > 76 Secret Policemans Balls > 8 Something Completely Differents > 12 Lives of Brian > 49 Spatulas > > > ... and here's my very first attempt at a Python program > I'd be interested to know what you think, you can't hurt my feelings > just be brutal (but fair). There is very little error checking as you > can see and I'm sure you can crash the program easily. > 'Better' implementations most welcome > > #! /usr/bin/env python3.2 > > import fileinput > from sys import argv > from operator import itemgetter > > l=[] I prefer to initialize an empty collection just before the loop that's going to fill it. Then if you later decide to generalize some other part of the code, it's less likely to break. So i'd move this line to right-before the for loop. > t = tuple Even if you were going to use this initialization later, it doesn't do what you think it does. It doesn't create a tuple, it just makes another reference to the class. If you had wanted an empty tuple, you should either do t=tuple(), or better t=() > filename=argv[1] > lineCount=10 > I'd suggest getting into the habit of doing all your argv parsing in one place. So check for argv[2] here, rather than inside the loop below. Eventually you're going to have code complex enough to use an argument parsing library. And of course, something to tell your use what the arguments are supposed to be. > with fileinput.input(files=(filename)) as f: fileinput is much more general than you want for processing a single file. That may be deliberate, if you're picturing somebody using wildcards on their input. But if so, you should probably use a different name, something that indicates plural. > for line in f: > t=(line.split('\t')) > t[0]=int(t[0]) > l.append(t) > l=sorted(l, key=itemgetter(0)) > Your sample data has duplicate numbers. So you really ought to decide how you'd like such lines sorted in the output. Your present code simply preserves the present order of such lines. But if you remove the key parameter entirely, the default sort order will sort with t[0] as primary key, and t[1] as tie-breaker. That'd probably be what I'd do, after trying to clarify with the client what the desired sort order was. > try: > inCount = int(argv[2]) > lineCount = inCount > except IndexError: > #just catch the error and continue > None > > for c in range(lineCount): > t=l[c] > print(t[0], t[1], sep='\t', end='') > > Thanks > > Lipska > > A totally off-the-wall query. Are you using a source control system, such as git ? It can make you much braver about refactoring a working program. -- DaveA From bruce.sherwood at gmail.com Sat Jul 21 16:36:41 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sat, 21 Jul 2012 14:36:41 -0600 Subject: A thread import problem In-Reply-To: <500AD83B.1090403@davea.name> References: <87a9yt7bw6.fsf@handshake.de> <500AD83B.1090403@davea.name> Message-ID: Thanks much for this clear statement. I hadn't managed to find any documentation on this specific issue. Bruce Sherwood On Sat, Jul 21, 2012 at 10:26 AM, Dave Angel wrote: > Two of the things you mustn't do during an import: > > 1) start or end any threads > 2) import something that's already in the chain of pending imports. > (otherwise known as recursive imports, or import loop). And there's a > special whammy reserved for those who import the script as though it > were a module. > > Like any rule, there are possible exceptions. But you're much better > off factoring your code better. > > I haven't managed to understand your software description, so i'm not > making a specific suggestion. But I know others have pointed out that > you should do as little as possible in top-level code of an imported > module. Make the work happen in a function, and call that function from > the original script, not from inside some import. An imported module's > top-level code should do nothing more complex than initialize module > constants. > > > -- > > DaveA > > From d at davea.name Sat Jul 21 16:53:29 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 16:53:29 -0400 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <500AD83B.1090403@davea.name> Message-ID: <500B16C9.6070608@davea.name> On 07/21/2012 04:36 PM, Bruce Sherwood wrote: > Thanks much for this clear statement. I hadn't managed to find any > documentation on this specific issue. > > Bruce Sherwood > > On Sat, Jul 21, 2012 at 10:26 AM, Dave Angel wrote: >> Two of the things you mustn't do during an import: >> >> 1) start or end any threads >> 2) import something that's already in the chain of pending imports. >> (otherwise known as recursive imports, or import loop). And there's a >> special whammy reserved for those who import the script as though it >> were a module. >> >> Like any rule, there are possible exceptions. But you're much better >> off factoring your code better. >> >> I haven't managed to understand your software description, so i'm not >> making a specific suggestion. But I know others have pointed out that >> you should do as little as possible in top-level code of an imported >> module. Make the work happen in a function, and call that function from >> the original script, not from inside some import. An imported module's >> top-level code should do nothing more complex than initialize module >> constants. >> >> >> -- >> >> DaveA >> >> (You top-posted, which makes it harder to figure out who said what.) For docs on the threading thing, see: http://docs.python.org/library/threading.html " ... an import should not have the side effect of spawning a new thread and then waiting for that thread in any way..." -- DaveA From sscc at mweb.co.za Sat Jul 21 16:57:56 2012 From: sscc at mweb.co.za (Alex Strickland) Date: Sat, 21 Jul 2012 22:57:56 +0200 Subject: ANN: dbf.py 0.94 In-Reply-To: <5009F0D9.1050900@stoneleaf.us> References: <5009F0D9.1050900@stoneleaf.us> Message-ID: <500B17D4.8040702@mweb.co.za> Hi > Getting closer to a stable release. > > Latest version has a simpler, cleaner API, and works on PyPy (and > hopefully the other implementations as well ;), as well as CPython. > > Get your copy at http://python.org/pypi/dbf. > > Bug reports, comments, and kudos welcome! ;) "Not supported: index files": I have been using http://sourceforge.net/projects/harbour-project/ for years where a guy called Przemyslaw Czerpak has written an absolutely bullet proof implementation of NTX and CDX for DBF. Maybe it will interest you. PS : bareable is spelt bearable. -- Regards Alex From max at alcyone.com Sat Jul 21 17:28:18 2012 From: max at alcyone.com (Erik Max Francis) Date: Sat, 21 Jul 2012 14:28:18 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <5009166e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 07/20/2012 02:05 AM, Virgil Stokes wrote: > On 20-Jul-2012 10:27, Steven D'Aprano wrote: >> The fellow looked relived and said "Oh thank god, I thought you said >> *million*!" > > How does this relate to the python list? It's also a seriously old joke. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis She's your moon, she's your sun / She could even be the one -- Nik Kershaw From max at alcyone.com Sat Jul 21 17:32:36 2012 From: max at alcyone.com (Erik Max Francis) Date: Sat, 21 Jul 2012 14:32:36 -0700 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <3vnfd9-343.ln1@satorlaser.homedns.org> <-8SdnVrXGqie25jNnZ2dnUVZ7qKdnZ2d@bt.com> <5005A103.9050802@stoneleaf.us> <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> <50076437$0$1756$c3e8da3$76491128@news.astraweb.com> <3d919437-80a8-424f-ae90-fb829434dba2@po9g2000pbb.googlegroups.com> <500804cc$0$29978$c3e8da3$5496439d@news.astraweb.com> <50084FEC.7040806@tim.thechases.com> <500912bb$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 07/20/2012 03:28 AM, BartC wrote: > "Erik Max Francis" wrote in message > news:GsKdnWOQPKOOvZTNnZ2dnUVZ5s2dnZ2d at giganews.com... >> On 07/20/2012 01:11 AM, Steven D'Aprano wrote: >>> On Thu, 19 Jul 2012 13:50:36 -0500, Tim Chase wrote: > >>> I'm reminded of Graham's Number, which is so large that there aren't >>> enough molecules in the universe to write it out as a power tower >>> a^b^c^d^..., or even in a tower of hyperpowers a^^b^^c^^d^^... It was >>> the >>> provable upper bound to a question to which experts in the field thought >>> the most likely answer was ... six. >>> >>> (The bounds have since been reduced: the lower bound is now 13, and the >>> upper bound is *much* smaller than Graham's Number but still >>> inconceivably ginormous.) >> >> You don't even need to go that high. Even a run-of-the-mill googol >> (10^100) is far larger than the total number of elementary particles in >> the observable Universe. > > But you can write it down, even as a straightforward number, without any > problem. Perhaps a googolplex (10^10^100 iirc) would be difficult to > write it down in full, but I have just represented it as an exponent > with little difficulty. > > These bigger numbers can't be written down, because there will never be > enough material, even using multiple systems of exponents. But that's true for precisely the same reason as what I said. If you're going to write a number down in standard format (whatever the base), then the number of digits needed scales as the logarithm of the number (again, whatever the base). log_10 10^100 is trivially 100, so a rough order of magnitude in that form is easy to write down. But the log_10 10^10^100 is 10^100 = a googol, which is already more than the number of elementary particles in the observable Universe. > (A few years ago the biggest number I'd heard of was Skewes' Number > (something like 10^10^10^34), but even that is trivial to write using > conventional exponents as I've just shown. Graham's Number is in a > different > class altogether.) Anything's trivial to "write down." Just say "the number such that ..." and you've written it down. Even "numbers" that aren't really numbers, such as transfinite cardinals! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis She's your moon, she's your sun / She could even be the one -- Nik Kershaw From bruce.sherwood at gmail.com Sat Jul 21 17:35:26 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sat, 21 Jul 2012 15:35:26 -0600 Subject: A thread import problem In-Reply-To: <500B16C9.6070608@davea.name> References: <87a9yt7bw6.fsf@handshake.de> <500AD83B.1090403@davea.name> <500B16C9.6070608@davea.name> Message-ID: On Sat, Jul 21, 2012 at 2:53 PM, Dave Angel wrote: > On 07/21/2012 04:36 PM, Bruce Sherwood wrote: >> Thanks much for this clear statement. I hadn't managed to find any >> documentation on this specific issue. >> >> Bruce Sherwood >> >> On Sat, Jul 21, 2012 at 10:26 AM, Dave Angel wrote: >>> Two of the things you mustn't do during an import: >>> >>> 1) start or end any threads >>> 2) import something that's already in the chain of pending imports. >>> (otherwise known as recursive imports, or import loop). And there's a >>> special whammy reserved for those who import the script as though it >>> were a module. >>> >>> Like any rule, there are possible exceptions. But you're much better >>> off factoring your code better. >>> >>> I haven't managed to understand your software description, so i'm not >>> making a specific suggestion. But I know others have pointed out that >>> you should do as little as possible in top-level code of an imported >>> module. Make the work happen in a function, and call that function from >>> the original script, not from inside some import. An imported module's >>> top-level code should do nothing more complex than initialize module >>> constants. >>> >>> >>> -- >>> >>> DaveA >>> >>> > > (You top-posted, which makes it harder to figure out who said what.) > > For docs on the threading thing, see: > > http://docs.python.org/library/threading.html > > " ... an import should not have the side effect of spawning a new thread > and then waiting for that thread in any way..." > > > > > -- > > DaveA > Thanks. I had read that as forbidding "waiting for that thread", not forbidding spawning a new thread. The following sentence says, "Failing to abide by this restriction can lead to a deadlock if the spawned thread directly or indirectly attempts to import a module." I gather that a clearer, more forceful statement might be, "Failing to abide by this restriction WILL lead to a deadlock if the spawned thread directly or indirectly attempts to import a module." All of which implies the behavior I've seen in various experiments, namely that as long as the spawned thread doesn't do any imports, I haven't seen any problems with spawning a thread in an imported module. I take your word for it that this is a no-no, but I don't know why. Bruce Sherwood From breamoreboy at yahoo.co.uk Sat Jul 21 17:49:51 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 21 Jul 2012 22:49:51 +0100 Subject: ANN: dbf.py 0.94 In-Reply-To: <500B17D4.8040702@mweb.co.za> References: <5009F0D9.1050900@stoneleaf.us> <500B17D4.8040702@mweb.co.za> Message-ID: On 21/07/2012 21:57, Alex Strickland wrote: > Hi > >> Getting closer to a stable release. >> >> Latest version has a simpler, cleaner API, and works on PyPy (and >> hopefully the other implementations as well ;), as well as CPython. >> >> Get your copy at http://python.org/pypi/dbf. >> >> Bug reports, comments, and kudos welcome! ;) > > "Not supported: index files": > > I have been using http://sourceforge.net/projects/harbour-project/ for > years where a guy called Przemyslaw Czerpak has written an absolutely > bullet proof implementation of NTX and CDX for DBF. Maybe it will > interest you. > > PS : bareable is spelt bearable. > and PS is spelt p.s. :) -- Cheers. Mark Lawrence. From d at davea.name Sat Jul 21 18:33:05 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 18:33:05 -0400 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <500AD83B.1090403@davea.name> <500B16C9.6070608@davea.name> Message-ID: <500B2E21.5000206@davea.name> On 07/21/2012 05:35 PM, Bruce Sherwood wrote: > On Sat, Jul 21, 2012 at 2:53 PM, Dave Angel wrote: >> >> For docs on the threading thing, see: >> >> http://docs.python.org/library/threading.html >> >> " ... an import should not have the side effect of spawning a new thread >> and then waiting for that thread in any way..." >> >> >> >> >> -- >> >> DaveA >> > Thanks. I had read that as forbidding "waiting for that thread", not > forbidding spawning a new thread. The following sentence says, > "Failing to abide by this restriction can lead to a deadlock if the > spawned thread directly or indirectly attempts to import a module." I > gather that a clearer, more forceful statement might be, "Failing to > abide by this restriction WILL lead to a deadlock if the spawned > thread directly or indirectly attempts to import a module." All of > which implies the behavior I've seen in various experiments, namely > that as long as the spawned thread doesn't do any imports, I haven't > seen any problems with spawning a thread in an imported module. I take > your word for it that this is a no-no, but I don't know why. > > Bruce Sherwood I don't know just what will work and what will not; But there are lots of subtle and indirect ways of "waiting for that thread" and I suspect that import is one of them. Since I've never seen a case where we had to break the general rule, it just seems easier to keep it clean. No threading inside an import. Same with recursive imports. I could list some of the specific problems that crop up, but since the only time recursive imports are unavoidable is when you're constrained by preexisting 3rd party software that does something strange, it seems easier to make a simple rule that's easy enough to test for. if you try to import the script (that imported you) as though it were a module, you end up with two copies of that module, and if they have any non-constant globals, you can get very strange symptoms. In other recursion cases, -- DaveA From jeanpierreda at gmail.com Sat Jul 21 19:07:28 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 21 Jul 2012 19:07:28 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Sat, Jul 21, 2012 at 2:25 PM, Chris Angelico wrote: > On Sun, Jul 22, 2012 at 4:16 AM, Rick Johnson > wrote: >> It was a nice run Google. We had good times and bad times. A few smiles and cries. >> >> LMBTFY > > So, what... you reckon Microsoft is going to be the paragon of > righteousness against the squalor of Google's information-grubbing > tactics? Fascinating. It's happened before. The example that made me really realize this was when my university, the University of Toronto, was considering both Microsoft and Google as mail providers for students last year. They chose Microsoft, to a mass of student responses to the effect of "but Microsoft is Evil!". It turns out that they ended up choosing Microsoft because they gave stronger privacy guarantees. People hold grudges against MS too strongly, and they believe too much in Google's righteousness. They are both big companies that don't necessarily care about you. -- Devin From bruce.sherwood at gmail.com Sat Jul 21 19:10:05 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sat, 21 Jul 2012 17:10:05 -0600 Subject: A thread import problem In-Reply-To: <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> Message-ID: On Sat, Jul 21, 2012 at 4:16 PM, Dennis Lee Bieber wrote: > On Sat, 21 Jul 2012 10:11:30 -0600, Bruce Sherwood > declaimed the following in > gmane.comp.python.general: > > >> >> --------------------------- >> testABA.py -- execute this file >> >> from ABA import * >> print('exec testABA') >> from math import sin >> print(sin(3.14159/6)) >> >> ---------------------------- >> testABA_noimport.py -- a version of testABA.py without the import of ABA >> >> print('exec testABA_noimport') >> from math import sin >> print(sin(3.14159/6)) >> >> ----------------------------- >> ABA.py >> >> from thread import start_new_thread >> from time import sleep >> import sys >> >> user = 'testABA_noimport' >> start_new_thread(lambda: __import__(user), ()) >> print('after start_new_thread\n') >> >> while True: >> sleep(1) >> > > And all along you are still coding where imported modules are doing > work DURING THE IMPORT. Anything beyond initializing module level > constants or importing modules needed by the module should be placed > into a function which can be executed by the top-level importer AFTER > the import has finished. > > -=-=-=-=- testABA.py > print ("testABA: top") > > from math import sin, pi > import time > > print ("testABA: defining worker function") > def runner(): #this is the key -- a function IN the module > #that does the real work > print ("testABA.runner: starting work\n") > time.sleep(2.5) > print (sin(pi)) > time.sleep(2.5) > print ("\ntestABA.runner: end of work") > > print ("testABA: after set-up") > > if __name__ == "__main__": > print ("testABA: was not an import, running main task") > runner() #invoke the function if module is not imported > print ("testABA: end") > -=-=-=-=- > > -=-=-=-=- ABA.py > import threading > > USER = "testABA" > > print ("ABA: importing " + USER) > modl = __import__(USER) > > print ("ABA: starting runner") > th = threading.Thread(target=modl.runner) > th.start() > > print ("ABA: waiting for completion") > th.join() > > print ("ABA: done") > -=-=-=-=- > > And showing the results... > > -=-=-=-=- > E:\UserData\Wulfraed\My Documents\Python Progs>testABA > testABA: top > testABA: defining worker function > testABA: after set-up > testABA: was not an import, running main task > testABA.runner: starting work > > 1.22460635382e-016 > > testABA.runner: end of work > testABA: end > > E:\UserData\Wulfraed\My Documents\Python Progs>ABA > ABA: importing testABA > testABA: top > testABA: defining worker function > testABA: after set-up > ABA: starting runner > testABA.runner: starting work > > ABA: waiting for completion > 1.22460635382e-016 > > testABA.runner: end of work > ABA: done > -=-=-=-=- > > Note that "testABA.py" is designed to be used as a stand-alone > program, but is also designed to be imported where all the real work is > done from a function that is NOT run during the import. The program that > imports "testABA" is then responsible for actually starting the worker. > > I put the sleeps into testABA.runner() so that you can see that the > main process isn't blocked (note the "ABA: waiting..." output) > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, but the problem I need to solve does not permit putting a function like runner in the main program. I'm constrained to being able to handle the API of VPython (vpython.org), which lets you write programs like the following (call it user.py), which animates a 3D cube moving to the right, using OpenGL: from visual import box b = box() while True: b.pos.x += 0.001 In VPython at present, the visual module sets up (using C++ and Boost) a secondary thread that periodically updates the 3D scene using the current objects and their attributes, and handles events. On the Mac this is done with Carbon, which is dying, so I need to base VPython on the Mac on Cocoa, for which the interact loop must be in the primary thread. Hence my need to turn the architecture inside out while nevertheless handling the existing API. The cleanest scheme is to have the user's program user.py import a module "visual" that spawns a new process, "python visual2.py user.py", where visual2.py reads the source from user.py, comments out the "import visual", and exec's this modified source in a secondary thread. This works because visual2.py is now the main module. Unfortunately, if user.py is run from IDLE, print output goes to a terminal window rather than to the IDLE shell window, and I don't know how to direct the output to that shell window. For this reason I've been experimenting with other schemes, and it took a while to understand that a thread spawned in an imported module cannot do imports. I've even managed to carry out a real kludge of executing imports found in user.py at the top level of visual, creating a dictionary of globals to pass to an exec of the source in user.py with all imports there commented out. It works, but ugh. Bruce Sherwood From rosuav at gmail.com Sat Jul 21 19:16:24 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 09:16:24 +1000 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Sun, Jul 22, 2012 at 9:07 AM, Devin Jeanpierre wrote: > People hold grudges against MS too strongly, and they believe too much > in Google's righteousness. They are both big companies that don't > necessarily care about you. Just to clarify, I'm not advocating the "Google is perfect" stance either; in both cases you're looking at a huge company and a zero-dollar service. That means you're completely at their mercy in terms of feature support, and you're most likely going to have your information harvested as a means of spamming you with ads. And as you can see from the headers, I use gmail too. I'm fully aware that they're scanning my emails to target the ads I see; it doesn't bother me. I have another email address at a domain that I own, with the mail server being an actual computer that I own, and Google's welcome to read through all my mailing list posts. It'd be no different if python.org provided their own free-to-use webmail service. I'd be assuming you guys are targeting me with ads, and it wouldn't bother me. :) ChrisA From steve+comp.lang.python at pearwood.info Sat Jul 21 20:13:20 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 00:13:20 GMT Subject: Sudden doubling of nearly all messages References: Message-ID: <500b45a0$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 06:48:29 -0400, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? No I have not. It sounds like a problem with your Usenet provider. Remember that this news group is a mirror of the mailing list python-list at python.org so you can check the mail archives to see if the problem is there. It is also mirrored by gmane (I *think* it is gmane.comp.python.general). > Previously, I've seen some messages double posted, and it was nearly > always a newbie, presumably posting via some low-end gateway. Some people also annoyingly send to both the newsgroup *and* the mailing list, not realising -- or not caring -- that they are the same thing. -- Steven From steve+comp.lang.python at pearwood.info Sat Jul 21 20:20:28 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 00:20:28 GMT Subject: Sudden doubling of nearly all messages References: Message-ID: <500b474c$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sun, 22 Jul 2012 04:25:21 +1000, Chris Angelico wrote: > Use whichever service you like, but don't seriously expect anything that > you don't pay money for to be perfectly featured AND not spy on you. http://duckduckgo.com/privacy.html -- Steven From steve+comp.lang.python at pearwood.info Sat Jul 21 20:27:24 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 00:27:24 GMT Subject: Sudden doubling of nearly all messages References: Message-ID: <500b48ec$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 19:07:28 -0400, Devin Jeanpierre wrote: > People hold grudges against MS too strongly, and they believe too much > in Google's righteousness. They are both big companies that don't > necessarily care about you. +10000 Google's motto "Don't be evil" should really be, "Don't be evil unless there's a lot of money in it". I personally know a couple of people working for Google, and their famed geek-friendly work environment is not all it is cracked up to be either. I think the IT world is better now than it was 10 years ago, because an industry dominated by three big, competing entities who hate each other (Microsoft, Apple, Google) is better than a monopoly of one (Microsoft). But we, the users and consumers, should never make the mistake of thinking that *any* of the three have our best interests at heart. -- Steven From steve+comp.lang.python at pearwood.info Sat Jul 21 20:32:39 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 00:32:39 GMT Subject: My first ever Python program, comments welcome References: Message-ID: <500b4a27$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 20:40:46 +0100, MRAB wrote: > On 21/07/2012 20:08, Lipska the Kat wrote: >> l=sorted(l, key=itemgetter(0)) > > Short is: > > l.sort(key=itemgetter(0)) Shorter, and the semantics are subtly different. The sorted function returns a copy of the input list. The list.sort method sorts the list in place. -- Steven From d at davea.name Sat Jul 21 20:33:56 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 20:33:56 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: <500b45a0$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500b45a0$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500B4A74.3040401@davea.name> On 07/21/2012 08:13 PM, Steven D'Aprano wrote: > On Sat, 21 Jul 2012 06:48:29 -0400, Dave Angel wrote: > >> Has anybody else noticed the sudden double-posting of nearly all >> messages in the python mailing list? > No I have not. > > It sounds like a problem with your Usenet provider. Remember that this > news group is a mirror of the mailing list python-list at python.org so you > can check the mail archives to see if the problem is there. It is also > mirrored by gmane (I *think* it is gmane.comp.python.general). > I don't have a usenet provider, I use the straight email, collected as regular email, by Thunderbird. I thought for a while that perhaps my imap provider had hiccupped, and just reloaded all the same messages. But it happened in several sessions, and for the messages I checked, the emails were *NOT* identical. >> Previously, I've seen some messages double posted, and it was nearly >> always a newbie, presumably posting via some low-end gateway. > Some people also annoyingly send to both the newsgroup *and* the mailing > list, not realising -- or not caring -- that they are the same thing. > > > That may be because many other messages (including this one from you) list the newsgroup in the headers, so a reply-all generates it as one of the recipients. The only reason I don't fall into that trap is that I have Thunderbird configured to *not* send to any newsgroup. -- DaveA From rosuav at gmail.com Sat Jul 21 20:38:19 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 10:38:19 +1000 Subject: Sudden doubling of nearly all messages In-Reply-To: <500b474c$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500b474c$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 22, 2012 at 10:20 AM, Steven D'Aprano wrote: > On Sun, 22 Jul 2012 04:25:21 +1000, Chris Angelico wrote: > >> Use whichever service you like, but don't seriously expect anything that >> you don't pay money for to be perfectly featured AND not spy on you. > > http://duckduckgo.com/privacy.html They go for privacy at the cost of everything else, and that's fine. But you still can't depend on its featureset. With a mailing list / newsgroup reader, there's a whole lot of little things that you'd probably like, but you can't depend on it; such things cost money, and most companies that give you stuff that cost money without charging you money are going to be selling ad space, ergo the temptation to harvest information about you. But as I said, I don't care. Google doesn't get any information about me that I'm not willing for them to get. Let 'em show me ads. And sometimes they're even useful! ChrisA From steve+comp.lang.python at pearwood.info Sat Jul 21 20:56:55 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 00:56:55 GMT Subject: My first ever Python program, comments welcome References: Message-ID: <500b4fd6$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sat, 21 Jul 2012 16:10:51 -0400, Dave Angel wrote: >> with fileinput.input(files=(filename)) as f: > > fileinput is much more general than you want for processing a single > file. That may be deliberate, if you're picturing somebody using > wildcards on their input. But if so, you should probably use a > different name, something that indicates plural. Also, fileinput is more a convenience module than a serious production quality tool. It works, it does the job, but it can be slow. From the source: Performance: this module is unfortunately one of the slower ways of processing large numbers of input lines. -- Steven From jeanpierreda at gmail.com Sat Jul 21 21:31:31 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 21 Jul 2012 21:31:31 -0400 Subject: Basic question about speed/coding style/memory In-Reply-To: <500a711f$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500a711f$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Jul 21, 2012 at 5:06 AM, Steven D'Aprano wrote: > So there is approximately 0.03 second difference per TWO MILLION > if...else blocks, or about 15 nanoseconds each. This is highly unlikely > to be the bottleneck in your code. Assuming the difference is real, and > not just measurement error, the difference is insignificant. It's probably real. For if-else, the true case needs to make a jump before it returns, but for if-return, there's no jump and the return is inlined. -- Devin > So, don't worry about which is faster. Write whichever is more natural, > easier to read and write. The most important advice. Even when it's a larger difference! :) -- Devin From rantingrickjohnson at gmail.com Sat Jul 21 21:33:02 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sat, 21 Jul 2012 18:33:02 -0700 (PDT) Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 6:16:24 PM UTC-5, Chris Angelico wrote: > Just to clarify, I'm not advocating the [...snip...] Well. Well. Backpedaling AND brown-nosing in a single post. Nice! From rantingrickjohnson at gmail.com Sat Jul 21 21:33:02 2012 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Sat, 21 Jul 2012 18:33:02 -0700 (PDT) Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Saturday, July 21, 2012 6:16:24 PM UTC-5, Chris Angelico wrote: > Just to clarify, I'm not advocating the [...snip...] Well. Well. Backpedaling AND brown-nosing in a single post. Nice! From rosuav at gmail.com Sat Jul 21 21:52:58 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 11:52:58 +1000 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On Sun, Jul 22, 2012 at 11:33 AM, Rick Johnson wrote: > On Saturday, July 21, 2012 6:16:24 PM UTC-5, Chris Angelico wrote: > >> Just to clarify, I'm not advocating the > [...snip...] > > Well. Well. Backpedaling AND brown-nosing in a single post. Nice! Absolutely. Haven't you noticed that I'm one of those mad people who goes everywhere in reverse? My backpedal is saying the exact same thing as my frontpedal! Curiouser and curiouser... ChrisA From python at mrabarnett.plus.com Sat Jul 21 21:56:20 2012 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 22 Jul 2012 02:56:20 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: <500b4a27$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500b4a27$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500B5DC4.7020204@mrabarnett.plus.com> On 22/07/2012 01:32, Steven D'Aprano wrote: > On Sat, 21 Jul 2012 20:40:46 +0100, MRAB wrote: > >> On 21/07/2012 20:08, Lipska the Kat wrote: >>> l=sorted(l, key=itemgetter(0)) >> >> Short is: >> >> l.sort(key=itemgetter(0)) > > Shorter, and the semantics are subtly different. > > The sorted function returns a copy of the input list. > > The list.sort method sorts the list in place. > Since the result is bound to the original name, the result is the same. From rosuav at gmail.com Sat Jul 21 21:59:38 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 11:59:38 +1000 Subject: My first ever Python program, comments welcome In-Reply-To: <500B5DC4.7020204@mrabarnett.plus.com> References: <500b4a27$0$29978$c3e8da3$5496439d@news.astraweb.com> <500B5DC4.7020204@mrabarnett.plus.com> Message-ID: On Sun, Jul 22, 2012 at 11:56 AM, MRAB wrote: > Since the result is bound to the original name, the > result is the same. Yes, assuming there are no other refs. >>> a=[3,2,1] >>> b=a >>> a=sorted(a) >>> a [1, 2, 3] >>> b [3, 2, 1] ChrisA From d at davea.name Sat Jul 21 22:01:42 2012 From: d at davea.name (Dave Angel) Date: Sat, 21 Jul 2012 22:01:42 -0400 Subject: My first ever Python program, comments welcome In-Reply-To: <500B5DC4.7020204@mrabarnett.plus.com> References: <500b4a27$0$29978$c3e8da3$5496439d@news.astraweb.com> <500B5DC4.7020204@mrabarnett.plus.com> Message-ID: <500B5F06.7030906@davea.name> On 07/21/2012 09:56 PM, MRAB wrote: > On 22/07/2012 01:32, Steven D'Aprano wrote: >> On Sat, 21 Jul 2012 20:40:46 +0100, MRAB wrote: >> >>> On 21/07/2012 20:08, Lipska the Kat wrote: >>>> l=sorted(l, key=itemgetter(0)) >>> >>> Short is: >>> >>> l.sort(key=itemgetter(0)) >> >> Shorter, and the semantics are subtly different. >> >> The sorted function returns a copy of the input list. >> >> The list.sort method sorts the list in place. >> > Since the result is bound to the original name, the > result is the same. > In this particular program, yes. But if there's another variable bound to the same list, then the fact that there's a new object from sorted() makes a difference. -- DaveA From ethan at stoneleaf.us Sat Jul 21 22:45:31 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 21 Jul 2012 19:45:31 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: <500B17D4.8040702@mweb.co.za> References: <5009F0D9.1050900@stoneleaf.us> <500B17D4.8040702@mweb.co.za> Message-ID: <500B694B.1010705@stoneleaf.us> Alex Strickland wrote: > Hi > >> Getting closer to a stable release. >> >> Latest version has a simpler, cleaner API, and works on PyPy (and >> hopefully the other implementations as well ;), as well as CPython. >> >> Get your copy at http://python.org/pypi/dbf. >> >> Bug reports, comments, and kudos welcome! ;) > > "Not supported: index files": > > I have been using http://sourceforge.net/projects/harbour-project/ for > years where a guy called Przemyslaw Czerpak has written an absolutely > bullet proof implementation of NTX and CDX for DBF. Maybe it will > interest you. I'll check it out, thanks! > PS : bareable is spelt bearable. I wondered about that. :/ ~Ethan~ From rustompmody at gmail.com Sat Jul 21 22:55:47 2012 From: rustompmody at gmail.com (rusi) Date: Sat, 21 Jul 2012 19:55:47 -0700 (PDT) Subject: My first ever Python program, comments welcome References: Message-ID: On Jul 22, 1:10?am, Dave Angel wrote: > A totally off-the-wall query. ?Are you using a source control system, > such as git ? ?It can make you much braver about refactoring a working > program. Question in a similar vein: What development environment do you use? My impression is that the majority of pythonistas use a non-ide editor like vi or emacs Ive been using emacs for 20 years and python-mode of emacs is very useful but I am increasingly concerned that emacs is refusing to move with the times. Which is why I am particularly curious how an ol Java-head finds eclipse+python (http://pydev.org/ ) From dieter at handshake.de Sun Jul 22 02:04:37 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sun, 22 Jul 2012 08:04:37 +0200 Subject: A thread import problem References: <87a9yt7bw6.fsf@handshake.de> Message-ID: <87txx05o22.fsf@handshake.de> Bruce Sherwood writes: > Thanks much for this suggestion. I'm not sure I've correctly > understood the operation "start_new_thread(lambda: __import__( module>), ())". By "your module" do you mean the user program which > imported the module that will execute start_new_thread? By "your_module", I meant what you have called "user.py" elsewhere in this thread -- the thing that does the animation. Of course, my suggestion implies that "visual.py" is somewhat changed. It is supposed to no longer set up the GUI environment automatically but do so only when its "setup_gui" function is called, and starting the GUI main loop, too, is no longer automatic but explicite. > It hadn't > occurred to me to have A import B and B import A, though now that you > describe this (if that's indeed what you mean) it makes sense. I do not propose to do that -- it can lead to problems. In my proposal, you have two modules: one the "main" module which sets up the GUI environment, starts the animation in a separate thread and then activate the GUI main loop. The second module contains the code you have shown in a previous message. Of course, the second module can be eliminated by putting its content into a function and then calling this function in the "start_new_thread" (instead of "lambda: __import__(...)"). From dieter at handshake.de Sun Jul 22 02:18:44 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sun, 22 Jul 2012 08:18:44 +0200 Subject: A thread import problem References: <87a9yt7bw6.fsf@handshake.de> Message-ID: <87pq7o5nej.fsf@handshake.de> Bruce Sherwood writes: > ... > The failure of this test case suggests that one cannot do imports > inside secondary threads started in imported modules, something I keep > tripping over. But I hope you'll be able to tell me that I'm doing > something wrong! As you know multiple threads can be dangerous when they concurrently change common data structures. Locks are used to protect those data structures. Locking can introduce other problems - like deadlocks (something you seem to observe). I have not looked at the concrete implementation. However, the Python documentation suggests that the import machinery uses its own locks (beside the "Global Interpreter Lock"). It seems to be a "thread lock", which would mean that a thread is not blocked when it already holds the lock - however any other thread would block. This easily can lead to a deadlock -- when you wait for the other thread "in any way". There should be no problem when you complete the whole import chain without any waiting for the thread. However, should you start the GUI main loop inside the import chain, you will never complete this chain. From dieter at handshake.de Sun Jul 22 02:21:01 2012 From: dieter at handshake.de (Dieter Maurer) Date: Sun, 22 Jul 2012 08:21:01 +0200 Subject: Sudden doubling of nearly all messages References: <500A88FD.40504@davea.name> Message-ID: <87liic5naq.fsf@handshake.de> Dave Angel writes: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? I am reading this list via "gmane" and do not see any double postings. From __peter__ at web.de Sun Jul 22 03:56:50 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Jul 2012 09:56:50 +0200 Subject: My first ever Python program, comments welcome References: Message-ID: Lipska the Kat wrote: > Greetings Pythoners > > A short while back I posted a message that described a task I had set > myself. I wanted to implement the following bash shell script in Python > > Here's the script > > sort -nr $1 | head -${2:-10} > > this script takes a filename and an optional number of lines to display > and sorts the lines in numerical order, printing them to standard out. > if no optional number of lines are input the script prints 10 lines > > Here's the file. > > 50 Parrots > 12 Storage Jars > 6 Lemon Currys > 2 Pythons > 14 Spam Fritters > 23 Flying Circuses > 1 Meaning Of Life > 123 Holy Grails > 76 Secret Policemans Balls > 8 Something Completely Differents > 12 Lives of Brian > 49 Spatulas > > > ... and here's my very first attempt at a Python program > I'd be interested to know what you think, you can't hurt my feelings > just be brutal (but fair). There is very little error checking as you > can see and I'm sure you can crash the program easily. > 'Better' implementations most welcome > #! /usr/bin/env python3.2 > > import fileinput > from sys import argv > from operator import itemgetter > > l=[] > t = tuple > filename=argv[1] > lineCount=10 > > with fileinput.input(files=(filename)) as f: Note that (filename) is not a tuple, just a string surrounded by superfluous parens. >>> filename = "foo.bar" >>> (filename) 'foo.bar' >>> (filename,) ('foo.bar',) >>> filename, ('foo.bar',) You are lucky that FileInput() tests if its files argument is just a single string. > for line in f: > t=(line.split('\t')) > t[0]=int(t[0]) > l.append(t) > l=sorted(l, key=itemgetter(0)) > > try: > inCount = int(argv[2]) > lineCount = inCount > except IndexError: > #just catch the error and continue > None > > for c in range(lineCount): > t=l[c] > print(t[0], t[1], sep='\t', end='') > I prefer a more structured approach even for such a tiny program: - process all commandline args - read data - sort - clip extra lines - write data I'd break it into these functions: def get_commmandline_args(): """Recommended library: argparse. Its FileType can deal with stdin/stdout. """ def get_quantity(line): return int(line.split("\t", 1)[0]) def sorted_by_quantity(lines): """Leaves the lines intact, so you don't have to reassemble them later on.""" return sorted(lines, key=get_quantity) def head(lines, count): """Have a look at itertools.islice() for a more general approach""" return lines[:count] if __name__ == "__main__": # protecting the script body allows you to import # the script as a library into other programs # and reuse its functions and classes. # Also: play nice with pydoc. Try # $ python -m pydoc -w ./yourscript.py args = get_commandline_args() with args.infile as f: lines = sorted_by_quantity(f) with args.outfile as f: f.writelines(head(lines, args.line_count)) Note that if you want to handle large files gracefully you need to recombine sorted_by_quantity() and head() (have a look at heapq.nsmallest() which was already mentioned in the other thread). From nordenmark at gmail.com Sun Jul 22 04:12:04 2012 From: nordenmark at gmail.com (Nicklas Nordenmark) Date: Sun, 22 Jul 2012 10:12:04 +0200 Subject: py2app bundling scikits-image etc. Message-ID: <8C0C74C9154346598227037A57D34AB6@gmail.com> Hey guys, didn't know where else to post so I thought I'd give this list a shot. I've been googling a lot but hasn't been able to find any reasonable answers. I'm on a macbook running Lion trying to bundle a pretty extensive application that's using: * wxPython * numpy * scipy * reportlab I'm using python2.7 and py2app for the bundling and here's the setup.py file: import ez_setup ez_setup.use_setuptools() from setuptools import setup Plist={} DATA_FILES = ['../rm_logo.jpg'] OPTIONS = {'argv_emulation': True, 'plist': Plist, } setup( app=["../sasdm.py"], data_files=DATA_FILES, description="Description", author="Author", options={'py2app': OPTIONS}, setup_requires=["py2app"], ) I've tried both python setup.py py2app and sudo python setup.py py2app The bundling always ends up failing with the message: error: cannot copy tree '/Library/Python/2.7/site-packages/skimage/data/chessboard_GRAY_U8.npz': not a directory I've confirmed that "/Library/Python/2.7/site-packages/skimage/data/chessboard_GRAY_U8.npz" in fact does exist. I've installed the latest development version of scikits-image too but no apparent difference there. I appreciate any clues. Regards -- Nicklas Nordenmark -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Jul 22 04:14:34 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 22 Jul 2012 09:14:34 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: On 22/07/2012 03:55, rusi wrote: > On Jul 22, 1:10 am, Dave Angel wrote: > >> A totally off-the-wall query. Are you using a source control system, >> such as git ? It can make you much braver about refactoring a working >> program. > > Question in a similar vein: What development environment do you use? > My impression is that the majority of pythonistas use a non-ide editor > like vi or emacs > Ive been using emacs for 20 years and python-mode of emacs is very > useful but I am increasingly concerned that emacs is refusing to move > with the times. > > Which is why I am particularly curious how an ol Java-head finds > eclipse+python (http://pydev.org/ ) > Wouldn't describe myself as "an ol Java-head" but I disliked eclipse 10 years ago. I tried it again earlier this year and still disliked it. It's like entering a legless cart horse for the Derby or the Grand National. YMMV. -- Cheers. Mark Lawrence. From lipska at lipskathekat.com Sun Jul 22 04:37:11 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sun, 22 Jul 2012 09:37:11 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: On 21/07/12 21:10, Dave Angel wrote: > On 07/21/2012 03:08 PM, Lipska the Kat wrote: >> Greetings Pythoners >> >> A short while back I posted a message that described a task I had set >> myself. I wanted to implement the following bash shell script in Python >> snip >> >> > > A totally off-the-wall query. Are you using a source control system, > such as git ? It can make you much braver about refactoring a working > program. Thanks for your comments, I've taken them on board, I'm most familiar with with cvs and svn for source control. I've also used Microsoft source safe. I generally just use what's given to me by whoever is paying me and don't worry too much about the details. Many in the Linux world seem to use git. Seeing as I've been using Linux at home since the early days of slackware I suppose I'd better look into it. Strangely enough I've never had a paid job using Linux. I've worked on multiuser UNIX systems and Sun Workstations but never Linux so I guess the need has never arisen. The Java world seems to largely use Maven to manage their code. It's a bit of a headbanger and I've never used it. Ant and FTP are my current faves at home. Primitive but good enough for my personal and business sites. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From bahamutzero8825 at gmail.com Sun Jul 22 04:49:12 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 22 Jul 2012 03:49:12 -0500 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: <500BBE88.70308@gmail.com> On 7/22/2012 3:37 AM, Lipska the Kat wrote: > Many in > the Linux world seem to use git. Seeing as I've been using Linux at home > since the early days of slackware I suppose I'd better look into it. There are Mercurial (aka Hg) and Bazaar as well for DVCS. AFAIK, git, Mercurial, and Bazaar are all fine choices and the one to use will mainly boil down to personal preference. I prefer Mercurial myself. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From lipska at lipskathekat.com Sun Jul 22 05:20:35 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sun, 22 Jul 2012 10:20:35 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: On 22/07/12 03:55, rusi wrote: > On Jul 22, 1:10 am, Dave Angel wrote: > >> A totally off-the-wall query. Are you using a source control system, >> such as git ? It can make you much braver about refactoring a working >> program. > > Question in a similar vein: What development environment do you use? > My impression is that the majority of pythonistas use a non-ide editor > like vi or emacs > Ive been using emacs for 20 years and python-mode of emacs is very > useful but I am increasingly concerned that emacs is refusing to move > with the times. My current 'Python development environment' is gedit with line numbering turned on and a terminal window to run chmodded scripts :-) > > Which is why I am particularly curious how an ol Java-head finds > eclipse+python (http://pydev.org/ ) Python and eclipse ... Noooooooooooooooooooooooooooooooooooooooooo ;-) Well I have to say that I've used Eclipse with the myEclipse plugin for a number of years now and although it has it's moments it has earned me LOADS of MONEY so I can't really criticise it. I have Eclipse installed on a Windows box so I may try the plugin ... but actually I'm really enjoying doing things the 'old fashioned way' again. I'm going to do 'proper OO' version of the shell script to learn about wiring different modules together ... I find the official documentation hard to navigate though. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From alan.ristow at gmail.com Sun Jul 22 05:30:52 2012 From: alan.ristow at gmail.com (Alan Ristow) Date: Sun, 22 Jul 2012 11:30:52 +0200 Subject: Sudden doubling of nearly all messages In-Reply-To: <500A88FD.40504@davea.name> References: <500A88FD.40504@davea.name> Message-ID: <500BC84C.2000001@gmail.com> On 07/21/2012 12:48 PM, Dave Angel wrote: > Has anybody else noticed the sudden double-posting of nearly all > messages in the python mailing list? [snip] > I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for > non-digest mode. I read the messages in threaded mode. > I'm pretty sure it is Thunderbird-related -- I have had this issue before as well. Unfortunately, I cannot remember how I solved it. It seems like there was a particular box that needed to be checked or unchecked in the IMAP settings for the mail server, but I can't be sure anymore. Alan From nad at acm.org Sun Jul 22 05:39:16 2012 From: nad at acm.org (Ned Deily) Date: Sun, 22 Jul 2012 02:39:16 -0700 Subject: py2app bundling scikits-image etc. References: <8C0C74C9154346598227037A57D34AB6@gmail.com> Message-ID: In article <8C0C74C9154346598227037A57D34AB6 at gmail.com>, Nicklas Nordenmark wrote: > Hey guys, didn't know where else to post so I thought I'd give this list a > shot. I've been googling a lot but hasn't been able to find any reasonable > answers. Probably the best place to ask questions about py2app is on the Python Mac SIG list: http://www.python.org/community/sigs/current/pythonmac-sig/ -- Ned Deily, nad at acm.org From d at davea.name Sun Jul 22 05:49:59 2012 From: d at davea.name (Dave Angel) Date: Sun, 22 Jul 2012 05:49:59 -0400 Subject: Sudden doubling of nearly all messages In-Reply-To: <500BC84C.2000001@gmail.com> References: <500A88FD.40504@davea.name> <500BC84C.2000001@gmail.com> Message-ID: <500BCCC7.1060609@davea.name> On 07/22/2012 05:30 AM, Alan Ristow wrote: > On 07/21/2012 12:48 PM, Dave Angel wrote: >> Has anybody else noticed the sudden double-posting of nearly all >> messages in the python mailing list? > [snip] >> I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for >> non-digest mode. I read the messages in threaded mode. >> > I'm pretty sure it is Thunderbird-related -- I have had this issue > before as well. Unfortunately, I cannot remember how I solved it. It > seems like there was a particular box that needed to be checked or > unchecked in the IMAP settings for the mail server, but I can't be > sure anymore. > > Alan Thanks. But the problem appeared suddenly, and ended suddenly. And i didn't go into Account-settings or Preferences during that time. -- DaveA From rosuav at gmail.com Sun Jul 22 06:17:18 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 22 Jul 2012 20:17:18 +1000 Subject: My first ever Python program, comments welcome In-Reply-To: <500BBE88.70308@gmail.com> References: <500BBE88.70308@gmail.com> Message-ID: On Sun, Jul 22, 2012 at 6:49 PM, Andrew Berg wrote: > On 7/22/2012 3:37 AM, Lipska the Kat wrote: >> Many in >> the Linux world seem to use git. Seeing as I've been using Linux at home >> since the early days of slackware I suppose I'd better look into it. > There are Mercurial (aka Hg) and Bazaar as well for DVCS. AFAIK, git, > Mercurial, and Bazaar are all fine choices and the one to use will > mainly boil down to personal preference. I prefer Mercurial myself. Agreed. I poked around with Bazaar a bit this year, and it seems to lack some features. But certainly hg and git are both excellent choices, with bzr not significantly far behind. I prefer git, personally; on Windows, though, I would recommend hg. Probably the best feature of any of them (one which, I believe, is now standard in all three) is 'bisect' with a command. It's "git bisect run", or "hg bisect -c", or "bzr bisect run". You can search back through a huge time period without any human interaction. I did that a while ago with a docs-building problem; the current state wouldn't successfully generate its docs from a fresh start, even though it could update them from a previous state. It took 45 minutes (!) of chuggity-chug compilation to find the actual cause of the problem, and no effort from me (since "make doc" already gave the right exit codes). Use source control now; you'll reap the benefits later! ChrisA From bouncingcats at gmail.com Sun Jul 22 06:46:25 2012 From: bouncingcats at gmail.com (David) Date: Sun, 22 Jul 2012 20:46:25 +1000 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: On 22/07/2012, Lipska the Kat wrote: > On 21/07/12 21:10, Dave Angel wrote: >> >> A totally off-the-wall query. Are you using a source control system, >> such as git ? It can make you much braver about refactoring a working >> program. > > Thanks for your comments, I've taken them on board, > I'm most familiar with with cvs and svn for source control. I've also > used Microsoft source safe. I generally just use what's given to me by > whoever is paying me and don't worry too much about the details. Many in > the Linux world seem to use git. Seeing as I've been using Linux at home > since the early days of slackware I suppose I'd better look into it. What Dave said. I used CVS briefly and then git and its gui tools for last 5 years. Took me a while to get comfortable with it, but now it turns managing complex, evolving text files into fun and I cannot imagine working without its power and flexibility. First thing I do on any programming task: git init From lipska at lipskathekat.com Sun Jul 22 08:36:50 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sun, 22 Jul 2012 13:36:50 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: References: <500BBE88.70308@gmail.com> Message-ID: On 22/07/12 11:17, Chris Angelico wrote: > On Sun, Jul 22, 2012 at 6:49 PM, Andrew Berg wrote: >> On 7/22/2012 3:37 AM, Lipska the Kat wrote: >>> Many in >>> the Linux world seem to use git. snip > Use source control now; you'll reap the benefits later! from sudo apt-get install git to git add *.py was about 5 minutes and that included reading the basic documentation. POSITIVELY the fastest install and the least trouble from any source control app ever Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From biofobico at gmail.com Sun Jul 22 10:48:12 2012 From: biofobico at gmail.com (Paulo) Date: Sun, 22 Jul 2012 07:48:12 -0700 (PDT) Subject: Looking for good tutorials after reading "Byte of Python" Message-ID: <9af4cd7e-88a6-4d7c-a0fe-18b936ce66be@googlegroups.com> My main goal is to do web development with Django/flask or another framework that suits me best. But I think that I should learn a bit more of Python before diving into a framework. I would like to know if anyone has some good tutorials like building a to-do list app or any other type of programs so I can learn by doing and also as a guiding kinda thing. Thanks in advance. P.S. excuse my poor english. From sg552 at hotmail.co.uk Sun Jul 22 11:12:04 2012 From: sg552 at hotmail.co.uk (Rotwang) Date: Sun, 22 Jul 2012 16:12:04 +0100 Subject: Sudden doubling of nearly all messages In-Reply-To: References: Message-ID: On 21/07/2012 19:16, Rick Johnson wrote: > [...] > > It's due to the new Google Groups interface. They started forcing everyone to use the new buggy version about a week ago EVEN THOUGH the old interface is just fine. I disagree - the old interface was dreadful and needed fixing. The new one is much worse, obviously. -- I have made a thing that superficially resembles music: http://soundcloud.com/eroneity/we-berated-our-own-crapiness From lipska at lipskathekat.com Sun Jul 22 11:12:31 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sun, 22 Jul 2012 16:12:31 +0100 Subject: Looking for good tutorials after reading "Byte of Python" In-Reply-To: <9af4cd7e-88a6-4d7c-a0fe-18b936ce66be@googlegroups.com> References: <9af4cd7e-88a6-4d7c-a0fe-18b936ce66be@googlegroups.com> Message-ID: <2YWdnbiZsv78hZHNnZ2dnUVZ8gidnZ2d@bt.com> On 22/07/12 15:48, Paulo wrote: > My main goal is to do web development with Django/flask or another framework that suits me best. But I think that I should learn a bit more of Python before diving into a framework. I would like to know if anyone has some good tutorials like building a to-do list app or any other type of programs so I can learn by doing and also as a guiding kinda thing. > > Thanks in advance. > > P.S. excuse my poor english You may have already seen this but there is a tutorial on the python site http://docs.python.org/py3k/ (python3.2.3) There is also one at http://www.tutorialspoint.com/python/index.htm that looks like it could be worth reading Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From roy at panix.com Sun Jul 22 11:39:30 2012 From: roy at panix.com (Roy Smith) Date: Sun, 22 Jul 2012 11:39:30 -0400 Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: In article <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA at giganews.com>, Tony the Tiger wrote: > Hi, > Is there such a thing in the language, or do I have to invent it myself? > > I came up with the following: > > # options.modus_list contains, e.g., "[2,3,4]" > # (a string from the command line) > # MODUS_LIST contains, e.g., [2,4,8,16] > # (i.e., a list of integers) > > if options.modus_list: > intTmp = [] > modTmp = options.modus_list[1:-1] > for itm in modTmp: > intTmp.append(int(itm)) > MODUS_LIST = intTmp To answer the question you asked, to convert a list of strings to a list of ints, you want to do something like: MODUS_LIST = [int(i) for i in options.modus_list] But, to answer the question you didn't ask, if you're trying to parse command-line arguments, you really want to use the argparse module. It's a little complicated to learn, but it's well worth the effort. From alister.ware at ntlworld.com Sun Jul 22 11:39:54 2012 From: alister.ware at ntlworld.com (Alister) Date: Sun, 22 Jul 2012 15:39:54 GMT Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote: > Hi, > Is there such a thing in the language, or do I have to invent it myself? > > I came up with the following: > > # options.modus_list contains, e.g., "[2,3,4]" > # (a string from the command line) > # MODUS_LIST contains, e.g., [2,4,8,16] > # (i.e., a list of integers) > > if options.modus_list: > intTmp = [] > modTmp = options.modus_list[1:-1] > for itm in modTmp: > intTmp.append(int(itm)) > MODUS_LIST = intTmp > > There are probably never more than maybe between one to four items in > the options.modus_list, and its contents as integers should always > replace all of the original MODUS_LIST, because it is up to the user to > decide what should be used for calculating the result. > > The above works (unless I have introduced some bug when I copied into my > editor here), but I would like to know if there already is such a thing, > or something better than the above. I'd hate to re-invent the wheel. > > TIA > > > /Grrr looks like a classic list comprehension to me and can be achieved in a single line MODUS_LIST=[int(x) for x in options.modus_list] -- NOTICE: -- THE ELEVATORS WILL BE OUT OF ORDER TODAY -- (The nearest working elevator is in the building across the street.) From bv8bv8bv8 at gmail.com Sun Jul 22 12:15:58 2012 From: bv8bv8bv8 at gmail.com (BV BV) Date: Sun, 22 Jul 2012 09:15:58 -0700 (PDT) Subject: All About The Quran Message-ID: <28e12ae5-5263-457a-b0e1-c30f9f19f830@a8g2000vbk.googlegroups.com> All About The Quran The Quran is a Divine Miracle of Literature [Prophesy - Science - Warnings - Wisdom - Truths]...and it has been Preserved 100% In the Original Language - for over 1,400 years! Humanity has received Divine Guidance only through two channels: The Word of Almighty God ("Allah" [in Arabic]) [scriptures, Bible, Psalms, etc.] The Prophets sent by the Allah to communicate His Will to mankind These two things have always been going together, hand in hand. More important though, there were at that time, tens of thousands of his companions ("sahabi" in Arabic) who memorized the complete Quran from the instruction of the prophet Muhammad (peace be upon him). Even the prophet himself (peace be upon him) used to recite it with angel Gabriel once a year and in the last year of his life he recited it two times just before the month in which he died. Next, the leader who came after the prophet Muhammad (peace be upon him) (Abu Bakr) entrusted the collection of the Quran to be written in one volume by one of the Prophet's scribe, Zaid Ibn Thabit. He kept it till his death. Then the next leader, Umar and after him to his daughter, Hafsa who had been one of the wives of Prophet Muhammad (peace be upon him). Then from the original text which now resides in Topkope Museum, in Istanbul, Turkey, the next leader, Uthman prepared several other exact duplications and sent them to various Muslim territories such as; Uzbekistan and Turkey and other places. These scriptures are still in museums there and one has found its way to a museum in England as well. All of them are exactly the same. Today many of the Muslims from these areas are still memorizing the Quran. The Quran was so meticulously preserved because it is the Book of Guidance for all of humanity for all times. That is why it does not address just the Arabs, in whose language it was revealed. In fact Arabs today do not comprise more than 13% of the Today of Muslims in the world today. The Quran speaks to "mankind" Quran speaks to all of mankind on a general basis without regard to race, tribe, color, social position, financial condition or genealogy. Allah the Almighty says: "O Mankind! What has seduced you from your Lord so Generous?" [Noble Quran 82:6] The Practical Teachings of the Quran Teachings of Quran are established by the example of Muhammad (peace be upon him) and the good Muslims throughout the ages have endeavored to emulate his teachings both in thought and conduct. The distinctive approach of the Quran is that its instructions are aimed at the general welfare of the mankind and are based on the possibilities within his reach. The Quran is Wisdom Conclusive. It neither condemns nor tortures the flesh nor does it neglect the soul. It does not humanize God, nor does it deify man. Everything is carefully placed where it belongs in the total scheme of creation. Yet it obviously is not written in human style (chronological order). Those who would claim that the prophet Muhammad (peace be upon him) was the author of the Quran are claiming something that is humanly impossible. How could any person of the 7th century utter such scientific truths as those found in the Quran? Could he describe the evolution of the embryo inside the uterus so accurately as we find it now recorded in modern science? [See: Dr. Keith Moore's book - on embryology] Secondly, is it logical to believe that Muhammad (peace be upon him) who up to the age of forty was marked only for his honesty and integrity, began all of a sudden the authorship of a book matchless in literary merit and the equivalent of which the whole legion of the Arab poets and orators of the highest caliber could not produce? And lastly, is it justified to say that Muhammad (peace be upon him) who was known as "Al-Ameen" (trustworthy) in his society and who is still admired by the non-Muslim scholars for his honesty, would lie about receiving the Quran (which forbids lying) from the Angel Gabriel and then still be able to establish the best human society on the face of the earth, based on truth? Surely, any sincere and unbiased searcher of truth must come to the conclusion that the Quran is the revealed Book of Almighty Allah. Readers can easily see how the modern world is coming closer to reality regarding the truth of the Quran. We appeal to all open minded scholars to study the Quran in the light of the aforementioned points. We invite all to challenge the validity and accuracy of the sciences known to man today and keep in mind that this is the EXACT TEXT used by the Prophet Muhammad (peace be upon him) over one thousand four hundred years ago. We are sure that any such attempt will convince the reader that the Quran could never have been written by any human being ever. >From allahsquran.com From rustompmody at gmail.com Sun Jul 22 12:18:26 2012 From: rustompmody at gmail.com (rusi) Date: Sun, 22 Jul 2012 09:18:26 -0700 (PDT) Subject: My first ever Python program, comments welcome References: Message-ID: <37a37376-18ff-46af-97f0-36fd764a8c26@m2g2000pbv.googlegroups.com> On Jul 22, 2:20?pm, Lipska the Kat wrote: > Well I have to say that I've used Eclipse with the myEclipse plugin for > a number of years now and although it has it's moments it has earned me > LOADS of MONEY so I can't really criticise it. Ive probably tried to use eclipse about 4 times in the last 8 years. Always run away in terror. Still I'm never sure whether eclipse is stupid or I am... First time I'm hearing of myEclipse. Thanks. What does it have/do that standard eclipse (JDT?) does not? > Python and eclipse ... Noooooooooooooooooooooooooooooooooooooooooo ;-) Very curious about this. You made 'Loads of money' with eclipse but want to stay away from it? Simply cannot make out this thing called 'java-programmer-culture'... From janpeterr at freenet.de Sun Jul 22 12:20:18 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sun, 22 Jul 2012 19:20:18 +0300 Subject: Converting a list of strings into a list of integers? In-Reply-To: References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: <500C2842.4040204@freenet.de> On 22.07.2012 18:39, Alister wrote: > On Sun, 22 Jul 2012 10:29:44 -0500, Tony the Tiger wrote: >> I came up with the following: >> >> # options.modus_list contains, e.g., "[2,3,4]" >> # (a string from the command line) >> # MODUS_LIST contains, e.g., [2,4,8,16] >> # (i.e., a list of integers) >> >> if options.modus_list: >> intTmp = [] >> modTmp = options.modus_list[1:-1] >> for itm in modTmp: >> intTmp.append(int(itm)) >> MODUS_LIST = intTmp >> >> >> TIA >> >> >> /Grrr > > looks like a classic list comprehension to me and can be achieved in a > single line > > MODUS_LIST=[int(x) for x in options.modus_list] > > > Hi, I am not sure why everyone is using the for-iterator option over a "map", but I would do it like that: MODUS_LIST= map(int, options.modus_list) "map" works on a list and does commandX (here "int" conversion, use "str" for string.. et cetera) on sequenceY, returning a sequence. More in the help file. And if I'm not completely mistaken, it's also the quicker way to do performance wise. But I can't completely recall the exact reason. Jan From __peter__ at web.de Sun Jul 22 12:30:48 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Jul 2012 18:30:48 +0200 Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> <3rCdnUOiWpMhvpHNnZ2dnUVZ7vSdnZ2d@giganews.com> Message-ID: Tony the Tiger wrote: > On Sun, 22 Jul 2012 11:39:30 -0400, Roy Smith wrote: > >> To answer the question you asked, to convert a list of strings to a list >> of ints, you want to do something like: >> >> MODUS_LIST = [int(i) for i in options.modus_list] > > Thanks. I'll look into that. I now remember reading about the technique > (in Mark Lutz' "Learning Python"), but it seems I'm getting old as I tend > to forget about it from time to time. ;) > >> But, to answer the question you didn't ask, if you're trying to parse >> command-line arguments, you really want to use the argparse module. It's >> a little complicated to learn, but it's well worth the effort. > > Your suggestions about the argparse. Well, it seems it does pretty much > the same as OptionParser which I use now. Perhaps it has more features > (that I probably won't need in my 30 line script), I only need to keep > track of maybe one or two options. Maybe one of these days, when I have > little else to do, or when the OptionParser stops working, I'll give it a > try. Thanks. :) Here's an argparse example: $ cat argparse_list.py import argparse parser = argparse.ArgumentParser() parser.add_argument("-m", "--modus", type=int, nargs="*") print parser.parse_args().modus $ python argparse_list.py None $ python argparse_list.py -m [] $ python argparse_list.py -m 1 [1] $ python argparse_list.py -m 1 2 3 [1, 2, 3] From drsalists at gmail.com Sun Jul 22 12:42:28 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 22 Jul 2012 09:42:28 -0700 Subject: command line option parsing and pylint? Message-ID: Is there such a thing as a Python option parsing module, that plays well with pylint? I've been doing my own option parsing to get working static analysis. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Jul 22 13:01:11 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Jul 2012 17:01:11 GMT Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: <500c31d7$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sun, 22 Jul 2012 19:20:18 +0300, Jan Riechers wrote: > "map" works on a list and does commandX (here "int" conversion, use > "str" for string.. et cetera) on sequenceY, returning a sequence. More > in the help file. > > And if I'm not completely mistaken, it's also the quicker way to do > performance wise. But I can't completely recall the exact reason. The following only applies the standard CPython implementation. Other implementations may be different. In particular, PyPy turns everything you know about optimizing Python code on its head, and can often approach the speed of optimized C code in pure Python. map is faster than an ordinary for-loop if the function you are applying is a builtin like int, str, etc. But if you have to write your own pure- Python function, the overhead of calling a function negates the advantage of map, which is no faster than a for-loop. For example: results = map(int, sequence) # calls builtin `int` hoists the call to int into the fast C layer, instead of the slow Python layer, and should be faster than results = [] for x in sequence: results.append(int(x)) which runs at the speed of Python. But: results = map(lambda x: x+1, sequence) # calls pure Python function if no faster than a for-loop: results = [] for x in sequence: results.append(x+1) Note: this has *nothing* to do with the use of lambda. Writing the "+1" function above using def instead of lambda would give the same results. List comprehensions are at least as fast as map, since they too hoist the calculation into the fast C layer. They have the added advantage that they can calculate arbitrarily complex Python expressions in the C layer without needing an intermediate function. So: map(lambda x: x**2 - 3, sequence) runs more-or-less at the speed of an ordinary for-loop, but the list comprehension version: [x**2 - 3 for x in sequence] should be faster and doesn't rely on an intermediate function. So in general, a list comprehension will be no slower than map, and may be faster; both will be no slower than a for-loop, and may be faster. Or at least, this was the case last time I checked. -- Steven From no.email at nospam.invalid Sun Jul 22 13:03:07 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 22 Jul 2012 10:03:07 -0700 Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: <7xliibpw38.fsf@ruckus.brouhaha.com> Tony the Tiger writes: > # options.modus_list contains, e.g., "[2,3,4]" Try this: import ast MODUS_LIST = ast.literal_eval(options.modus_list) literal_eval is like eval except it can only evaluate literals rather than calling functions and the like. The idea is you can use it on untrusted data. From drobinow at gmail.com Sun Jul 22 13:03:10 2012 From: drobinow at gmail.com (David Robinow) Date: Sun, 22 Jul 2012 13:03:10 -0400 Subject: Converting a list of strings into a list of integers? In-Reply-To: <500C2842.4040204@freenet.de> References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> <500C2842.4040204@freenet.de> Message-ID: On Sun, Jul 22, 2012 at 12:20 PM, Jan Riechers wrote: > On 22.07.2012 18:39, Alister wrote: >> looks like a classic list comprehension to me and can be achieved in a >> single line >> MODUS_LIST=[int(x) for x in options.modus_list] > Hi, > > I am not sure why everyone is using the for-iterator option over a "map", > but I would do it like that: > MODUS_LIST= map(int, options.modus_list) > > "map" works on a list and does commandX (here "int" conversion, use "str" > for string.. et cetera) on sequenceY, returning a sequence. More in the help > file. > > And if I'm not completely mistaken, it's also the quicker way to do > performance wise. But I can't completely recall the exact reason. Because if you don't have a functional background 'map' is unfamiliar. Although I've been aware of it for years I still can't remember if it's map(int, list) or map(list,int) and although with a small effort I could force it into my brain, I know that many of the people reading my code are as ignorant as I am. The list comprehension seems clearer to me. From janpeterr at freenet.de Sun Jul 22 13:10:34 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sun, 22 Jul 2012 20:10:34 +0300 Subject: Converting a list of strings into a list of integers? In-Reply-To: References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> <500C2842.4040204@freenet.de> Message-ID: <500C340A.3040000@freenet.de> On 22.07.2012 20:03, David Robinow wrote: > On Sun, Jul 22, 2012 at 12:20 PM, Jan Riechers wrote: >> On 22.07.2012 18:39, Alister wrote: >>> looks like a classic list comprehension to me and can be achieved in a >>> single line >>> MODUS_LIST=[int(x) for x in options.modus_list] >> Hi, >> >> I am not sure why everyone is using the for-iterator option over a "map", >> but I would do it like that: >> MODUS_LIST= map(int, options.modus_list) >> >> "map" works on a list and does commandX (here "int" conversion, use "str" >> for string.. et cetera) on sequenceY, returning a sequence. More in the help >> file. >> >> And if I'm not completely mistaken, it's also the quicker way to do >> performance wise. But I can't completely recall the exact reason. > Because if you don't have a functional background 'map' is > unfamiliar. Although I've been aware of it for years I still can't > remember if it's map(int, list) or map(list,int) and although with a > small effort I could force it into my brain, I know that many of the > people reading my code are as ignorant as I am. The list comprehension > seems clearer to me. > > Hello, no offense by that, I just was wondering why everyone uses the list comprehension instead the built-in map in this case - I'm still using Python 2.7.3 so perhaps things might have changed a little. :) So far Jan From ian.g.kelly at gmail.com Sun Jul 22 13:16:26 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 22 Jul 2012 11:16:26 -0600 Subject: Converting a list of strings into a list of integers? In-Reply-To: <500C2842.4040204@freenet.de> References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> <500C2842.4040204@freenet.de> Message-ID: On Sun, Jul 22, 2012 at 10:20 AM, Jan Riechers wrote: > Hi, > > I am not sure why everyone is using the for-iterator option over a "map", > but I would do it like that: > > MODUS_LIST= map(int, options.modus_list) > > "map" works on a list and does commandX (here "int" conversion, use "str" > for string.. et cetera) on sequenceY, returning a sequence. More in the help > file. > > And if I'm not completely mistaken, it's also the quicker way to do > performance wise. But I can't completely recall the exact reason. My recollection is that map has the edge if you can pass it a built-in or a C extension function, like int, or a complicated Python function that you would end up calling anyway in the list comprehension. The situation changes though if you can write the comprehension to remove the overhead of the Python function call. For example: map(lambda x: x+1, my_list) [x+1 for x in my_list] By performing the addition inline instead of calling a function to do it, the list comprehension wins performance-wise in this scenario. So as a simple rule of thumb I will typically choose between map or a comprehension based on whether I need to call a function or not (and also based on how pretty or ugly the resulting code is). Anything further would just be premature optimization. Also keep in mind that in Python 3 map returns an iterator instead of a list, so for a fair comparison you would have to compose the map with a list() call. Cheers, Ian From lipska at lipskathekat.com Sun Jul 22 13:23:26 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Sun, 22 Jul 2012 18:23:26 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: <37a37376-18ff-46af-97f0-36fd764a8c26@m2g2000pbv.googlegroups.com> References: <37a37376-18ff-46af-97f0-36fd764a8c26@m2g2000pbv.googlegroups.com> Message-ID: On 22/07/12 17:18, rusi wrote: > On Jul 22, 2:20 pm, Lipska the Kat wrote: > >> Well I have to say that I've used Eclipse with the myEclipse plugin for >> a number of years now and although it has it's moments it has earned me >> LOADS of MONEY so I can't really criticise it. > > Ive probably tried to use eclipse about 4 times in the last 8 years. > Always run away in terror. > Still I'm never sure whether eclipse is stupid or I am... > > First time I'm hearing of myEclipse. Thanks. What does it have/do that > standard eclipse (JDT?) does not? Eclipse for Java supports development of 'standard' Java applications that is applications that use the standard Java Distributions (JDK). MyEclipse adds support for J2EE and a bunch of other stuff. I used it mainly for jsp syntax highlighting, HTML syntax highlighting and Servlet development. It's marketed as a J2EE and web development IDE. It comes with an embedded Tomcat server and some versions support common frameworks such as Spring and Hibernate. Struts is supported by default I think although I always stayed away from frameworks when I could. I preferred to write Java rather than XML :-) Check out http://www.myeclipseide.com/ for an example of marketing bling. >> Python and eclipse ... Noooooooooooooooooooooooooooooooooooooooooo ;-) > Very curious about this. You made 'Loads of money' with eclipse but > want to stay away from it? > Simply cannot make out this thing called 'java-programmer-culture'... How dare you sir, I'm not a Java programmer I am a 'retired' software engineer ;-) Heh heh, Nothing to do with Eclipse, just another thing to get my head around. For work and Java IMHO you can't beat eclipse... at the moment I'm getting my head around git, reminding myself of C, learning Python and re-learning make. Enough already; but if there's a python plugin I guess I'll get around to it eventually Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From janpeterr at freenet.de Sun Jul 22 13:27:29 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Sun, 22 Jul 2012 20:27:29 +0300 Subject: Converting a list of strings into a list of integers? In-Reply-To: <500c31d7$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> <500c31d7$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500C3801.4020500@freenet.de> On 22.07.2012 20:01, Steven D'Aprano wrote: [SNIP] > map is faster than an ordinary for-loop if the function you are applying > is a builtin like int, str, etc. But if you have to write your own pure- > Python function, the overhead of calling a function negates the advantage > of map, which is no faster than a for-loop. For example: > > results = map(int, sequence) # calls builtin `int` > > hoists the call to int into the fast C layer, instead of the slow Python > layer, and should be faster than > > results = [] > for x in sequence: > results.append(int(x)) > > which runs at the speed of Python. But: > > results = map(lambda x: x+1, sequence) # calls pure Python function > > if no faster than a for-loop: > > results = [] > for x in sequence: > results.append(x+1) > > Note: this has*nothing* to do with the use of lambda. Writing the "+1" > function above using def instead of lambda would give the same results. [SNAP] Hi Steven, besides that I testdrive Pypy (and still am impressed, other topic) - your answer was what I was picking for ;) Especially this part of you: > map is faster than an ordinary for-loop if the function you are applying > is a builtin like int, str, etc. [underlaying c-layer] But if you have to write your own pure- > Python function, the overhead of calling a function negates the advantage > of map [...] I did not know that the speed gain is up foremost present when using built-ins, but that's for sure something to keep in mind when writing code. Thanks for your explanation, clarifies a lot! Jan From bruce.sherwood at gmail.com Sun Jul 22 15:04:25 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sun, 22 Jul 2012 13:04:25 -0600 Subject: A thread import problem In-Reply-To: <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: On Sat, Jul 21, 2012 at 5:47 PM, Dennis Lee Bieber wrote: > On Sat, 21 Jul 2012 17:10:05 -0600, Bruce Sherwood > declaimed the following in > gmane.comp.python.general: > > >> Thanks, but the problem I need to solve does not permit putting a >> function like runner in the main program. I'm constrained to being >> able to handle the API of VPython (vpython.org), which lets you write >> programs like the following (call it user.py), which animates a 3D >> cube moving to the right, using OpenGL: >> >> from visual import box >> b = box() >> while True: >> b.pos.x += 0.001 > > Well, based on that sample, wrap THAT as "runner" > > def runner(): > from visual import box > b = box() > while True: > b.pos.x += 0.0001 > > and don't /call/ runner() until after all the main system is configured. > (And runner could, if need be, be "called" as a thread). > > Not having a Mac, I can't do tests... but everything I've seen so > far comes down to NOT IMPORTING anything that tries to spawn threads > /during the import/. > > A properly designed module (as I showed with my testABA.py) only > "runs" stuff if loaded as the main program; any other use (import) only > does imports and defines module level entities -- running anything is > deferred for the program that did the import to invoke AFTER the import > finished. > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list I don't have the luxury of doing things the "approved" way. I'm constrained by extensive legacy code (and legacy educational documentation for student use) to be able to run programs such as this one: from visual import box b = box() while True: b.pos.x += 0.001 Another way of saying this is that I'm not building an app, in which case I would structure things in a simple and straightforward manner. I am instead trying to maintain and update a library that allows novice programmers to write programs that generate real-time navigable 3D animations, writing minimalist programs that work cross-platform. Bruce Sherwood From drsalists at gmail.com Sun Jul 22 18:48:04 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 22 Jul 2012 15:48:04 -0700 Subject: default repr? Message-ID: If a class has defined its own __repr__ method, is there a way of getting the default repr output for that class anyway? I'm attempting to graph some objects by digging around in the garbage collector's idea of what objects exist, and when I go to format them for the graph node labels, the ones that haven't defined a __repr__ look nice, but the ones that have come out looking strangely. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Jul 22 18:54:00 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 23 Jul 2012 08:54:00 +1000 Subject: default repr? In-Reply-To: References: Message-ID: On Mon, Jul 23, 2012 at 8:48 AM, Dan Stromberg wrote: > If a class has defined its own __repr__ method, is there a way of getting > the default repr output for that class anyway? Methods are just functions, and you can call any method of any class with any object as its first parameter. object.__repr__(some_object) Though this mightn't work with everything. I wasn't able to paint a list as a tuple - "tuple.__repr__([1,2,3])" threw a TypeError. Oh well. There's a limit to the ways Python lets you shoot yourself in the foot. ChrisA From oscar.j.benjamin at gmail.com Sun Jul 22 18:54:13 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 22 Jul 2012 23:54:13 +0100 Subject: default repr? In-Reply-To: References: Message-ID: On 22 July 2012 23:48, Dan Stromberg wrote: > > If a class has defined its own __repr__ method, is there a way of getting > the default repr output for that class anyway? > For new style classes you can just call object.__repr__ e.g.: In [1]: class A(object): ...: pass ...: In [2]: class B(object): ...: def __repr__(self): ...: return 'foo' ...: In [3]: a = A() In [4]: b = B() In [5]: repr(a) Out[5]: '<__main__.A object at 0x2136b10>' In [6]: repr(b) Out[6]: 'foo' In [7]: object.__repr__(b) Out[7]: '<__main__.B object at 0x2136c10>' Oscar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrisjrn at gmail.com Sun Jul 22 19:09:52 2012 From: chrisjrn at gmail.com (Chris Neugebauer) Date: Mon, 23 Jul 2012 09:09:52 +1000 Subject: Four weeks until PyCon Australia 2012: Have you registered yet? Message-ID: Things have been very busy here at PyCon Australia 2012 headquarters -- we've been busy putting the finishing touches on what we hope will be an amazing conference for Python programmers from around Australia and beyond. === T-shirt registration deadline: Tuesday 31 July. === Of course, a conference is nothing without people attending, and there's still plenty of opportunity to join in the fun. Registrations for the conference will remain open until the week of the conference, or until we sell out; but if you want one of our fantastic conference t-shirts, you'll need to have your registration finalised on Tuesday, 31 July. Prices for reigstrations start at $44 for students, and $198 for individuals. You can register at http://2012.pycon-au.org/register/prices === More Events! === For those of you attending the conference, you'll be pleased to know that we've confirmed a few more of our events for the conference. The annual PyLadies breakfast is happening on the Saturday, before conference festivities start, at Wrest Point's Pier One waterfront restaurant. This event is open to all female delegates to the conference, and is being sponsored by our good friends at Google Australia. We've also finalised details of our conference dinner -- we'll be sharing details of these with you next week, but needless to say, we're very excited about it, and can't wait to share this with you. === About PyCon Australia === PyCon Australia is the national conference for the Python Programming Community. The third PyCon Australia will be held on August 18 and 19, 2012 in Hobart, Tasmania, bringing together professional, student and enthusiast developers with a love for developing with Python. PyCon Australia informs the country?s Python developers with presentations, tutorials and panel sessions by experts and core developers of Python, as well as the libraries and frameworks that they rely on. To find out more about PyCon Australia 2012, visit our website at http://pycon-au.org or e-mail us at contact at pycon-au.org. PyCon Australia is presented by Linux Australia (www.linux.org.au) and acknowledges the support of our Gold sponsors: Google Australia (www.google.com.au), and the Australian Computer Society (Tasmanian Branch) (www.acs.org.au); our Event partners: Kogan, and Secret Lab; and our Silver sponsors: the Python Software Foundation, the Django Software Foundation, Anchor Systems, 99designs, Red Hat, BitBucket by Atlassian, ekit, Ionata Web Solutions, RimuHosting, and CSIRO. -- --Christopher Neugebauer Jabber: chrisjrn at gmail.com -- IRC: chrisjrn on irc.freenode.net -- AIM: chrisjrn157 -- MSN: chris at neugebauer.id.au -- WWW: http://chris.neugebauer.id.au -- Twitter/Identi.ca: @chrisjrn From bruce.sherwood at gmail.com Sun Jul 22 19:14:28 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Sun, 22 Jul 2012 17:14:28 -0600 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: On Sun, Jul 22, 2012 at 3:48 PM, Dennis Lee Bieber wrote: > On Sun, 22 Jul 2012 13:04:25 -0600, Bruce Sherwood > declaimed the following in > gmane.comp.python.general: > > >> Another way of saying this is that I'm not building an app, in which >> case I would structure things in a simple and straightforward manner. >> I am instead trying to maintain and update a library that allows >> novice programmers to write programs that generate real-time navigable >> 3D animations, writing minimalist programs that work cross-platform. >> > I suspect you don't need to update the library so much as enforce a > project style that prevents your import-thread-import cycle. In short, > something like that hypothetical "runner()" design. > > Oh, and document that style in detail: "importable modules shall > only perform module level definition of entities during import -- no > code that actually processes data"; "importable modules shall make use > of the 'if __name__ == "__main__": main()' convention to identify when > the module is being used stand-alone, and thereby invoke the main > processing; otherwise the module.main() function is to be invoked only > be the module doing the imports, after the import has completed" > etc. > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list There's nothing wrong with the current VPython architecture, which does use good style, but there are two absolute, conflicting requirements that I have to meet. (1) The simple program API I've shown must be preserved, because there exist a large number of such programs in existence, used by lots of people. I can't change the API. Among other uses, every semester there are about 5000 students in introductory college science courses, especially physics, who do computational modeling with 3D visualizations based on instructional materials that teach the existing API. There is also a large number of instructors who depend on existing VPython demo programs to continue working even if the college upgrades Python and VPython. This isn't some little project where I'm able to teach my small group of collaborators how they should structure programs. (2) My hand is forced by Apple no longer supporting Carbon. Among other aspects of this, Carbon can't be used with 64-bit Python, and more and more Mac users of VPython want to use 64-bit Python. So there has to be a version of VPython that is based on Cocoa, but Cocoa is required to be the primary thread. This requirement, combined with the absolute requirement that the VPython API cannot be changed, is the problem I face. I have to turn the architecture inside out, independent of whether the solution meets all criteria for good Python programming style. Bruce Sherwood From steve+comp.lang.python at pearwood.info Sun Jul 22 20:24:54 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 00:24:54 GMT Subject: default repr? References: Message-ID: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 08:54:00 +1000, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 8:48 AM, Dan Stromberg > wrote: >> If a class has defined its own __repr__ method, is there a way of >> getting the default repr output for that class anyway? If the class, call it C, is a subclass of some other class (or classes), then there is also the repr of the parent. You can get to that by calling parent.__repr__(instance), although there are some subtleties. In Python 2, there are old-style or classic classes that don't inherit from anything else. I don't believe there is any way to get the repr of a classic class with no __repr__ method *except* from an instance with no __repr__ method. So the answer for C below will be No: # Python 2.x class C: def __repr__(self): return "C()" But for new-style classes in Python 2, or all classes in Python 3, the answer is Yes. All classes inherit from object, directly or indirectly, so you can either call the object repr or use super: # Python 2.x or 3.x class K(object): # inheriting from object makes it "new style" def __repr__(self): # but please don't do this -- see below for a better way print(object.__repr__(self)) return "K()" You can specify the parent class directly by name, as above, grab its __repr__ method, and call it. But that's the wrong solution: it does not work correctly with multiple inheritance, and even if you don't use MI yourself, it means that nobody else can use your class for MI. Better is to allow Python to work out which parent class you have, even if you already know the answer and only have one parent. The dance is a little more complex, but now you are multiple-inheritance-safe: # Python 2.x or 3.x class K(object): def __repr__(self): # this ONLY works for new-style classes print(super(K, self).__repr__()) return "K()" Python 3 offers some additional magic: if you don't give super() any arguments, the compiler magically does the right thing: # Python 3.x class K(object): # or just "class K" def __repr__(self): print(super().__repr__()) return "K()" > Methods are just functions, and you can call any method of any class > with any object as its first parameter. Not quite: they have to be an instance of that class. > object.__repr__(some_object) That will work because everything is an instance of object (apart from classic classes in Python 2). > Though this mightn't work with everything. I wasn't able to paint a list > as a tuple - "tuple.__repr__([1,2,3])" threw a TypeError. Oh well. > There's a limit to the ways Python lets you shoot yourself in the foot. Of course -- [1,2,3] is not a tuple, so how would tuple know what to do with it? -- Steven From rosuav at gmail.com Sun Jul 22 20:29:33 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 23 Jul 2012 10:29:33 +1000 Subject: default repr? In-Reply-To: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 10:24 AM, Steven D'Aprano wrote: >> Methods are just functions, and you can call any method of any class >> with any object as its first parameter. > > Not quite: they have to be an instance of that class. > >> Though this mightn't work with everything. I wasn't able to paint a list >> as a tuple - "tuple.__repr__([1,2,3])" threw a TypeError. Oh well. >> There's a limit to the ways Python lets you shoot yourself in the foot. > > Of course -- [1,2,3] is not a tuple, so how would tuple know what to do > with it? Hmm. I would have thought that methods were like all other functions: they take their arguments and do code with them. Duck typing and all. I stand corrected, then. In any case, it works fine for methods of object, at least with Python 3 and with new-style classes in Py2. (Other than backward compatibility with old code, is there any reason to use an old-style class?) ChrisA From jeanpierreda at gmail.com Sun Jul 22 20:44:56 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 22 Jul 2012 20:44:56 -0400 Subject: default repr? In-Reply-To: References: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Jul 22, 2012 at 8:29 PM, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 10:24 AM, Steven D'Aprano > wrote: >> Not quite: they have to be an instance of that class. ----8<---- > Hmm. I would have thought that methods were like all other functions: > they take their arguments and do code with them. Duck typing and all. > I stand corrected, then. On Python 3 you are correct. >>> class A: ... def print(self): ... print(self) ... >>> A.print(2) 2 -- Devin From d at davea.name Sun Jul 22 21:03:57 2012 From: d at davea.name (Dave Angel) Date: Sun, 22 Jul 2012 21:03:57 -0400 Subject: Converting a list of strings into a list of integers? In-Reply-To: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: <500CA2FD.40105@davea.name> On 07/22/2012 11:29 AM, Tony the Tiger wrote: > Hi, > Is there such a thing in the language, or do I have to invent it myself? > > I came up with the following: > > # options.modus_list contains, e.g., "[2,3,4]" > # (a string from the command line) > > > > So which is it, a list of strings, or a string? Your subject line does not agree with the comment. -- DaveA From steve+comp.lang.python at pearwood.info Sun Jul 22 21:40:26 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 01:40:26 GMT Subject: default repr? References: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500cab8a$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 10:29:33 +1000, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 10:24 AM, Steven D'Aprano > wrote: >>> Methods are just functions, and you can call any method of any class >>> with any object as its first parameter. >> >> Not quite: they have to be an instance of that class. >> >>> Though this mightn't work with everything. I wasn't able to paint a >>> list as a tuple - "tuple.__repr__([1,2,3])" threw a TypeError. Oh >>> well. There's a limit to the ways Python lets you shoot yourself in >>> the foot. >> >> Of course -- [1,2,3] is not a tuple, so how would tuple know what to do >> with it? > > Hmm. I would have thought that methods were like all other functions: > they take their arguments and do code with them. Duck typing and all. I > stand corrected, then. > > In any case, it works fine for methods of object, at least with Python 3 > and with new-style classes in Py2. Naturally. In Python 3, and for new-style classes in 2, any instance is an instance of object. As the base class of everything, object has a generic repr that can handle everything. But subclasses are entitled to be more picky. What would you expect int.__repr__ do with a tuple for an argument? Raise an error, of course, and a TypeError at that. Which it does, in both 2 and 3: py> int.__repr__( (1, 2) ) Traceback (most recent call last): File "", line 1, in TypeError: descriptor '__repr__' requires a 'int' object but received a 'tuple' In general, you should assume that an arbitrary method will insist on its "self" argument actually being a valid instance of its class. There may be occasions where that is not the case, but don't count on it. I expect that this is under-specified behaviour: whether it works or not is implementation-specific, and so may change from compiler to compiler, or version to version. The mechanism behind method look-up is slightly complex, and changed significantly in Python 3. In Python 2, *both* these lookups: myclass.mymethod myinstance.mymethod return a *method object* -- the first case returns an "unbound method", which needs self to be provided when it is called, and the second returns a "bound method", which already knows what value of self to use (myinstance). In CPython, they are the same type with slightly different reprs, but that's an implementation detail. In either case, the method type enforces the rule that self is an instance of the type. In Python 3, the rule is slightly different. As before, *bound* methods (those that already have self supplied) are still returned when you look- up on an instance: myinstance.mymethod # returns a bound method object but unbound methods are no longer returned. (I presume you could still create one, by hand, but haven't tried.) Instead, looking up on the class returns the raw function object without the method wrapper, and that does no type-checking on self unless the developer put one in. Which built-in methods have got. > (Other than backward compatibility with old code, is there any reason to > use an old-style class?) Old-style classes have subtle differences in behaviour, and in principle at least are slightly faster. (At least they were back in Python 2.2.) Some differences include: 1) descriptor protocol does not work, including properties 2) super does not work 3) no __getattribute__ 4) magic dunder methods such as __add__ do not bypass the instance 5) automatic delegation is trivial So if you *require* such differences, then they would be good reasons for using classic classes. But frankly, as far as I can tell only #4 and #5 are positive differences, the others are reasons to avoid classic classes. -- Steven From jeanpierreda at gmail.com Mon Jul 23 01:50:12 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 23 Jul 2012 01:50:12 -0400 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: On Sun, Jul 22, 2012 at 7:14 PM, Bruce Sherwood wrote: > (2) My hand is forced by Apple no longer supporting Carbon. Among > other aspects of this, Carbon can't be used with 64-bit Python, and > more and more Mac users of VPython want to use 64-bit Python. So there > has to be a version of VPython that is based on Cocoa, but Cocoa is > required to be the primary thread. This requirement, combined with the > absolute requirement that the VPython API cannot be changed, is the > problem I face. I have to turn the architecture inside out, > independent of whether the solution meets all criteria for good Python > programming style. I had exactly this problem with Tkinter on Mac. The API involved "synchronous" calls to update a GUI written in tkinter, which ran in another thread (so e.g. students could call the API from the interactive interpreter). This didn't work on new Mac OS X releases, because Tkinter had to be run in the main thread after some update -- and also because of this deadlock issue with imports (but I didn't know that until later). I ended up solving it by running the Tkinter in the main thread of a different process, which could handle RPC invocations asynchronously, and sending remote invocations via a synchronous RPC library in the parent process. Maybe you can do something similar in your case? -- Devin From ivan.cvetkovic at pakel.hr Mon Jul 23 03:12:02 2012 From: ivan.cvetkovic at pakel.hr (Ivan@work) Date: Mon, 23 Jul 2012 09:12:02 +0200 Subject: My first ever Python program, comments welcome In-Reply-To: References: Message-ID: On 21.07.2012 21:08, Lipska the Kat wrote: > Greetings Pythoners > > A short while back I posted a message that described a task I had set > myself. I wanted to implement the following bash shell script in Python > > Here's the script > > sort -nr $1 | head -${2:-10} > > this script takes a filename and an optional number of lines to display > and sorts the lines in numerical order, printing them to standard out. > if no optional number of lines are input the script prints 10 lines > > Here's the file. > > 50 Parrots > 12 Storage Jars > 6 Lemon Currys > 2 Pythons > 14 Spam Fritters > 23 Flying Circuses > 1 Meaning Of Life > 123 Holy Grails > 76 Secret Policemans Balls > 8 Something Completely Differents > 12 Lives of Brian > 49 Spatulas > > > ... and here's my very first attempt at a Python program > I'd be interested to know what you think, you can't hurt my feelings > just be brutal (but fair). There is very little error checking as you > can see and I'm sure you can crash the program easily. > 'Better' implementations most welcome > > #! /usr/bin/env python3.2 > > import fileinput > from sys import argv > from operator import itemgetter > > l=[] You can do without this, see below. > t = tuple This initialization does nothing. Assignment t=(line.split('\t')) makes `t` a list (not a tuple), discarding any previous value. And you don't really need t: > with fileinput.input(files=(filename)) as f: > for line in f: > t=(line.split('\t')) > t[0]=int(t[0]) > l.append(t) List comprehension is your friend, and now you don't need to initialize l to an empty list. with open(filename) as f: l = [line.split('\t') for line in f] The first element of each row is now a string, but it's easy to fix: > l=sorted(l, key=itemgetter(0)) Use in-place sorting and cast the sorting element to int l.sort(key=lambda t: int(t[0])) > inCount = int(argv[2]) > lineCount = inCount lineCount = int(argv[2]) works just fine > > for c in range(lineCount): > t=l[c] > print(t[0], t[1], sep='\t', end='') Whenever you write "for i in range(n)" you're (probably) doing it wrong. Here you can use list slicing, and as a bonus the program doesn't bomb when lineCount is greater than length(l) for t in l[:lineCount]: print(t[0], t[1], sep='\t', end='') From rosuav at gmail.com Mon Jul 23 03:59:42 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 23 Jul 2012 17:59:42 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHKSLi4uLi4uLpE=?= In-Reply-To: References: Message-ID: On Fri, Jul 20, 2012 at 5:56 PM, levi nie wrote: > the meaning of r?.......?? It's a raw string. http://docs.python.org/py3k/tutorial/introduction.html#strings Chris Angelico From steve+comp.lang.python at pearwood.info Mon Jul 23 04:07:15 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 08:07:15 GMT Subject: the meaning of =?iso-8859-7?b?cqIuLi4uLi4uoQ==?= References: Message-ID: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> On Mon, 23 Jul 2012 17:59:42 +1000, Chris Angelico wrote: > On Fri, Jul 20, 2012 at 5:56 PM, levi nie wrote: >> the meaning of r?.......?? > > It's a raw string. Technically, no, it's a SyntaxError, because the Original Poster has used some sort of "Smart Quotes" characters r?? instead of good old fashioned typewriter-style quotes r'' or r"". If you're going to ask programming questions using an email client that changes what you type, including smart quotes, special hyphens or other characters, you're going to have a bad time. -- Steven From lipska at lipskathekat.com Mon Jul 23 06:02:58 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Mon, 23 Jul 2012 11:02:58 +0100 Subject: python package confusion Message-ID: Hello again pythoners I'm trying to understand the python package stuff I have the following directory /home/lipska/python/dev/mods In this directory I have two files, both executable ---------------------- #! /usr/bin/env python3.2 # fibo.py Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() ---------------------- #! /usr/bin/env python3.2 # test.py fibo module test program import fibo fibo.fib(1000) ----------------------- The PYTHONPATH ev is set to /home/lipska/python/dev/mods:. in .bashrc The following interactive session works thusly lipska at ubuntu:~/python/dev/mods$ python3.2 Python 3.2.3 (default, Jul 17 2012, 14:23:10) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import fibo >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> However if I try and run test.py as an executable I get the following error lipska at ubuntu:~/python/dev/mods$ test.py Traceback (most recent call last): File "./test.py", line 5, in fib(1000) NameError: name 'fib' is not defined if I print sys.path I get the following >>> print(sys.path) ['', '/usr/local/lib/python32.zip', '/usr/local/lib/python3.2', '/usr/local/lib/python3.2/plat-linux2', '/usr/local/lib/python3.2/lib-dynload', '/home/lipska/.local/lib/python3.2/site-packages', '/usr/local/lib/python3.2/site-packages'] The documentation states that ... sys.path is initialized from these locations: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). But apparently the additional locations I specify in .bashrc are not being added to sys.path I also have an empty file __init__.py in the mods directory Not sure what I'm doing wrong here Any help much appreciated. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From d at davea.name Mon Jul 23 06:19:26 2012 From: d at davea.name (Dave Angel) Date: Mon, 23 Jul 2012 06:19:26 -0400 Subject: python package confusion In-Reply-To: References: Message-ID: <500D252E.1000804@davea.name> On 07/23/2012 06:02 AM, Lipska the Kat wrote: > Hello again pythoners > > I'm trying to understand the python package stuff > > I have the following directory > > /home/lipska/python/dev/mods > > In this directory I have two files, both executable > > ---------------------- > > #! /usr/bin/env python3.2 > > # fibo.py Fibonacci numbers module > > def fib(n): # write Fibonacci series up to n > a, b = 0, 1 > while b < n: > print(b, end=' ') > a, b = b, a+b > print() > > ---------------------- > > #! /usr/bin/env python3.2 > > # test.py fibo module test program > > import fibo > > fibo.fib(1000) > > ----------------------- > > The PYTHONPATH ev is set to /home/lipska/python/dev/mods:. > in .bashrc > > The following interactive session works thusly > > lipska at ubuntu:~/python/dev/mods$ python3.2 > Python 3.2.3 (default, Jul 17 2012, 14:23:10) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import fibo > >>> fibo.fib(1000) > 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 > >>> > > However if I try and run test.py as an executable I get the following > error > > lipska at ubuntu:~/python/dev/mods$ test.py > Traceback (most recent call last): > File "./test.py", line 5, in > fib(1000) > NameError: name 'fib' is not defined > That line isn't the way you showed it in the source. You showed us source as fibo.fib(1000), and the error message shows it as fib(1000) So you're either cutting & pasting wrong, or you have two test.py files. -- DaveA From jeanpierreda at gmail.com Mon Jul 23 06:22:45 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 23 Jul 2012 06:22:45 -0400 Subject: python package confusion In-Reply-To: References: Message-ID: On Mon, Jul 23, 2012 at 6:02 AM, Lipska the Kat wrote: > The PYTHONPATH ev is set to /home/lipska/python/dev/mods:. > in .bashrc Did you export it? Show us your .bashrc, or the relevant line in it exactly. (And make sure that it isn't defined multiple times). Also adding . to the import search path is probably a bad diea. > lipska at ubuntu:~/python/dev/mods$ test.py > Traceback (most recent call last): > File "./test.py", line 5, in > fib(1000) > NameError: name 'fib' is not defined Neither of the files you described in your email message contain the line "fib(1000)", so you pasted the wrong files. > I also have an empty file __init__.py in the mods directory This only matters if you want to "import mods". -- Devin From lipska at lipskathekat.com Mon Jul 23 06:54:04 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Mon, 23 Jul 2012 11:54:04 +0100 Subject: python package confusion In-Reply-To: References: Message-ID: <4r6dneYzruLQsJDNnZ2dnUVZ8u2dnZ2d@bt.com> On 23/07/12 11:19, Dave Angel wrote: > On 07/23/2012 06:02 AM, Lipska the Kat wrote: >> Hello again pythoners snip > That line isn't the way you showed it in the source. You showed us > source as fibo.fib(1000), and the error message shows it as fib(1000) > > So you're either cutting& pasting wrong, or you have two test.py files. jeez, you are right. I must be getting old. Apologies for wasting your time. Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From lipska at lipskathekat.com Mon Jul 23 07:02:03 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Mon, 23 Jul 2012 12:02:03 +0100 Subject: python package confusion In-Reply-To: References: Message-ID: On 23/07/12 11:22, Devin Jeanpierre wrote: > On Mon, Jul 23, 2012 at 6:02 AM, Lipska the Kat wrote: >> The PYTHONPATH ev is set to /home/lipska/python/dev/mods:. >> in .bashrc > > Did you export it? Show us your .bashrc, or the relevant line in it > exactly. (And make sure that it isn't defined multiple times). forgot to export it > Also adding . to the import search path is probably a bad diea. I removed it >> lipska at ubuntu:~/python/dev/mods$ test.py >> Traceback (most recent call last): >> File "./test.py", line 5, in >> fib(1000) >> NameError: name 'fib' is not defined > Neither of the files you described in your email message contain the > line "fib(1000)", so you pasted the wrong files. See grovelling apology in other reply > >> I also have an empty file __init__.py in the mods directory > > This only matters if you want to "import mods". huh .. OK, I'll read again Thanks for taking the time to reply It all works now Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From bouncingcats at gmail.com Mon Jul 23 07:16:30 2012 From: bouncingcats at gmail.com (David) Date: Mon, 23 Jul 2012 21:16:30 +1000 Subject: python package confusion In-Reply-To: References: Message-ID: On 23/07/2012, Lipska the Kat wrote: > Hello again pythoners [snip] > Any help much appreciated. Hi Lipska Glad you got it sorted. In case you are not aware of this: Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor The tutor list caters specifically for requests for basic assistance such as you made in this thread, and code review such as in your thread prior. It too is a busy list, and many of the people who have responded to your previous threads here are also present there, so you'll get the same high quality answers there too. By the way, I had a followup to my previous message to you re git, and emailed it to you directly because it would be off-topic here, but the email bounced. It seems that you are displaying an invalid email address, at least here I get: $ ping lipskathekat.com ping: unknown host lipskathekat.com So if you are interested in that, feel free to email me directly, or not as you wish. From hfaber at invalid.net Mon Jul 23 07:23:01 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 13:23:01 +0200 Subject: dict: keys() and values() order guaranteed to be same? Message-ID: Hi group, I have a question of which I'm unsure if the specification guarantees it. With an arbitrary dictionaty d, are d.keys() and d.values() guaraneed to be in the same order? I.e. what I mean is: # For all dictionaries d: assert({ list(d.keys())[i]: list(d.values())[i] for i in range(len(d)) } == d) I'm curious if it's allowed because in a special case it would make for a nice shortcut and clean code. I think however that the implementation may chose not to have them in the same order necessarily -- then I'd obviously avoid relying on it. Best regards, Joe From phihag at phihag.de Mon Jul 23 07:40:42 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 23 Jul 2012 13:40:42 +0200 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: References: Message-ID: <500D383A.9090500@phihag.de> On 07/23/2012 01:23 PM, Henrik Faber wrote: > With an arbitrary dictionaty d, are d.keys() and d.values() > guaraneed to be in the same order? Yes. From the documentation[1]: If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. In most cases, you should simply use items() though. Can you elaborate on the use case for needing both keys() and values(), where items() is not applicable? - Philipp [1] http://docs.python.org/library/stdtypes.html#dict.items -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From stefan_ml at behnel.de Mon Jul 23 07:43:14 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Jul 2012 13:43:14 +0200 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: References: Message-ID: Henrik Faber, 23.07.2012 13:23: > I have a question of which I'm unsure if the specification guarantees > it. With an arbitrary dictionaty d, are d.keys() and d.values() > guaraneed to be in the same order? I.e. what I mean is: > > # For all dictionaries d: > assert({ list(d.keys())[i]: list(d.values())[i] for i in range(len(d)) } > == d) > > I'm curious if it's allowed because in a special case it would make for > a nice shortcut and clean code. I think however that the implementation > may chose not to have them in the same order necessarily -- then I'd > obviously avoid relying on it. You should. Stefan From lipska at lipskathekat.com Mon Jul 23 07:43:48 2012 From: lipska at lipskathekat.com (Lipska the Kat) Date: Mon, 23 Jul 2012 12:43:48 +0100 Subject: python package confusion In-Reply-To: References: Message-ID: On 23/07/12 12:16, David wrote: > On 23/07/2012, Lipska the Kat wrote: > >> Hello again pythoners > [snip] > > Any help much appreciated. > > Hi Lipska > > Glad you got it sorted. > > In case you are not aware of this: > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I'll certainly look into it, thanks. It was more a problem of trying to do too many things at once and doing none of them well. Pathetic excuse I know but it's the best I've got. :-( > So if you are interested in that, feel free to email me directly, or > not as you wish. I've sent you message Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From stefan_ml at behnel.de Mon Jul 23 07:58:37 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 23 Jul 2012 13:58:37 +0200 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: <500D383A.9090500@phihag.de> References: <500D383A.9090500@phihag.de> Message-ID: Philipp Hagemeister, 23.07.2012 13:40: > On 07/23/2012 01:23 PM, Henrik Faber wrote: >> With an arbitrary dictionaty d, are d.keys() and d.values() >> guaraneed to be in the same order? > > Yes. From the documentation[1]: > > If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() > are called with no intervening modifications to the dictionary, the > lists will directly correspond. > > [1] http://docs.python.org/library/stdtypes.html#dict.items Interesting. I wonder if other implementations like Jython and PyPy really adhere to this official guarantee. At least Jython has the same paragraph in its documentation and I would expect that PyPy follows it as well. http://www.jython.org/docs/library/stdtypes.html#mapping-types-dict Maybe this guarantee is just easy enough to build on the given implementation details of a platform that it's a common property. Iteration over data structures should tend to be deterministic, after all. Stefan From hfaber at invalid.net Mon Jul 23 08:19:30 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 14:19:30 +0200 Subject: dict: keys() and values() order guaranteed to be same? References: Message-ID: On 23.07.2012 13:40, Philipp Hagemeister wrote: > On 07/23/2012 01:23 PM, Henrik Faber wrote: >> With an arbitrary dictionaty d, are d.keys() and d.values() >> guaraneed to be in the same order? > > Yes. From the documentation[1]: > > If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() > are called with no intervening modifications to the dictionary, the > lists will directly correspond. Ah, nice! > In most cases, you should simply use items() though. Can you elaborate > on the use case for needing both keys() and values(), where items() is > not applicable? I need to parse and modify the keys of the dict and pass the keys as a compound object to a function, which expects the values to be passed as an argument list (weird, but can't change that). The order of arguments is arbitrary (as the iteration over a dict is), but there has to be a 1-to-1 relation bewtween the compound object's key order and the argument list's value order. Best regards, Henrik From A.Serebrenik at tue.nl Mon Jul 23 08:51:06 2012 From: A.Serebrenik at tue.nl (Alexander Serebrenik) Date: Mon, 23 Jul 2012 05:51:06 -0700 (PDT) Subject: Gender, Representativeness and Reputation in StackOverflow Message-ID: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> Do you participate in StackOverflow discussions? As a part of a joint on-going research effort of the Brunel University (UK) and Eindhoven University of Technology (The Netherlands) on the impact of collaboration sites on the developers community, we would like to understand the demographics of StackOverflow participants and their activity. Specifically we are focusing on how genders, minorities and cultural background are represented in the population of users and participants of StackOverflow. Therefore, we have prepared a small questionnaire: https://docs.google.com/spreadsheet/viewform?formkey=dEhtUVNQTEJmRTlwMVJSQ1hkeUZTR3c6MQ#gid=0 In our previous research we have proposed an h-index for open source developers (http://scholar.google.com/scholar?q=%22Developing+an+h-index+for+OSS+developers.%22), and we have a paper under review about how web activity (also Stack Overflow's) could be used by candidates as their resumes. Filling this questionnaire should not take more than a couple of minutes. Personal data will not be made available to third parties and no identifiable details about individual participants will be published. Best regards, Andrea Capiluppi (andrea.capiluppi @ brunel.ac.uk) [Lecturer, Brunel University, UK; NL; SO userid: 1528556] Alexander Serebrenik (a.serebrenik @ tue.nl) [Assistant Professor, Eindhoven University of Technology, NL; SO userid: 1277111] Bogdan Vasilescu (b.n.vasilescu @ tue.nl) [PhD student, Eindhoven University of Technology, NL; SO userid: 1285620] Discussion of this survey on Meta Stack Overflow: http://meta.stackoverflow.com/questions/139901/gender-representativeness-and-reputation-in-stackoverflow From roy at panix.com Mon Jul 23 08:55:22 2012 From: roy at panix.com (Roy Smith) Date: Mon, 23 Jul 2012 08:55:22 -0400 Subject: the meaning of rユ.......ï¾ References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: In article <500d0632$0$1504$c3e8da3$76491128 at news.astraweb.com>, Steven D'Aprano wrote: > Technically, no, it's a SyntaxError, because the Original Poster has used > some sort of "Smart Quotes" characters r?????? instead of good old fashioned > typewriter-style quotes r'' or r"". > > If you're going to ask programming questions using an email client that > changes what you type, including smart quotes, special hyphens or other > characters, you're going to have a bad time. Some day, we're going to have programming languages that take advantage of the full unicode character set. Right now, we're working in ASCII and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line strings). Not to mention <=, >=, ==, !=. And in languages other than python, things like ->, => (arrows for structure membership), and so on. When I first started writing C code, it was on ASR-33s which did not support curly baces. We wrote ??( for { and ??) for } (although I think the translation was handled entirely in the TTY driver and the compiler was never in on the joke). 20 or 30 years from now, people are going to look back on us neanderthals and laugh about how we had to write r''. From sarbjit1987 at gmail.com Mon Jul 23 09:01:23 2012 From: sarbjit1987 at gmail.com (Sarbjit singh) Date: Mon, 23 Jul 2012 06:01:23 -0700 (PDT) Subject: How to print stdout before writing stdin using subprocess module in Python? Message-ID: <6b50a02c-835a-41cb-83c9-8d051a516e38@googlegroups.com> I am writing a script in which in the external system command may sometimes require user input. I am not able to handle that properly. I have tried using os.popen4 and subprocess module but could not achieve the desired behavior. Below mentioned example would show this problem using "cp" command. ("cp" command is used to show this problem, i am calling some different exe which may similarly prompt for user response in some scenarios). In this example there are two files present on disk and when user tries to copy file1 to file2, an conformer message comes up. proc = subprocess.Popen("cp -i a.txt b.txt", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,) stdout_val, stderr_val = proc.communicate() print stdout_val b.txt? proc.communicate("y") Now in this example if i read only stdout/stderr and prints it, later on if i try to write "y" or "n" based on user's input, i got an error that channel is closed. Can some one please help me on achieving this behavior in python such that i can print stdout first, then should take user input and write stdin later on. From rosuav at gmail.com Mon Jul 23 09:06:45 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 23 Jul 2012 23:06:45 +1000 Subject: =?UTF-8?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u77+9wr4=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 10:55 PM, Roy Smith wrote: > Some day, we're going to have programming languages that take advantage > of the full unicode character set. Right now, we're working in ASCII > and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line > strings). Not to mention <=, >=, ==, !=. And in languages other than > python, things like ->, => (arrows for structure membership), and so on. REXX predates Unicode, I think, or at least its widespread adoption, but it has a non-ASCII operator: http://www.rexswain.com/rexx.html#operators But personally, I've always used backslash. It's nothing to do with ASCII and everything to do with having it on the keyboard. Before you get a language that uses full Unicode, you'll need to have fairly generally available keyboards that have those keys. ChrisA From sscc at mweb.co.za Mon Jul 23 09:10:22 2012 From: sscc at mweb.co.za (Alex Strickland) Date: Mon, 23 Jul 2012 15:10:22 +0200 Subject: the meaning of =?windows-1252?Q?r=EF=BE=95=2E=2E=2E=2E=2E=2E?= =?windows-1252?Q?=2E=EF=BE?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500D4D3E.70206@mweb.co.za> On 2012/07/23 02:55 PM, Roy Smith wrote: > Some day, we're going to have programming languages that take advantage > of the full unicode character set. Right now, we're working in ASCII > and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line > strings). Not to mention <=, >=, ==, !=. And in languages other than > python, things like ->, => (arrows for structure membership), and so on. It'll be pretty. -- Regards Alex From oscar.benjamin at bristol.ac.uk Mon Jul 23 09:14:29 2012 From: oscar.benjamin at bristol.ac.uk (Oscar Benjamin) Date: Mon, 23 Jul 2012 14:14:29 +0100 Subject: default repr? In-Reply-To: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500c99d5$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23 July 2012 01:24, Steven D'Aprano wrote: > On Mon, 23 Jul 2012 08:54:00 +1000, Chris Angelico wrote: > > > On Mon, Jul 23, 2012 at 8:48 AM, Dan Stromberg > > wrote: > >> If a class has defined its own __repr__ method, is there a way of > >> getting the default repr output for that class anyway? > > If the class, call it C, is a subclass of some other class (or classes), > then there is also the repr of the parent. You can get to that by calling > parent.__repr__(instance), although there are some subtleties. > > In Python 2, there are old-style or classic classes that don't inherit > from anything else. I don't believe there is any way to get the repr of a > classic class with no __repr__ method *except* from an instance with no > __repr__ method. So the answer for C below will be No: > > # Python 2.x > class C: > def __repr__(self): > return "C()" > You coudl always implement repr yourself: def repr_oldstyle(obj): mod = obj.__class__.__module__ cls = obj.__class__.__name__ mem = '0x' + hex(id(obj))[2:].zfill(8).upper() return '<{0}.{1} instance at {2}>'.format(mod, cls, mem) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Jul 23 09:22:10 2012 From: d at davea.name (Dave Angel) Date: Mon, 23 Jul 2012 09:22:10 -0400 Subject: the meaning of =?UTF-8?B?cu++lS4uLi4uLi7vv73Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500D5002.4060404@davea.name> On 07/23/2012 09:06 AM, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 10:55 PM, Roy Smith wrote: >> Some day, we're going to have programming languages that take advantage >> of the full unicode character set. Right now, we're working in ASCII >> and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line >> strings). Not to mention <=, >=, ==, !=. And in languages other than >> python, things like ->, => (arrows for structure membership), and so on. > REXX predates Unicode, I think, or at least its widespread adoption, > but it has a non-ASCII operator: > > http://www.rexswain.com/rexx.html#operators > > But personally, I've always used backslash. It's nothing to do with > ASCII and everything to do with having it on the keyboard. Before you > get a language that uses full Unicode, you'll need to have fairly > generally available keyboards that have those keys. > > ChrisA Keyboards with 110,000 keys on them; wonderful. And much larger characters on the screen, so that all those can be distinguished. And of course all fonts have to support all those characters. Back to 20 character lines. -- DaveA From roy at panix.com Mon Jul 23 09:22:31 2012 From: roy at panix.com (Roy Smith) Date: Mon, 23 Jul 2012 09:22:31 -0400 Subject: the meaning of r¹.......?3Ž4 References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > But personally, I've always used backslash. It's nothing to do with > ASCII and everything to do with having it on the keyboard. Before you > get a language that uses full Unicode, you'll need to have fairly > generally available keyboards that have those keys. The same was true of "languages that use full ASCII". ASR-33s didn't support full ASCII. Neither did punched cards. All in good time. From hfaber at invalid.net Mon Jul 23 09:24:21 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 15:24:21 +0200 Subject: the meaning of =?windows-1252?Q?r=EF=BE=95=2E=2E=2E=2E=2E=2E?= =?windows-1252?Q?=2E=EF=BE?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 14:55, Roy Smith wrote: > In article <500d0632$0$1504$c3e8da3$76491128 at news.astraweb.com>, > Steven D'Aprano wrote: > >> Technically, no, it's a SyntaxError, because the Original Poster has used >> some sort of "Smart Quotes" characters r?????? instead of good old fashioned >> typewriter-style quotes r'' or r"". >> >> If you're going to ask programming questions using an email client that >> changes what you type, including smart quotes, special hyphens or other >> characters, you're going to have a bad time. > > Some day, we're going to have programming languages that take advantage > of the full unicode character set. Right now, we're working in ASCII > and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line > strings). Not to mention <=, >=, ==, !=. And in languages other than > python, things like ->, => (arrows for structure membership), and so on. I disagree. Firstly, Python could already support the different types of strings even with the ASCII character set. For example, the choice could have made to treat the apostophe string 'foo' differently from the double quote string "foo". Then, the backtick could have been used `foo`. Bash for example uses all three and all three have very different meanings. Python is different: explicit is better than implicit, and I'd rather have the "r" the signifies what weird magic is going on instead of having some weird language rules. It would not be different with some UTF-8 "rawstring" magic backticks. Secondly, there's a reason that >=, <= and friends are in use. Every keyboard has a > key and every keyboard has a = key. I don't know any that would have >=, <= or != as UTF-8. It is useful to use only a limited set of characters. And if I think of PHP's latest fiasco that happened with unicode characters, it makes me shudder to think you'd want that stuff in Python. If I remember correctly, it was the Turkish locale that they stuggled with: Turkey apparently does not have a capital "I", so some weird PHP magic code broke with the Turkish locale in effect. Having to keep crap like that in mind is just plain horrible. I'm very happy with the way Python does it. Best regards, Henrik From hfaber at invalid.net Mon Jul 23 09:26:59 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 15:26:59 +0200 Subject: the meaning of =?windows-1252?Q?r=EF=BE=95=2E=2E=2E=2E=2E=2E?= =?windows-1252?Q?=2E=EF=BE?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 14:55, Roy Smith wrote: > Some day, we're going to have programming languages that take advantage > of the full unicode character set. Plus, if I may add this: It's *your* newsreader that broke the correctly declared ISO-8859-7 encoded subject of the OP. What a bitter irony that demonstrates nicely that even in the 2010s complete and ultimate Unicode support is far from here. Best regards, Henrik From NOSPAM.wrong at wrong.invalid Mon Jul 23 09:32:09 2012 From: NOSPAM.wrong at wrong.invalid (E.) Date: Mon, 23 Jul 2012 13:32:09 +0000 (UTC) Subject: can someone teach me this? References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On 2012-07-21, Menghsiu Lee wrote: > Hi, > I have tried 1000 times to compile this python file to be an exe file > by using py2exe and gui2exe But, it does not work out. I am thinking > if there can be some genius teaching me how to make this happen. The > link in below is the complete code with all sources. Everything is > open to everyone since I change this from another expert. > > http://dl.dropbox.com/u/63928380/blackjack.rar > > Thanks for your help and instructions. > > Best regards, > > menghsiu Maybe you want to show us what you've tried so far. -- e. From rosuav at gmail.com Mon Jul 23 09:35:45 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 23 Jul 2012 23:35:45 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 11:24 PM, Henrik Faber wrote: > And if I think of PHP's latest fiasco that happened with unicode > characters, it makes me shudder to think you'd want that stuff in > Python. If I remember correctly, it was the Turkish locale that they > stuggled with: Turkey apparently does not have a capital "I", so some > weird PHP magic code broke with the Turkish locale in effect. Having to > keep crap like that in mind is just plain horrible. I'm very happy with > the way Python does it. That said, though, there's good argument in allowing full Unicode in *identifiers*. If I'm allowed to name something "foo", then a German should be allowed to name something "fo?". And since identifiers are case sensitive (at least, they are in all good languages...), there should be no issues with not having particular letters. ChrisA From __peter__ at web.de Mon Jul 23 09:38:00 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Jul 2012 15:38 +0200 Subject: How to print stdout before writing stdin using subprocess module in Python? References: <6b50a02c-835a-41cb-83c9-8d051a516e38@googlegroups.com> Message-ID: Sarbjit singh wrote: > I am writing a script in which in the external system command may > sometimes require user input. I am not able to handle that properly. I > have tried using os.popen4 and subprocess module but could not achieve the > desired behavior. > > Below mentioned example would show this problem using "cp" command. ("cp" > command is used to show this problem, i am calling some different exe > which may similarly prompt for user response in some scenarios). In this > example there are two files present on disk and when user tries to copy > file1 to file2, an conformer message comes up. > > proc = subprocess.Popen("cp -i a.txt b.txt", shell=True, > stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,) > stdout_val, stderr_val = proc.communicate() print stdout_val b.txt? > > proc.communicate("y") > > Now in this example if i read only stdout/stderr and prints it, later on > if i try to write "y" or "n" based on user's input, i got an error that > channel is closed. Can some one please help me on achieving this behavior > in python such that i can print stdout first, then should take user input > and write stdin later on. I think you need something like expect: http://pypi.python.org/pypi/pexpect From andrea.crotti.0 at gmail.com Mon Jul 23 09:51:05 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 23 Jul 2012 14:51:05 +0100 Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: 2012/7/20 Chris Angelico : > On Thu, Jul 19, 2012 at 8:15 PM, andrea crotti > wrote: >> We need to be able to reload code on a live system. This live system >> has a daemon process always running but it runs many subprocesses with >> multiprocessing, and the subprocesses might have a short life... >> ... >> As long as I import the code in the function and make sure to remove the >> "pyc" files everything seems to work.. >> Are there any possible problems which I'm not seeing in this approach or >> it's safe? > > Python never promises reloading reliability, but from my understanding > of what you've done here, it's probably safe. However, you may find > that you're using the wrong language for the job; it depends on how > expensive it is to spin off all those processes and ship their work to > them. But if that's not an issue, I'd say you have something safe > there. (Caveat: I've given this only a fairly cursory examination, and > I'm not an expert. Others may have more to say. I just didn't want the > resident Markov chainer to be the only one to respond!!) > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list Thanks Chris, always nice to get a "human" answer ;) Anyway the only other problem which I found is that if I start the subprocesses after many other things are initialised, it might happen that the reloading doesn't work correctly, is that right? Because sys.modules will get inherited from the subprocesses and it will not reimport what has been already imported as far as I understood.. So or I make sure I import everything only where it is needed or (and maybe better and more explicit) I remove manually from sys.modules all the modules that I want to reload, what do you think? From hfaber at invalid.net Mon Jul 23 09:52:32 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 15:52:32 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 15:35, Chris Angelico wrote: > That said, though, there's good argument in allowing full Unicode in > *identifiers*. If I'm allowed to name something "foo", then a German > should be allowed to name something "fo?". And since identifiers are > case sensitive (at least, they are in all good languages...), there > should be no issues with not having particular letters. To you have a "?" key on your keyboard? I have one. It wouldn't be a problem for me. Most English layouts probably don't. It would be annoying. If you allow for UTF-8 identifiers you'll have to be horribly careful what to include and what to exclude. Is the non-breaking space a valid character for a identifier? Technically it's a different character than the normal space, so why shouldn't it be? What an awesome idea! What about ? vs x? Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs I vs ?? Do you think if you need to maintain such code you'll immediately know the difference between the 13 (!) different "I"s I just happened to pull out randomly you need to chose and how to get it? What about ? vs ?? Or ? vs ?? Or ? vs ?? Or d vs ? vs ? vs ? vs ?? Or ? vs g? Or ? vs u? I've not even mentioned the different punctuation marks and already it's hell of a mess, although I just happened to look into a few pages. Having UTF-8 in identifiers is a horrible idea. It makes perfect sense to support it within strings (as Python3 does), but I would hate for Python to include them into identifiers. Then again, I'm pretty sure this is not planned anytime soon. Best regards, Henrik From hfaber at invalid.net Mon Jul 23 09:55:26 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 15:55:26 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 15:52, Henrik Faber wrote: > but I would hate for > Python to include them into identifiers. Then again, I'm pretty sure > this is not planned anytime soon. Dear Lord. Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f??b?r = 3 >>> f??b?r 3 I didn't know this. How awful. Regards, Johannes From hfaber at invalid.net Mon Jul 23 09:59:37 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 15:59:37 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 15:55, Henrik Faber wrote: > Dear Lord. > > Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> f??b?r = 3 >>>> f??b?r > 3 > > I didn't know this. How awful. Apparently, not all characters are fine with Python. Why can I not have domino tiles are identifier characters? >>> ? = 9 File "", line 1 ? = 9 ^ SyntaxError: invalid character in identifier I think there needs to be a PEP for that. Regads, Henrik From bruce.sherwood at gmail.com Mon Jul 23 10:07:26 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Mon, 23 Jul 2012 08:07:26 -0600 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: Thanks much for the useful suggestion, and also thanks for your sympathy and understanding of my plight! Bruce Sherwood On Sun, Jul 22, 2012 at 11:50 PM, Devin Jeanpierre wrote: > On Sun, Jul 22, 2012 at 7:14 PM, Bruce Sherwood > wrote: >> (2) My hand is forced by Apple no longer supporting Carbon. Among >> other aspects of this, Carbon can't be used with 64-bit Python, and >> more and more Mac users of VPython want to use 64-bit Python. So there >> has to be a version of VPython that is based on Cocoa, but Cocoa is >> required to be the primary thread. This requirement, combined with the >> absolute requirement that the VPython API cannot be changed, is the >> problem I face. I have to turn the architecture inside out, >> independent of whether the solution meets all criteria for good Python >> programming style. > > I had exactly this problem with Tkinter on Mac. The API involved > "synchronous" calls to update a GUI written in tkinter, which ran in > another thread (so e.g. students could call the API from the > interactive interpreter). This didn't work on new Mac OS X releases, > because Tkinter had to be run in the main thread after some update -- > and also because of this deadlock issue with imports (but I didn't > know that until later). > > I ended up solving it by running the Tkinter in the main thread of a > different process, which could handle RPC invocations asynchronously, > and sending remote invocations via a synchronous RPC library in the > parent process. > > Maybe you can do something similar in your case? > > -- Devin From alain at dpt-info.u-strasbg.fr Mon Jul 23 10:08:11 2012 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 23 Jul 2012 16:08:11 +0200 Subject: the meaning of =?utf-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <87wr1uy3hw.fsf@dpt-info.u-strasbg.fr> Henrik Faber writes: > On 23.07.2012 15:55, Henrik Faber wrote: > >> Dear Lord. >> >> Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) >> [GCC 4.5.2] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> f??b?r = 3 >>>>> f??b?r >> 3 >> >> I didn't know this. How awful. > > Apparently, not all characters are fine with Python. Why can I not have > domino tiles are identifier characters? The answer is in the language reference: http://docs.python.org/py3k/reference/lexical_analysis.html#identifiers -- Alain. From jeanpierreda at gmail.com Mon Jul 23 10:10:22 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 23 Jul 2012 10:10:22 -0400 Subject: =?UTF-8?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLDr8K+4oCiLi4uLi4uLsOvwr4=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 9:52 AM, Henrik Faber wrote: > If you allow for UTF-8 identifiers you'll have to be horribly careful > what to include and what to exclude. Is the non-breaking space a valid > character for a identifier? Technically it's a different character than > the normal space, so why shouldn't it be? What an awesome idea! > > What about ? vs x? Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs > ? vs I vs ?? Do you think if you need to maintain such code you'll > immediately know the difference between the 13 (!) different "I"s I just > happened to pull out randomly you need to chose and how to get it? What > about ? vs ?? Or ? vs ?? Or ? vs ?? Or d vs ? vs ? vs ? vs ?? Or ? vs g? > Or ? vs u? Yes, as soon as we add unicode to anything everyone will go insane and write gibberish. -- Devin From rosuav at gmail.com Mon Jul 23 10:15:56 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 00:15:56 +1000 Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: On Mon, Jul 23, 2012 at 11:51 PM, andrea crotti wrote: > Anyway the only other problem which I found is that if I start the > subprocesses after many other things are initialised, it might happen > that the reloading doesn't work correctly, is that right? > > Because sys.modules will get inherited from the subprocesses and it > will not reimport what has been already imported as far as I > understood.. > > So or I make sure I import everything only where it is needed or (and > maybe better and more explicit) I remove manually from sys.modules all > the modules that I want to reload, what do you think? That would probably be correct. However, I still think you may be fighting against the language instead of playing to its strengths. I've never fiddled with sys.modules like that, but I know some have, without problem. ChrisA From rosuav at gmail.com Mon Jul 23 10:19:55 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 00:19:55 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 11:52 PM, Henrik Faber wrote: > What about ? vs x? Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs > ? vs I vs ?? Do you think if you need to maintain such code you'll > immediately know the difference between the 13 (!) different "I"s I just > happened to pull out randomly you need to chose and how to get it? What > about ? vs ?? Or ? vs ?? Or ? vs ?? Or d vs ? vs ? vs ? vs ?? Or ? vs g? > Or ? vs u? If they're different characters, they're different. It's not unlike the confusion you can already get between uppercase I and lowercase l, or between uppercase and lowercase of the same letter, or between rn and m, or between any other of myriad confusingly-similar pairs that can be found just in ASCII. Of course, SOMEBODY is going to make use of those to improve upon this sort of code: http://thedailywtf.com/Articles/Uppity.aspx ChrisA From invalid at invalid.invalid Mon Jul 23 10:27:19 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 23 Jul 2012 14:27:19 +0000 (UTC) Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: On 2012-07-22, Jan Riechers wrote: > I am not sure why everyone is using the for-iterator option over a > "map", but I would do it like that: > > MODUS_LIST= map(int, options.modus_list) > > "map" works on a list and does commandX (here "int" conversion, use > "str" for string.. et cetera) on sequenceY, returning a sequence. More > in the help file. "map" is what comes to mind first for me, but that's probably because 1) Before I learned Python, I learned other more functional languages where map was the definitive answer. 2) When I first learned Python it didn't have list comprehensions. That said, "map" seems to be frowned upon by the Python community for reasons I've never really understood, and most people are going to prefer reading a list comprehension. "What most people are going to prefer reading" does matter... -- Grant Edwards grant.b.edwards Yow! ... the MYSTERIANS are at in here with my CORDUROY gmail.com SOAP DISH!! From hfaber at invalid.net Mon Jul 23 10:40:00 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 16:40:00 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 16:10, Devin Jeanpierre wrote: > On Mon, Jul 23, 2012 at 9:52 AM, Henrik Faber wrote: >> If you allow for UTF-8 identifiers you'll have to be horribly careful >> what to include and what to exclude. Is the non-breaking space a valid >> character for a identifier? Technically it's a different character than >> the normal space, so why shouldn't it be? What an awesome idea! >> >> What about ? vs x? Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs >> ? vs I vs ?? Do you think if you need to maintain such code you'll >> immediately know the difference between the 13 (!) different "I"s I just >> happened to pull out randomly you need to chose and how to get it? What >> about ? vs ?? Or ? vs ?? Or ? vs ?? Or d vs ? vs ? vs ? vs ?? Or ? vs g? >> Or ? vs u? > > Yes, as soon as we add unicode to anything everyone will go insane and > write gibberish. No, you misunderstood me. I didn't say people are going to write gibberish. What I'm saying is that as a foreigner (who doesn't know most of these characters), it can be hard to accurately choose which one is the correct one. This is especially true if the appropriate keys are not available on your keyboard. So it makes maintenance of other people's code much more difficult if they didn't on their own chose to limit themselves to ASCII. Regards, Henrik From hfaber at invalid.net Mon Jul 23 10:42:51 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 16:42:51 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 16:19, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 11:52 PM, Henrik Faber wrote: >> What about ? vs x? Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs >> ? vs I vs ?? Do you think if you need to maintain such code you'll >> immediately know the difference between the 13 (!) different "I"s I just >> happened to pull out randomly you need to chose and how to get it? What >> about ? vs ?? Or ? vs ?? Or ? vs ?? Or d vs ? vs ? vs ? vs ?? Or ? vs g? >> Or ? vs u? > > If they're different characters, they're different. It's not unlike > the confusion you can already get between uppercase I and lowercase l, > or between uppercase and lowercase of the same letter, or between rn > and m, or between any other of myriad confusingly-similar pairs that > can be found just in ASCII. But your reasoning is flawed: bascially you're saying some things are already confusing, so it's just fine to add more confusion. It is not in my opinion. And that the computer can differentiate different characters is also perfectly clear to me. The interpreter can also tell the difference between a non-breaking space and a regular space. Yet the non breaking space is not valid for a identifying character. This is because readability counts. People write and maintain code, not machines. Confusion should be kept to the miminum if possible. > Of course, SOMEBODY is going to make use of those to improve upon this > sort of code: > > http://thedailywtf.com/Articles/Uppity.aspx If that was written by my coworkers, I'd strangle them. Regards, Henrik From breamoreboy at yahoo.co.uk Mon Jul 23 10:43:33 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 23 Jul 2012 15:43:33 +0100 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23/07/2012 14:59, Henrik Faber wrote: > On 23.07.2012 15:55, Henrik Faber wrote: > >> Dear Lord. >> >> Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) >> [GCC 4.5.2] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> f??b?r = 3 >>>>> f??b?r >> 3 >> >> I didn't know this. How awful. > > Apparently, not all characters are fine with Python. Why can I not have > domino tiles are identifier characters? > >>>> ? = 9 > File "", line 1 > ? = 9 > ^ > SyntaxError: invalid character in identifier > > I think there needs to be a PEP for that. well get writing then as there's nothing to stop you. > > Regads, > Henrik > -- Cheers. Mark Lawrence. From hfaber at invalid.net Mon Jul 23 10:43:55 2012 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 23 Jul 2012 16:43:55 +0200 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23.07.2012 16:43, Mark Lawrence wrote: >> Apparently, not all characters are fine with Python. Why can I not have >> domino tiles are identifier characters? >> >>>>> ? = 9 >> File "", line 1 >> ? = 9 >> ^ >> SyntaxError: invalid character in identifier >> >> I think there needs to be a PEP for that. > > well get writing then as there's nothing to stop you. I might wait until April 1st next year with that ;-) Best regards, Henrik From dieter at handshake.de Mon Jul 23 10:48:24 2012 From: dieter at handshake.de (Dieter Maurer) Date: Mon, 23 Jul 2012 16:48:24 +0200 Subject: A thread import problem References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: <87hasysfd3.fsf@handshake.de> Bruce Sherwood writes: > ... > There's nothing wrong with the current VPython architecture, which > does use good style, but there are two absolute, conflicting > requirements that I have to meet. > > (1) The simple program API I've shown must be preserved, because there > exist a large number of such programs in existence, used by lots of > people. I can't change the API. Among other uses, every semester there > are about 5000 students in introductory college science courses, > especially physics, who do computational modeling with 3D > visualizations based on instructional materials that teach the > existing API. There is also a large number of instructors who depend > on existing VPython demo programs to continue working even if the > college upgrades Python and VPython. This isn't some little project > where I'm able to teach my small group of collaborators how they > should structure programs. You might keep the "programs" (one of which you have shown) but change the way how they are "called" (and change the internal working of "visual"). In my "proposal", your "program" is not changed in any way -- but it is not called directly but activated ("imported") from something like a starting module. From viewfromoffice at gmail.com Mon Jul 23 10:50:03 2012 From: viewfromoffice at gmail.com (Stone Li) Date: Mon, 23 Jul 2012 22:50:03 +0800 Subject: What's wrong with this code? Message-ID: I'm totally confused by this code: Code: > a = None > b = None > c = None > d = None > x = [[a,b], > [c,d]] > e,f = x[1] > print e,f > c = 1 > d = 2 > print e,f > e = 1 > f = 2 > print c,d > > Output: None None > None None > 1 2 > I'm expecting the code as: > None None > 1 2 > 1 2 > > What's wrong? And this question made my GUI program totally out of control. Thanks[?] -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 338.gif Type: image/gif Size: 541 bytes Desc: not available URL: From rosuav at gmail.com Mon Jul 23 10:53:20 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 00:53:20 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 12:40 AM, Henrik Faber wrote: > No, you misunderstood me. I didn't say people are going to write > gibberish. What I'm saying is that as a foreigner (who doesn't know most > of these characters), it can be hard to accurately choose which one is > the correct one. This is especially true if the appropriate keys are not > available on your keyboard. So it makes maintenance of other people's > code much more difficult if they didn't on their own chose to limit > themselves to ASCII. This sounds like a job for a project's style guide. Have the language support full Unicode (or maybe "everything except whitespace" or whatever), and let each project head stipulate the project's own restrictions. ChrisA From jeanpierreda at gmail.com Mon Jul 23 11:02:52 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 23 Jul 2012 11:02:52 -0400 Subject: =?UTF-8?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLDr8K+4oCiLi4uLi4uLsOvwr4=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 10:40 AM, Henrik Faber wrote: > No, you misunderstood me. I didn't say people are going to write > gibberish. What I'm saying is that as a foreigner (who doesn't know most > of these characters), it can be hard to accurately choose which one is > the correct one. This is especially true if the appropriate keys are not > available on your keyboard. So it makes maintenance of other people's > code much more difficult if they didn't on their own chose to limit > themselves to ASCII. I understand, and agree. But that's not always all that likely a situation. If your company only employs native Arabic speakers, why not use Arabic variable names and Arabic script? You'll get more out of making the language easy to understand for the people that work there, than out of hedging your bets on the off chance that some American will stroll in and be confused. (It is my understanding that, in any case, many non-English companies do their coding in English. That doesn't mean it's a general rule that should be forced on everyone.) -- Devin From steve+comp.lang.python at pearwood.info Mon Jul 23 11:20:19 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 15:20:19 GMT Subject: dict: keys() and values() order guaranteed to be same? References: <500D383A.9090500@phihag.de> Message-ID: <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 13:58:37 +0200, Stefan Behnel wrote: > Philipp Hagemeister, 23.07.2012 13:40: >> On 07/23/2012 01:23 PM, Henrik Faber wrote: >>> With an arbitrary dictionaty d, are d.keys() and d.values() guaraneed >>> to be in the same order? >> >> Yes. From the documentation[1]: >> >> If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() >> are called with no intervening modifications to the dictionary, the >> lists will directly correspond. >> >> [1] http://docs.python.org/library/stdtypes.html#dict.items > > Interesting. I wonder if other implementations like Jython and PyPy > really adhere to this official guarantee. If they want to claim to be implementations of Python, as opposed to merely some Python-like language with identical syntax but different behaviour, then they better adhere to it. If they don't honour the language promise, then they are buggy. [...] > Maybe this guarantee is just easy enough to build on the given > implementation details of a platform that it's a common property. Easy or hard, it is a promise of the language. (Although if you think about the implementation of dicts as hash tables, it does seem likely that it is trivial to enforce this -- one would have to work *harder* to break that promise than to keep it.) > Iteration over data structures should tend to be deterministic, after > all. Deterministic is not a very strong promise. The order of iteration of dict.keys() is deterministic but not easily predictable, since it depends on the history of the dictionary. The output of random.random() is deterministic but (pseudo-)random. Python's promise is much stronger than merely "deterministic": while it does not promise what order the keys will be returned, it does promise that whatever that order turns out to be, they will returned in the same order as the matching values (unless you modify the dict while iterating). -- Steven From rosuav at gmail.com Mon Jul 23 11:24:29 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 01:24:29 +1000 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On Tue, Jul 24, 2012 at 12:50 AM, Stone Li wrote: > > I'm totally confused by this code: > > Code: Boiling it down to just the bit that matters: c = None d = None x = [c,d] e,f = x c = 1 d = 2 print e,f When you assign "e,f = x", you're taking the iterable x and unpacking its contents. There's no magical "referenceness" that makes e bind to the same thing as c; all that happens is that the objects in x gain additional references. When you rebind c and d later, that doesn't change x, nor e/f. What you've done is just this: x = [None, None] e,f = x c = 1 d = 2 print e,f It's clear from this version that changing c and d shouldn't have any effect on e and f. In Python, any time you use a named variable in an expression, you can substitute the object that that name is referencing - it's exactly the same. (That's one of the things I love about Python. No silly rules about what you can do with a function return value - if you have a function that returns a list, you can directly subscript or slice it. Yay!) ChrisA From breamoreboy at yahoo.co.uk Mon Jul 23 11:29:33 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 23 Jul 2012 16:29:33 +0100 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 23/07/2012 15:43, Henrik Faber wrote: > On 23.07.2012 16:43, Mark Lawrence wrote: > >>> Apparently, not all characters are fine with Python. Why can I not have >>> domino tiles are identifier characters? >>> >>>>>> ? = 9 >>> File "", line 1 >>> ? = 9 >>> ^ >>> SyntaxError: invalid character in identifier >>> >>> I think there needs to be a PEP for that. >> >> well get writing then as there's nothing to stop you. > > I might wait until April 1st next year with that ;-) > > Best regards, > Henrik > Sorry not with you is there something special about April 1st next year? -- Cheers. Mark Lawrence. From rustompmody at gmail.com Mon Jul 23 11:31:33 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 08:31:33 -0700 (PDT) Subject: Converting a list of strings into a list of integers? References: <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA@giganews.com> Message-ID: <34429e4a-307a-498a-b31e-92fc17f278c8@tz10g2000pbc.googlegroups.com> On Jul 23, 7:27?pm, Grant Edwards wrote: > That said, "map" seems to be frowned upon by the Python community for > reasons I've never really understood,... Maybe the analogy: comprehension : map :: relational calculus : relational algebra In particular map, filter correspond to project and select in algebra. In principle the two are equivalent (Codd's theorem) however in practice, the calculus is found to be more declarative whereas the algebra is more suitable for specifying execution plans. From emile at fenx.com Mon Jul 23 11:36:19 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Jul 2012 08:36:19 -0700 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On 7/23/2012 7:50 AM Stone Li said... > I'm totally confused by this code: > > Code: > > a = None > b = None > c = None > d = None > x = [[a,b], > [c,d]] > e,f = x[1] > print e,f This prints the first None,None > c = 1 > d = 2 > print e,f And nothing has happened to e or f, so this is the second None,None Why do you expect 1,2? Emile > e = 1 > f = 2 > print c,d > > Output: > > None None > None None > 1 2 > > > I'm expecting the code as: > > None None > 1 2 > 1 2 > > > What's wrong? > And this question made my GUI program totally out of control. > Thanks > > From python at mrabarnett.plus.com Mon Jul 23 11:46:49 2012 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 23 Jul 2012 16:46:49 +0100 Subject: the meaning of =?UTF-8?B?cj8uLi4uLi4uw6/Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500D71E9.30504@mrabarnett.plus.com> On 23/07/2012 14:24, Henrik Faber wrote: [snip] > And if I think of PHP's latest fiasco that happened with unicode > characters, it makes me shudder to think you'd want that stuff in > Python. If I remember correctly, it was the Turkish locale that they > stuggled with: Turkey apparently does not have a capital "I", so some > weird PHP magic code broke with the Turkish locale in effect. Having to > keep crap like that in mind is just plain horrible. I'm very happy with > the way Python does it. > When Turkish changed to the Latin alphabet, the letter pair I/i was split into 2 separate letters, each with an uppercase and a lowercase form: I/? (uppercase without dot and lowercase without dot) and ?/i (uppercase with dot and lowercase with dot). From steve+comp.lang.python at pearwood.info Mon Jul 23 11:49:25 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 15:49:25 GMT Subject: the meaning of =?iso-8859-15?b?cu++lS4uLi4uLi7vvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d7285$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 08:55:22 -0400, Roy Smith wrote: > Some day, we're going to have programming languages that take advantage > of the full unicode character set. I don't know about the full Unicode character set, since there are many more than 10000 characters, and few languages require that many distinct tokens. But if you mean a richer character set than mere ASCII, then I agree, provided if by "some day" you mean nearly half a century ago. http://en.wikipedia.org/wiki/APL_%28programming_language%29 Sort an array by the length of the word: X[?X+.?' ';] compared to Python: words.sort(key=len) I think that's a clear example of why APL has never quite taken the world by storm. It makes Perl look like human-readable pseudo-code. It isn't necessary to go to APL's extremes to get the power of a richer character set. Back in the 1990s, Apple's Hypertalk language allowed single character synonyms for certain operators, including: ? for <> ? for <= ? for >= ? for / ? for sqrt See OpenXION for a modern, non-GUI version: http://www.openxion.org/ Unicode includes a very rich set of operator characters. Assuming the character input problem were solved, it would be awesome to be able to define a rich set of operators beyond the few Python already has. For example, we could use proper ? and ? operators for set intersection and union, or use chevrons ?? as delimiters for types without clashing with lists [], tuples(), sets and dicts {}. And wouldn't you rather see something like "string??" instead of "string\n\r"? I know I would. Of course, the character input problem *is* a genuine problem. Between that and the issue of character display (not all fonts are capable of showing all characters) I wouldn't hold my breath for full Unicode syntax any time soon. -- Steven From gordon at panix.com Mon Jul 23 11:56:36 2012 From: gordon at panix.com (John Gordon) Date: Mon, 23 Jul 2012 15:56:36 +0000 (UTC) Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: In Mark Lawrence writes: > Sorry not with you is there something special about April 1st next year? In the United States, April 1st (also known as April Fool's Day) is an occasion for practical jokes, faked 'news' stories, and general silliness. I don't know if it is observed outside the U.S. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From steve+comp.lang.python at pearwood.info Mon Jul 23 11:59:59 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 15:59:59 GMT Subject: the meaning of =?UTF-8?b?cu++lS4uLi4uLi7vv73Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d74ff$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 23:06:45 +1000, Chris Angelico wrote: > On Mon, Jul 23, 2012 at 10:55 PM, Roy Smith wrote: >> Some day, we're going to have programming languages that take advantage >> of the full unicode character set. Right now, we're working in ASCII >> and creating silly digrams/trigrams like r'' for raw strings (and >> triple-quotes for multi-line strings). Not to mention <=, >=, ==, !=. >> And in languages other than python, things like ->, => (arrows for >> structure membership), and so on. > > REXX predates Unicode, I think, or at least its widespread adoption, but > it has a non-ASCII operator: > > http://www.rexswain.com/rexx.html#operators Only one? Pfft. What's the difference between >> "Strictly greater than" and < "Greater than"? > But personally, I've always used backslash. It's nothing to do with > ASCII and everything to do with having it on the keyboard. Before you > get a language that uses full Unicode, you'll need to have fairly > generally available keyboards that have those keys. Or sensible, easy to remember mnemonics for additional characters. Back in 1984, Apple Macs made it trivial to enter useful non-ASCII characters from the keyboard. E.g.: Shift-4 gave $ Option-4 gave ? Option-c gave ? Option-r gave ? Dead-keys made accented characters easy too: Option-u o gave ? Option-u e gave ? etc. And because it was handled by the operating system, *every* application supported it, automatically. -- Steven From rosuav at gmail.com Mon Jul 23 12:09:04 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 02:09:04 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 1:56 AM, John Gordon wrote: > In Mark Lawrence writes: > >> Sorry not with you is there something special about April 1st next year? > > In the United States, April 1st (also known as April Fool's Day) is an > occasion for practical jokes, faked 'news' stories, and general silliness. > > I don't know if it is observed outside the U.S. It is, in many places. It's one of the few truly international holidays. The next nearest, Pi Day, has two different dates (the American and the European - of course, here in Australia, we celebrate both). ChrisA From rosuav at gmail.com Mon Jul 23 12:10:18 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 02:10:18 +1000 Subject: =?UTF-8?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u77+9wr4=?= In-Reply-To: <500d74ff$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <500d74ff$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 1:59 AM, Steven D'Aprano wrote: >> http://www.rexswain.com/rexx.html#operators > > Only one? Pfft. > > What's the difference between >> "Strictly greater than" and < "Greater > than"? The non-strict forms strip trailing spaces off strings before comparing. I can't remember now if there are other differences. ChrisA From rosuav at gmail.com Mon Jul 23 12:15:45 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 02:15:45 +1000 Subject: Encapsulation, inheritance and polymorphism In-Reply-To: References: <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 2:18 AM, Albert van der Horst wrote: > Example from recipee's: > > Stirr until the egg white is stiff. > > Alternative: > Stirr egg white for half an hour, > but if the egg white is stiff keep your spoon still. > > (Cooking is not my field of expertise, so the wording may > not be quite appropriate. ) Method. Take egg white from refrigerator. Put egg white into mixing bowl. Stir for 30 minutes. Stir the egg white. Stir the egg white until stirred. That's valid code, incidentally. Not Python code, but it is executable. And it includes a useless count-down-to-zero loop. ChrisA From albert at spenarnc.xs4all.nl Mon Jul 23 12:18:18 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 23 Jul 2012 16:18:18 GMT Subject: Encapsulation, inheritance and polymorphism References: <5006b48a$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <5006b48a$0$29978$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: Even with a break, why bother continuing through the body of the function >when you already have the result? When your calculation is done, it's >done, just return for goodness sake. You wouldn't write a search that >keeps going after you've found the value that you want, out of some >misplaced sense that you have to look at every value. Why write code with >unnecessary guard values and temporary variables out of a misplaced sense >that functions must only have one exit? Example from recipee's: Stirr until the egg white is stiff. Alternative: Stirr egg white for half an hour, but if the egg white is stiff keep your spoon still. (Cooking is not my field of expertise, so the wording may not be quite appropriate. ) >-- >Steven Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From rosuav at gmail.com Mon Jul 23 12:18:54 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 02:18:54 +1000 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500D383A.9090500@phihag.de> <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 1:20 AM, Steven D'Aprano wrote: > (Although if you think about the implementation of dicts as hash tables, > it does seem likely that it is trivial to enforce this -- one would have > to work *harder* to break that promise than to keep it.) However, it would be quite reasonable to implement a dict as a splay tree, and have values() return them nearest-first. This would mean that just reading from the dictionary could change the order of values(), yet it wouldn't make the implementation non-conformant. Of course, if I want splay tree semantics, I'd rather explicitly ask for that. But it'd be legal. ChrisA From rridge at csclub.uwaterloo.ca Mon Jul 23 12:19:49 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 23 Jul 2012 12:19:49 -0400 Subject: the meaning of rユ.......ï¾ References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: Roy Smith wrote: >When I first started writing C code, it was on ASR-33s which did not >support curly baces. We wrote ??( for { and ??) for } (although I think the translation was >handled entirely in the TTY driver and the compiler was never in on the >joke). 20 or 30 years from now, people are going to look back on us >neanderthals and laugh about how we had to write r''. No, it's not going to change in 20 or 30 years. The ASR-33 Teletype was pretty much obsolete by the time C escaped Bell Labs. You were programming in a 70's language using early 60's technology and suffered accordingly. Today, the technology to support "Unicode" operators in programming langauges is both widespread and has existed for a long time now. I'm sure you've heard of APL, which both predates Unicode and C and is almost old as the ASR-33. If any one actually wanted another programming language like this it would've come into existance 20 or 30 years ago not 20 or 30 years from now. Python actually choose to go the other direction and choose to use keywords as operators instead of symbols in a number of instances. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From steve+comp.lang.python at pearwood.info Mon Jul 23 12:33:45 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 16:33:45 GMT Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d7ce8$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 15:24:21 +0200, Henrik Faber wrote: > I disagree. Firstly, Python could already support the different types of > strings even with the ASCII character set. For example, the choice could > have made to treat the apostophe string 'foo' differently from the > double quote string "foo". Then, the backtick could have been used > `foo`. In Python 2, backticks are a synonym for the repr() function: py> x = object() py> `x` '' That's gone in Python 3. > Bash for example uses all three and all three have very different > meanings. Python is different: explicit is better than implicit, and I'd > rather have the "r" the signifies what weird magic is going on instead > of having some weird language rules. It would not be different with some > UTF-8 "rawstring" magic backticks. I'm not entirely sure why you think that r"..." is more explicit than some other quote marks, say `...`. Apart from the mnemonic "r for raw- string", they're both equally mysterious language rules. (Just try explaining why backslashes in raw-strings are normal characters, *unless* the last character of the string is a backslash.) py> print r"ab\" File "", line 1 print r"ab\" ^ SyntaxError: EOL while scanning single-quoted string 0_o Personally, I like Python's quoting rules, even with quirks like the above. I don't like quoting rules that magically evaluate expressions or interpolate variables. > Secondly, there's a reason that >=, <= and friends are in use. Every > keyboard has a > key and every keyboard has a = key. I don't know any > that would have >=, <= or != as UTF-8. It is useful to use only a > limited set of characters. You don't need a keyboard with a bazillion keys. You just need a keyboard with a couple of extra modifier keys, and some good mnemonics for what characters go with what keys. Plus a mechanism for entering arbitrary code points that otherwise aren't attached to a key. Hey, if the Japanese and Chinese can manage it, English speakers can surely find a way to enter ? or ? without a keyboard the size of a battleship. > And if I think of PHP's latest fiasco that happened with unicode > characters, it makes me shudder to think you'd want that stuff in > Python. Oh please. Just because the PHP "designers" couldn't design a hammer doesn't mean that the idea of hammers is faulty. (Cynical about PHP? Who, me?) > If I remember correctly, it was the Turkish locale that they > stuggled with: Turkey apparently does not have a capital "I", Not exactly. It has two. Unlike most other European languages, Turkish and a few other languages includes both a dotted and dotless I. Other languages mix them up: dotted lowercase i goes with dotless uppercase I, like in English. But in Turkish, you have ? <=> I and i <=> ?. http://en.wikipedia.org/wiki/Dotted_and_dotless_I And if this wasn't so serious, it would be hilarious: http://gizmodo.com/382026/a-cellphones-missing-dot-kills-two-people-puts-three-more-in-jail -- Steven From albert at spenarnc.xs4all.nl Mon Jul 23 12:36:43 2012 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 23 Jul 2012 16:36:43 GMT Subject: Encapsulation, inheritance and polymorphism References: <50076437$0$1756 Message-ID: In article , Erik Max Francis wrote: >Anything's trivial to "write down." Just say "the number such that ..." >and you've written it down. Even "numbers" that aren't really numbers, >such as transfinite cardinals! Now it isn't trivial to write down. It has been proven (of course in an anti-intuitionistic 1] , Cantor-universe) that there is always a larger cardinal, and that there is no consistent way to write them down. In other ways, you have to keep inventing new notations, hardly a trivial matter. See also Hofstaedter: Goedel, Escher, Bach. > >-- >Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ Groetjes Albert 1] The likes of Brouwer found these silly exercises.) -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From steve+comp.lang.python at pearwood.info Mon Jul 23 12:53:49 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 16:53:49 GMT Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d819d$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 15:52:32 +0200, Henrik Faber wrote: > If you allow for UTF-8 identifiers you'll have to be horribly careful > what to include and what to exclude. Is the non-breaking space a valid > character for a identifier? Technically it's a different character than > the normal space, so why shouldn't it be? What an awesome idea! Because it's not a letter. Using Python 3: py> nbs = '\N{NO-BREAK SPACE}' py> import unicodedata py> unicodedata.category(nbs) 'Zs' py> unicodedata.category('a') 'Ll' Not every character is valid in identifiers, not even in ASCII. Why would Unicode be any different? Before Python added unicode identifiers, many issues were discussed and resolved. See the PEP that discusses it: http://www.python.org/dev/peps/pep-3131/ > What about ? vs x? No, because ? is not a letter. > Or ? vs ? vs ? vs ? vs ? vs ? vs ? vs ? vs ... Yes, we get the point. Some letters look similar to other letters. Since these are all different letters, they are treated differently in identifiers, no differently from O vs 0 and I vs l vs 1. Dyslexics will rightly complain that s and z look too similar, and b and d even more so. Perhaps they too should be banned from identifiers? -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 23 12:54:49 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 16:54:49 GMT Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d81d9$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 10:10:22 -0400, Devin Jeanpierre wrote: > Yes, as soon as we add unicode to anything everyone will go insane and > write gibberish. :) -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 23 13:10:47 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Jul 2012 17:10:47 GMT Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500d8597$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 16:29:33 +0100, Mark Lawrence wrote: > On 23/07/2012 15:43, Henrik Faber wrote: [...] >> I might wait until April 1st next year with that ;-) >> >> Best regards, >> Henrik >> >> > Sorry not with you is there something special about April 1st next year? As a Brit (or at least someone with a .uk email address) surely you know about the British tradition of April Fools jokes on 1st of April? http://en.wikipedia.org/wiki/Spaghetti_tree_hoax http://www.python.org/dev/peps/pep-0401/ http://www.python.org/dev/peps/pep-0313/ http://entrian.com/goto/ And perhaps most relevant of all: http://www.python.org/dev/peps/pep-3117/ -- Steven From bruceg113355 at gmail.com Mon Jul 23 13:19:40 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 10:19:40 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email Message-ID: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> All, I am trying to figure out how to send a image in the body of a email when Making a Meeting Request. Below is my current code. Thanks, Bruce # code below is mainly from http://harunprasad.blogspot.com/2012/01/python-make-meeting-request-appointment.html # -------------------------------------------------------------------------------------------------------------- import win32com.client oOutlook = win32com.client.Dispatch("Outlook.Application") appt = oOutlook.CreateItem(1) appt.Start = '2012-07-24 08:00' appt.Subject = '5th Meeting' appt.Duration = 60 appt.Location = 'Conference Room, Main' appt.Body = "This is body text\n" attach1 = "someimage.jpg" appt.Attachments.Add (attach1) #prefer to have attachment inline (body) of email appt.MeetingStatus = 1 appt.Recipients.Add("someone at email.com") #enter valid email here appt.Save() appt.Send() print "Done" From roy at panix.com Mon Jul 23 13:33:34 2012 From: roy at panix.com (Roy Smith) Date: Mon, 23 Jul 2012 10:33:34 -0700 (PDT) Subject: Initial nose experience In-Reply-To: References: Message-ID: <056eb595-984c-4a63-8b54-298ef0e06b86@googlegroups.com> Does nose run all of its collected tests in a single process? I've got a test which monkey-patches an imported module. Will all of the other tests collected in the same run of nosetests see the patch? From ian.g.kelly at gmail.com Mon Jul 23 14:11:05 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 23 Jul 2012 12:11:05 -0600 Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> Message-ID: On Mon, Jul 23, 2012 at 11:19 AM, wrote: > All, > > I am trying to figure out how to send a image in the body of a email when Making a Meeting Request. You need to use html in the body with an tag that references the attachment. See: http://stackoverflow.com/questions/4312687/how-to-embed-images-in-email One of the answers there contains an Outlook-specific example, which is written in C# but should still be translatable to what you are doing. From eric.lemings at gmail.com Mon Jul 23 14:16:22 2012 From: eric.lemings at gmail.com (eric.lemings at gmail.com) Date: Mon, 23 Jul 2012 11:16:22 -0700 (PDT) Subject: Using Python packaging tools to maintain source distributions in other languages? Message-ID: <3e0353ce-cc80-4e2b-9c5a-9878d02cd98a@googlegroups.com> Greetings all, I would like to leverage the Python packaging tools (e.g. distutils, setuptools, distribute, et. al.) to maintain (i.e. download, extract, configure, make, install, package) source distributions other than Python modules (e.g. zlib, openssl). Are there any open-source packages/tools that already do this? Any documentation in print or on the web that outlines a basic plan for doing such? Any and all help greatly appreciated. From janpeterr at freenet.de Mon Jul 23 14:29:23 2012 From: janpeterr at freenet.de (Jan Riechers) Date: Mon, 23 Jul 2012 21:29:23 +0300 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <500D9803.5000708@freenet.de> On 23.07.2012 16:55, Henrik Faber wrote: > On 23.07.2012 15:52, Henrik Faber wrote: > >> but I would hate for >> Python to include them into identifiers. Then again, I'm pretty sure >> this is not planned anytime soon. > > Dear Lord. > > Python 3.2 (r32:88445, Dec 8 2011, 15:26:58) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> f??b?r = 3 >>>> f??b?r > 3 > > I didn't know this. How awful. > > Regards, > Johannes > I can't understand at all why this (even as German) is supported. Programs and developments, and in particular Python, should not only be accessible but also understandable by everyone - meaning that I don't exclude folks by starting to write my code in Esperanto letters. Otherwise the next thing one might working on is a script normalizer which Engli-fies foreign variable names... similar to Py2to3. Outside for display usage it has a right place to make usage of Unicode, like for French with all the accents Danish, Swedish and other languages, but some "old"-standards should stay in place, meaning to use English, so it stays accessible and understandable. Jan From nobody at nowhere.com Mon Jul 23 14:29:27 2012 From: nobody at nowhere.com (Nobody) Date: Mon, 23 Jul 2012 19:29:27 +0100 Subject: How to print stdout before writing stdin using subprocess module in Python? References: <6b50a02c-835a-41cb-83c9-8d051a516e38@googlegroups.com> Message-ID: On Mon, 23 Jul 2012 06:01:23 -0700, Sarbjit singh wrote: > proc = subprocess.Popen("cp -i a.txt b.txt", shell=True, > stdin=subprocess.PIPE, stdout=subprocess.PIPE, > stderr=subprocess.STDOUT,) > stdout_val, stderr_val = proc.communicate() > print stdout_val b.txt? > > proc.communicate("y") > > Now in this example if i read only stdout/stderr and prints it, later on > if i try to write "y" or "n" based on user's input, i got an error that > channel is closed. Can some one please help me on achieving this > behavior in python such that i can print stdout first, then should take > user input and write stdin later on. You can't use .communicate() if you want an interact with the child process. Any text given as an argument is sent to the child, then the child's stdin is closed. Then it reads the child's stdout and/or stderr until the child terminates. If you want to interact with the child, you need to write to proc.stdin and read from proc.stdout and/or proc.stderr. And you need to do this asynchronously, i.e. you either need to use non-blocking I/O or multiple threads, otherwise you risk deadlock. Look at the source code for the .communicate() method in subprocess.py for examples (the Unix version uses non-blocking I/O, the Windows version uses threads). Even that may not be enough, as the child process may behave differently if std{in,out,err} are pipes rather than a tty. Typically, stdin and stdout are line-buffered when associated with a tty but block-buffered otherwise (e.g. when associated with a pipe). If pipes don't work, the only solution may be to run the child process on a pseudo-tty (pty); see the pty module or the os.openpty() function. From bruceg113355 at gmail.com Mon Jul 23 14:33:02 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 11:33:02 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> Message-ID: <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> I tried something similar to the example at http://stackoverflow.com/questions/4312687/how-to-embed-images-in-email . Problem is, this line is not understood: mail.BodyFormat = OlBodyFormat.olFormatHTML Traceback (most recent call last): ... appt.BodyFormat = OlBodyFormat.olFormatHTML NameError: name 'OlBodyFormat' is not defined Bruce From ethan at stoneleaf.us Mon Jul 23 14:38:37 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 23 Jul 2012 11:38:37 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: <500B694B.1010705@stoneleaf.us> References: <5009F0D9.1050900@stoneleaf.us> <500B17D4.8040702@mweb.co.za> <500B694B.1010705@stoneleaf.us> Message-ID: <500D9A2D.3030006@stoneleaf.us> Ethan Furman wrote: > Alex Strickland wrote: >> "Not supported: index files": >> >> I have been using http://sourceforge.net/projects/harbour-project/ for >> years where a guy called Przemyslaw Czerpak has written an absolutely >> bullet proof implementation of NTX and CDX for DBF. Maybe it will >> interest you. > > I'll check it out, thanks! Unfortunately his code is GPL'ed, so I can't use it. :( ~Ethan~ From rridge at csclub.uwaterloo.ca Mon Jul 23 14:43:23 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 23 Jul 2012 14:43:23 -0400 Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d7ce8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >Hey, if the Japanese and Chinese can manage it, English speakers can >surely find a way to enter ?? or ??? without a keyboard the size of a >battleship. Japanese and Chinese programmers don't use (and don't seem to want to) use non-ASCII characters outside of strings and comments even when the language (supposedly) allows it. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From bamrmm at gmail.com Mon Jul 23 15:59:14 2012 From: bamrmm at gmail.com (Brian Murphy) Date: Mon, 23 Jul 2012 15:59:14 -0400 Subject: socket Message-ID: hey guys i have a question i have not programmed in python for about 8 years now. i am trying to set up a simple password protected server. i have tried to research information but am not lucky. can someone point me in the right direction? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Mon Jul 23 16:05:06 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 23 Jul 2012 13:05:06 -0700 Subject: ANN: dbf.py 0.94 In-Reply-To: References: <5009F0D9.1050900@stoneleaf.us> <500A2260.20806@fossworkflowguides.com> <500A61FB.7060600@stoneleaf.us> <500AF1AD.5080106@stoneleaf.us> Message-ID: <500DAE72.9060503@stoneleaf.us> Chris Angelico wrote: > On Sun, Jul 22, 2012 at 4:15 AM, Ethan Furman wrote: >> I'll support 3.3+, but not with the same code base: I want to use all the >> cool features that 3.3 has! :) > > The trouble with double-codebasing is that you have double > maintenance. But sure. So long as your time isn't under great > pressure, it can be quite effective. Once I get dbf.py to 1.0 release, it will enter maintenance/bug-fix-only mode, and I'll start on the 3.3+ version. The 1.0 release will have the final API, support for Clipper tables, hopefully support for auto-incrementing fields, maybe support for .idx files, plus everything there now. .cdx files (and maybe .idx files) will have to wait for the 3.3+ version. There, now I have a roadmap to follow! :) ~Ethan~ From python at bdurham.com Mon Jul 23 16:20:17 2012 From: python at bdurham.com (python at bdurham.com) Date: Mon, 23 Jul 2012 16:20:17 -0400 Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> Message-ID: <1343074817.3804.140661105695801.3C338A4D@webmail.messagingengine.com> > Problem is, this line is not understood: > > mail.BodyFormat = OlBodyFormat.olFormatHTML Try olBodyFormat (lower case 'o') Malcolm From ian.g.kelly at gmail.com Mon Jul 23 16:32:36 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 23 Jul 2012 14:32:36 -0600 Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> Message-ID: On Mon, Jul 23, 2012 at 12:33 PM, wrote: > I tried something similar to the example at http://stackoverflow.com/questions/4312687/how-to-embed-images-in-email . > > Problem is, this line is not understood: > mail.BodyFormat = OlBodyFormat.olFormatHTML > > Traceback (most recent call last): > ... > appt.BodyFormat = OlBodyFormat.olFormatHTML > NameError: name 'OlBodyFormat' is not defined Assuming you've run makepy to generate the static dispatch Python module for the Outlook type library, all generated constants are available via win32com.client.constants Try: appt.BodyFormat = win32com.client.constants.olFormatHTML From rowen at uw.edu Mon Jul 23 17:00:37 2012 From: rowen at uw.edu (Russell E. Owen) Date: Mon, 23 Jul 2012 14:00:37 -0700 Subject: What's wrong with this code? References: Message-ID: In article , Chris Angelico wrote: > On Tue, Jul 24, 2012 at 12:50 AM, Stone Li wrote: > > > > I'm totally confused by this code: > > > > Code: > > Boiling it down to just the bit that matters: > > c = None > d = None > x = [c,d] > e,f = x > c = 1 > d = 2 > print e,f > > When you assign "e,f = x", you're taking the iterable x and unpacking > its contents. There's no magical "referenceness" that makes e bind to > the same thing as c; all that happens is that the objects in x gain > additional references. When you rebind c and d later, that doesn't > change x, nor e/f. > > What you've done is just this: > > x = [None, None] > e,f = x > c = 1 > d = 2 > print e,f > > It's clear from this version that changing c and d shouldn't have any > effect on e and f. In Python, any time you use a named variable in an > expression, you can substitute the object that that name is > referencing - it's exactly the same. (That's one of the things I love > about Python. No silly rules about what you can do with a function > return value - if you have a function that returns a list, you can > directly subscript or slice it. Yay!) Good explanation. Perhaps what the original poster needs is a container of some kind, e.g. a class with the value as an instance variable. Then you can pass around references to the container and read or modify the value(s) stored in it when you need them. Here is a simple example: class Container(object): def __init__(self, value): self.value = value c = Container(5) d = Container(6) x = [c, d] e, f = x c.value = None d.value = "hello" print e.value, f.value None "hello" -- Russell From emile at fenx.com Mon Jul 23 17:02:23 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 23 Jul 2012 14:02:23 -0700 Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> Message-ID: On 7/23/2012 11:33 AM bruceg113355 at gmail.com said... > I tried something similar to the example at http://stackoverflow.com/questions/4312687/how-to-embed-images-in-email . > > Problem is, this line is not understood: > mail.BodyFormat = OlBodyFormat.olFormatHTML If I read the example properly, this is bvisual basic and should result in some form of visual basic error (possibly library related) if anything and not a python traceback. Emile > > Traceback (most recent call last): > ... > appt.BodyFormat = OlBodyFormat.olFormatHTML > NameError: name 'OlBodyFormat' is not defined > > Bruce > From tjreedy at udel.edu Mon Jul 23 17:07:40 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jul 2012 17:07:40 -0400 Subject: the meaning of =?UTF-8?B?cuKAmS4uLi4uLi7igJg=?= In-Reply-To: References: Message-ID: On 7/23/2012 3:59 AM, Chris Angelico wrote: > On Fri, Jul 20, 2012 at 5:56 PM, levi nie wrote: >> the meaning of r?.......?? > > It's a raw string. > > http://docs.python.org/py3k/tutorial/introduction.html#strings Strictly speaking, it is a raw string literal, which should be parsed as raw (string literal) and NOT as (raw string) literal. I know that the docs sometimes leave off 'literal', but that sometimes confuses people that there is such a thing as a raw string instance. -- Terry Jan Reedy From tjreedy at udel.edu Mon Jul 23 17:19:10 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jul 2012 17:19:10 -0400 Subject: can someone teach me this? In-Reply-To: References: <040e860f-f107-4f70-9c20-2635b514469c@googlegroups.com> Message-ID: On 7/23/2012 9:32 AM, E. wrote: > On 2012-07-21, Menghsiu Lee wrote: >> Hi, >> I have tried 1000 times to compile this python file to be an exe file >> by using py2exe and gui2exe But, it does not work out. You should show what happened. >> I am thinking >> if there can be some genius teaching me how to make this happen. The >> link in below is the complete code with all sources. Everything is >> open to everyone since I change this from another expert. >> >> http://dl.dropbox.com/u/63928380/blackjack.rar Not everyone can decode .rar files. You should store there a .py file or if you must, a standard .zip. But before you ask for help, you should try to minimize the code to something that still has the problem. Asking people to look through multiple files may be a bit much. If you find that removing block x lets the file compile, then you have found a source of the problem, if not the solution. -- Terry Jan Reedy From bruceg113355 at gmail.com Mon Jul 23 17:24:02 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 14:24:02 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> Message-ID: <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> These do not work: appt.BodyFormat = olBodyFormat.olFormatHTML ... appt.BodyFormat = olBodyFormat.olFormatHTML NameError: name 'olBodyFormat' is not defined appt.BodyFormat = win32com.client.constants.olFormatHTML ... appt.BodyFormat = win32com.client.constants.olFormatHTML File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__ raise AttributeError(a) AttributeError: olFormatHTML Bruce From bruceg113355 at gmail.com Mon Jul 23 17:24:02 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 14:24:02 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> Message-ID: <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> These do not work: appt.BodyFormat = olBodyFormat.olFormatHTML ... appt.BodyFormat = olBodyFormat.olFormatHTML NameError: name 'olBodyFormat' is not defined appt.BodyFormat = win32com.client.constants.olFormatHTML ... appt.BodyFormat = win32com.client.constants.olFormatHTML File "C:\Python26\lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__ raise AttributeError(a) AttributeError: olFormatHTML Bruce From dihedral88888 at googlemail.com Mon Jul 23 17:42:53 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Mon, 23 Jul 2012 14:42:53 -0700 (PDT) Subject: Basic question about speed/coding style/memory In-Reply-To: References: Message-ID: <4c65a8f9-91a9-4306-b794-0289db0be84d@googlegroups.com> Jan Riechers? 2012?7?21????UTC+8??3?33?27???? > Hello Pythonlist, > > I have one very basic question about speed,memory friendly coding, and > coding style of the following easy "if"-statement in Python 2.7, but Im > sure its also the same in Python 3.x > > Block > #---------------------------------- > if statemente_true: if an evaluated expression result is non-zero, then > doSomething() > else: # execute this block if the expression evaluated as zero > doSomethingElseInstead() > > #---------------------------------- > > versus this block: > #---------------------------------- > if statement_true: > doSomething() > return > > doSomethingElseInstead() > > #---------------------------------- > > > I understand the first pattern that I tell the interpreter to do: > Check if the conditional is true, run "doSomething()" else go inside the > else block and "doSomethingElseInstead()". > > while the 2nd does only checks: > doSomething() if statement_true, if not, just go directly to > "doSomethingElseInstead() > > > Now, very briefly, what is the better way to proceed in terms of > execution speed, readability, coding style? > Letting out the fact that, in order to prevent > "doSomethingElseInstead"-Block to execute, a return has to provided. > > Thank you for reading and hope someone brings light into that. > > Your fellow python programmer > Jan Well, the C-style branching is inherited in python. Expressions and statements are different. From dihedral88888 at googlemail.com Mon Jul 23 17:42:53 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Mon, 23 Jul 2012 14:42:53 -0700 (PDT) Subject: Basic question about speed/coding style/memory In-Reply-To: References: Message-ID: <4c65a8f9-91a9-4306-b794-0289db0be84d@googlegroups.com> Jan Riechers? 2012?7?21????UTC+8??3?33?27???? > Hello Pythonlist, > > I have one very basic question about speed,memory friendly coding, and > coding style of the following easy "if"-statement in Python 2.7, but Im > sure its also the same in Python 3.x > > Block > #---------------------------------- > if statemente_true: if an evaluated expression result is non-zero, then > doSomething() > else: # execute this block if the expression evaluated as zero > doSomethingElseInstead() > > #---------------------------------- > > versus this block: > #---------------------------------- > if statement_true: > doSomething() > return > > doSomethingElseInstead() > > #---------------------------------- > > > I understand the first pattern that I tell the interpreter to do: > Check if the conditional is true, run "doSomething()" else go inside the > else block and "doSomethingElseInstead()". > > while the 2nd does only checks: > doSomething() if statement_true, if not, just go directly to > "doSomethingElseInstead() > > > Now, very briefly, what is the better way to proceed in terms of > execution speed, readability, coding style? > Letting out the fact that, in order to prevent > "doSomethingElseInstead"-Block to execute, a return has to provided. > > Thank you for reading and hope someone brings light into that. > > Your fellow python programmer > Jan Well, the C-style branching is inherited in python. Expressions and statements are different. From tjreedy at udel.edu Mon Jul 23 17:44:27 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jul 2012 17:44:27 -0400 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> Message-ID: <500DC5BB.8030100@udel.edu> On 7/23/2012 8:51 AM, Alexander Serebrenik wrote: > Do you participate in StackOverflow discussions? > > As a part of a joint on-going research effort of the Brunel > University (UK) and Eindhoven University of Technology (The > Netherlands) on the impact of collaboration sites on the developers > community, we would like to understand the demographics of > StackOverflow participants and their activity. Specifically we are > focusing on how genders, minorities and cultural background are > represented in the population of users and participants of > StackOverflow. StackOverflow is open to anyone in the world who can write and read English. Aside from political interference and language problems, the other factors should be mostly irrelevant. > Therefore, we have prepared a small questionnaire: > https://docs.google.com/spreadsheet/viewform?formkey=dEhtUVNQTEJmRTlwMVJSQ1hkeUZTR3c6MQ#gid=0 The scientific value of self-selected respondents is pretty low. > In our previous research we have proposed an h-index for open source > developers > (http://scholar.google.com/scholar?q=%22Developing+an+h-index+for+OSS+developers.%22), This is a deceptive and time-wasting link. It only says ... Abstract The public data available in Open Source Software (OSS) repositories has been used for many practical reasons: detecting community structures; identifying key roles among developers; understanding software quality; predicting the arousal of bugs in large ... which is not even the first sentence of the abstract. I still have no idea what 'h' means. The actual link is http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=6224288&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D6224288 and the cost to read is $31 as part of a large conference proceedings book. (Apparently, members can read the 4 pages for free.) Leaving aside the point that this is not directly related to Python, my opinion is that if the authors will not make past and future papers freely available, not even an abstract, they should not ask for valuable free data from freely donated time. -- Terry Jan Reedy From dihedral88888 at googlemail.com Mon Jul 23 17:48:37 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Mon, 23 Jul 2012 14:48:37 -0700 (PDT) Subject: Basic question about speed/coding style/memory In-Reply-To: References: <500A5B47.1060805@freenet.de> Message-ID: <923126ef-02cc-4749-a99a-0c351e6c21df@googlegroups.com> Chris Angelico? 2012?7?21????UTC+8??5?04?12???? > On Sat, Jul 21, 2012 at 5:33 PM, Jan Riechers <janpeterr at freenet.de> wrote: > > Block > > #---------------------------------- > > if statemente_true: > > doSomething() > > else: > > doSomethingElseInstead() > > > > #---------------------------------- > > This means, to me, that the two options are peers - you do this or you do that. > > > versus this block: > > #---------------------------------- > > if statement_true: > > doSomething() > > return > > > > doSomethingElseInstead() > > > > #---------------------------------- > > This would be for an early abort. Don't bother doing most of this > function's work, just doSomething. Might be an error condition, or > perhaps an optimized path. > > Definitely for error conditions, I would use the second option. The > "fail and bail" notation keeps the entire error handling in one place: > > def func(x,y,z): > if x<0: > y+=5 > return > if y<0: > raise PEBKAC("There's an idiot here somewhere") > # ... do the rest of the work > This is the caller responsible style when passing parameters to functions. Checking types of parameters both in the caller and the callee does slow down a little bit. > Note the similarity between the control structures. Raising an > exception immediately terminates processing, without polluting the > rest of the function with an unnecessary indentation level. Early > aborting through normal function return can do the same thing. > > But this is purely a matter of style. I don't think there's any > significance in terms of processing time or memory usage, and even if > there is, it would be dwarfed by considerations of readability. Make > your code look like what it's doing, and let the execution take care > of itself. > > ChrisA From dihedral88888 at googlemail.com Mon Jul 23 17:48:37 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Mon, 23 Jul 2012 14:48:37 -0700 (PDT) Subject: Basic question about speed/coding style/memory In-Reply-To: References: <500A5B47.1060805@freenet.de> Message-ID: <923126ef-02cc-4749-a99a-0c351e6c21df@googlegroups.com> Chris Angelico? 2012?7?21????UTC+8??5?04?12???? > On Sat, Jul 21, 2012 at 5:33 PM, Jan Riechers <janpeterr at freenet.de> wrote: > > Block > > #---------------------------------- > > if statemente_true: > > doSomething() > > else: > > doSomethingElseInstead() > > > > #---------------------------------- > > This means, to me, that the two options are peers - you do this or you do that. > > > versus this block: > > #---------------------------------- > > if statement_true: > > doSomething() > > return > > > > doSomethingElseInstead() > > > > #---------------------------------- > > This would be for an early abort. Don't bother doing most of this > function's work, just doSomething. Might be an error condition, or > perhaps an optimized path. > > Definitely for error conditions, I would use the second option. The > "fail and bail" notation keeps the entire error handling in one place: > > def func(x,y,z): > if x<0: > y+=5 > return > if y<0: > raise PEBKAC("There's an idiot here somewhere") > # ... do the rest of the work > This is the caller responsible style when passing parameters to functions. Checking types of parameters both in the caller and the callee does slow down a little bit. > Note the similarity between the control structures. Raising an > exception immediately terminates processing, without polluting the > rest of the function with an unnecessary indentation level. Early > aborting through normal function return can do the same thing. > > But this is purely a matter of style. I don't think there's any > significance in terms of processing time or memory usage, and even if > there is, it would be dwarfed by considerations of readability. Make > your code look like what it's doing, and let the execution take care > of itself. > > ChrisA From rosuav at gmail.com Mon Jul 23 17:49:35 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 07:49:35 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHKSLi4uLi4uLpE=?= In-Reply-To: References: Message-ID: On Tue, Jul 24, 2012 at 7:07 AM, Terry Reedy wrote: > On 7/23/2012 3:59 AM, Chris Angelico wrote: >> >> On Fri, Jul 20, 2012 at 5:56 PM, levi nie wrote: >>> >>> the meaning of r?.......?? >> >> >> It's a raw string. >> >> http://docs.python.org/py3k/tutorial/introduction.html#strings > > Strictly speaking, it is a raw string literal, which should be parsed as raw > (string literal) and NOT as (raw string) literal. I know that the docs > sometimes leave off 'literal', but that sometimes confuses people that there > is such a thing as a raw string instance. True, but then, the same elision is also seen in, for instance, 12345 being an "integer" not a "decimal integer literal". There's no difference between 0x3039 and 12345, but if someone asked what the 0x meant, I'd explain it as "hex literal". Though you're right, it does cause some problems. ChrisA From driscoll at cs.wisc.edu Mon Jul 23 18:01:33 2012 From: driscoll at cs.wisc.edu (Evan Driscoll) Date: Mon, 23 Jul 2012 17:01:33 -0500 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: <500DC5BB.8030100@udel.edu> References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500DC5BB.8030100@udel.edu> Message-ID: <500DC9BD.4020603@cs.wisc.edu> On 01/-10/-28163 01:59 PM, Terry Reedy wrote: > This is a deceptive and time-wasting link.... > > Leaving aside the point that this is not directly related to Python, my > opinion is that if the authors will not make past and future papers > freely available, not even an abstract, they should not ask for valuable > free data from freely donated time. Leaving aside questions of relevance to the email list and the quality of results from a self-selected survey, the PDF is linked directly from the Google Scholar link in the original post: "[PDF] from tue.nl". Evan From ethan at stoneleaf.us Mon Jul 23 18:09:02 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 23 Jul 2012 15:09:02 -0700 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: <500DC5BB.8030100@udel.edu> References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500DC5BB.8030100@udel.edu> Message-ID: <500DCB7E.9010709@stoneleaf.us> Terry Reedy wrote: > Leaving aside the point that this is not directly related to Python, my > opinion is that if the authors will not make past and future papers > freely available, not even an abstract, they should not ask for valuable > free data from freely donated time. Thanks, Terry! Save me some valuable time. ~Ethan~ From tjreedy at udel.edu Mon Jul 23 18:14:28 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jul 2012 18:14:28 -0400 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: <500DC9BD.4020603@cs.wisc.edu> References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500DC5BB.8030100@udel.edu> <500DC9BD.4020603@cs.wisc.edu> Message-ID: On 7/23/2012 6:01 PM, Evan Driscoll wrote: > Leaving aside questions of relevance to the email list and the quality > of results from a self-selected survey, the PDF is linked directly from > the Google Scholar link in the original post: "[PDF] from tue.nl". You're right, off to the side where I missed it. http://www.win.tue.nl/~aserebre/MSR2012.pdf for anyone interested. So I withdraw the corresponding parts of my comment. Of course, A.S. could have just posted it instead of or in addition to the indirect link. Now that I look at it, I agree with the intent. -- Terry Jan Reedy From A.Serebrenik at tue.nl Mon Jul 23 18:14:39 2012 From: A.Serebrenik at tue.nl (Alexander Serebrenik) Date: Mon, 23 Jul 2012 15:14:39 -0700 (PDT) Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500DC5BB.8030100@udel.edu> Message-ID: 1) The paper referenced contains 4 pages, so it should be available via IEEXplore. Moreover, you can find a copy on http://www.win.tue.nl/~aserebre/MSR2012.pdf 2) Since the survey is only one of the techniques we intend to use, and it will be augmented by analysing the data publicly available in the SE dump, I believe the selection bias is appropriately addressed. From A.Serebrenik at tue.nl Mon Jul 23 18:14:39 2012 From: A.Serebrenik at tue.nl (Alexander Serebrenik) Date: Mon, 23 Jul 2012 15:14:39 -0700 (PDT) Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500DC5BB.8030100@udel.edu> Message-ID: 1) The paper referenced contains 4 pages, so it should be available via IEEXplore. Moreover, you can find a copy on http://www.win.tue.nl/~aserebre/MSR2012.pdf 2) Since the survey is only one of the techniques we intend to use, and it will be augmented by analysing the data publicly available in the SE dump, I believe the selection bias is appropriately addressed. From gheskett at wdtv.com Mon Jul 23 20:01:27 2012 From: gheskett at wdtv.com (Gene Heskett) Date: Mon, 23 Jul 2012 20:01:27 -0400 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> Message-ID: <201207232001.27673.gheskett@wdtv.com> On Monday 23 July 2012 19:42:29 Alexander Serebrenik did opine: > 1) The paper referenced contains 4 pages, so it should be available via > IEEXplore. Moreover, you can find a copy on > http://www.win.tue.nl/~aserebre/MSR2012.pdf > > 2) Since the survey is only one of the techniques we intend to use, and > it will be augmented by analysing the data publicly available in the SE > dump, I believe the selection bias is appropriately addressed. I think you are missing the point, Alexander. From my limited reading here as I lurk, you seem to taking freely available data and putting it behind the infamous IEEE paywall. If that isn't the case, I apologize. That sort of thing will always tend to chase the folks who could probably make the best use of it, away. I could well be full of it, but that is how this now old man who has been chasing electrons and making them do work useful for me and my employers for the last 62 years, sees and tastes my experiences with IEEE. Its a bad taste in my mouth every time we meet. If you think I'm kidding about the years above, I had fingerprints on the pcb's of the two tv cameras that were on the Trieste when it, Lt. Walsh and Jacques Cousteau went down into the mohole in Feb. 1960. That, and $1.32 will get you a 16 oz cup of coffee to go at my local 7-11. :) Cheers, Gene -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author) My web page: is up! Faster, faster, you fool, you fool! -- Bill Cosby From bruceg113355 at gmail.com Mon Jul 23 20:42:15 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 17:42:15 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> Message-ID: <354a3a37-3ce9-4992-a017-e4f5d8feeb55@googlegroups.com> This assignment works: import win32com.client oOutlook = win32com.client.Dispatch("Outlook.Application") appt = oOutlook.CreateItem(0) appt.BodyFormat = win32com.client.constants.olFormatHTML But this assignment does not work: import win32com.client oOutlook = win32com.client.Dispatch("Outlook.Application" appt = oOutlook.CreateItem(1) #appointment appt.BodyFormat = win32com.client.constants.olFormatHTML AttributeError: ... object has no attribute 'BodyFormat' It simply appears an Appointment Item does not support .BodyFormat Images are delivered as attachments, can not be in the body (inline) of the appointment email. Bruce From bruceg113355 at gmail.com Mon Jul 23 20:42:15 2012 From: bruceg113355 at gmail.com (bruceg113355 at gmail.com) Date: Mon, 23 Jul 2012 17:42:15 -0700 (PDT) Subject: Python and Outlook, sendinf an image in the body of email In-Reply-To: <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> References: <641dab69-9782-4bf3-8a01-34237c4f189a@googlegroups.com> <22e9b14a-d660-4ec9-a67b-0fcdc9ef1463@googlegroups.com> <69adceee-49d0-4348-b439-04b6362ebd0d@googlegroups.com> Message-ID: <354a3a37-3ce9-4992-a017-e4f5d8feeb55@googlegroups.com> This assignment works: import win32com.client oOutlook = win32com.client.Dispatch("Outlook.Application") appt = oOutlook.CreateItem(0) appt.BodyFormat = win32com.client.constants.olFormatHTML But this assignment does not work: import win32com.client oOutlook = win32com.client.Dispatch("Outlook.Application" appt = oOutlook.CreateItem(1) #appointment appt.BodyFormat = win32com.client.constants.olFormatHTML AttributeError: ... object has no attribute 'BodyFormat' It simply appears an Appointment Item does not support .BodyFormat Images are delivered as attachments, can not be in the body (inline) of the appointment email. Bruce From johnroth1 at gmail.com Mon Jul 23 20:50:04 2012 From: johnroth1 at gmail.com (John Roth) Date: Mon, 23 Jul 2012 17:50:04 -0700 (PDT) Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHKSLi4uLi4uLpE=?= In-Reply-To: References: Message-ID: On Monday, July 23, 2012 1:59:42 AM UTC-6, Chris Angelico wrote: > On Fri, Jul 20, 2012 at 5:56 PM, levi nie <levinie001 at gmail.com> wrote: > > the meaning of r?.......?? > > It's a raw string. > > http://docs.python.org/py3k/tutorial/introduction.html#strings > > Chris Angelico Since this seems to have wandered into the question of unicode support for operators and identifiers in Python, I'll add a few general comments. First, adding unicode operators has been discussed several times, and the answer has always been what several people have stated: lack of support from keyboards and fonts. As far as I can tell, the only significant issue that unicode operators would solve is set operators. Currently they overload the arithmetic operators, so it's not possible to have an object with both arithmetic and set behavior supported by operator syntax. I'm not sure how important that is in the real world. Identifiers can have any character that's marked as alphabetic in the unicode data base. The doc gives the exact criteria, but it's driven by checking the actual data base, or rather Python's copy of it. PEP 8 requires sticking to the Ascii character set except for comments, and then only when it's needed for properly spelling someone's name. Of course, anyone can do anything they want, but Python doesn't have a culture of deliberately trying to write illegible code. And yes, Python did have a problem with the Turkish "i". It got fixed without all the sturm and drang that seems to accompany PHP issues. From johnroth1 at gmail.com Mon Jul 23 20:50:04 2012 From: johnroth1 at gmail.com (John Roth) Date: Mon, 23 Jul 2012 17:50:04 -0700 (PDT) Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHKSLi4uLi4uLpE=?= In-Reply-To: References: Message-ID: On Monday, July 23, 2012 1:59:42 AM UTC-6, Chris Angelico wrote: > On Fri, Jul 20, 2012 at 5:56 PM, levi nie <levinie001 at gmail.com> wrote: > > the meaning of r?.......?? > > It's a raw string. > > http://docs.python.org/py3k/tutorial/introduction.html#strings > > Chris Angelico Since this seems to have wandered into the question of unicode support for operators and identifiers in Python, I'll add a few general comments. First, adding unicode operators has been discussed several times, and the answer has always been what several people have stated: lack of support from keyboards and fonts. As far as I can tell, the only significant issue that unicode operators would solve is set operators. Currently they overload the arithmetic operators, so it's not possible to have an object with both arithmetic and set behavior supported by operator syntax. I'm not sure how important that is in the real world. Identifiers can have any character that's marked as alphabetic in the unicode data base. The doc gives the exact criteria, but it's driven by checking the actual data base, or rather Python's copy of it. PEP 8 requires sticking to the Ascii character set except for comments, and then only when it's needed for properly spelling someone's name. Of course, anyone can do anything they want, but Python doesn't have a culture of deliberately trying to write illegible code. And yes, Python did have a problem with the Turkish "i". It got fixed without all the sturm and drang that seems to accompany PHP issues. From amc96 at cam.ac.uk Mon Jul 23 21:19:29 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Tue, 24 Jul 2012 02:19:29 +0100 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On 23/07/2012 15:50, Stone Li wrote: > I'm totally confused by this code: > > Code: > > a = None > b = None > c = None > d = None > x = [[a,b], > [c,d]] > e,f = x[1] > print e,f > c = 1 > d = 2 > print e,f > e = 1 > f = 2 > print c,d > > Output: > > None None > None None > 1 2 > > > > I'm expecting the code as: > > None None > 1 2 > 1 2 > > > > What's wrong? > And this question made my GUI program totally out of control. > Thanks c = 1 and d = 2 are overwriting the variable c (= None) and d (= None) with new variables 1 and 2. As x already captured c and d while they were none, the variables e and f do not change (not would the, even if you subsequently changed x) Python is a statically scoped language, whereas the functionality you are expecting would be an example of dynamically scoped. Care to reveal your programming background? ~Andrew From steve+comp.lang.python at pearwood.info Mon Jul 23 21:30:34 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 01:30:34 GMT Subject: Gender, Representativeness and Reputation in StackOverflow References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> Message-ID: <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 23 Jul 2012 17:44:27 -0400, Terry Reedy wrote: > On 7/23/2012 8:51 AM, Alexander Serebrenik wrote: >> Do you participate in StackOverflow discussions? >> >> As a part of a joint on-going research effort of the Brunel University >> (UK) and Eindhoven University of Technology (The Netherlands) on the >> impact of collaboration sites on the developers community, we would >> like to understand the demographics of StackOverflow participants and >> their activity. Specifically we are focusing on how genders, minorities >> and cultural background are represented in the population of users and >> participants of StackOverflow. > > StackOverflow is open to anyone in the world who can write and read > English. Aside from political interference and language problems, the > other factors should be mostly irrelevant. Should be irrelevant. But how do you know that they are irrelevant unless you check? By intuition? If you don't measure, how do you know? Do you really mean to suggest that your intuition that sexism and racism have no effect on the reputation of StackOverflow participants is so infallible that it's not worth doing a study to find out? >> Therefore, we have prepared a small questionnaire: >> https://docs.google.com/spreadsheet/viewform? formkey=dEhtUVNQTEJmRTlwMVJSQ1hkeUZTR3c6MQ#gid=0 > > The scientific value of self-selected respondents is pretty low. Not necessarily. But you would need to check how the researchers account for the bias to tell. [...] > Leaving aside the point that this is not directly related to Python, my > opinion is that if the authors will not make past and future papers > freely available, not even an abstract, they should not ask for valuable > free data from freely donated time. Well of course it is your time and your judgement to make, but in my opinion even non-free scientific knowledge is better than ignorance. -- Steven From jeanpierreda at gmail.com Mon Jul 23 22:51:07 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 23 Jul 2012 22:51:07 -0400 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 9:30 PM, Steven D'Aprano wrote: >> Leaving aside the point that this is not directly related to Python, my >> opinion is that if the authors will not make past and future papers >> freely available, not even an abstract, they should not ask for valuable >> free data from freely donated time. > > Well of course it is your time and your judgement to make, but in my > opinion even non-free scientific knowledge is better than ignorance. When people boycott a product, it isn't because not having the product is better than having the product. That's clearly untrue: despite the reasons for the boycott, the product has some value. They boycott it because by doing so, they can get something better than or -- they can get . (At least, in theory :) Why settle for a terrible situation, when we could be encouraging people to do better? /me has been paying too much attention to the Elsevier boycott -- Devin From bruce.sherwood at gmail.com Mon Jul 23 23:33:09 2012 From: bruce.sherwood at gmail.com (Bruce Sherwood) Date: Mon, 23 Jul 2012 21:33:09 -0600 Subject: A thread import problem In-Reply-To: References: <87a9yt7bw6.fsf@handshake.de> <2u8m085co3j3n97jorkl04o5hr1orqb7la@invalid.netcom.com> <5gfm08htgbrum782hfv5fqkb4084qra7vq@invalid.netcom.com> Message-ID: I'm happy to report that Robin Dunn, the developer of wxPython, showed me how to solve my VPython architectural problem, using wxPython. I attach a test program based on wxPython that has all of the properties I was looking for (though it needs some minor cleanups, including quitting gracefully, and handling timing better). The attached program userpoll.py imports the wxpython-based module wxpoll.py which does the following: Creates a wxpython environment but does not start the interact loop. Reads the source of the user program. Finds the import of the module and adds imported entities to globals used with exec. Comments out this import statement in the source. Does an exec of the modified source, in the primary thread. Because the exec is not done in a secondary thread, there are no problems associated with other imports such as math that may be in the user program. The exec-ed program has a loop in it, containing a rate statement which clamps to no more than 100 iterations per second (to make the animation run at a reasonable speed) and which calls a one-shot interact function in the import module. In other words, polling is used rather than using an interact loop, thereby avoiding the nearly intractable threading problems. Happily, Robin found a way to make this polling work with Cocoa on the Mac. I can now move forward with implementing this machinery for VPython, to be able to run VPython programs on 64-bit Pythons on the Mac. Hurray! You will find massive violations of "good practice" in the attached module, because in order to pull this off I have to do lots of calculations at the top level of the module. However, I believe the structure is in fact entirely reasonable and a good solution to a very tricky problem. Thanks to those of you who have made suggestions in this forum that fed into finding a solution. I'll put in a big plug for wxPython (wxpython.org), which is a great way to do cross-platform GUI development with Python. Bruce Sherwood -------------- next part -------------- A non-text attachment was scrubbed... Name: userpoll.py Type: application/octet-stream Size: 208 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: wxpoll.py Type: application/octet-stream Size: 8171 bytes Desc: not available URL: From rustompmody at gmail.com Mon Jul 23 23:56:25 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 20:56:25 -0700 (PDT) Subject: Freedom and Data (was Gender, Representativeness and Reputation in StackOverflow) References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 24, 7:51?am, Devin Jeanpierre wrote: > On Mon, Jul 23, 2012 at 9:30 PM, Steven D'Aprano > > wrote: > >> Leaving aside the point that this is not directly related to Python, my > >> opinion is that if the authors will not make past and future papers > >> freely available, not even an abstract, they should not ask for valuable > >> free data from freely donated time. > > > Well of course it is your time and your judgement to make, but in my > > opinion even non-free scientific knowledge is better than ignorance. > > When people boycott a product, it isn't because not having the product > is better than having the product. That's clearly untrue: despite the > reasons for the boycott, the product has some value. They boycott it > because by doing so, they can get something better than badness> or -- they can get . (At > least, in theory :) The world in which we live (and this list's subject in particular) would not exist without the idealism of people like rms, linus and specifically GvR. And yet too much misguided idealism defeats its own cause. Specifically I believe that rms has lost relevance because he's overspent his unquestionable technical prowess too much on political agendas. In the age of 'cloud computing,' Tim O'Reilly's stance on data is particularly relevant in this (kind of) discussions: "The market, in short, is no longer for software, open source or proprietary. Tomorrow's market is all about data." from http://news.cnet.com/8301-13505_3-10264471-16.html And I have a simple test that I use in my talks to see if my audience of computer industry professionals is thinking with the old paradigm or the new. "How many of you use Linux?" I ask. Depending on the venue, 20-80% of the audience might raise its hands. "How many of you use Google?" Every hand in the room goes up. And the light begins to dawn. Every one of them uses Google's massive complex of 100,000 Linux servers, but they were blinded to the answer by a mindset in which "the software you use" is defined as the software running on the computer in front of you. Most of the "killer apps" of the Internet, applications used by hundreds of millions of people, run on Linux or FreeBSD. But the operating system, as formerly defined, is to these applications only a component of a larger system. Their true platform is the Internet. from http://www.oreillynet.com/pub/a/oreilly/tim/articles/paradigmshift_0504.html > Why settle for a terrible situation, when we could be encouraging > people to do better? Because there could be non-trivial costs to doing that 'encouragement?' > > /me has been paying too much attention to the Elsevier boycott > > -- Devin From rosuav at gmail.com Tue Jul 24 00:19:34 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 14:19:34 +1000 Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 12:51 PM, Devin Jeanpierre wrote: > When people boycott a product, it isn't because not having the product > is better than having the product. That's clearly untrue: despite the > reasons for the boycott, the product has some value. That's because you don't call it boycotting when the product has no value. I'm not in the habit of purchasing used cigarette ash, and I suspect you're not buying any either, but that's not a boycott. ChrisA From rosuav at gmail.com Tue Jul 24 00:28:53 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 14:28:53 +1000 Subject: Freedom and Data (was Gender, Representativeness and Reputation in StackOverflow) In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 1:56 PM, rusi wrote: > "How many of you use Linux?" I ask. The awkwardness is in the definition of the question. Many of the products that I buy will have, at some point, been carried by a truck, but I would answer "No" if someone asked me if I use a truck. Would you say that you "use", say, Windows 2000? Do you even *know* if any of the web sites you use are built on it? What about Cisco Router, Model ? I personally have no idea what networking hardware my ISPs use, nor should I care. When I do a Google search, I don't "use" their Linux; I use only the TCP/IP socket connection. If they were to rip out Linux tomorrow and put in a perfect replacement that they wrote in-house, I wouldn't know and, to be honest, wouldn't care. In the same way, they don't care if I write my own web server; they'll crawl the documents just the same. Doesn't mean they "use" my custom web server, and certainly doesn't mean that everyone who does a search that's affected by my content has "used" that server. > Their true platform is the Internet. Indeed it is. Operating system means nothing; IP transmissions mean everything. Your platform is a TCP socket (or, less commonly, a stream of UDP or other packets). ChrisA From rustompmody at gmail.com Tue Jul 24 01:13:30 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 22:13:30 -0700 (PDT) Subject: My first ever Python program, comments welcome References: <37a37376-18ff-46af-97f0-36fd764a8c26@m2g2000pbv.googlegroups.com> Message-ID: <273a9070-c0b0-4b64-9741-9327f37c07fe@d6g2000pbt.googlegroups.com> On Jul 22, 10:23?pm, Lipska the Kat wrote: > Heh heh, Nothing to do with Eclipse, just another thing to get my head > around. For work and Java IMHO you can't beat eclipse... > at the moment I'm getting my head around git, Bumped into this yesterday. Seems like a good aid to git-comprehension https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh > reminding myself of C, learning Python > and re-learning make. Enough already; but if there's a python plugin I > guess I'll get around to it eventually Seems like a strange combo. It should be (C&make)|(python&X)|(Java&Ant) where X could range from Setup http://docs.python.org/distutils/setupscript.html to distribute http://guide.python-distribute.org/ to scons http://www.scons.org/ Why burden yourself by making the '|'s into '&'s? From rustompmody at gmail.com Tue Jul 24 01:26:29 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 22:26:29 -0700 (PDT) Subject: Freedom and Data (was Gender, Representativeness and Reputation in StackOverflow) References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <504eb11d-42d7-4582-9a3d-de1cd51e5768@d6g2000pbt.googlegroups.com> On Jul 24, 9:28?am, Chris Angelico wrote: > On Tue, Jul 24, 2012 at 1:56 PM, rusi wrote: > > "How many of you use Linux?" I ask. > > The awkwardness is in the definition of the question. Many of the > products that I buy will have, at some point, been carried by a truck, > but I would answer "No" if someone asked me if I use a truck. Would > you say that you "use", say, Windows 2000? Do you even *know* if any > of the web sites you use are built on it? What about Cisco Router, > Model ? I personally have no idea what > networking hardware my ISPs use, nor should I care. > > When I do a Google search, I don't "use" their Linux; I use only the > TCP/IP socket connection. If they were to rip out Linux tomorrow and > put in a perfect replacement that they wrote in-house, I wouldn't know > and, to be honest, wouldn't care. In the same way, they don't care if > I write my own web server; they'll crawl the documents just the same. > Doesn't mean they "use" my custom web server, and certainly doesn't > mean that everyone who does a search that's affected by my content has > "used" that server. > > > Their true platform is the Internet. > > Indeed it is. Operating system means nothing; IP transmissions mean > everything. Your platform is a TCP socket (or, less commonly, a stream > of UDP or other packets). > > ChrisA You make it sound very clear cut. I see more mess (maybe I am messy?) People use cars. That simple car-use implies the use of petrol and the atmosphere. Multiply that by the billions that use cars and we have a global- warming problem. Likewise google. Google uses the freely developed - linux - the gnu ecosystem - html/http-web - TCP/IP stack Would google be where it is without these? Sure google is also giving back. How much is genuine and how much is PR? No intention to ask rhetorical questions. Each one of us at each point needs to ask: Shall I stick my neck out or just get on with my business? From steve+comp.lang.python at pearwood.info Tue Jul 24 01:34:34 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 05:34:34 GMT Subject: Gender, Representativeness and Reputation in StackOverflow References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <500e33ea$0$1779$c3e8da3$76491128@news.astraweb.com> On Mon, 23 Jul 2012 22:51:07 -0400, Devin Jeanpierre wrote: > On Mon, Jul 23, 2012 at 9:30 PM, Steven D'Aprano > wrote: >>> Leaving aside the point that this is not directly related to Python, >>> my opinion is that if the authors will not make past and future papers >>> freely available, not even an abstract, they should not ask for >>> valuable free data from freely donated time. >> >> Well of course it is your time and your judgement to make, but in my >> opinion even non-free scientific knowledge is better than ignorance. > > When people boycott a product, it isn't because not having the product > is better than having the product. That's clearly untrue: despite the > reasons for the boycott, the product has some value. They boycott it > because by doing so, they can get something better than badness> or -- they can get . (At > least, in theory :) I don't think that's why people boycott products. I think that boycotts are a clear example of people making a moral decision to punish somebody for doing wrong, even at the cost to themselves. Sometimes significant costs, as in missing out altogether. We don't say, except in jest, "I needed to get gas for my car, but Acme Fuels were 2 cents more expensive than CQ Petroleum, so I boycotted Acme and bought from CQ." No, a boycott is more like "I think Acme Fuels are unethical and immoral, and so I am boycotting them until they change their behaviour, even though they are cheaper than CQ Petroleum." Or, "Nectarine Computers are doing bad things in China, so I will never by an Nectarine ePod or eCommunicator even though I think the other brands aren't worth having." In short, boycotts aren't merely an attempt to get a better deal. There is a strong element of moral outrage and punishment of a transgressor to boycotts. "You have broken a social contract, so we will ostracize you in whatever way we can, even if that means losing the benefits you can provide." > Why settle for a terrible situation, when we could be encouraging people > to do better? I am sympathetic to the view that closed science is not real science, and that it is "cheating" in some sense. But I think it is a grey area where the practitioners should be cut some slack, rather than a clear case of unethical behaviour. After all, even patents eventually expire, and even closed journals don't prevent knowledge from leaking out into the wider scientific community and hence into the general community. -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 24 01:38:16 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 05:38:16 GMT Subject: python package confusion References: Message-ID: <500e34c8$0$1779$c3e8da3$76491128@news.astraweb.com> On Mon, 23 Jul 2012 06:22:45 -0400, Devin Jeanpierre wrote: > Also adding . to the import search path is probably a bad diea. I don't know about a bad idea or not, but it is certainly redundant, because Python automatically adds '' (equivalent to '.') to the very start of the search path. -- Steven From rustompmody at gmail.com Tue Jul 24 01:56:42 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 22:56:42 -0700 (PDT) Subject: Gender, Representativeness and Reputation in StackOverflow References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> <500e33ea$0$1779$c3e8da3$76491128@news.astraweb.com> Message-ID: > On Mon, 23 Jul 2012 22:51:07 -0400, Devin Jeanpierre wrote: > > When people boycott a product, it isn't because not having the product > > is better than having the product. That's clearly untrue: despite the > > reasons for the boycott, the product has some value. They boycott it > > because by doing so, they can get something better than > badness> or -- they can get . (At > > least, in theory :) > On Jul 24, 10:34 am, Steven D'Aprano wrote: > I don't think that's why people boycott products. I think that boycotts > are a clear example of people making a moral decision to punish somebody > for doing wrong, even at the cost to themselves. Sometimes significant > costs, as in missing out altogether. > I dont see so much difference -- maybe you missed the 'badness' in Devin's quote? People who lose family, get jailed, blown-up etc for causes they believe in, have the equation (at least in their value-system) that the 'badness' is enough that these eventualities are acceptable. From rustompmody at gmail.com Tue Jul 24 01:59:10 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 23 Jul 2012 22:59:10 -0700 (PDT) Subject: Using Python packaging tools to maintain source distributions in other languages? References: <3e0353ce-cc80-4e2b-9c5a-9878d02cd98a@googlegroups.com> Message-ID: On Jul 23, 11:16?pm, eric.lemi... at gmail.com wrote: > Greetings all, > > I would like to leverage the Python packaging tools (e.g. distutils, setuptools, distribute, et. al.) to maintain (i.e. download, extract, configure, make, install, package) source distributions other than Python modules (e.g. zlib, openssl). > > Are there any open-source packages/tools that already do this? ?Any documentation in print or on the web that outlines a basic plan for doing such? > > Any and all help greatly appreciated. Ive heard good things about scons http://en.wikipedia.org/wiki/SCons From breamoreboy at yahoo.co.uk Tue Jul 24 02:23:37 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 24 Jul 2012 07:23:37 +0100 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On 24/07/2012 02:19, Andrew Cooper wrote: > On 23/07/2012 15:50, Stone Li wrote: >> I'm totally confused by this code: >> >> Code: >> >> a = None >> b = None >> c = None >> d = None >> x = [[a,b], >> [c,d]] >> e,f = x[1] >> print e,f >> c = 1 >> d = 2 >> print e,f >> e = 1 >> f = 2 >> print c,d >> >> Output: >> >> None None >> None None >> 1 2 >> >> >> >> I'm expecting the code as: >> >> None None >> 1 2 >> 1 2 >> >> >> >> What's wrong? >> And this question made my GUI program totally out of control. >> Thanks > > c = 1 and d = 2 are overwriting the variable c (= None) and d (= None) > with new variables 1 and 2. As x already captured c and d while they > were none, the variables e and f do not change (not would the, even if > you subsequently changed x) > > Python is a statically scoped language, whereas the functionality you > are expecting would be an example of dynamically scoped. > > Care to reveal your programming background? > > ~Andrew > strictly speaking Python doesn't have variables, it has names. This will possibly start a flame war which, by the standards of this ng/ml, will be an intense conflagration, hence the duck and cover. -- Cheers. Mark Lawrence. From orgnut at yahoo.com Tue Jul 24 03:01:11 2012 From: orgnut at yahoo.com (Larry Hudson) Date: Tue, 24 Jul 2012 00:01:11 -0700 Subject: the meaning of =?UTF-8?B?cu++lS4uLi4uLi7vv73Cvg==?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On 07/23/2012 06:22 AM, Dave Angel wrote: > On 07/23/2012 09:06 AM, Chris Angelico wrote: >> On Mon, Jul 23, 2012 at 10:55 PM, Roy Smith wrote: >>> Some day, we're going to have programming languages that take advantage >>> of the full unicode character set. Right now, we're working in ASCII >>> and creating silly digrams/trigrams like r'' for raw strings (and triple-quotes for multi-line >>> strings). Not to mention <=, >=, ==, !=. And in languages other than >>> python, things like ->, => (arrows for structure membership), and so on. >> REXX predates Unicode, I think, or at least its widespread adoption, >> but it has a non-ASCII operator: >> >> http://www.rexswain.com/rexx.html#operators >> >> But personally, I've always used backslash. It's nothing to do with >> ASCII and everything to do with having it on the keyboard. Before you >> get a language that uses full Unicode, you'll need to have fairly >> generally available keyboards that have those keys. >> >> ChrisA > > > Keyboards with 110,000 keys on them; wonderful. And much larger > characters on the screen, so that all those can be distinguished. And > of course all fonts have to support all those characters. > > Back to 20 character lines. > Somewhat different than this discussion, and I'm not familiar with it myself, but I've read about the "Space Cadet Keyboard". It's described (among other places) at: http://catb.org/jargon/html/S/space-cadet-keyboard.html -=- Larry -=- OT: This "Jargon File" can be an entertaining read. I found "The Story of Mel" particularly fascinating. From A.Serebrenik at tue.nl Tue Jul 24 03:26:22 2012 From: A.Serebrenik at tue.nl (Alexander Serebrenik) Date: Tue, 24 Jul 2012 00:26:22 -0700 (PDT) Subject: Gender, Representativeness and Reputation in StackOverflow In-Reply-To: References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> <500e33ea$0$1779$c3e8da3$76491128@news.astraweb.com> Message-ID: <66aec784-0132-48d8-85a4-1ad85e18f663@googlegroups.com> As a scientist I would be more than happy to publish in Open-Access Journals rather than in IEEE/ACM/Springer-published ones. However, I also have to be sure that my publications reach the scientific community and make an impact on it. Unfortunately, in many fields AFAIK the better journals (= higher impact, etc) are access-restricted, while the open-access ones are overloaded by low-quality submissions and are no much better than a trash bin. From jeanpierreda at gmail.com Tue Jul 24 03:38:48 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 24 Jul 2012 03:38:48 -0400 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On Tue, Jul 24, 2012 at 2:23 AM, Mark Lawrence wrote: > strictly speaking Python doesn't have variables, it has names. This will > possibly start a flame war which, by the standards of this ng/ml, will be an > intense conflagration, hence the duck and cover. The two terms are nearly synonymous when one talks about Python (and both are used in the language reference). I mean, what's so "strict" about the way you're speaking? -- Devin From ulrich.eckhardt at dominolaser.com Tue Jul 24 03:47:38 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 24 Jul 2012 09:47:38 +0200 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: There is one model that has helped me much understanding how Python ticks and that is the model of name tags. The code "a = 1" creates an integer with value 1 and attaches a tag with "a" written on it using a small piece of rope. Now, if you attach the tag to a different item, it obviously doesn't change the original integer. Also, you can attach more than one tag to the integer or even none. Further, a tag doesn't even have to be attached to anything (this happens if you use a local variable before assigning to it). This operation of tagging something is done with the "=" operator. Now, coming back to your code... Am 23.07.2012 16:50, schrieb Stone Li: > I'm totally confused by this code: > > Code: > >> a = None >> b = None >> c = None >> d = None This adds the tags "a", "b", "c" and "d" to None. >> x = [[a,b], >> [c,d]] "[a, b]" creates a list, containing two anonymous tags (they don't have anything written on them but they are accessible via index) attached to what "a" and "b" are currently attached to [0]. The same happens for "[c, d]". The two lists are then put into another list with a similar mechanism, and that list of lists is then tagged "x". >> e,f = x[1] This takes the second element of "x" (the [c, d] above) and tags it with "e" and "f". This syntax implicitly unpacks the list so the assignment operator adds the two tags "e" and "f" to the first and second element referenced by that list. Both "e" and "f" finally end up attached to "None". >> c = 1 >> d = 2 These two remove the rope attaching "c" and "d" to "None" and instead attach them to the integers "1" and "2". I hope your Python's behaviour makes sense to you now! Uli [0] Note that in almost all cases, when referring to a tag, Python implicitly operates on the object attached to it. One case (the only one?) where it doesn't is the "del" statement. From jeanpierreda at gmail.com Tue Jul 24 03:49:31 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 24 Jul 2012 03:49:31 -0400 Subject: python package confusion In-Reply-To: <500e34c8$0$1779$c3e8da3$76491128@news.astraweb.com> References: <500e34c8$0$1779$c3e8da3$76491128@news.astraweb.com> Message-ID: On Tue, Jul 24, 2012 at 1:38 AM, Steven D'Aprano wrote: > I don't know about a bad idea or not, but it is certainly redundant, > because Python automatically adds '' (equivalent to '.') to the very > start of the search path. No, it only does that if Python is reading commands from stdin, or if Python was run with the -c option, or maybe some other situations. It doesn't do it if you just run a program, as in "python myfile.py". -- Devin From paul.nest.ce.pas at gmail.com Tue Jul 24 03:50:22 2012 From: paul.nest.ce.pas at gmail.com (paul618) Date: Tue, 24 Jul 2012 00:50:22 -0700 (PDT) Subject: groveling over a file for Q:: and A:: stmts Message-ID: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> #!/usr/bin/env python # grep_for_QA.py I am only looking to isolate uniq Q:: and A:: stmts from my daily files # # note: This algorithm will fail if there are any blank lines within the Q and A area of interest (a paragraph) # D. Beazley is my fav documentation import re, glob import pprint as pp sampledata = ''' A:: And Straight Street is playin on the Radio Free Tibet. What are the chances, DTMB? Q:: About 1 in 518400, Professor. A:: Correct! Err, I thought it was 1:410400, but close enough for jazz! ''' pattern0 = re.compile("Q::") pattern1 = re.compile("A::") # objects of interest can start with A:: ;; not alway Q:: END_OF_PARAGRAPH_pat = "\n\s*\n" path = "/Users/paultaney/dailies2012/0722" # an example of real data set. toggle = False L = [] M = [] #file = open(path, "r") try: #for line in file.readlines(): for line in sampledata: try: # Later, I also need to treat Unicode -- and I am clueless. # falsestarts:: #line.encode("utf8").decode('xxx', 'ignore') #line.encode("utf8", 'ignore') #line.decode('8859') #line.decode('8859') # 8859, Latin-1 doesn't cover my CJK pastings AT ALL #line.decode('GB18030') # 171006 -- ack #encoded_line = line # xxx line.encode("utf8") mo0 = re.search(pattern0, line) mo1 = re.search(pattern1, line) mo2 = re.search(END_OF_PARAGRAPH_pat, line) if mo0: if 1: print ("I see pattern 0") toggle = True if 1: print(line) M.append(mo0.group()) if mo1: if 1: print ("I see pattern 1") toggle = True M.append(mo1.group()) if mo2 and toggle: if 1: print ("I see pattern 2 AND toggle is set") # got one. save it for uniqifying, and empty the container toggle = False L.append(M) M = [] except Exception as e: print("--- " + e + " ---") except UnicodeDecodeError: #encoded_line = encoded_line.urlsafe_b64encode(re.replace("asdf", encoded_line)) #line = re.sub(".+", "--- asdf ---", line) pass L.sort print (L) # and what"s wrong with some of this, here! #myHash = set(L) # uniqify #pp.pprint(myHash) # july 23, 131001 hike! From steve at holdenweb.com Tue Jul 24 03:54:05 2012 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Jul 2012 00:54:05 -0700 Subject: DjangoCon US 2012 Message-ID: <3B56F1ED-A848-4FDA-8870-A22C875933A3@theopenbastion.com> Pythonistas: We are happy to remind all Django users that DjangoCon US is in DC this year, from September 3-8 (main conference September 4-6). Early bird pricing is available until August 3, and the schedule will be published shortly after this announcement is made. http://djangocon.us/ Since this is DjangoCon's first ever visit to the East coast we are hoping for good attendance from up and down the East coast, but some delegates will come from as far away as Australia, so Americans have no excuse! regards Steve -- The Open Bastion is the Holden Web http://TheOpenBastion.com/ subsidiary responsible for http://holdenweb.com/ technical events such as DjangoCon http://djangocon.us/ From samdansobe at yahoo.com Tue Jul 24 04:06:16 2012 From: samdansobe at yahoo.com (Sammy Danso) Date: Tue, 24 Jul 2012 01:06:16 -0700 (PDT) Subject: How to deal with python 32bit memory error Message-ID: <1343117176.63442.YahooMailClassic@web161206.mail.bf1.yahoo.com> Hello Experts, I am having a 'memory error', which suggest that I have run out of memory, but I am not sure this is the case as I have considerable amount of memory unused on my computer. A little search suggest this is a limitation of python 32 and an option is to have a 64bit. I however have other plug-ins, which are tied to the 32bit so this is not the best option in my case. I was wondering whether there is an elegant way to dealing with this without installing a 6bit version of python. Thanks very much in advance. Sammy -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Tue Jul 24 04:21:08 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 08:21:08 GMT Subject: groveling over a file for Q:: and A:: stmts References: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> Message-ID: <500e5af4$0$1779$c3e8da3$76491128@news.astraweb.com> On Tue, 24 Jul 2012 00:50:22 -0700, paul618 wrote: > #!/usr/bin/env python > # grep_for_QA.py I am only looking to isolate uniq Q:: and A:: stmts > from my daily files # > # note: This algorithm will fail if there are any blank lines within > the Q and A area of interest (a paragraph) > > # D. Beazley is my fav documentation If you are going to ask a question, please ask a question. Don't just dump a whole pile of code in our laps and expect us to work out what your question is. It may help if you read this page: http://sscce.org/ Some further comments below: > import re, glob > import pprint as pp > > sampledata = ''' > A:: And Straight Street is playin on the Radio Free Tibet. What are the > chances, DTMB? Q:: About 1 in 518400, Professor. > A:: Correct! Err, I thought it was 1:410400, but close enough for > jazz! > > > ''' > > pattern0 = re.compile("Q::") There is no point in using a regular expression for something as trivial as that. That is like swinging a 20 kg sledge-hammer to crack a peanut. Just use a string method: if my_string.startswith("Q::"): ... [...] > # Later, I also need to treat Unicode -- and I am clueless. If you have a question about Unicode, you should ask it. If you have not already read this page, you should read it now: http://www.joelonsoftware.com/printerFriendly/articles/Unicode.html > except Exception as e: > print("--- " + e + " ---") Please don't throw away useful debugging information. You should learn to read exception tracebacks, not hide them. They contain a lot of very useful information to help you debug your code. > except UnicodeDecodeError: > #encoded_line = encoded_line.urlsafe_b64encode(re.replace("asdf", > encoded_line)) #line = re.sub(".+", "--- asdf ---", line) pass This will never be caught because any UnicodeDecodeError will already be caught by the "except Exception" line above. > L.sort > print (L) > > # and what"s wrong with some of this, here! #myHash = set(L) # > uniqify > #pp.pprint(myHash) # july 23, 131001 hike! I don't know what's wrong with it. What do you expect it to do, and what does it actually do instead? -- Steven From rosuav at gmail.com Tue Jul 24 04:24:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 24 Jul 2012 18:24:57 +1000 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On Tue, Jul 24, 2012 at 5:47 PM, Ulrich Eckhardt wrote: > There is one model that has helped me much understanding how Python ticks > and that is the model of name tags. The code "a = 1" creates an integer with > value 1 and attaches a tag with "a" written on it using a small piece of > rope. A double strand of rope, I think. If it were one strand, we'd write "a - 1". :) > [0] Note that in almost all cases, when referring to a tag, Python > implicitly operates on the object attached to it. One case (the only one?) > where it doesn't is the "del" statement. I'd say that del is more closely related to assignment than anything else. You can go "a = None" to mark that a now points to nothing, or you can "del a" to de-rope a altogether. ChrisA From ian.g.kelly at gmail.com Tue Jul 24 04:26:28 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 02:26:28 -0600 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: On Mon, Jul 23, 2012 at 7:19 PM, Andrew Cooper wrote: > Python is a statically scoped language, whereas the functionality you > are expecting would be an example of dynamically scoped. While it's true that Python is statically scoped, that has nothing at all to do with the code from the OP's question, which contains only one (global) scope anyway. The real issue is confusion between name binding and object mutation. By reassigning c and d, the OP is evidently trying to mutate the list named x (or to be more precise, the list that is the second element of the list named x). But this doesn't work, because name-binding doesn't mutate objects as it does in languages with variable semantics (C, for example); it merely rebinds the names to different objects. c and d end up bound to values that weren't in the list to begin with, meanwhile the list remains unchanged and e and f are still just bound to None. From steve+comp.lang.python at pearwood.info Tue Jul 24 04:26:53 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 08:26:53 GMT Subject: What's wrong with this code? References: Message-ID: <500e5c4c$0$1779$c3e8da3$76491128@news.astraweb.com> On Tue, 24 Jul 2012 09:47:38 +0200, Ulrich Eckhardt wrote: > [0] Note that in almost all cases, when referring to a tag, Python > implicitly operates on the object attached to it. One case (the only > one?) where it doesn't is the "del" statement. Name-binding: x = 1 operates on the name "x", not the object. The object 1 does not know it has been bound to anything -- that's one weakness of the "tag" model, because it implies that objects know what tags they have attached. They don't. Imports: import x also operates on the name x and not the object. -- Steven From steve+comp.lang.python at pearwood.info Tue Jul 24 04:33:02 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Jul 2012 08:33:02 GMT Subject: Gender, Representativeness and Reputation in StackOverflow References: <30cde2cd-ee38-4b54-87cc-5c0a79e9f1c6@googlegroups.com> <500dfaba$0$29978$c3e8da3$5496439d@news.astraweb.com> <500e33ea$0$1779$c3e8da3$76491128@news.astraweb.com> Message-ID: <500e5dbe$0$1779$c3e8da3$76491128@news.astraweb.com> On Mon, 23 Jul 2012 22:56:42 -0700, rusi wrote: >> On Mon, 23 Jul 2012 22:51:07 -0400, Devin Jeanpierre wrote: >> > When people boycott a product, it isn't because not having the >> > product is better than having the product. That's clearly untrue: >> > despite the reasons for the boycott, the product has some value. They >> > boycott it because by doing so, they can get something better than >> > or -- they can get > > badness>. (At least, in theory :) >> >> > On Jul 24, 10:34 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> I don't think that's why people boycott products. I think that boycotts >> are a clear example of people making a moral decision to punish >> somebody for doing wrong, even at the cost to themselves. Sometimes >> significant costs, as in missing out altogether. >> >> > I dont see so much difference -- maybe you missed the 'badness' in > Devin's quote? No, I saw it. The difference is that I read Devin as suggesting that people are motivated by a sense of "I want to get Product X, without the badness", which implies that the primary driving force is "get Product X", rather than "avoid badness". In a sense, Devin suggests that boycotts are a form of bargaining: give us a better product by reducing the badness, and we'll buy. (Whether Devin *intended* this implication is another question.) I'm suggesting that the primary motivation is "this company is doing bad, I wish to punish them by withholding my purchases, even to my own detriment". I'm suggesting that, at least to some degree, people are *not* bargaining for better products when they engage in a boycott. They are punishing a cheater, and to some degree they may never quite forgive and forget. I can't speak for others, but 30(?) years later, I still sometimes consciously forgo buying Nestle products because of their unethical promotion of expensive baby formula at the expense of breast-feeding in Africa. As time goes by, this urge becomes weaker, but it never quite goes away. A more relevant example might be the way many people in the FOSS community do not and will not forgive Microsoft for their bad behaviour in the past, even now that they have mostly, and reluctantly, accepted that they have to coexist with Linux. Or this: http://xkcd.com/1057/ Of course, people are complex and their motivations can be a tangled web of contradictory and complimentary urges. But "punish the cheater" is an extremely powerful motivation in human beings. -- Steven From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Tue Jul 24 04:34:27 2012 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Tue, 24 Jul 2012 10:34:27 +0200 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: Am 23.07.2012 16:50 schrieb Stone Li: > I'm totally confused by this code: > > Code: > > a = None > b = None > c = None > d = None > x = [[a,b], > [c,d]] > e,f = x[1] > print e,f > c = 1 > d = 2 > print e,f > e = 1 > f = 2 > print c,d > > Output: > > None None > None None > 1 2 > > > I'm expecting the code as: > > None None > 1 2 > 1 2 > > > What's wrong? Your expectation :-) With c = 1 and d = 2 you do not change the respective objects, but you assign other objects to the same names. The old content is still contained in x[1]. If you would only modify these objects (not possible as ints are immutable), you would notice the changes here and there. Thomas From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Tue Jul 24 04:45:56 2012 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Tue, 24 Jul 2012 10:45:56 +0200 Subject: the meaning of r`.......` In-Reply-To: <500d74ff$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <500d74ff$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 23.07.2012 17:59 schrieb Steven D'Aprano: >> Before you >> get a language that uses full Unicode, you'll need to have fairly >> generally available keyboards that have those keys. Or at least keys or key combinations for the stuff you need, which might differ e. g. with the country you live in. There are countries which have keyboards with ????, others with ????, and so on. > Or sensible, easy to remember mnemonics for additional characters. Back > in 1984, Apple Macs made it trivial to enter useful non-ASCII characters > from the keyboard. E.g.: > > Shift-4 gave $ > Option-4 gave ? > Option-c gave ? > Option-r gave ? So what? If I type Shift-3 here, I get a ? (U+00A7). And the ? (U+00B0) comes with Shift-^, the ? (U+00B5) with AltGr-M and the ? sign with AltGr+E. > Dead-keys made accented characters easy too: > > Option-u o gave ? > Option-u e gave ? And if I had a useful OS here at work, I even could use the compose key to produce many other non-ASCII characters. To be able to create each and every of them is not needed in order to have support for them in a language, just the needed ones. Useful editors use them as well, although you have not all of them on your keyboard. Thomas From paul.nest.ce.pas at gmail.com Tue Jul 24 05:34:08 2012 From: paul.nest.ce.pas at gmail.com (paul618) Date: Tue, 24 Jul 2012 02:34:08 -0700 (PDT) Subject: groveling over a file for Q:: and A:: stmts In-Reply-To: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> References: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> Message-ID: <46de1224-b27c-49ea-aeb1-b27c89294f14@googlegroups.com> Hi Steve: Thank you for your quick response. Ah, indeed I failed to ask my question:: Why doesnt this code print the sampledata? Instead it prints the empty list. The answer is probably quite simple, as I really am an idiot. Thanks again, paul From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Tue Jul 24 05:34:38 2012 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Tue, 24 Jul 2012 11:34:38 +0200 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: Am 24.07.2012 09:47 schrieb Ulrich Eckhardt: > [0] Note that in almost all cases, when referring to a tag, Python > implicitly operates on the object attached to it. One case (the only > one?) where it doesn't is the "del" statement. The del and the =, concerning the left side. But even those don't do that under all circumstances. Think about __setitem__, __setattr__, __set__, __delitem__, __delattr__, __delete__. Thomas From gandalf at shopzeus.com Tue Jul 24 05:55:29 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 24 Jul 2012 11:55:29 +0200 Subject: How to represent dates BC Message-ID: <500E7111.9080803@shopzeus.com> >>> import datetime >>> old_date = datetime.date(1,12,31) >>> str(old_date) '0001-12-31' >>> one_year = datetime.timedelta(days=365) >>> str(one_year) '365 days, 0:00:00' >>> old_date - 10*one_year Traceback (most recent call last): File "", line 1, in OverflowError: date value out of range >>> My main problem is that I have an application that stores dates in a PostgreSQL database. The PostgreSQL date type is capable of storing dates from 4713 BC to 294276 AD. http://www.postgresql.org/docs/9.2/static/datatype-datetime.html The application itself stores historical data of events. Apparently, the Python datetime.date object cannot handle dates before 1 AD. The psycopg2 driver converts date values to date objects. But not in this case: >>> conn = dbpool.borrow("central") >>> conn.getqueryvalue("select '1311-03-14 BC'::date") Traceback (most recent call last): File "", line 1, in .... (some more tracelog here)..... data = cur.fetchone() ValueError: year is out of range >>> What is the good solution? I could - in theory - store the dates in a text field, but then I won't be able to create incides on dates, add/substract with other date values etc. I could try to always use something like: select extract(year from date_field) as year,extract(month from date_field) as month,extract(day from date_field) as day .... but this is really messy! What is the good representation here? Should I implement my own date type? (I wouldn't want to.) Thanks, Laszlo From d at davea.name Tue Jul 24 05:58:25 2012 From: d at davea.name (Dave Angel) Date: Tue, 24 Jul 2012 05:58:25 -0400 Subject: How to deal with python 32bit memory error In-Reply-To: <1343117176.63442.YahooMailClassic@web161206.mail.bf1.yahoo.com> References: <1343117176.63442.YahooMailClassic@web161206.mail.bf1.yahoo.com> Message-ID: <500E71C1.6030802@davea.name> On 07/24/2012 04:06 AM, Sammy Danso wrote: > Hello Experts, > I am having a 'memory error', Please post the actual error message. > which suggest that I > have run out of memory, but I am not sure this is the case as I have > considerable amount of memory unused on my computer. What OS, version, and bitness. What 32bit Python? How do you know you have unused memory? How much total memory, how much swapspace, and what are you using to tell how much of each is unused? How big is the process when it dies? And how are you determining that? > A little > search suggest this is a limitation of python 32 and an option is to > have a 64bit. I however have other plug-ins, which are tied to the 32bit > so this is not the best option in my case. There are some limitations to 32 bits, that have nothing to do with Python specifically. However, they have different impact, depending on the environment you're running in. First and foremost, address are 32bits, which limits them to 4gb of ram. So out of your 32Gig of swapspace, a best-case maximum regardless of OS is 4Gig. No operating system lets you actually get that high. > I was wondering whether there is an elegant way to dealing with this without installing a 6bit version of python. The most elegant way of solving it is to reduce the amount of memory your program is using. For example, instead of building large lists, perhaps you can use generators. Simplest example (for Python 2.x) is xrange rather than range. For another example, reduce the globals. Create large objects inside a limited function, and discard them when done (by returning from the function). > Thanks very much in advance. > Sammy > When responding, please remember to post your response *AFTER* the part you're quoting. Most of your previous posts here have been top-posted. -- DaveA From ulrich.eckhardt at dominolaser.com Tue Jul 24 06:05:33 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 24 Jul 2012 12:05:33 +0200 Subject: What's wrong with this code? In-Reply-To: References: Message-ID: Am 24.07.2012 10:24, schrieb Chris Angelico: > On Tue, Jul 24, 2012 at 5:47 PM, Ulrich Eckhardt > wrote: >> There is one model that has helped me much understanding how Python ticks >> and that is the model of name tags. The code "a = 1" creates an integer with >> value 1 and attaches a tag with "a" written on it using a small piece of >> rope. > > A double strand of rope, I think. If it were one strand, we'd write "a - 1". :) Two fibers, possibly twisted.... let's call it string! I really had to think about how to call the thing while avoiding the term string in order not to add to the confusion... (: Uli From lists at cheimes.de Tue Jul 24 06:29:32 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 24 Jul 2012 12:29:32 +0200 Subject: How to represent dates BC In-Reply-To: <500E7111.9080803@shopzeus.com> References: <500E7111.9080803@shopzeus.com> Message-ID: Am 24.07.2012 11:55, schrieb Laszlo Nagy: > What is the good representation here? Should I implement my own date > type? (I wouldn't want to.) JDN [1] is a commonly used format for wide ranges of dates. I've used it in the past to refer to days BC. PyPI offers a Python module [2] that looks well written and documented. HTH, Christian [1] http://en.wikipedia.org/wiki/Julian_Day_Number [2] http://pypi.python.org/pypi/jdcal/1.0 From lists at cheimes.de Tue Jul 24 07:07:54 2012 From: lists at cheimes.de (Christian Heimes) Date: Tue, 24 Jul 2012 13:07:54 +0200 Subject: How to deal with python 32bit memory error In-Reply-To: <500E71C1.6030802@davea.name> References: <1343117176.63442.YahooMailClassic@web161206.mail.bf1.yahoo.com> <500E71C1.6030802@davea.name> Message-ID: Am 24.07.2012 11:58, schrieb Dave Angel: > There are some limitations to 32 bits, that have nothing to do with > Python specifically. However, they have different impact, depending on > the environment you're running in. First and foremost, address are > 32bits, which limits them to 4gb of ram. So out of your 32Gig of > swapspace, a best-case maximum regardless of OS is 4Gig. No operating > system lets you actually get that high. The usable amount of memory is much lower than 4 GB for a 32bit program. A typical program can use about 2.4 to 2.7 GB virtual address space for heap. The exact amount is hard to predicate as it depends on the operating system, memory allocator and other settings. The rest of the 4 GB virtual address space is reserved for stack, mapping of dynamic libraries and operating system routines. The amount of usable memory on the heap (area returned by malloc()) is often lowered by memory fragmentation. If your program tries to malloc 100 MB of memory but the largest contiguous area is just 98 MB you'll get a memory error, too. Christian From lipskathekat at yahoo.co.uk Tue Jul 24 07:34:14 2012 From: lipskathekat at yahoo.co.uk (Lipska the Kat) Date: Tue, 24 Jul 2012 12:34:14 +0100 Subject: My first ever Python program, comments welcome In-Reply-To: <273a9070-c0b0-4b64-9741-9327f37c07fe@d6g2000pbt.googlegroups.com> References: <37a37376-18ff-46af-97f0-36fd764a8c26@m2g2000pbv.googlegroups.com> <273a9070-c0b0-4b64-9741-9327f37c07fe@d6g2000pbt.googlegroups.com> Message-ID: On 24/07/12 06:13, rusi wrote: > On Jul 22, 10:23 pm, Lipska the Kat wrote: > >> Heh heh, Nothing to do with Eclipse, just another thing to get my head >> around. For work and Java IMHO you can't beat eclipse... >> at the moment I'm getting my head around git, > > Bumped into this yesterday. Seems like a good aid to git-comprehension > https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh eek ... now that's a shell script to be proud of isn't it .. and it works [lipska at ubuntu fileio (master)]$ impressive. Good find, thanks. >> reminding myself of C, learning Python >> and re-learning make. Enough already; but if there's a python plugin I >> guess I'll get around to it eventually > > Seems like a strange combo. It should be > (C&make)|(python&X)|(Java&Ant) > where X could range from %-} > Setup http://docs.python.org/distutils/setupscript.html > to distribute http://guide.python-distribute.org/ > to scons http://www.scons.org/ Well that's the joy of life in semi-retirement. I can do as I please I read something somewhere the other day about living longer if you retire early, well I retired early but if I live another 50 years it won't be long enough to learn everything I want to. Java&Ant everyday C&make a while back python& well I sort of got sidetracked by python ... and then I got sidetracked by git !!! Lipska -- Lipska the Kat: Troll hunter, Sandbox destroyer and Farscape dreamer of Aeryn Sun. From ivdneut at gmail.com Tue Jul 24 07:48:42 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 04:48:42 -0700 (PDT) Subject: Daemon loses __file__ reference after a while. Message-ID: Hello, I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: Exception info: Traceback (most recent call last): File "scheduler.py", line 376, in applyrule result = execrule(rule_code) File "scheduler.py", line 521, in execrule rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] NameError: name '__file__' is not defined This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: (virtual-env)[user at host ~]$ python --version Python 2.6.6 (virtual-env)[user at host ~]$ cat /etc/redhat-release Red Hat Enterprise Linux Server release 6.2 (Santiago) I would greatly appreciate any pointers on where to start looking to find the problem. Ian. From gandalf at shopzeus.com Tue Jul 24 07:52:37 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 24 Jul 2012 13:52:37 +0200 Subject: How to represent dates BC In-Reply-To: References: <500E7111.9080803@shopzeus.com> Message-ID: <500E8C85.8040502@shopzeus.com> On 2012-07-24 12:29, Christian Heimes wrote: > Am 24.07.2012 11:55, schrieb Laszlo Nagy: >> What is the good representation here? Should I implement my own date >> type? (I wouldn't want to.) > JDN [1] is a commonly used format for wide ranges of dates. I've used it > in the past to refer to days BC. PyPI offers a Python module [2] that > looks well written and documented. It was really useful, thanks. I also figured out how to convert julian date to timestamp in postgresql: |to_date(2455452::text, 'J') | So it is possible to create incides. L -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Jul 24 08:10:45 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 24 Jul 2012 13:10:45 +0100 Subject: groveling over a file for Q:: and A:: stmts In-Reply-To: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> References: <4851867b-6c8e-41e4-8d39-56e10e193a12@googlegroups.com> Message-ID: <500E90C5.6010700@mrabarnett.plus.com> On 24/07/2012 08:50, paul618 wrote: > #!/usr/bin/env python > # grep_for_QA.py I am only looking to isolate uniq Q:: and A:: stmts from my daily files > # > # note: This algorithm will fail if there are any blank lines within the Q and A area of interest (a paragraph) > > # D. Beazley is my fav documentation > > import re, glob > import pprint as pp > > sampledata = ''' > A:: And Straight Street is playin on the Radio Free Tibet. What are the chances, DTMB? > Q:: About 1 in 518400, Professor. > A:: Correct! Err, I thought it was 1:410400, but close enough for jazz! > > > ''' > > pattern0 = re.compile("Q::") > pattern1 = re.compile("A::") # objects of interest can start with A:: ;; not alway Q:: > END_OF_PARAGRAPH_pat = "\n\s*\n" > > path = "/Users/paultaney/dailies2012/0722" # an example of real data set. > > toggle = False > L = [] > M = [] > > #file = open(path, "r") > try: > #for line in file.readlines(): > for line in sampledata: sampledata is a string, therefore this is iterating over the string, which yields characters, not lines. Try using sampledata.splitlines(): for line in sampledata.splitlines(): > try: > # Later, I also need to treat Unicode -- and I am clueless. > > # falsestarts:: > #line.encode("utf8").decode('xxx', 'ignore') > #line.encode("utf8", 'ignore') > #line.decode('8859') > #line.decode('8859') # 8859, Latin-1 doesn't cover my CJK pastings AT ALL > #line.decode('GB18030') # 171006 -- ack > #encoded_line = line # xxx line.encode("utf8") > > mo0 = re.search(pattern0, line) This searches for pattern0 anywhere in the line. You really want to check whether the line starts with pattern0, which is better done with: line.startswith("Q::") > mo1 = re.search(pattern1, line) > mo2 = re.search(END_OF_PARAGRAPH_pat, line) > > if mo0: > if 1: print ("I see pattern 0") > toggle = True > if 1: print(line) > M.append(mo0.group()) > > if mo1: > if 1: print ("I see pattern 1") > toggle = True > M.append(mo1.group()) > > if mo2 and toggle: > if 1: print ("I see pattern 2 AND toggle is set") > # got one. save it for uniqifying, and empty the container > toggle = False > L.append(M) > M = [] > > except Exception as e: > print("--- " + e + " ---") > > except UnicodeDecodeError: > #encoded_line = encoded_line.urlsafe_b64encode(re.replace("asdf", encoded_line)) > #line = re.sub(".+", "--- asdf ---", line) > pass > > L.sort > print (L) > > # and what"s wrong with some of this, here! > #myHash = set(L) # uniqify > #pp.pprint(myHash) # july 23, 131001 hike! > From ivdneut at gmail.com Tue Jul 24 08:17:51 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 05:17:51 -0700 (PDT) Subject: Daemon loses __file__ reference after a while Message-ID: <33df007b-6953-4606-871c-7a9b995739f2@googlegroups.com> Hello all, I have a deamon process that runs for some considerable time (weeks) without any problems. At some point it starts throwing the following exception: File "/some/path/scheduler.py", line 376, in applyrule result = execrule(rule_code) File "/some/path/scheduler.py", line 521, in execrule rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] NameError: name '__file__' is not defined This section is executed *all the time* but somehow stops working after a while. I have searched the web and this group, but can only find references to this occurring when run interactively, which is not the case here. When I restart the process the problem, at least temporarily, disappears. I am running the script in a virtual-env on a stock Red Hat EL 6.2 installation: (my-env)[user at host ~]$ python --version Python 2.6.6 (my-env)[user at host ~]$ cat /etc/redhat-release Red Hat Enterprise Linux Server release 6.2 (Santiago) Thank you very much in advance for any pointers as to where to start looking to find the problem. Ian. (If this post occurs twice, I apologize. Google groups was complaining about my post taking long to process and to wait a few minutes and try again if it didn't show up, which as far as I can determine, it didn't.) From airween at gmail.com Tue Jul 24 08:24:31 2012 From: airween at gmail.com (Ervin =?utf-8?Q?Heged=C3=BCs?=) Date: Tue, 24 Jul 2012 14:24:31 +0200 Subject: Daemon loses __file__ reference after a while. In-Reply-To: References: Message-ID: <20120724122429.GA4955@arxnet.hu> hello, On Tue, Jul 24, 2012 at 04:48:42AM -0700, ivdneut at gmail.com wrote: > Hello, > > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > Exception info: Traceback (most recent call last): > File "scheduler.py", line 376, in applyrule > result = execrule(rule_code) > File "scheduler.py", line 521, in execrule > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > NameError: name '__file__' is not defined > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. could you send the relevant part of the code? I mean: how do you daemonize your process? > I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: > > (virtual-env)[user at host ~]$ python --version > Python 2.6.6 > (virtual-env)[user at host ~]$ cat /etc/redhat-release > Red Hat Enterprise Linux Server release 6.2 (Santiago) If you use fork(), it drops all file descriptors, and creates new ones - may be then loss the __file__...? a. -- I ? UTF-8 From gandalf at shopzeus.com Tue Jul 24 08:29:19 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 24 Jul 2012 14:29:19 +0200 Subject: Daemon loses __file__ reference after a while In-Reply-To: <33df007b-6953-4606-871c-7a9b995739f2@googlegroups.com> References: <33df007b-6953-4606-871c-7a9b995739f2@googlegroups.com> Message-ID: <500E951F.1070504@shopzeus.com> On 2012-07-24 14:17, ivdneut at gmail.com wrote: > Hello all, > > I have a deamon process that runs for some considerable time (weeks) without any problems. At some point it starts throwing the following exception: > > File "/some/path/scheduler.py", line 376, in applyrule > result = execrule(rule_code) > File "/some/path/scheduler.py", line 521, in execrule > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > NameError: name '__file__' is not defined It is not a direct solution to your problem, but can you save the value of os.path.dirname(__file__) into another variable? From gandalf at shopzeus.com Tue Jul 24 08:31:13 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 24 Jul 2012 14:31:13 +0200 Subject: Daemon loses __file__ reference after a while. In-Reply-To: <20120724122429.GA4955@arxnet.hu> References: <20120724122429.GA4955@arxnet.hu> Message-ID: <500E9591.7090605@shopzeus.com> > If you use fork(), it drops all file descriptors, and creates new > ones - may be then loss the __file__...? > I don't think this is the case. He wrote that the process runs for weeks without problems, and code using __file__ is being executed all the time. From ivdneut at gmail.com Tue Jul 24 08:41:22 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 05:41:22 -0700 (PDT) Subject: Daemon loses __file__ reference after a while. In-Reply-To: References: Message-ID: <29b90361-7bb9-4774-a081-938856f62fda@googlegroups.com> On Tuesday, July 24, 2012 2:24:31 PM UTC+2, Ervin Heged?s wrote: > hello, > > On Tue, Jul 24, 2012 at 04:48:42AM -0700, ivdneut at gmail.com wrote: > > Hello, > > > > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > > > Exception info: Traceback (most recent call last): > > File "scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > > > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. > > could you send the relevant part of the code? > > I mean: how do you daemonize your process? It's done by a double fork: ## First fork() pid = os.fork() if pid != 0: sys.exit(0) # parent exits. ## create new session os.setsid() ## ignore SIGHUP signal.signal(signal.SIGHUP, signal.SIG_IGN) ## Second fork() pid = os.fork() if pid != 0: sys.exit(0) # First child exits. ## Change working directory to the home directory. homedir = pwd.getpwuid(os.geteuid())[5] os.chdir(homedir) os.umask(0) for fd in range(0, 1024): try: os.close(fd) except: pass # fd not open, ignore this exception. The original C version of this code is from W.R. Stevens' daemon_init() routine in "UNIX Network Programming Volume 1, second edition" > > > I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: > > > > (virtual-env)[user at host ~]$ python --version > > Python 2.6.6 > > (virtual-env)[user at host ~]$ cat /etc/redhat-release > > Red Hat Enterprise Linux Server release 6.2 (Santiago) > > If you use fork(), it drops all file descriptors, and creates new > ones - may be then loss the __file__...? I doubt this would be it, or it would stop working immediately, since daemonization is done upon startup of the process. File descriptors are closed immediately upon startup, it doesn't seem to affect the reference to the __file__ string (which is not a file object, but a str object) > > > a. > > > -- > I ? UTF-8 On Tuesday, July 24, 2012 2:24:31 PM UTC+2, Ervin Heged?s wrote: > hello, > > On Tue, Jul 24, 2012 at 04:48:42AM -0700, ivdneut at gmail.com wrote: > > Hello, > > > > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > > > Exception info: Traceback (most recent call last): > > File "scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > > > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. > > could you send the relevant part of the code? > > I mean: how do you daemonize your process? > > > I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: > > > > (virtual-env)[user at host ~]$ python --version > > Python 2.6.6 > > (virtual-env)[user at host ~]$ cat /etc/redhat-release > > Red Hat Enterprise Linux Server release 6.2 (Santiago) > > If you use fork(), it drops all file descriptors, and creates new > ones - may be then loss the __file__...? > > > a. > > > -- > I ? UTF-8 From ivdneut at gmail.com Tue Jul 24 08:41:22 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 05:41:22 -0700 (PDT) Subject: Daemon loses __file__ reference after a while. In-Reply-To: References: Message-ID: <29b90361-7bb9-4774-a081-938856f62fda@googlegroups.com> On Tuesday, July 24, 2012 2:24:31 PM UTC+2, Ervin Heged?s wrote: > hello, > > On Tue, Jul 24, 2012 at 04:48:42AM -0700, ivdneut at gmail.com wrote: > > Hello, > > > > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > > > Exception info: Traceback (most recent call last): > > File "scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > > > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. > > could you send the relevant part of the code? > > I mean: how do you daemonize your process? It's done by a double fork: ## First fork() pid = os.fork() if pid != 0: sys.exit(0) # parent exits. ## create new session os.setsid() ## ignore SIGHUP signal.signal(signal.SIGHUP, signal.SIG_IGN) ## Second fork() pid = os.fork() if pid != 0: sys.exit(0) # First child exits. ## Change working directory to the home directory. homedir = pwd.getpwuid(os.geteuid())[5] os.chdir(homedir) os.umask(0) for fd in range(0, 1024): try: os.close(fd) except: pass # fd not open, ignore this exception. The original C version of this code is from W.R. Stevens' daemon_init() routine in "UNIX Network Programming Volume 1, second edition" > > > I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: > > > > (virtual-env)[user at host ~]$ python --version > > Python 2.6.6 > > (virtual-env)[user at host ~]$ cat /etc/redhat-release > > Red Hat Enterprise Linux Server release 6.2 (Santiago) > > If you use fork(), it drops all file descriptors, and creates new > ones - may be then loss the __file__...? I doubt this would be it, or it would stop working immediately, since daemonization is done upon startup of the process. File descriptors are closed immediately upon startup, it doesn't seem to affect the reference to the __file__ string (which is not a file object, but a str object) > > > a. > > > -- > I ? UTF-8 On Tuesday, July 24, 2012 2:24:31 PM UTC+2, Ervin Heged?s wrote: > hello, > > On Tue, Jul 24, 2012 at 04:48:42AM -0700, ivdneut at gmail.com wrote: > > Hello, > > > > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > > > Exception info: Traceback (most recent call last): > > File "scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > > > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. > > could you send the relevant part of the code? > > I mean: how do you daemonize your process? > > > I am running python from a virtual-env installation from a stock Red Hat EL 6.2 installation: > > > > (virtual-env)[user at host ~]$ python --version > > Python 2.6.6 > > (virtual-env)[user at host ~]$ cat /etc/redhat-release > > Red Hat Enterprise Linux Server release 6.2 (Santiago) > > If you use fork(), it drops all file descriptors, and creates new > ones - may be then loss the __file__...? > > > a. > > > -- > I ? UTF-8 From ivdneut at gmail.com Tue Jul 24 08:44:23 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 05:44:23 -0700 (PDT) Subject: Daemon loses __file__ reference after a while In-Reply-To: References: <33df007b-6953-4606-871c-7a9b995739f2@googlegroups.com> Message-ID: On Tuesday, July 24, 2012 2:29:19 PM UTC+2, Laszlo Nagy wrote: > On 2012-07-24 14:17, ivdneut at gmail.com wrote: > > Hello all, > > > > I have a deamon process that runs for some considerable time (weeks) without any problems. At some point it starts throwing the following exception: > > > > File "/some/path/scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "/some/path/scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > It is not a direct solution to your problem, but can you save the value > of os.path.dirname(__file__) into another variable? That might be a workaround that I'm seriously pondering as well. Thank you. Ian. (sorry for google messing up my posts) From ivdneut at gmail.com Tue Jul 24 08:44:23 2012 From: ivdneut at gmail.com (ivdneut at gmail.com) Date: Tue, 24 Jul 2012 05:44:23 -0700 (PDT) Subject: Daemon loses __file__ reference after a while In-Reply-To: References: <33df007b-6953-4606-871c-7a9b995739f2@googlegroups.com> Message-ID: On Tuesday, July 24, 2012 2:29:19 PM UTC+2, Laszlo Nagy wrote: > On 2012-07-24 14:17, ivdneut at gmail.com wrote: > > Hello all, > > > > I have a deamon process that runs for some considerable time (weeks) without any problems. At some point it starts throwing the following exception: > > > > File "/some/path/scheduler.py", line 376, in applyrule > > result = execrule(rule_code) > > File "/some/path/scheduler.py", line 521, in execrule > > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > > NameError: name '__file__' is not defined > It is not a direct solution to your problem, but can you save the value > of os.path.dirname(__file__) into another variable? That might be a workaround that I'm seriously pondering as well. Thank you. Ian. (sorry for google messing up my posts) From jeanpierreda at gmail.com Tue Jul 24 10:02:56 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 24 Jul 2012 10:02:56 -0400 Subject: =?UTF-8?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLDr8K+4oCiLi4uLi4uLsOvwr4=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Jul 23, 2012 at 12:09 PM, Chris Angelico wrote: > It is, in many places. It's one of the few truly international > holidays. The next nearest, Pi Day, has two different dates (the > American and the European - of course, here in Australia, we celebrate > both). Here in Canada we celebrate Tau day. -- Devin (... I wish.) From ben+python at benfinney.id.au Tue Jul 24 10:35:29 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2012 00:35:29 +1000 Subject: the meaning of =?utf-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> Message-ID: <87r4s1rzv2.fsf@benfinney.id.au> Chris Angelico writes: > [?] Pi Day, has two different dates (the American and the European - > of course, here in Australia, we celebrate both). What would be the two days? The 14th day of the 3rd month, and, um, what? Or do you Australians have the third day of the fourteenth month? -- \ ?Earth gets its price for what Earth gives us.? ?James Russell | `\ Lowell | _o__) | Ben Finney From maarten.sneep at knmi.nl Tue Jul 24 10:44:44 2012 From: maarten.sneep at knmi.nl (Maarten) Date: Tue, 24 Jul 2012 07:44:44 -0700 (PDT) Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: <87r4s1rzv2.fsf@benfinney.id.au> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> Message-ID: <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> On Tuesday, July 24, 2012 4:35:29 PM UTC+2, Ben Finney wrote: > Chris Angelico writes: > > > [?] Pi Day, has two different dates (the American and the European - > > of course, here in Australia, we celebrate both). > > What would be the two days? The 14th day of the 3rd month, and, um, > what? > > Or do you Australians have the third day of the fourteenth month? You just missed it: 22/7 Maarten From rosuav at gmail.com Tue Jul 24 10:50:07 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 25 Jul 2012 00:50:07 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: <87r4s1rzv2.fsf@benfinney.id.au> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> Message-ID: On Wed, Jul 25, 2012 at 12:35 AM, Ben Finney wrote: > Chris Angelico writes: > >> [?] Pi Day, has two different dates (the American and the European - >> of course, here in Australia, we celebrate both). > > What would be the two days? The 14th day of the 3rd month, and, um, > what? Americans celebrate March 14th as 3.14; some Europeans celebrate July 22nd as 22/7 (which is 3.142857, fairly close to 3.14159). We claim both, and also June 28th (aka Tau Day or Two Pi Day, 6.28). > Or do you Australians have the third day of the fourteenth month? The extra months would explain why we're ever so much more productive than the rest of the world! Now if only we could be productive at more than just dole bludging... ChrisA From dieter at handshake.de Tue Jul 24 10:59:27 2012 From: dieter at handshake.de (Dieter Maurer) Date: Tue, 24 Jul 2012 16:59:27 +0200 Subject: Daemon loses __file__ reference after a while. References: Message-ID: <87y5m9p5m8.fsf@handshake.de> "ivdneut at gmail.com" writes: > I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: > > Exception info: Traceback (most recent call last): > File "scheduler.py", line 376, in applyrule > result = execrule(rule_code) > File "scheduler.py", line 521, in execrule > rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] > NameError: name '__file__' is not defined > > This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. This is strange indeed. I have only one vague idea: should something try to terminate the process, modules would start to lose their variables during shutdown. From cpppwner at gmail.com Tue Jul 24 11:01:28 2012 From: cpppwner at gmail.com (cpppwner at gmail.com) Date: Tue, 24 Jul 2012 08:01:28 -0700 (PDT) Subject: Python 2.6 StreamReader.readline() Message-ID: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> Hi, I have a simple question, I'm using something like the following lines in python 2.6.2 reader = codecs.getreader(encoding) lines = [] with open(filename, 'rb') as f: lines = reader(f, 'strict').readlines(keepends=False) where encoding == 'utf-16-be' Everything works fine, except that lines[0] is equal to codecs.BOM_UTF16_BE Is this behaviour correct, that the BOM is still present? Thanks in advance for your help. Best, Stefan From subhabangalore at gmail.com Tue Jul 24 11:39:02 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Tue, 24 Jul 2012 08:39:02 -0700 (PDT) Subject: HMM and CRF Package Message-ID: Dear Group, I was looking for the following solutions. (i) a Python Hidden Markov Model(HMM) library. (ii)a Python Conditional Random Field(CRF) library. (iii) I am using Python 3.2.1 on Windows 7(64 bit) and also like to get a NLTK version. (iv) I may use unicode character as input. If any one may kindly help me out. Best Regards, Subhabrata Banerjee. Gurgaon. India. From ian.g.kelly at gmail.com Tue Jul 24 12:36:53 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 10:36:53 -0600 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> Message-ID: On Tue, Jul 24, 2012 at 8:50 AM, Chris Angelico wrote: > Americans celebrate March 14th as 3.14; some Europeans celebrate July > 22nd as 22/7 (which is 3.142857, fairly close to 3.14159). We claim > both, and also June 28th (aka Tau Day or Two Pi Day, 6.28). Hey now, Tau Day is an American invention, so no claiming it as an Australian thing. We just need to get a few more people here to start observing it; that's all. From rosuav at gmail.com Tue Jul 24 12:42:40 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 25 Jul 2012 02:42:40 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> Message-ID: On Wed, Jul 25, 2012 at 2:36 AM, Ian Kelly wrote: > On Tue, Jul 24, 2012 at 8:50 AM, Chris Angelico wrote: >> Americans celebrate March 14th as 3.14; some Europeans celebrate July >> 22nd as 22/7 (which is 3.142857, fairly close to 3.14159). We claim >> both, and also June 28th (aka Tau Day or Two Pi Day, 6.28). > > Hey now, Tau Day is an American invention, so no claiming it as an > Australian thing. We just need to get a few more people here to start > observing it; that's all. I never did. We celebrate it as Two Pi Day here. You're most welcome to lay claim to its invention, as long as you release it under an acceptable Free license. Of course, you're legitimately able to put non-commercial clauses in (after what happened to Christmas, I wouldn't blame you), but we'd just have to invent our own day to celebrate instead. The calendar perceives censorship as damage, and routes around it... ChrisA From ethan at stoneleaf.us Tue Jul 24 12:59:45 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 24 Jul 2012 09:59:45 -0700 Subject: the meaning of =?windows-1252?Q?r=EF=BE=95=2E=2E=2E=2E=2E=2E?= =?windows-1252?Q?=2E=EF=BE?= In-Reply-To: References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> Message-ID: <500ED481.4090809@stoneleaf.us> Ian Kelly wrote: > On Tue, Jul 24, 2012 at 8:50 AM, Chris Angelico wrote: >> Americans celebrate March 14th as 3.14; some Europeans celebrate July >> 22nd as 22/7 (which is 3.142857, fairly close to 3.14159). We claim >> both, and also June 28th (aka Tau Day or Two Pi Day, 6.28). > > Hey now, Tau Day is an American invention, so no claiming it as an > Australian thing. We just need to get a few more people here to start > observing it; that's all. I'm in! At least for next year. Assuming I remember... ~Ethan~ From giuseppe.amatulli at gmail.com Tue Jul 24 14:27:05 2012 From: giuseppe.amatulli at gmail.com (giuseppe.amatulli at gmail.com) Date: Tue, 24 Jul 2012 11:27:05 -0700 (PDT) Subject: no data exclution and unique combination. Message-ID: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> Hi, would like to take eliminate a specific number in an array and its correspondent in an other array, and vice-versa. given a=np.array([1,2,4,4,5,4,1,4,1,1,2,4]) b=np.array([1,2,3,5,4,4,1,3,2,1,3,4]) no_data_a=1 no_data_b=2 a_clean=array([4,4,5,4,4,4]) b_clean=array([3,5,4,4,3,4]) after i need to calculate unique combination in pairs to count the observations and obtain (4,3,2) (4,5,1) (5,4,1) (4,4,2) For the fist task i did a_No_data_a = a[a != no_data_a] b_No_data_a = b[a != no_data_a] b_clean = b_No_data_a[b_No_data_a != no_data_b] a_clean = a_No_data_a[a_No_data_a != no_data_b] but the results are not really stable. For the second task The np.unique would solve the problem if it can be apply to a two arrays. Any idea? thanks in advance Giuseppe From python at mrabarnett.plus.com Tue Jul 24 14:51:34 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 24 Jul 2012 19:51:34 +0100 Subject: no data exclution and unique combination. In-Reply-To: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> References: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> Message-ID: <500EEEB6.1050904@mrabarnett.plus.com> On 24/07/2012 19:27, giuseppe.amatulli at gmail.com wrote: > Hi, > would like to take eliminate a specific number in an array and its correspondent in an other array, and vice-versa. > > given > > a=np.array([1,2,4,4,5,4,1,4,1,1,2,4]) > b=np.array([1,2,3,5,4,4,1,3,2,1,3,4]) > > no_data_a=1 > no_data_b=2 > > a_clean=array([4,4,5,4,4,4]) > b_clean=array([3,5,4,4,3,4]) > > after i need to calculate unique combination in pairs to count the observations > and obtain > (4,3,2) > (4,5,1) > (5,4,1) > (4,4,2) > > For the fist task i did > > a_No_data_a = a[a != no_data_a] > b_No_data_a = b[a != no_data_a] > > b_clean = b_No_data_a[b_No_data_a != no_data_b] > a_clean = a_No_data_a[a_No_data_a != no_data_b] > > but the results are not really stable. > mask = (a != no_data_a) & (b != no_data_b) a_clean = a[mask] b_clean = b[mask] > For the second task > The np.unique would solve the problem if it can be apply to a two arrays. > From python at mrabarnett.plus.com Tue Jul 24 15:08:38 2012 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 24 Jul 2012 20:08:38 +0100 Subject: no data exclution and unique combination. In-Reply-To: <500EEEB6.1050904@mrabarnett.plus.com> References: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> <500EEEB6.1050904@mrabarnett.plus.com> Message-ID: <500EF2B6.2060707@mrabarnett.plus.com> On 24/07/2012 19:51, MRAB wrote: > On 24/07/2012 19:27, giuseppe.amatulli at gmail.com wrote: >> Hi, >> would like to take eliminate a specific number in an array and its correspondent in an other array, and vice-versa. >> >> given >> >> a=np.array([1,2,4,4,5,4,1,4,1,1,2,4]) >> b=np.array([1,2,3,5,4,4,1,3,2,1,3,4]) >> >> no_data_a=1 >> no_data_b=2 >> >> a_clean=array([4,4,5,4,4,4]) >> b_clean=array([3,5,4,4,3,4]) >> >> after i need to calculate unique combination in pairs to count the observations >> and obtain >> (4,3,2) >> (4,5,1) >> (5,4,1) >> (4,4,2) >> >> For the fist task i did >> >> a_No_data_a = a[a != no_data_a] >> b_No_data_a = b[a != no_data_a] >> >> b_clean = b_No_data_a[b_No_data_a != no_data_b] >> a_clean = a_No_data_a[a_No_data_a != no_data_b] >> >> but the results are not really stable. >> > mask = (a != no_data_a) & (b != no_data_b) > a_clean = a[mask] > b_clean = b[mask] > >> For the second task >> The np.unique would solve the problem if it can be apply to a two arrays. >> I couldn't figure out how to do the second part in numpy, so: from collections import Counter counts = Counter(zip(a_clean, b_clean)) counts = [pair + (count,) for pair, count in counts.items()] From ian.g.kelly at gmail.com Tue Jul 24 15:28:01 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 13:28:01 -0600 Subject: no data exclution and unique combination. In-Reply-To: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> References: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> Message-ID: On Jul 24, 2012 12:32 PM, wrote: > after i need to calculate unique combination in pairs to count the observations > and obtain > (4,3,2) > (4,5,1) > (5,4,1) > (4,4,2) I don't know about a numpy solution, but this could be achieved by collections.Counter(zip(a, b)).items(). That gives you: ((4,3),2) ((4,5),1) Etc. If you really want triples instead of pair-value pairs, then you would need to flatten the tuples yourself. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Jul 24 15:32:07 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jul 2012 15:32:07 -0400 Subject: no data exclution and unique combination. In-Reply-To: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> References: <864b0104-daa8-4ea5-8003-6cfaab19fdea@googlegroups.com> Message-ID: On 7/24/2012 2:27 PM, giuseppe.amatulli at gmail.com wrote: > Hi, > would like to take eliminate a specific number in an array and its correspondent in an other array, and vice-versa. > > given > > a=np.array([1,2,4,4,5,4,1,4,1,1,2,4]) > b=np.array([1,2,3,5,4,4,1,3,2,1,3,4]) > > no_data_a=1 > no_data_b=2 > > a_clean=array([4,4,5,4,4,4]) > b_clean=array([3,5,4,4,3,4]) As I discovered when running the solution before, your test data are wrong, leaving out 2,3 before the last pair (4,4). Anyway, for those interested in a plain Python solution, without numpy: a=[1,2,4,4,5,4,1,4,1,1,2,4] b=[1,2,3,5,4,4,1,3,2,1,3,4] no_data_a=1 no_data_b=2 a_clean=(4,4,5,4,4,2,4) b_clean=(3,5,4,4,3,3,4) cleaned = list(zip(*(pair for pair in zip(a,b) if pair[0] != no_data_a and pair[1] != no_data_b))) print(cleaned, cleaned == [a_clean, b_clean]) # [(4, 4, 5, 4, 4, 2, 4), (3, 5, 4, 4, 3, 3, 4)] True -- Terry Jan Reedy From no.email at nospam.invalid Tue Jul 24 15:32:32 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Tue, 24 Jul 2012 12:32:32 -0700 Subject: Daemon loses __file__ reference after a while. References: Message-ID: <7xobn50xbj.fsf@ruckus.brouhaha.com> Dieter Maurer writes: > I have only one vague idea: should something try to terminate the > process, modules would start to lose their variables during shutdown. That happens all the time with multi-threaded programs, because the shutdown is happening concurrently with other threads doing stuff. Are there threads in this particular program? From wanderer at dialup4less.com Tue Jul 24 15:57:50 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 24 Jul 2012 12:57:50 -0700 (PDT) Subject: assert expressions Message-ID: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> If I use the code assert False, "unhandled option" I get output like: option -q not recognized for help use --help What other expressions can I use other than "unhandled option"? Is there a list somewhere? Thanks From ian.g.kelly at gmail.com Tue Jul 24 16:02:49 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 14:02:49 -0600 Subject: Daemon loses __file__ reference after a while. In-Reply-To: <87y5m9p5m8.fsf@handshake.de> References: <87y5m9p5m8.fsf@handshake.de> Message-ID: On Tue, Jul 24, 2012 at 8:59 AM, Dieter Maurer wrote: > "ivdneut at gmail.com" writes: > >> I have a daemon process that runs for a considerable amount of time (weeks on end) without any problems. At some point I start getting the exception: >> >> Exception info: Traceback (most recent call last): >> File "scheduler.py", line 376, in applyrule >> result = execrule(rule_code) >> File "scheduler.py", line 521, in execrule >> rulepath = os.path.dirname(__file__)+"/"+'/'.join(rule['modules'])+"/"+rule['rulename'] >> NameError: name '__file__' is not defined >> >> This section of the code is executed in this process *all the time*, but suddenly stops working. I have been searching for similar issues online, but only come accross people having problems because they run the script interactively. This is not the case here. > > This is strange indeed. > > I have only one vague idea: should something try to terminate the > process, modules would start to lose their variables during shutdown. That's a good theory. Or perhaps something in the code itself is handling the module's globals() and very occasionally does something that is incorrect and destructive. From ian.g.kelly at gmail.com Tue Jul 24 16:08:43 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 14:08:43 -0600 Subject: Daemon loses __file__ reference after a while. In-Reply-To: <7xobn50xbj.fsf@ruckus.brouhaha.com> References: <7xobn50xbj.fsf@ruckus.brouhaha.com> Message-ID: On Tue, Jul 24, 2012 at 1:32 PM, Paul Rubin wrote: > Dieter Maurer writes: >> I have only one vague idea: should something try to terminate the >> process, modules would start to lose their variables during shutdown. > > That happens all the time with multi-threaded programs, because the > shutdown is happening concurrently with other threads doing stuff. Are > there threads in this particular program? It also comes up in single-threaded programs that use finalizers (__del__ methods). At the time an object is finalized, many globals might already be gone. From ian.g.kelly at gmail.com Tue Jul 24 16:31:25 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 14:31:25 -0600 Subject: assert expressions In-Reply-To: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> Message-ID: On Tue, Jul 24, 2012 at 1:57 PM, Wanderer wrote: > If I use the code > > assert False, "unhandled option" > > I get output like: > > option -q not recognized > for help use --help > > What other expressions can I use other than "unhandled option"? Is there a list somewhere? Are you using argparse or optparse or getopt or something else altogether? And where are you placing this assert? It would be helpful to see some actual code to understand what you are doing. And by the way, assert is a very bad way to check user input or to unconditionally raise an exception. The reason is that if Python is invoked with -O, then all assertions are removed from the compiled bytecode, and then your unconditional exception code doesn't raise any exception at all. If you want to raise an exception, just do it: raise Exception("unhandled option") Ideally, you would also subclass Exception to create a more specific exception class for your custom exception: class UnhandledOptionException(Exception): pass # Then, later on... raise UnhandledOptionException("-q") From wanderer at dialup4less.com Tue Jul 24 16:44:57 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 24 Jul 2012 13:44:57 -0700 (PDT) Subject: assert expressions References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> Message-ID: <8c5da998-e428-4000-adba-f5eee86ac971@d32g2000yqn.googlegroups.com> On Jul 24, 4:31?pm, Ian Kelly wrote: > On Tue, Jul 24, 2012 at 1:57 PM, Wanderer wrote: > > If I use the code > > > assert False, "unhandled option" > > > I get output like: > > > option -q not recognized > > for help use --help > > > What other expressions can I use other than "unhandled option"? Is there a list somewhere? > > Are you using argparse or optparse or getopt or something else > altogether? ?And where are you placing this assert? ?It would be > helpful to see some actual code to understand what you are doing. > > And by the way, assert is a very bad way to check user input or to > unconditionally raise an exception. ?The reason is that if Python is > invoked with -O, then all assertions are removed from the compiled > bytecode, and then your unconditional exception code doesn't raise any > exception at all. ?If you want to raise an exception, just do it: > > raise Exception("unhandled option") > > Ideally, you would also subclass Exception to create a more specific > exception class for your custom exception: > > class UnhandledOptionException(Exception): > ? ? pass > > # Then, later on... > > raise UnhandledOptionException("-q") I'm using getopt but not at that point. I really don't have a problem. I'm just curious. I've never seen anything else after assert False, Here is some code. def main(argv=None): help_message = \ ("\nOtFixture.py:\n Set the Optics Test Fixture Light Source Light Level\n" + "Options:\n" " -l, --level= \n" + " -v, --verbose: Print messages to the terminal.\n" " -h, --help: This message\n") level = None verbose = False helpflag = False options = "hl:v" long_options = ["help","level=","verbose"] if argv is None: argv = sys.argv try: try: opts, _args = getopt.getopt(argv[1:], options,long_options) except getopt.error, msg: raise Usage(msg) for o, a in opts: if o in ("-h", "--help"): print help_message helpflag = True elif o in ("-l", "--level"): level = a elif o in ("-v", "--verbose"): verbose = True else: assert False, "unhandled option" if not helpflag: if level == None: level = raw_input("Enter the light level from 0.0 to 100.0%: ") if level.replace(".", "", 1).isdigit(): level = float(level) else: msg = "\n" + str(level) + " is not a number.\n" raise Usage(msg) if verbose and level is not None: print "The level is ", level, " percent" if level is not None: if 0.0 <= level <= 100.0: ot = OtFixture(verbose) ot.setLightLevel(level) print "Light Level set to ", level,"%." else: msg = "\n" + str(level) + " is not in the range 0.0 to 100.0%\n" raise Usage(msg) except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == "__main__": sys.exit(main()) From wanderer at dialup4less.com Tue Jul 24 16:47:41 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 24 Jul 2012 13:47:41 -0700 (PDT) Subject: assert expressions References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> Message-ID: <8cac515d-fb79-4043-8df0-8d54335a00fb@j4g2000yqj.googlegroups.com> On Jul 24, 4:31?pm, Ian Kelly wrote: > On Tue, Jul 24, 2012 at 1:57 PM, Wanderer wrote: > > If I use the code > > > assert False, "unhandled option" > > > I get output like: > > > option -q not recognized > > for help use --help > > > What other expressions can I use other than "unhandled option"? Is there a list somewhere? > > Are you using argparse or optparse or getopt or something else > altogether? ?And where are you placing this assert? ?It would be > helpful to see some actual code to understand what you are doing. > > And by the way, assert is a very bad way to check user input or to > unconditionally raise an exception. ?The reason is that if Python is > invoked with -O, then all assertions are removed from the compiled > bytecode, and then your unconditional exception code doesn't raise any > exception at all. ?If you want to raise an exception, just do it: > > raise Exception("unhandled option") > > Ideally, you would also subclass Exception to create a more specific > exception class for your custom exception: > > class UnhandledOptionException(Exception): > ? ? pass > > # Then, later on... > > raise UnhandledOptionException("-q") I left out the Usage class class Usage(Exception): def __init__(self, msg): self.msg = msg From wanderer at dialup4less.com Tue Jul 24 16:56:22 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 24 Jul 2012 13:56:22 -0700 (PDT) Subject: assert expressions References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> <8cac515d-fb79-4043-8df0-8d54335a00fb@j4g2000yqj.googlegroups.com> Message-ID: <68944ec3-e6c3-4623-ac83-8ab35a14124a@u2g2000yqj.googlegroups.com> On Jul 24, 4:47?pm, Wanderer wrote: > On Jul 24, 4:31?pm, Ian Kelly wrote: > > > > > > > > > > > On Tue, Jul 24, 2012 at 1:57 PM, Wanderer wrote: > > > If I use the code > > > > assert False, "unhandled option" > > > > I get output like: > > > > option -q not recognized > > > for help use --help > > > > What other expressions can I use other than "unhandled option"? Is there a list somewhere? > > > Are you using argparse or optparse or getopt or something else > > altogether? ?And where are you placing this assert? ?It would be > > helpful to see some actual code to understand what you are doing. > > > And by the way, assert is a very bad way to check user input or to > > unconditionally raise an exception. ?The reason is that if Python is > > invoked with -O, then all assertions are removed from the compiled > > bytecode, and then your unconditional exception code doesn't raise any > > exception at all. ?If you want to raise an exception, just do it: > > > raise Exception("unhandled option") > > > Ideally, you would also subclass Exception to create a more specific > > exception class for your custom exception: > > > class UnhandledOptionException(Exception): > > ? ? pass > > > # Then, later on... > > > raise UnhandledOptionException("-q") > > I left out the Usage class > > class Usage(Exception): > ? ? def __init__(self, msg): > ? ? ? ? self.msg = msg I seem to be missing a post. Here is the code. class Usage(Exception): def __init__(self, msg): self.msg = msg def main(argv=None): help_message = \ ("\nOtFixture.py:\n Set the Optics Test Fixture Light Source Light Level\n" + "Options:\n" " -l, --level= \n" + " -v, --verbose: Print messages to the terminal.\n" " -h, --help: This message\n") level = None verbose = False helpflag = False options = "hl:v" long_options = ["help","level=","verbose"] if argv is None: argv = sys.argv try: try: opts, _args = getopt.getopt(argv[1:], options,long_options) except getopt.error, msg: raise Usage(msg) for o, a in opts: if o in ("-h", "--help"): print help_message helpflag = True elif o in ("-l", "--level"): level = a elif o in ("-v", "--verbose"): verbose = True else: assert False, "unhandled option" if not helpflag: if level == None: level = raw_input("Enter the light level from 0.0 to 100.0%: ") if level.replace(".", "", 1).isdigit(): level = float(level) else: msg = "\n" + str(level) + " is not a number.\n" raise Usage(msg) if verbose and level is not None: print "The level is ", level, " percent" if level is not None: if 0.0 <= level <= 100.0: ot = OtFixture(verbose) ot.setLightLevel(level) print "Light Level set to ", level,"%." else: msg = "\n" + str(level) + " is not in the range 0.0 to 100.0%\n" raise Usage(msg) except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 if __name__ == "__main__": sys.exit(main()) I don't really have a problem. I'm was just curious. How do you invoke python -O? When I run python.exe -O OtFixture.py -q, I get the same response. It's a capital letter O, right? From ian.g.kelly at gmail.com Tue Jul 24 17:22:48 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 24 Jul 2012 15:22:48 -0600 Subject: assert expressions In-Reply-To: <8c5da998-e428-4000-adba-f5eee86ac971@d32g2000yqn.googlegroups.com> References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> <8c5da998-e428-4000-adba-f5eee86ac971@d32g2000yqn.googlegroups.com> Message-ID: On Tue, Jul 24, 2012 at 2:44 PM, Wanderer wrote: > I'm using getopt but not at that point. I really don't have a problem. > I'm just curious. I've never seen anything else after > assert False, > > Here is some code. It doesn't matter what you put after the assert False, because that line is not actually reached. When getopt sees the -q, it immediately raises a getopt.error, which you catch and then immediately reraise as a Usage exception, which is then caught and printed at the end. The chained ifs with the assert statement never even execute in this scenario. Seeing the assert in context, it makes more sense. It's not intercepting some unimplemented option and preventing the program from proceeding; it's there as a development tool to catch programming errors where an option is added to the getopt configuration but is not implemented in the if chain. From eric.lemings at gmail.com Tue Jul 24 17:25:35 2012 From: eric.lemings at gmail.com (eric.lemings at gmail.com) Date: Tue, 24 Jul 2012 14:25:35 -0700 (PDT) Subject: Using Python packaging tools to maintain source distributions in other languages? In-Reply-To: References: <3e0353ce-cc80-4e2b-9c5a-9878d02cd98a@googlegroups.com> Message-ID: <641fa765-57ba-4ae0-9e9d-59a72971f5b5@googlegroups.com> On Monday, July 23, 2012 11:59:10 PM UTC-6, Rusi wrote: > On Jul 23, 11:16?pm, eric.lemi... at gmail.com wrote: > > Greetings all, > > > > I would like to leverage the Python packaging tools (e.g. distutils, setuptools, distribute, et. al.) to maintain (i.e. download, extract, configure, make, install, package) source distributions other than Python modules (e.g. zlib, openssl). > > > > Are there any open-source packages/tools that already do this? ?Any documentation in print or on the web that outlines a basic plan for doing such? > > > > Any and all help greatly appreciated. > > Ive heard good things about scons > http://en.wikipedia.org/wiki/SCons I've heard about SCons but don't know much about it. From what little I've read, it's only a make tool replacement. I'm looking for more "end-to-end" maintenance tools similar to -- perhaps built upon -- disutils, setuptools, and company. From wanderer at dialup4less.com Tue Jul 24 17:25:44 2012 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 24 Jul 2012 14:25:44 -0700 (PDT) Subject: assert expressions References: <9f6bed70-1ec1-4e3e-bdd0-c96013bf7df2@googlegroups.com> <8c5da998-e428-4000-adba-f5eee86ac971@d32g2000yqn.googlegroups.com> Message-ID: <1ebab0bd-f302-47e2-b125-3da9f9deeb38@y12g2000yqe.googlegroups.com> On Jul 24, 5:22?pm, Ian Kelly wrote: > On Tue, Jul 24, 2012 at 2:44 PM, Wanderer wrote: > > I'm using getopt but not at that point. I really don't have a problem. > > I'm just curious. I've never seen anything else after > > assert False, > > > Here is some code. > > It doesn't matter what you put after the assert False, because that > line is not actually reached. ?When getopt sees the -q, it immediately > raises a getopt.error, which you catch and then immediately reraise as > a Usage exception, which is then caught and printed at the end. ?The > chained ifs with the assert statement never even execute in this > scenario. > > Seeing the assert in context, it makes more sense. ?It's not > intercepting some unimplemented option and preventing the program from > proceeding; it's there as a development tool to catch programming > errors where an option is added to the getopt configuration but is not > implemented in the if chain. Thanks. Now it makes more sense. From gelonida at gmail.com Tue Jul 24 17:39:30 2012 From: gelonida at gmail.com (Gelonida N) Date: Tue, 24 Jul 2012 23:39:30 +0200 Subject: howto do a robust simple cross platform beep In-Reply-To: <4ed2a36d-a034-45d8-84f7-aa71ff17d8b5@googlegroups.com> References: <4ed2a36d-a034-45d8-84f7-aa71ff17d8b5@googlegroups.com> Message-ID: On 07/15/2012 03:15 AM, rantingrickjohnson at gmail.com wrote:> On Friday, July 13, 2012 8:00:05 PM UTC-5, gelonida wrote: >> I just want to use a beep command that works cross platform. [...] I >> just want to use them as alert, when certain events occur within a >> very long running non GUI application. > > I can see a need for this when facing a non GUI interface. That's exactly my usecase. A rather tiny script running for hours and telling the users when results are ready. But even "IF" you do manage to play a sound in a cross platform manner; if the speaker volume is too low, or the speakers are turned off, or the computer does not have speakers connected, etc... your user will never hear the alert! In this case, beeping the built-in speaker has the fail-safe advantage. > Well the user starts the script, because he wants to get immediate notification while being able mimimize the window, work on a different a machine or doing some paperwork or discussions. So it would be up to him to configure the volume appropraitely. > Why not wrap up the functionality and release a module yourself? If you are not sure how to access the speaker on one or more OSs then ask on the list. I would love to see some community effort behind this. > I'm having no some ugly code, that is working on the platforms, that I am using. I'm rather busy, and have no experience in publishing coe, that's good enough for the community. I could try to use this a test case for learning to create communicty modules. Is there any decent getting started guide. Could I use github (as O know git already)? Assuming, the module would achieve a state, where it could be usable by others. How would one register on Pypi? > PS: Better make sure this module does not exist though ;-) > I didn't find one, that's why I asked here. From rosuav at gmail.com Tue Jul 24 17:52:27 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 25 Jul 2012 07:52:27 +1000 Subject: howto do a robust simple cross platform beep In-Reply-To: References: <4ed2a36d-a034-45d8-84f7-aa71ff17d8b5@googlegroups.com> Message-ID: On Wed, Jul 25, 2012 at 7:39 AM, Gelonida N wrote: > On 07/15/2012 03:15 AM, rantingrickjohnson at gmail.com wrote:> On Friday, July > 13, 2012 8:00:05 PM UTC-5, gelonida wrote: >>> I just want to use a beep command that works cross platform. [...] I >>> just want to use them as alert, when certain events occur within a >>> very long running non GUI application. >> >> I can see a need for this when facing a non GUI interface. > That's exactly my usecase. > A rather tiny script running for hours and telling the users when results > are ready. Sounds reasonable. I'd be inclined to solve just my own problem, though; work it out for the platforms you use, and don't worry too much about the rest. But that's because I'm lazy :) > Could I use github (as O know git already)? You certainly could, though that doesn't help with the whole "building a module" part. (And I can't help there either, never done it. Sorry.) There are quite a few ways of creating an alert such as you describe. The easiest way may be to play a .WAV file rather than a system beep; there are a number of different options on different platforms, so your module could be written in pure Python and basically wrap the whole lot up into a huge bunch of "except ImportError" checks. Here's a few ways: http://stackoverflow.com/questions/307305/play-a-sound-with-python Burying all that complexity behind a simple "play_sound()" function would be handy, and you could easily start with just 2-3 options and add more later. ChrisA From timothy.c.delaney at gmail.com Tue Jul 24 17:56:34 2012 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Wed, 25 Jul 2012 07:56:34 +1000 Subject: [OT] git and hg in prompt (was: My first ever Python program, comments welcome) Message-ID: On 24 July 2012 21:34, Lipska the Kat wrote: > On 24/07/12 06:13, rusi wrote: > >> On Jul 22, 10:23 pm, Lipska the Kat wrote: >> >> Heh heh, Nothing to do with Eclipse, just another thing to get my head >>> around. For work and Java IMHO you can't beat eclipse... >>> at the moment I'm getting my head around git, >>> >> >> Bumped into this yesterday. Seems like a good aid to git-comprehension >> https://github.com/git/git/**blob/master/contrib/** >> completion/git-prompt.sh >> > > eek ... now that's a shell script to be proud of isn't it .. and it works > [lipska at ubuntu fileio (master)]$ impressive. Good find, thanks. OT, but I have the following in my prompt covering both git and hg - much simpler, but gives similar information. Extending should be fairly easy. function hg_ps1() { # requires http://stevelosh.com/projects/hg-prompt/ #hg prompt '[{update}{{tags|:}:}{{bookmark}:}{branch}:{rev}] ' 2> /dev/null hg prompt '[{update}{branch}:{rev}] ' 2> /dev/null } function git_ps1() { local head="`git rev-list -n 1 --abbrev-commit HEAD 2> /dev/null`" if [ "${head}" != "" ] ; then local branch="`git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`" # Puts a ^ in the prompt if this revision is not FETCH_HEAD local uptodate="`git log --no-color -n 1 --pretty=format:^ HEAD..FETCH_HEAD 2> /dev/null`" # Puts a comparison with the remote tracking branch in the prompt: + (ahead), - (behind) or * (both - diverged). local tracking="`git branch -avv --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/ */ /g' -e 's/* \(.*\)/\1/' -e 's/^[^[]*\[\([^]]*\)\].*$/\1/' -e 's/^.*ahead [0-9][0-9]*/+/' -e 's/[^+].*behind [0-9][0-9]*.*$/-/' -e '/^[^+-]/d' -e 's/+-/*/'`" echo "[${tracking}${uptodate}${branch}:${head}] " return 0 fi return 1 } function git_hg_ps1() { git_ps1 if [ $? -eq 0 ] ; then return 0 fi hg_ps1 return $? } export PS1='$(git_hg_ps1)\[\033[1;30m\]${USERNAME}@${HOSTNAME}:\[\033[0m\]\[\033[1;30m\]${PWD%%${PWD##$HOME}}\[\033[0m\]${PWD##$HOME}> ' It's designed to call as few external processes as possible (esp. when not in a git repository) since it's used on Windows as well (msys, should work in cygwin) and spawning on Windows is slow. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Jul 24 18:03:19 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 24 Jul 2012 18:03:19 -0400 Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: On Fri, Jul 13, 2012 at 9:00 PM, Gelonida N wrote: > I tried the simplest approach (just printing the BEL character '\a' chr(7) > to the console. That's what I do when I want to send an audible alert to the user of a console based program. It's then up to the user's terminal to do whatever the user wants. Printing a BEL character has the added advantage that it plays nicely with programs that are run remotely (through ssh sessions and the like). Personally, I'm usually in a screen session, inside either an xterm or over an ssh link, and have visual bells turned on so I can see the alerts, even when they pop up in another screen. -- Jerry From drsalists at gmail.com Tue Jul 24 18:19:41 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 24 Jul 2012 22:19:41 +0000 Subject: howto do a robust simple cross platform beep In-Reply-To: References: Message-ID: On Sat, Jul 14, 2012 at 1:00 AM, Gelonida N wrote: > > What I do at the moment is: > > For Windows I use winsound.Beep > > For Linux I create some raw data and pipe it into sox's > 'play' command. > > I don't consider this very elegant You may want to get over that. Some software vendors/distributors don't want you to be able to do things portably. Others have "not invented here" syndrome. A lot of programming is adding multiple ways of doing the same thing to program around the stupid wars ("choices") the vendors and distributors push on us. Or if you're really an idealist, start your own project to abstract away these silly details. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Tue Jul 24 21:39:33 2012 From: rustompmody at gmail.com (Rusi) Date: Tue, 24 Jul 2012 18:39:33 -0700 (PDT) Subject: Using Python packaging tools to maintain source distributions in other languages? References: <3e0353ce-cc80-4e2b-9c5a-9878d02cd98a@googlegroups.com> <641fa765-57ba-4ae0-9e9d-59a72971f5b5@googlegroups.com> Message-ID: <755f75c0-1157-4582-8c6c-b5ac7a34ec26@oo8g2000pbc.googlegroups.com> On Jul 25, 2:25?am, eric.lemi... at gmail.com wrote: > On Monday, July 23, 2012 11:59:10 PM UTC-6, Rusi wrote: > > Ive heard good things about scons http://en.wikipedia.org/wiki/SCons > > I've heard about SCons but don't know much about it. ?From what little I've read, it's > only a make tool replacement. ?I'm looking for more "end-to-end" maintenance tools similar to -- > perhaps built upon -- disutils, setuptools, and company. Maybe try the relevant lists/fora like the foll? http://groups.google.com/group/packaging-guide/about http://mail.python.org/mailman/listinfo/distutils-sig From ben+python at benfinney.id.au Tue Jul 24 23:07:03 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2012 13:07:03 +1000 Subject: the meaning of =?utf-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> Message-ID: <87lii8sfmw.fsf@benfinney.id.au> Maarten writes: > You just missed it: > 22/7 Which is appropriate, since 22/7 misses ? by a wide margin. (355/113 is my favourite approximation to ?, and is far more accurate.) ?1 on associating 22/7 as anything to do with ?. +1 on celebrating ? day! -- \ ?Why am I an atheist? I ask you: Why is anybody not an atheist? | `\ Everyone starts out being an atheist.? ?Andy Rooney, _Boston | _o__) Globe_ 1982-05-30 | Ben Finney From rosuav at gmail.com Wed Jul 25 00:11:07 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 25 Jul 2012 14:11:07 +1000 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: <87lii8sfmw.fsf@benfinney.id.au> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> Message-ID: On Wed, Jul 25, 2012 at 1:07 PM, Ben Finney wrote: > Which is appropriate, since 22/7 misses ? by a wide margin. (355/113 is > my favourite approximation to ?, and is far more accurate.) 22/7 is no worse than 3.14, though. Sure, 355/113 is closer still, but how often do really need more accuracy than 22/7? 3.142857 vs 3.141593 - it's 0.04% out, versus 3.14 which is 0.05% out. Anyway, 355/113 makes a really awkward date to celebrate. :) ChrisA From steve+comp.lang.python at pearwood.info Wed Jul 25 02:07:08 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 25 Jul 2012 06:07:08 GMT Subject: the meaning of =?UTF-8?b?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> Message-ID: <500f8d0c$0$11120$c3e8da3@news.astraweb.com> On Wed, 25 Jul 2012 13:07:03 +1000, Ben Finney wrote: > Maarten writes: > >> You just missed it: >> 22/7 > > Which is appropriate, since 22/7 misses ? by a wide margin. (355/113 is > my favourite approximation to ?, and is far more accurate.) Approximation? Pffft. I use the exact value: ? = 16*arctan(1/5) - 4*arctan(1/239) For those lacking ambition, another approximation is: ? ? 9801 ? (2206*?2) Other interesting approximations are: ? ? 9/5 + ?(9/5) ? ? ??(2143/22) See more here: http://mathworld.wolfram.com/PiFormulas.html http://mathworld.wolfram.com/PiApproximations.html > ?1 on associating 22/7 as anything to do with ?. I believe that 22/7 is the closest approximation to ? with a denominator under 100. It is the second convergent of the continued fraction: ? = [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, ...] which means that, like it or not, 22/7 *is* associated with ?. -- Steven From ulrich.eckhardt at dominolaser.com Wed Jul 25 02:09:49 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Wed, 25 Jul 2012 08:09:49 +0200 Subject: Python 2.6 StreamReader.readline() In-Reply-To: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> References: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> Message-ID: Am 24.07.2012 17:01, schrieb cpppwner at gmail.com: > reader = codecs.getreader(encoding) > lines = [] > with open(filename, 'rb') as f: > lines = reader(f, 'strict').readlines(keepends=False) > > where encoding == 'utf-16-be' > Everything works fine, except that lines[0] is equal to codecs.BOM_UTF16_BE > Is this behaviour correct, that the BOM is still present? Yes, assuming the first line only contains that BOM. Technically it's a space character, and why should those be removed? Uli From breamoreboy at yahoo.co.uk Wed Jul 25 02:37:33 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 25 Jul 2012 07:37:33 +0100 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= In-Reply-To: <500f8d0c$0$11120$c3e8da3@news.astraweb.com> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> <500f8d0c$0$11120$c3e8da3@news.astraweb.com> Message-ID: On 25/07/2012 07:07, Steven D'Aprano wrote: > On Wed, 25 Jul 2012 13:07:03 +1000, Ben Finney wrote: > >> Maarten writes: >> >>> You just missed it: >>> 22/7 >> >> Which is appropriate, since 22/7 misses ? by a wide margin. (355/113 is >> my favourite approximation to ?, and is far more accurate.) > > Approximation? Pffft. I use the exact value: > > ? = 16*arctan(1/5) - 4*arctan(1/239) > > > For those lacking ambition, another approximation is: > > ? ? 9801 ? (2206*?2) > > Other interesting approximations are: > > ? ? 9/5 + ?(9/5) > > ? ? ??(2143/22) > > See more here: > > http://mathworld.wolfram.com/PiFormulas.html > http://mathworld.wolfram.com/PiApproximations.html > > >> ?1 on associating 22/7 as anything to do with ?. > > I believe that 22/7 is the closest approximation to ? with a denominator > under 100. It is the second convergent of the continued fraction: > > ? = [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, ...] > > which means that, like it or not, 22/7 *is* associated with ?. > > > Any civil engineers reading this who would find 22/7 perfectly adequate for their task? -- Cheers. Mark Lawrence. From ben+python at benfinney.id.au Wed Jul 25 02:43:38 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2012 16:43:38 +1000 Subject: the meaning of =?utf-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> <500f8d0c$0$11120$c3e8da3@news.astraweb.com> Message-ID: <87boj4s5lx.fsf@benfinney.id.au> Mark Lawrence writes: > Any civil engineers reading this who would find 22/7 perfectly > adequate for their task? Civil engineering? Pffft, that deals with only a few orders of magnitude range at most. ?? is roughly 3? is usually good enough in that arena :-) -- \ ?You don't need a book of any description to help you have some | `\ kind of moral awareness.? ?Dr. Francesca Stavrakoloulou, bible | _o__) scholar, 2011-05-08 | Ben Finney From breamoreboy at yahoo.co.uk Wed Jul 25 03:13:22 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 25 Jul 2012 08:13:22 +0100 Subject: the meaning of =?UTF-8?B?csOvwr7igKIuLi4uLi4uw6/Cvg==?= In-Reply-To: <87boj4s5lx.fsf@benfinney.id.au> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> <500f8d0c$0$11120$c3e8da3@news.astraweb.com> <87boj4s5lx.fsf@benfinney.id.au> Message-ID: On 25/07/2012 07:43, Ben Finney wrote: > Mark Lawrence writes: > >> Any civil engineers reading this who would find 22/7 perfectly >> adequate for their task? > > Civil engineering? Pffft, that deals with only a few orders of magnitude > range at most. ?? is roughly 3? is usually good enough in that arena :-) > Love it. I, personally, hereby take back everything adverse that anyone else may ever have written about you :) -- Cheers. Mark Lawrence. From ulrich.eckhardt at dominolaser.com Wed Jul 25 04:40:45 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Wed, 25 Jul 2012 10:40:45 +0200 Subject: from future import pass_function Message-ID: Hi! I just had an idea, it occurred to me that the pass statement is pretty similar to the print statement, and similarly to the print() function, there could be a pass() function that does and returns nothing. Example: def pass(): return try: do_something() except: pass() One thing I don't like about this is the syntax class foo(object): pass() What do you think? Uli From walter at livinglogic.de Wed Jul 25 05:02:01 2012 From: walter at livinglogic.de (=?UTF-8?B?V2FsdGVyIETDtnJ3YWxk?=) Date: Wed, 25 Jul 2012 11:02:01 +0200 Subject: Python 2.6 StreamReader.readline() In-Reply-To: References: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> Message-ID: <500FB609.6030900@livinglogic.de> On 25.07.12 08:09, Ulrich Eckhardt wrote: > Am 24.07.2012 17:01, schrieb cpppwner at gmail.com: >> reader = codecs.getreader(encoding) >> lines = [] >> with open(filename, 'rb') as f: >> lines = reader(f, 'strict').readlines(keepends=False) >> >> where encoding == 'utf-16-be' >> Everything works fine, except that lines[0] is equal to >> codecs.BOM_UTF16_BE >> Is this behaviour correct, that the BOM is still present? > > Yes, assuming the first line only contains that BOM. Technically it's a > space character, and why should those be removed? If the first "character" in the file is a BOM the file encoding is probably not utf-16-be but utf-16. Servus, Walter From wxjmfauth at gmail.com Wed Jul 25 06:26:42 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 25 Jul 2012 03:26:42 -0700 (PDT) Subject: Python 2.6 StreamReader.readline() In-Reply-To: References: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> Message-ID: <721bbcde-4e0c-47bb-82e7-9f1ccfefb7f1@googlegroups.com> On Wednesday, July 25, 2012 11:02:01 AM UTC+2, Walter D?rwald wrote: > On 25.07.12 08:09, Ulrich Eckhardt wrote: > > > Am 24.07.2012 17:01, schrieb cpppwner at gmail.com: > >> reader = codecs.getreader(encoding) > >> lines = [] > >> with open(filename, 'rb') as f: > >> lines = reader(f, 'strict').readlines(keepends=False) > >> > >> where encoding == 'utf-16-be' > >> Everything works fine, except that lines[0] is equal to > >> codecs.BOM_UTF16_BE > >> Is this behaviour correct, that the BOM is still present? > > > > Yes, assuming the first line only contains that BOM. Technically it's a > > space character, and why should those be removed? > > If the first "character" in the file is a BOM the file encoding is > probably not utf-16-be but utf-16. > > Servus, > Walter The byte order mark, if present, is nothing else than an encoded >>> ud.name('\ufeff') 'ZERO WIDTH NO-BREAK SPACE' *code point*. Five "BOM" are possible (Unicode consortium). utf-8-sig, utf-16-be, utf-16-le, utf-32-be, utf-32-le. The codecs module provide many aliases. The fact that utf-16/32 does correspond to -le or to -be may vary according to the platforms, the compilers, ... >>> sys.version '3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]' >>> codecs.BOM_UTF16_BE b'\xfe\xff' >>> codecs.BOM_UTF16_LE b'\xff\xfe' >>> codecs.BOM_UTF16 b'\xff\xfe' >>> --- As far as I know, Py 2.7 or Py 3.2 never return a "BOM" when a file is read correctly. >>> with open('a-utf-16-be.txt', 'r', encoding='utf-16-be') as f: ... r = f.readlines() ... for zeile in r: ... print(zeile.rstrip()) ... abc ?l?ve c?ur ?uro >>> jmf From wxjmfauth at gmail.com Wed Jul 25 06:26:42 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 25 Jul 2012 03:26:42 -0700 (PDT) Subject: Python 2.6 StreamReader.readline() In-Reply-To: References: <65c7dc3b-3dce-45f2-981b-9c8171418f09@googlegroups.com> Message-ID: <721bbcde-4e0c-47bb-82e7-9f1ccfefb7f1@googlegroups.com> On Wednesday, July 25, 2012 11:02:01 AM UTC+2, Walter D?rwald wrote: > On 25.07.12 08:09, Ulrich Eckhardt wrote: > > > Am 24.07.2012 17:01, schrieb cpppwner at gmail.com: > >> reader = codecs.getreader(encoding) > >> lines = [] > >> with open(filename, 'rb') as f: > >> lines = reader(f, 'strict').readlines(keepends=False) > >> > >> where encoding == 'utf-16-be' > >> Everything works fine, except that lines[0] is equal to > >> codecs.BOM_UTF16_BE > >> Is this behaviour correct, that the BOM is still present? > > > > Yes, assuming the first line only contains that BOM. Technically it's a > > space character, and why should those be removed? > > If the first "character" in the file is a BOM the file encoding is > probably not utf-16-be but utf-16. > > Servus, > Walter The byte order mark, if present, is nothing else than an encoded >>> ud.name('\ufeff') 'ZERO WIDTH NO-BREAK SPACE' *code point*. Five "BOM" are possible (Unicode consortium). utf-8-sig, utf-16-be, utf-16-le, utf-32-be, utf-32-le. The codecs module provide many aliases. The fact that utf-16/32 does correspond to -le or to -be may vary according to the platforms, the compilers, ... >>> sys.version '3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]' >>> codecs.BOM_UTF16_BE b'\xfe\xff' >>> codecs.BOM_UTF16_LE b'\xff\xfe' >>> codecs.BOM_UTF16 b'\xff\xfe' >>> --- As far as I know, Py 2.7 or Py 3.2 never return a "BOM" when a file is read correctly. >>> with open('a-utf-16-be.txt', 'r', encoding='utf-16-be') as f: ... r = f.readlines() ... for zeile in r: ... print(zeile.rstrip()) ... abc ?l?ve c?ur ?uro >>> jmf From phihag at phihag.de Wed Jul 25 06:30:01 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Wed, 25 Jul 2012 12:30:01 +0200 Subject: from future import pass_function In-Reply-To: References: Message-ID: <500FCAA9.3080904@phihag.de> Unlike the print statement, pass has no overboarding complexity (like >>, printing tuples, etc.) - it just serves as a marker (and practicality beats purity). And you don't ever want to use pass as a value (say, for map() or the right side of an assignment). In fact, if pass were a function, users could construct strange code like x = pass() def pass(): raise Exception('Are you slacking off? Get back to work!') And don't forget that while the parentheses mainly confuse users, they're also making it harder to type, and feel like useless overhead (similar to the parentheses in if (x): ). In fact, I'd argue that if pass were a function, None would be the better placeholder: try: do_something() except: None # 2 hard-to-type (on a German keyboard) characters shorter # (and probably way faster: No function call overhead and no need # to actually find out what pass happens to be in this context) - Philipp On 07/25/2012 10:40 AM, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, > there could be a pass() function that does and returns nothing. > > Example: > def pass(): > return > > try: > do_something() > except: > pass() > > > One thing I don't like about this is the syntax > > class foo(object): > pass() > > > What do you think? > > Uli -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From nicholas.cole at gmail.com Wed Jul 25 06:33:24 2012 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Wed, 25 Jul 2012 11:33:24 +0100 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Wed, Jul 25, 2012 at 9:40 AM, Ulrich Eckhardt wrote: > What do you think? > I enjoyed the question, but actually I don't think this is a good idea. 1. If you really needed something like this, you could define it easily. def do_nothing(*args, **keywords): return None 2. If it were a built-in function, you would be able to override it, and then there would be chaos. Best, Nicholas From andrea.crotti.0 at gmail.com Wed Jul 25 06:46:04 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 25 Jul 2012 11:46:04 +0100 Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: 2012/7/23 Chris Angelico : > > That would probably be correct. However, I still think you may be > fighting against the language instead of playing to its strengths. > > I've never fiddled with sys.modules like that, but I know some have, > without problem. > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list I would also like to avoid this in general, but we have many subprocesses to launch and some of them might take weeks, so we need to have a process which is always running, because there is never a point in time where we can just say let's stop everything and start again.. Anyway if there are better solutions I'm still glad to hear them, but I would also like to keep it simple.. Another thing which now we need to figure out is how to communicate with the live process.. For example we might want to submit something manually, which should pass from the main process. The first idea is to have a separate process that opens a socket and listens for data on a local port, with a defined protocol. Then the main process can parse these commands and run them. Are there easier ways otherwise? From jeanpierreda at gmail.com Wed Jul 25 07:02:25 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 25 Jul 2012 07:02:25 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Wed, Jul 25, 2012 at 4:40 AM, Ulrich Eckhardt wrote: > What do you think? retort: def foo(): None -- Devin From jaroslav.dobrek at gmail.com Wed Jul 25 07:05:28 2012 From: jaroslav.dobrek at gmail.com (jaroslav.dobrek at gmail.com) Date: Wed, 25 Jul 2012 04:05:28 -0700 (PDT) Subject: catch UnicodeDecodeError Message-ID: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Hello, very often I have the following problem: I write a program that processes many files which it assumes to be encoded in utf-8. Then, some day, I there is a non-utf-8 character in one of several hundred or thousand (new) files. The program exits with an error message like this: UnicodeDecodeError: 'utf8' codec can't decode byte 0xe4 in position 60: invalid continuation byte I usually solve the problem by moving files around and by recoding them. What I really want to do is use something like try: # open file, read line, or do something else, I don't care except UnicodeDecodeError: sys.exit("Found a bad char in file " + file + " line " + str(line_number) Yet, no matter where I put this try-except, it doesn't work. How should I use try-except with UnicodeDecodeError? Jaroslav From pritamdas at teledna.com Wed Jul 25 07:29:52 2012 From: pritamdas at teledna.com (Pritam Das) Date: Wed, 25 Jul 2012 16:59:52 +0530 Subject: pexcept module Message-ID: <003001cd6a58$d11d5840$735808c0$@teledna.com> Is dere any good tutorial for pexcept module. Regards, Pritam Das Lead Engineer | pritamdas at teledna.com | www.teledna.com M: +91-7278039994 | P: 080-66661130 | F: 080-66661132 ISO 9001:2008 Certified ---------------------------------------------------------------------------- ----------------------------------- TeleDNA Communications Private Limited No. 23 & 24, 2nd Floor, AMR Tech Park, Hosur Road, Bangalore - 560 068 (India), For Disclaimer Please visit: http://www.teledna.com/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Wed Jul 25 07:33:26 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 25 Jul 2012 11:33:26 GMT Subject: from future import pass_function References: Message-ID: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 25 Jul 2012 10:40:45 +0200, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, [...] > try: > do_something() > except: > pass() What's the point of this? If you intend to do nothing, why call a function instead? There's a surprising amount of effort involved behind the scenes in calling a function. Python has to: 1) look up the function's name to get access to the function object 2) push any arguments onto the stack 3) determine the function object's type 4) look up its __call__ method 5) match the arguments (if any) with the parameter list (if any) 6) execute the function body 7) push the return result (None) onto the stack in case it's needed 8) and pop it off the stack. Turning pass into a function instead of a statement would essentially take something that does *nothing at all* into something that (figuratively speaking) jumps up to its feet, runs around the room three times, and then sits back down again. -- Steven From bahamutzero8825 at gmail.com Wed Jul 25 07:34:53 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 25 Jul 2012 06:34:53 -0500 Subject: catch UnicodeDecodeError In-Reply-To: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: <500FD9DD.7090003@gmail.com> On 7/25/2012 6:05 AM, jaroslav.dobrek at gmail.com wrote: > What I really want to do is use something like > > try: > # open file, read line, or do something else, I don't care > except UnicodeDecodeError: > sys.exit("Found a bad char in file " + file + " line " + str(line_number) > > Yet, no matter where I put this try-except, it doesn't work. > > How should I use try-except with UnicodeDecodeError? The same way you handle any other exception. The traceback will tell you the exact line that raised the exception. It helps us help you if you include the full traceback and give more detail than "it doesn't work". -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From phihag at phihag.de Wed Jul 25 07:35:09 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Wed, 25 Jul 2012 13:35:09 +0200 Subject: catch UnicodeDecodeError In-Reply-To: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: <500FD9ED.9060602@phihag.de> Hi Jaroslav, you can catch a UnicodeDecodeError just like any other exception. Can you provide a full example program that shows your problem? This works fine on my system: import sys open('tmp', 'wb').write(b'\xff\xff') try: buf = open('tmp', 'rb').read() buf.decode('utf-8') except UnicodeDecodeError as ude: sys.exit("Found a bad char in file " + "tmp") Note that you cannot possibly determine the line number if you don't know what encoding the file is in (and what EOL it uses). What you can do is count the number of bytes with the value 10 before ude.start, like this: lineGuess = buf[:ude.start].count(b'\n') + 1 - Philipp On 07/25/2012 01:05 PM, jaroslav.dobrek at gmail.com wrote: > it doesn't work -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From jaroslav.dobrek at gmail.com Wed Jul 25 08:09:40 2012 From: jaroslav.dobrek at gmail.com (jaroslav.dobrek at gmail.com) Date: Wed, 25 Jul 2012 05:09:40 -0700 (PDT) Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: > Hi Jaroslav, > > you can catch a UnicodeDecodeError just like any other exception. Can > you provide a full example program that shows your problem? > > This works fine on my system: > > > import sys > open('tmp', 'wb').write(b'\xff\xff') > try: > buf = open('tmp', 'rb').read() > buf.decode('utf-8') > except UnicodeDecodeError as ude: > sys.exit("Found a bad char in file " + "tmp") > Thank you. I got it. What I need to do is explicitly decode text. But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. What I am missing (especially for Python3) is something like: try: for line in sys.stdin: except UnicodeDecodeError: sys.exit("Encoding problem in line " + str(line_number)) I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. From jaroslav.dobrek at gmail.com Wed Jul 25 08:09:40 2012 From: jaroslav.dobrek at gmail.com (jaroslav.dobrek at gmail.com) Date: Wed, 25 Jul 2012 05:09:40 -0700 (PDT) Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: > Hi Jaroslav, > > you can catch a UnicodeDecodeError just like any other exception. Can > you provide a full example program that shows your problem? > > This works fine on my system: > > > import sys > open('tmp', 'wb').write(b'\xff\xff') > try: > buf = open('tmp', 'rb').read() > buf.decode('utf-8') > except UnicodeDecodeError as ude: > sys.exit("Found a bad char in file " + "tmp") > Thank you. I got it. What I need to do is explicitly decode text. But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. What I am missing (especially for Python3) is something like: try: for line in sys.stdin: except UnicodeDecodeError: sys.exit("Encoding problem in line " + str(line_number)) I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. From andrea.crotti.0 at gmail.com Wed Jul 25 09:56:42 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 25 Jul 2012 14:56:42 +0100 Subject: Dumping all the sql statements as backup Message-ID: I have some long running processes that do very long simulations which at the end need to write things on a database. At the moment sometimes there are network problems and we end up with half the data on the database. The half-data problem is probably solved easily with sessions and sqlalchemy (a db-transaction), but still we would like to be able to keep a backup SQL file in case something goes badly wrong and we want to re-run it manually.. This might also be useful if we have to rollback the db for some reasons to a previous day and we don't want to re-run the simulations.. Anyone did something similar? It would be nice to do something like: with CachedDatabase('backup.sql'): # do all your things From tdldev at gmail.com Wed Jul 25 10:52:45 2012 From: tdldev at gmail.com (Jack) Date: Wed, 25 Jul 2012 10:52:45 -0400 Subject: Dumping all the sql statements as backup In-Reply-To: References: Message-ID: <5010083D.4080307@gmail.com> On 07/25/2012 09:56 AM, andrea crotti wrote: > I have some long running processes that do very long simulations which > at the end need to write things on a database. > > At the moment sometimes there are network problems and we end up with > half the data on the database. > > The half-data problem is probably solved easily with sessions and > sqlalchemy (a db-transaction), but still we would like to be able to > keep a backup SQL file in case something goes badly wrong and we want to > re-run it manually.. > > This might also be useful if we have to rollback the db for some reasons > to a previous day and we don't want to re-run the simulations.. > > Anyone did something similar? > It would be nice to do something like: > > with CachedDatabase('backup.sql'): > # do all your things > Since you know the content of what the sql code is, why not just build the sql file(s) needed and store them so that in case of a burp you can just execute the code file. If you don't know the exact sql code, dump it to a file as the statements are constructed... The only problem you would run into in this scenario is duplicate data, which is also easily solvable by using transaction-level commits to the db. From ian.g.kelly at gmail.com Wed Jul 25 11:21:50 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 25 Jul 2012 09:21:50 -0600 Subject: =?windows-1252?B?UmU6IHRoZSBtZWFuaW5nIG9mIHLvvpUuLi4uLi4u774=?= In-Reply-To: <87lii8sfmw.fsf@benfinney.id.au> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <87r4s1rzv2.fsf@benfinney.id.au> <45c8f299-3420-4836-afcb-6e07957ba344@googlegroups.com> <87lii8sfmw.fsf@benfinney.id.au> Message-ID: On Tue, Jul 24, 2012 at 9:07 PM, Ben Finney wrote: > +1 on celebrating ? day! Also: http://tauday.com/ From andrea.crotti.0 at gmail.com Wed Jul 25 11:31:43 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Wed, 25 Jul 2012 16:31:43 +0100 Subject: Dumping all the sql statements as backup In-Reply-To: <5010083D.4080307@gmail.com> References: <5010083D.4080307@gmail.com> Message-ID: 2012/7/25 Jack Since you know the content of what the sql code is, why not just build > the sql file(s) needed and store them so that in case of a burp you can > just execute the code file. If you don't know the exact sql code, dump > it to a file as the statements are constructed... The only problem you > would run into in this scenario is duplicate data, which is also easily > solvable by using transaction-level commits to the db. > -- > http://mail.python.org/mailman/listinfo/python-list Yes but how do I construct them with SqlAlchemy? One possible option I found is to enable the logging of some parts of SqlAlchemy, and use that log, (echo=True in create_engine does something similar) but maybe there is a better option.. But I need to filter only the insert/update/delete probably.. And in general the processes have to run independently so in case of database connection problems I would just let them retry until it actually works. When the transaction actually works then in the backed up log I can add a marker(or archive the log), to avoid replaying it. From subhabangalore at gmail.com Wed Jul 25 11:58:40 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Wed, 25 Jul 2012 08:58:40 -0700 (PDT) Subject: HMM and CRF Package In-Reply-To: References: Message-ID: On Tuesday, July 24, 2012 9:09:02 PM UTC+5:30, (unknown) wrote: > Dear Group, > > I was looking for the following solutions. > > (i) a Python Hidden Markov Model(HMM) library. > (ii)a Python Conditional Random Field(CRF) library. > (iii) I am using Python 3.2.1 on Windows 7(64 bit) and also like to get a NLTK version. > (iv) I may use unicode character as input. > > If any one may kindly help me out. > > Best Regards, > Subhabrata Banerjee. > Gurgaon. > India. Dear Group, I worked out a solution. As most of the libraries give so many bindings and conditions best way is to make it. Not very tough, I made earlier, but as some files were lost so was thinking instead of a remake if ready versions work. Or may look change from Python 3 to previous version so when 3 will be supported solution. But can I install both Python 3 and Python2.x or call 2.x from 3.x? Regards, Subhabrata. From rosuav at gmail.com Wed Jul 25 12:05:39 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 26 Jul 2012 02:05:39 +1000 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Wed, Jul 25, 2012 at 6:40 PM, Ulrich Eckhardt wrote: > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, there > could be a pass() function that does and returns nothing. > > Example: > def pass(): > return > > try: > do_something() > except: > pass() Except that "pass" is a syntactic construct that basically says "hey, I have an indented block here, but there's no code in it". It's not executable any more than the syntactic token "INDENT" is. It's more closely related to the colon at the end of "try" than it is to the "do_something()" call. By comparison, Python 2's print statement is executable. It causes real action to happen at run-time. It makes sense to pass "print" as an argument to something; for instance: def some_generator(): yield blah map(print,some_generator()) Simple way of making the iterator display its yielded result. I cannot imagine any circumstance in which you'd want to map "pass" over everything. But then, as Teresa said, I'm only one, and possibly I'm wrong! ChrisA From ethan at stoneleaf.us Wed Jul 25 12:28:29 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 25 Jul 2012 09:28:29 -0700 Subject: from future import pass_function In-Reply-To: References: Message-ID: <50101EAD.5040406@stoneleaf.us> Ulrich Eckhardt wrote: > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, > there could be a pass() function that does and returns nothing. > > Example: > def pass(): > return > > try: > do_something() > except: > pass() Do you have a use case where `pass()` works but `pass` doesn't? ~Ethan~ From jeanpierreda at gmail.com Wed Jul 25 12:48:15 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 25 Jul 2012 12:48:15 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Wed, Jul 25, 2012 at 12:05 PM, Chris Angelico wrote: > Simple way of making the iterator display its yielded result. I cannot > imagine any circumstance in which you'd want to map "pass" over > everything. But then, as Teresa said, I'm only one, and possibly I'm > wrong! True. But it might be nice to use pass both in lambdas and regular functions, or to use pass as a variable name. (Unfortunately, these two niceties are somewhat in conflict.) -- Devin From sp at abusix.org Wed Jul 25 13:47:59 2012 From: sp at abusix.org (Simon Pirschel) Date: Wed, 25 Jul 2012 19:47:59 +0200 Subject: append in IMAP4 from imaplib very slow Message-ID: <5010314F.80001@abusix.com> Hi, I'm currently experimenting with IMAP using Python 2.7.3 and IMAP4 from imaplib. I noticed the performance to be very bad. I read 5000 files from a directory and append them to an IMAP INBOX. The hole procedure of reading and appending is taking about 210 seconds. I set up the exact same code in Perl to check if there is a general IMAP server configuration issue, since CPU and I/O isn't the problem. The same amount of data on the same IMAP server is done after 7.9 seconds using Perl. The difference is huge and I tried to narrow the issue down by profiling the Python code. The profile results are, 206 seconds are spent in calling socket.recv. Python Code: http://pastebin.com/d2c9d4Dx Profile Result: http://pastebin.com/rWCS8tAz Perl Code: http://pastebin.com/ZV3Yv74d Maybe someone can explain what's the problem, or help me debugging the issue. Thanks, Simon -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Wed Jul 25 14:14:31 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 25 Jul 2012 12:14:31 -0600 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Jul 25, 2012 10:51 AM, "Devin Jeanpierre" wrote: > True. But it might be nice to use pass both in lambdas and regular > functions, or to use pass as a variable name. You can already use pass (or the equivalent) in a lambda. lambda: None -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Wed Jul 25 14:17:59 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 25 Jul 2012 14:17:59 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Wed, Jul 25, 2012 at 2:14 PM, Ian Kelly wrote: > You can already use pass (or the equivalent) in a lambda. > > lambda: None This lacks my foolish consistency. -- Devin From d at davea.name Wed Jul 25 14:50:18 2012 From: d at davea.name (Dave Angel) Date: Wed, 25 Jul 2012 14:50:18 -0400 Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: <50103FEA.5050603@davea.name> On 07/25/2012 08:09 AM, jaroslav.dobrek at gmail.com wrote: > On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: >> Hi Jaroslav, >> >> you can catch a UnicodeDecodeError just like any other exception. Can >> you provide a full example program that shows your problem? >> >> This works fine on my system: >> >> >> import sys >> open('tmp', 'wb').write(b'\xff\xff') >> try: >> buf = open('tmp', 'rb').read() >> buf.decode('utf-8') >> except UnicodeDecodeError as ude: >> sys.exit("Found a bad char in file " + "tmp") >> > Thank you. I got it. What I need to do is explicitly decode text. > > But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. > > What I am missing (especially for Python3) is something like: > > try: > for line in sys.stdin: > except UnicodeDecodeError: > sys.exit("Encoding problem in line " + str(line_number)) > > I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. i can't understand your question. if the problem is that the system doesn't magically produce a variable called line_number, then generate it yourself, by counting in the loop. Don't forget that you can tell the unicode decoder to ignore bad characters, or to convert them to a specified placeholder. -- DaveA From tjreedy at udel.edu Wed Jul 25 15:58:50 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Jul 2012 15:58:50 -0400 Subject: HMM and CRF Package In-Reply-To: References: Message-ID: On 7/25/2012 11:58 AM, subhabangalore at gmail.com wrote: > As most of the libraries give so many bindings and conditions best way is to make it. Not very tough, I made earlier, but as some files were lost so was thinking instead of a remake if ready versions work. Or may look change from Python 3 to previous version so when 3 will be supported solution. But can I install both Python 3 and Python2.x or call 2.x from 3.x? You can have multiple versions of Python installed. Just be careful on *nix to use altinstall so as to not disturb the system install used by the system. Pythonx.y can only use code that works with x.y ;=). However, any Python process can use any other program via the subprocess module. You just have to work out the data transfer. -- Terry Jan Reedy From solipsis at pitrou.net Wed Jul 25 19:57:55 2012 From: solipsis at pitrou.net (Antoine Pitrou) Date: Wed, 25 Jul 2012 23:57:55 +0000 (UTC) Subject: append in IMAP4 from imaplib very slow References: <5010314F.80001@abusix.com> Message-ID: Simon Pirschel abusix.org> writes: > > Hi, > I'm currently experimenting with IMAP using Python 2.7.3 and IMAP4 > from imaplib. I noticed the performance to be very bad. I read 5000 > files from a directory and append them to an IMAP INBOX. The hole > procedure of reading and appending is taking about 210 seconds. > I set up the exact same code in Perl to check if there is a general > IMAP server configuration issue, since CPU and I/O isn't the > problem. The same amount of data on the same IMAP server is done > after 7.9 seconds using Perl. > The difference is huge and I tried to narrow the issue down by > profiling the Python code. > The profile results are, 206 seconds are spent in calling > socket.recv. This just means that most of the time is spent waiting for the server to reply. Perhaps the Perl and Python IMAP libraries use different IMAP commands for appending? Regards Antoine. -- Software development and contracting: http://pro.pitrou.net From rridge at csclub.uwaterloo.ca Wed Jul 25 21:42:18 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 25 Jul 2012 21:42:18 -0400 Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Ulrich Eckhardt wrote: > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, [...] > try: > do_something() > except: > pass() Steven D'Aprano wrote: >What's the point of this? Remember everything you've said about why its a good thing the that print statement is now a function? That. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From steve+comp.lang.python at pearwood.info Wed Jul 25 22:38:49 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Jul 2012 02:38:49 GMT Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 25 Jul 2012 21:42:18 -0400, Ross Ridge wrote: > Ulrich Eckhardt wrote: >> I just had an idea, it occurred to me that the pass statement is pretty >> similar to the print statement, > [...] >> try: >> do_something() >> except: >> pass() > > Steven D'Aprano wrote: >>What's the point of this? > > Remember everything you've said about why its a good thing the that > print statement is now a function? That. I can't believe I actually have to point this out explicitly, but pass is not print. Apart from them both starting with the letter "P", they are nothing alike. There are good reasons for making print a function, and they don't apply to pass because pass doesn't do what print does. The examples of pass-as-a-function shown by the Original Poster don't give any clue of what advantage there is to make pass a function. It appears that the only reason for this suggested change is that he would rather write "pass()" instead of "pass", possibly because he thinks it looks cool. (Actually, I reckon that what is driving this idea is that the OP is a beginner, and he's got a syntax error a few times from writing "pass()", and so he thought it would be easier to force other people to change tens or hundreds of thousands of Python programs to use "pass()" instead of "pass" than to just learn to stop putting parentheses after it. I remember what it was like to be a beginner with six weeks experience in a twenty year old language, full of shiny new ideas for "improving" it.) But of course I could be wrong. Ulrich, if you are still reading this, if you have good examples for how pass as a function would actually be better, and how it will let you do things in Python that can't easily be done now, I'm very interested to hear them. Who knows, if the idea is good enough, some day it may even happen. -- Steven From python.list at tim.thechases.com Wed Jul 25 23:21:25 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Jul 2012 22:21:25 -0500 Subject: append in IMAP4 from imaplib very slow In-Reply-To: <5010314F.80001@abusix.com> References: <5010314F.80001@abusix.com> Message-ID: <5010B7B5.5040206@tim.thechases.com> On 07/25/12 12:47, Simon Pirschel wrote: > I'm currently experimenting with IMAP using Python 2.7.3 and > IMAP4 from imaplib. I noticed the performance to be very bad. I > read 5000 files from a directory and append them to an IMAP > INBOX. The hole procedure of reading and appending is taking > about 210 seconds. > > I set up the exact same code in Perl to check if there is a > general IMAP server configuration issue, since CPU and I/O isn't > the problem. The same amount of data on the same IMAP server is > done after 7.9 seconds using Perl. > > The difference is huge and I tried to narrow the issue down by > profiling the Python code. The profile results are, 206 seconds > are spent in calling socket.recv. While I don't know the ins and outs of the Perl code, it looks like the Python imaplib.py is doing some pretty straight-forward send/receive work. However, IMAP4 does support both pipelining and multi-append extensions, so if the Perl code takes advantage of the features if the server offers them, it might be reaping significant gains over the na?ve Python code. Can you get a debugging dump of the commands being sent each way? (particularly if you see a bunch of APPEND commands before the reply acknowledgement, as detailed at [1]) -tkc [1] http://www.ietf.org/rfc/rfc3502.txt on page 4 From rridge at csclub.uwaterloo.ca Wed Jul 25 23:30:12 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 25 Jul 2012 23:30:12 -0400 Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >What's the point of this? Ross Ridge wrote: > Remember everything you've said about why its a good thing the that > print statement is now a function? That. Steven D'Aprano wrote: >I can't believe I actually have to point this out explicitly, but pass is >not print. Apart from them both starting with the letter "P", they are >nothing alike. There are good reasons for making print a function, and >they don't apply to pass because pass doesn't do what print does. No, they're very much alike. That's why all your arguments for print as function also apply just as well to pass a function. Your arguments had very little to do what what print actually did. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From thiebaud at weksteen.fr Wed Jul 25 23:47:24 2012 From: thiebaud at weksteen.fr (=?UTF-8?Q?Thi=C3=A9baud_Weksteen?=) Date: Thu, 26 Jul 2012 13:47:24 +1000 Subject: ssl: add =?UTF-8?Q?msg=5Fcallback?= Message-ID: <35c62d1b461a1b016ff18a3ba2f7936e@localhost> Hi python-list, I wrote a patch for Python 3.2.3 to expose the function SSL_CTX_set_msg_callback in the module _ssl. I was actually surprise this function was not already in the standard library as it is really handy: "SSL_CTX_set_msg_callback() or SSL_set_msg_callback() can be used to define a message callback function cb for observing all SSL/TLS protocol messages (such as handshake messages) that are received or sent." Here is the patch: https://github.com/tweksteen/abrupt-usecase/blob/master/python-ssl-3.2.3.patch Let me know your opinion on that. Does it worth being included? Thi?baud From rosuav at gmail.com Wed Jul 25 23:53:20 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 26 Jul 2012 13:53:20 +1000 Subject: from future import pass_function In-Reply-To: References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Jul 26, 2012 at 1:30 PM, Ross Ridge wrote: > Steven D'Aprano wrote: >>I can't believe I actually have to point this out explicitly, but pass is >>not print. Apart from them both starting with the letter "P", they are >>nothing alike. There are good reasons for making print a function, and >>they don't apply to pass because pass doesn't do what print does. > > No, they're very much alike. That's why all your arguments for print > as function also apply just as well to pass a function. Your arguments > had very little to do what what print actually did. Except that print / print() is executable. Execution proceeds through your code, comes to a "print", and goes off to handle that, then comes back to your code. But "pass" doesn't have code attached to it. Why should it be a function? One of the reasons for print becoming a function was its strange collection of modifiers. How do you, with the print statement, send output to someplace other than stdout? How do you make it not put a newline? Far more logical to make those into keyword-only arguments to a function, and far easier to later add more such options. What parameters do you give to "pass"? The pass keyword exists because Python can't have an empty pair of braces, or an empty semicolon, to represent a "null statement". It needs a keyword. That keyword is syntax, not code. ChrisA From rridge at csclub.uwaterloo.ca Thu Jul 26 00:03:55 2012 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 26 Jul 2012 00:03:55 -0400 Subject: from future import pass_function References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Ross Ridge wrote: > No, they're very much alike. That's why all your arguments for print > as function also apply just as well to pass a function. Your arguments > had very little to do what what print actually did. Chris Angelico wrote: >Except that print / print() is executable. Execution proceeds through >your code, comes to a "print", and goes off to handle that, then comes >back to your code. But "pass" doesn't have code attached to it. Why >should it be a function? For consistancy with print. What it does doesn't matter any more than what print did mattered. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From wuwei23 at gmail.com Thu Jul 26 00:17:12 2012 From: wuwei23 at gmail.com (alex23) Date: Wed, 25 Jul 2012 21:17:12 -0700 (PDT) Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0e861f99-f3ee-4721-8274-cc8fa26d87d5@c4g2000pba.googlegroups.com> On Jul 26, 11:42?am, Ross Ridge wrote: > Remember everything you've said about why its a good thing the that > print statement is now a function? ?That. You regularly have the need to override the behaviour of pass? Are you _really_ saying you see no distinction between an application- level function and a low-level command directed at the interpreter? From wuwei23 at gmail.com Thu Jul 26 00:20:35 2012 From: wuwei23 at gmail.com (alex23) Date: Wed, 25 Jul 2012 21:20:35 -0700 (PDT) Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Jul 26, 1:30?pm, Ross Ridge wrote: > No, they're very much alike. Repetition isn't evidence. You keep making this claim, so support it. > That's why all your arguments for print > as function also apply just as well to pass a function. ?Your arguments > had very little to do what what print actually did. As far as I can see, the only arguments Steven made were against pass as a function, with an illustration of the function call cost that pass-as-function would incur. Your arguments, on the other hand, amount to nothing more than "nuh uh!" From ethan at stoneleaf.us Thu Jul 26 00:32:33 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 25 Jul 2012 21:32:33 -0700 Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5010C861.1000206@stoneleaf.us> Ross Ridge wrote: > Ross Ridge wrote: >> No, they're very much alike. That's why all your arguments for print >> as function also apply just as well to pass a function. Your arguments >> had very little to do what what print actually did. > > Chris Angelico wrote: >> Except that print / print() is executable. Execution proceeds through >> your code, comes to a "print", and goes off to handle that, then comes >> back to your code. But "pass" doesn't have code attached to it. Why >> should it be a function? > > For consistancy with print. What it does doesn't matter any more than > what print did mattered. Of course what print did mattered. `print` was not changed to `print()` because a function looks cooler; it was changed because it does stuff, and what it does could be changed with parameters, and overriding it with your own custom thingie was a useful thing to do. What code does `pass` run? When do we pass parameters to `pass`? When do we need to override `pass`? Answers: None. Never. Still waiting for a reply from the OP for a use case. How does that quote go? "A foolish consistency is the hobgoblin of little minds"? This definitely fits that category. ~Ethan~ From rustompmody at gmail.com Thu Jul 26 01:09:38 2012 From: rustompmody at gmail.com (Rusi) Date: Wed, 25 Jul 2012 22:09:38 -0700 (PDT) Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <88c98ac0-5b44-4392-bd0c-8d9007047a52@f9g2000pbd.googlegroups.com> Ulrich: If you take a look at pep 3105 you find five rationales. http://www.python.org/dev/peps/pep-3105/#rationale If the first were the only one then your suggestion would have merit. There are also the other 4 in which pass and print dont really correspond. Steven wrote earlier: > I have an axe that has been passed down for generations through my > family, from my father, his father before him, and his father, and his > father before him. Occasionally we replace the handle, or put on a new > head, but that axe is almost as good as the day my great-great- > grandfather made it. Yeah I see that you are always wielding your great-great-grandfather's axe. As for example On Jul 26, 7:38 am, Steven D'Aprano wrote: > (Actually, I reckon that what is driving this idea is that the OP is a > beginner, and he's got a syntax error a few times from writing "pass()", > and so he thought it would be easier to force other people to change tens > or hundreds of thousands of Python programs to use "pass()" instead of > "pass" than to just learn to stop putting parentheses after it. I > remember what it was like to be a beginner with six weeks experience in a > twenty year old language, full of shiny new ideas for "improving" it.) Do you sharpen it sometimes? From mhrivnak at hrivnak.org Thu Jul 26 01:20:57 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Thu, 26 Jul 2012 01:20:57 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: If we want pass(), then why not break() and continue()? And also def() and class()? for(), while(), if(), with(), we can make them all callable objects! Except that they are control statements. They are not objects, they have no type, and they can never be evaluated in an expression. And most importantly, there is no value to be gained by making them objects. It is valuable for a language to have control statements, as others have already explained. This is an interesting exercise to think about what their nature is, but at the end of the day, embrace them for what they are. Michael On Wed, Jul 25, 2012 at 4:40 AM, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, there > could be a pass() function that does and returns nothing. > > Example: > def pass(): > return > > try: > do_something() > except: > pass() > > > One thing I don't like about this is the syntax > > class foo(object): > pass() > > > What do you think? > > Uli > -- > http://mail.python.org/mailman/listinfo/python-list From clp2 at rebertia.com Thu Jul 26 01:56:18 2012 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 25 Jul 2012 22:56:18 -0700 Subject: ssl: add msg_callback In-Reply-To: <35c62d1b461a1b016ff18a3ba2f7936e@localhost> References: <35c62d1b461a1b016ff18a3ba2f7936e@localhost> Message-ID: On Wed, Jul 25, 2012 at 8:47 PM, Thi?baud Weksteen wrote: > > Hi python-list, > > I wrote a patch for Python 3.2.3 to expose the function > SSL_CTX_set_msg_callback in the module _ssl. > > I was actually surprise this function was not already in the > standard library as it is really handy: Well, the underscore in the module name indicates that such modules are private implementation details, hence why _ssl is undocumented. > "SSL_CTX_set_msg_callback() or SSL_set_msg_callback() can be used > to define a message callback function cb for observing all SSL/TLS > protocol messages (such as handshake messages) that are received or sent." > > Here is the patch: > > https://github.com/tweksteen/abrupt-usecase/blob/master/python-ssl-3.2.3.patch > > Let me know your opinion on that. Does it worth being included? python-dev would probably be the best place to ask, since they have the ultimate say on whether to accept your patch: http://mail.python.org/mailman/listinfo/python-dev/ and/or you can file a bug in the tracker with your patch attached: http://bugs.python.org/ On the face of it, the feature sounds fairly useful for debugging. Cheers, Chris From ulrich.eckhardt at dominolaser.com Thu Jul 26 02:39:25 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 26 Jul 2012 08:39:25 +0200 Subject: from future import pass_function In-Reply-To: References: Message-ID: Am 25.07.2012 18:05, schrieb Chris Angelico: > By comparison, Python 2's print statement is executable. It causes > real action to happen at run-time. It makes sense to pass "print" as > an argument to something; for instance: > > def some_generator(): > yield blah > > map(print,some_generator()) > > Simple way of making the iterator display its yielded result. I cannot > imagine any circumstance in which you'd want to map "pass" over > everything. I have seen code that just created a list comprehension to iterate over something but was discarding the results. That could be a case for a "do nothing" function. Just having a function that does nothing would be useful in other places, too. In some cases, you want to print() some debug output in other cases you just use pass() to discard the debug output. Uli From ulrich.eckhardt at dominolaser.com Thu Jul 26 02:42:19 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 26 Jul 2012 08:42:19 +0200 Subject: from future import pass_function In-Reply-To: References: Message-ID: Am 26.07.2012 07:20, schrieb Michael Hrivnak: > If we want pass(), then why not break() and continue()? And also > def() and class()? for(), while(), if(), with(), we can make them all > callable objects! > > Except that they are control statements. They are not objects, they > have no type, and they can never be evaluated in an expression. And > most importantly, there is no value to be gained by making them > objects. pass is not a control statement, it is just a placeholder to make it explicit that there is nothing else to be expected here. Uli From ulrich.eckhardt at dominolaser.com Thu Jul 26 02:59:30 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 26 Jul 2012 08:59:30 +0200 Subject: from future import pass_function In-Reply-To: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 26.07.2012 04:38, schrieb Steven D'Aprano: > The examples of pass-as-a-function shown by the Original Poster don't > give any clue of what advantage there is to make pass a function. Just read the text, it just struck me how similar pass and print are, i.e. that neither actually needs to be a keyword. In some cases, I would rather use "return" to replace "pass" though. > It appears that the only reason for this suggested change is that he > would rather write "pass()" instead of "pass", possibly because he > thinks it looks cool. I have no idea where you got the "cool" from, it is not in my posting. I stated clearly that "I just had an idea", which should signal that I haven't thought about this for any extended period of time. Then I asked "What do you think?" exactly because I wanted to discuss this. No need to get defensive. ;) > (Actually, I reckon that what is driving this idea is that the OP is a > beginner, and he's got a syntax error a few times from writing "pass()", > and so he thought it would be easier to force other people to change tens > or hundreds of thousands of Python programs to use "pass()" instead of > "pass" than to just learn to stop putting parentheses after it. So, and in order to force people to write parens or break their code I have considered the possibility of importing that feature from __future__ for those people that want it? Seriously, Steven, as much as I like your regular contributions here, this time you had better logged off and taken a walk, because you come across as _very_ arrogant here. > But of course I could be wrong. Ulrich, if you are still reading this, if > you have good examples for how pass as a function would actually be > better, and how it will let you do things in Python that can't easily be > done now, I'm very interested to hear them. Who knows, if the idea is > good enough, some day it may even happen. No there is nothing that you strictly need a pass() function for. In summary, after reading this thread I have a lot of good arguments against this idea and few arguments supporting the idea. In any case I have many more arguments than those that I came up with myself, which is exactly what I asked for. Thanks to all that took part in this discussion! Uli From breamoreboy at yahoo.co.uk Thu Jul 26 03:43:48 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 26 Jul 2012 08:43:48 +0100 Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 26/07/2012 05:03, Ross Ridge wrote: > Ross Ridge wrote: >> No, they're very much alike. That's why all your arguments for print >> as function also apply just as well to pass a function. Your arguments >> had very little to do what what print actually did. > > Chris Angelico wrote: >> Except that print / print() is executable. Execution proceeds through >> your code, comes to a "print", and goes off to handle that, then comes >> back to your code. But "pass" doesn't have code attached to it. Why >> should it be a function? > > For consistancy with print. What it does doesn't matter any more than > what print did mattered. > > Ross Ridge > My all time favourite engineering quote, from the UK Ptarmigan tactical communications project, springs to my mind here regarding your comments about the comparison of print and pass. "I might not be a mechanical engineer, but that's fucking wrong". -- Cheers. Mark Lawrence. From jaroslav.dobrek at gmail.com Thu Jul 26 03:46:27 2012 From: jaroslav.dobrek at gmail.com (Jaroslav Dobrek) Date: Thu, 26 Jul 2012 00:46:27 -0700 (PDT) Subject: catch UnicodeDecodeError References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> On Jul 25, 8:50?pm, Dave Angel wrote: > On 07/25/2012 08:09 AM, jaroslav.dob... at gmail.com wrote: > > > > > > > > > > > On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: > >> Hi Jaroslav, > > >> you can catch a UnicodeDecodeError just like any other exception. Can > >> you provide a full example program that shows your problem? > > >> This works fine on my system: > > >> import sys > >> open('tmp', 'wb').write(b'\xff\xff') > >> try: > >> ? ? buf = open('tmp', 'rb').read() > >> ? ? buf.decode('utf-8') > >> except UnicodeDecodeError as ude: > >> ? ? sys.exit("Found a bad char in file " + "tmp") > > > Thank you. I got it. What I need to do is explicitly decode text. > > > But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. > > > What I am missing (especially for Python3) is something like: > > > try: > > ? ? for line in sys.stdin: > > except UnicodeDecodeError: > > ? ? sys.exit("Encoding problem in line " + str(line_number)) > > > I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. > > i can't understand your question. ?if the problem is that the system > doesn't magically produce a variable called line_number, then generate > it yourself, by counting > in the loop. That was just a very incomplete and general example. My problem is solved. What I need to do is explicitly decode text when reading it. Then I can catch exceptions. I might do this in future programs. I dislike about this solution that it complicates most programs unnecessarily. In programs that open, read and process many files I don't want to explicitly decode and encode characters all the time. I just want to write: for line in f: or something like that. Yet, writing this means to *implicitly* decode text. And, because the decoding is implicit, you cannot say try: for line in f: # here text is decoded implicitly do_something() except UnicodeDecodeError(): do_something_different() This isn't possible for syntactic reasons. The problem is that vast majority of the thousands of files that I process are correctly encoded. But then, suddenly, there is a bad character in a new file. (This is so because most files today are generated by people who don't know that there is such a thing as encodings.) And then I need to rewrite my very complex program just because of one single character in one single file. From sp at abusix.org Thu Jul 26 03:49:29 2012 From: sp at abusix.org (Simon Pirschel) Date: Thu, 26 Jul 2012 09:49:29 +0200 Subject: append in IMAP4 from imaplib very slow In-Reply-To: <5010B7B5.5040206@tim.thechases.com> References: <5010314F.80001@abusix.com> <5010B7B5.5040206@tim.thechases.com> Message-ID: <5010F689.8090701@abusix.com> On 07/26/2012 05:21 AM, Tim Chase wrote: > On 07/25/12 12:47, Simon Pirschel wrote: >> I'm currently experimenting with IMAP using Python 2.7.3 and >> IMAP4 from imaplib. I noticed the performance to be very bad. I >> read 5000 files from a directory and append them to an IMAP >> INBOX. The hole procedure of reading and appending is taking >> about 210 seconds. >> >> I set up the exact same code in Perl to check if there is a >> general IMAP server configuration issue, since CPU and I/O isn't >> the problem. The same amount of data on the same IMAP server is >> done after 7.9 seconds using Perl. >> >> The difference is huge and I tried to narrow the issue down by >> profiling the Python code. The profile results are, 206 seconds >> are spent in calling socket.recv. > While I don't know the ins and outs of the Perl code, it looks like > the Python imaplib.py is doing some pretty straight-forward > send/receive work. However, IMAP4 does support both pipelining and > multi-append extensions, so if the Perl code takes advantage of the > features if the server offers them, it might be reaping significant > gains over the na?ve Python code. > > Can you get a debugging dump of the commands being sent each way? > (particularly if you see a bunch of APPEND commands before the reply > acknowledgement, as detailed at [1]) > > -tkc > > [1] > http://www.ietf.org/rfc/rfc3502.txt on page 4 > I took a strace of all network related sys calls from Python and Perl. It seems both don't do multi appends and waiting for the OK after appending one mail. But the Python version is getting a completely different response. Python: "* 204 EXISTS\r\n* 1 RECENT\r\nNBGC3 OK [APPENDUID 1343283946 204] Append completed.\r\n" Perl: "2 OK [APPENDUID 1343283946 255] Append completed.\r\n" The Python lib seems to trigger a EXISTS and RECENT lookup on every append, which could be the performance difference. I couldn't figure out why, yet! Python strace: http://aboutsimon.com/py.strace Perl strace: http://aboutsimon.com/pl.strace Strings are shortened to 40 chars. Simon -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu Jul 26 03:50:02 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 26 Jul 2012 08:50:02 +0100 Subject: from future import pass_function In-Reply-To: References: Message-ID: On 26/07/2012 06:20, Michael Hrivnak wrote: > If we want pass(), then why not break() and continue()? And also > def() and class()? for(), while(), if(), with(), we can make them all > callable objects! And if we could persuade the BDFL to introduce braces, we could have {() and }() -- Cheers. Mark Lawrence. From stefan_ml at behnel.de Thu Jul 26 04:28:46 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 Jul 2012 10:28:46 +0200 Subject: catch UnicodeDecodeError In-Reply-To: <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> Message-ID: Jaroslav Dobrek, 26.07.2012 09:46: > My problem is solved. What I need to do is explicitly decode text when > reading it. Then I can catch exceptions. I might do this in future > programs. Yes, that's the standard procedure. Decode on the way in, encode on the way out, use Unicode everywhere in between. > I dislike about this solution that it complicates most programs > unnecessarily. In programs that open, read and process many files I > don't want to explicitly decode and encode characters all the time. I > just want to write: > > for line in f: And the cool thing is: you can! :) In Python 2.6 and later, the new Py3 open() function is a bit more hidden, but it's still available: from io import open filename = "somefile.txt" try: with open(filename, encoding="utf-8") as f: for line in f: process_line(line) # actually, I'd use "process_file(f)" except IOError, e: print("Reading file %s failed: %s" % (filename, e)) except UnicodeDecodeError, e: print("Some error occurred decoding file %s: %s" % (filename, e)) Ok, maybe with a better way to handle the errors than "print" ... For older Python versions, you'd use "codecs.open()" instead. That's a bit messy, but only because it was finally cleaned up for Python 3. > or something like that. Yet, writing this means to *implicitly* decode > text. And, because the decoding is implicit, you cannot say > > try: > for line in f: # here text is decoded implicitly > do_something() > except UnicodeDecodeError(): > do_something_different() > > This isn't possible for syntactic reasons. Well, you'd normally want to leave out the parentheses after the exception type, but otherwise, that's perfectly valid Python code. That's how these things work. > The problem is that vast majority of the thousands of files that I > process are correctly encoded. But then, suddenly, there is a bad > character in a new file. (This is so because most files today are > generated by people who don't know that there is such a thing as > encodings.) And then I need to rewrite my very complex program just > because of one single character in one single file. Why would that be the case? The places to change should be very local in your code. Stefan From steve+comp.lang.python at pearwood.info Thu Jul 26 04:36:15 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Jul 2012 08:36:15 GMT Subject: from future import pass_function References: Message-ID: <5011017e$0$11120$c3e8da3@news.astraweb.com> On Thu, 26 Jul 2012 08:39:25 +0200, Ulrich Eckhardt wrote: > I have seen code that just created a list comprehension to iterate over > something but was discarding the results. That could be a case for a "do > nothing" function. That would be a case for *not* using a list comprehension. Using a list comp when you don't want the results is the wrong way to do it. That's like hammering a screw into a wall with a wrench. Okay, I admit it, sometimes if I'm lazy and I'm in the interactive interpreter and I need to consume use up results from an iterator, I type: _ = [x for x in iterator] and then I kick myself because I could have just written: _ = list(iterator) but in actual code, I'm not so lazy to bang that screw into the wall using a wrench. I at least reach for a hammer: _ = [None for x in iterator] or better still, a drill: collections.deque(iterator, maxlen=0) But fine, you need a do-nothing function. Here you go: _ = [(lambda x: None)(x) for x in sequence] > Just having a function that does nothing would be useful in other > places, too. In some cases, you want to print() some debug output in > other cases you just use pass() to discard the debug output. You're still not giving reasons why *pass* should be a do-nothing function. Of course there are good use-cases for do-nothing functions, that goes without saying. But you have to explain why: 1) that do-nothing function is so common and so important that it has to be a built-in function; and 2) why it needs to be called "pass". Nobody is disputing the usefulness of do nothing functions. We're disputing that *pass* should be that function. -- Steven From jeanpierreda at gmail.com Thu Jul 26 05:16:17 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 26 Jul 2012 05:16:17 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Thu, Jul 26, 2012 at 1:20 AM, Michael Hrivnak wrote: > If we want pass(), then why not break() and continue()? And also > def() and class()? for(), while(), if(), with(), we can make them all > callable objects! No, you actually can't. You omit the one control flow statement that could actually be turned into a function, raise. None of the rest could in Python (except class), and one of the rest couldn't in any language (def). -- Devin From sp at abusix.org Thu Jul 26 05:25:40 2012 From: sp at abusix.org (Simon Pirschel) Date: Thu, 26 Jul 2012 11:25:40 +0200 Subject: append in IMAP4 from imaplib very slow In-Reply-To: <5010F689.8090701@abusix.com> References: <5010314F.80001@abusix.com> <5010B7B5.5040206@tim.thechases.com> <5010F689.8090701@abusix.com> Message-ID: <50110D14.7020906@abusix.com> On 07/26/2012 09:49 AM, Simon Pirschel wrote: > On 07/26/2012 05:21 AM, Tim Chase wrote: >> On 07/25/12 12:47, Simon Pirschel wrote: >>> I'm currently experimenting with IMAP using Python 2.7.3 and >>> IMAP4 from imaplib. I noticed the performance to be very bad. I >>> read 5000 files from a directory and append them to an IMAP >>> INBOX. The hole procedure of reading and appending is taking >>> about 210 seconds. >>> >>> I set up the exact same code in Perl to check if there is a >>> general IMAP server configuration issue, since CPU and I/O isn't >>> the problem. The same amount of data on the same IMAP server is >>> done after 7.9 seconds using Perl. >>> >>> The difference is huge and I tried to narrow the issue down by >>> profiling the Python code. The profile results are, 206 seconds >>> are spent in calling socket.recv. >> While I don't know the ins and outs of the Perl code, it looks like >> the Python imaplib.py is doing some pretty straight-forward >> send/receive work. However, IMAP4 does support both pipelining and >> multi-append extensions, so if the Perl code takes advantage of the >> features if the server offers them, it might be reaping significant >> gains over the na?ve Python code. >> >> Can you get a debugging dump of the commands being sent each way? >> (particularly if you see a bunch of APPEND commands before the reply >> acknowledgement, as detailed at [1]) >> >> -tkc >> >> [1] >> http://www.ietf.org/rfc/rfc3502.txt on page 4 >> > I took a strace of all network related sys calls from Python and Perl. > It seems both don't do multi appends and waiting for the OK after > appending one mail. But the Python version is getting a completely > different response. > > Python: "* 204 EXISTS\r\n* 1 RECENT\r\nNBGC3 OK [APPENDUID 1343283946 > 204] Append completed.\r\n" > Perl: "2 OK [APPENDUID 1343283946 255] Append completed.\r\n" > > The Python lib seems to trigger a EXISTS and RECENT lookup on every > append, which could be the performance difference. I couldn't figure > out why, yet! > > Python strace: http://aboutsimon.com/py.strace > Perl strace: http://aboutsimon.com/pl.strace > > Strings are shortened to 40 chars. > > > Simon Ok, forget about the EXISTS and RECENT response. The server will response this way if you selected a mailbox, which I did in the Python code but not in the Perl code. I disabled selecting the mailbox in Python and there is no difference in the runtime. So, this isn't the issue. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Jul 26 05:26:49 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Jul 2012 09:26:49 GMT Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50110d59$0$11120$c3e8da3@news.astraweb.com> On Thu, 26 Jul 2012 08:59:30 +0200, Ulrich Eckhardt wrote: > Am 26.07.2012 04:38, schrieb Steven D'Aprano: >> The examples of pass-as-a-function shown by the Original Poster don't >> give any clue of what advantage there is to make pass a function. > > Just read the text, it just struck me how similar pass and print are, > i.e. that neither actually needs to be a keyword. In some cases, I would > rather use "return" to replace "pass" though. I did read your text. I was not enlightened. >> It appears that the only reason for this suggested change is that he >> would rather write "pass()" instead of "pass", possibly because he >> thinks it looks cool. > > I have no idea where you got the "cool" from, it is not in my posting. I didn't say that was what you said. I made it clear that "cool" was *my* words. >> (Actually, I reckon that what is driving this idea is that the OP is a >> beginner, and he's got a syntax error a few times from writing >> "pass()", and so he thought it would be easier to force other people to >> change tens or hundreds of thousands of Python programs to use "pass()" >> instead of "pass" than to just learn to stop putting parentheses after >> it. > > So, and in order to force people to write parens or break their code I > have considered the possibility of importing that feature from > __future__ for those people that want it? Seriously, Steven, as much as > I like your regular contributions here, this time you had better logged > off and taken a walk, because you come across as _very_ arrogant here. *shrug* I'm just being honest. As you admitted, you hadn't really given the idea a lot of thought. Your examples didn't show any difference except a pair of parentheses () after the pass. I made two guesses on what motivated your suggestion, based on the information I had in front of me at the time. By the way, you trimmed out my comment where I admit to also having come up with changes to Python without giving any thought to the consequences. My guesses as to your motive for wanting to change "pass" were not based on your thoughts, which are hidden to me, but on the way I used to think. It took me a long time to learn that, for an established language like Python, change is nearly always for the worse, and any change that requires changing existing code better have a very good excuse. -- Steven From rosuav at gmail.com Thu Jul 26 05:42:11 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 26 Jul 2012 19:42:11 +1000 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Thu, Jul 26, 2012 at 7:16 PM, Devin Jeanpierre wrote: > On Thu, Jul 26, 2012 at 1:20 AM, Michael Hrivnak wrote: >> If we want pass(), then why not break() and continue()? And also >> def() and class()? for(), while(), if(), with(), we can make them all >> callable objects! > > No, you actually can't. > > You omit the one control flow statement that could actually be turned > into a function, raise. None of the rest could in Python (except > class), and one of the rest couldn't in any language (def). Well, if/while/for could be functions. So could with, probably. Now, def would be a little tricky... ChrisA From rosuav at gmail.com Thu Jul 26 05:46:14 2012 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 26 Jul 2012 19:46:14 +1000 Subject: catch UnicodeDecodeError In-Reply-To: <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> Message-ID: On Thu, Jul 26, 2012 at 5:46 PM, Jaroslav Dobrek wrote: > My problem is solved. What I need to do is explicitly decode text when > reading it. Then I can catch exceptions. I might do this in future > programs. Apologies if it's already been said (I'm only skimming this thread), but ISTM that you want to open the file in binary mode. You'll then get back a bytes() instead of a str(), and you can attempt to decode it separately. You may then need to do your own division into lines that way, though. ChrisA From jeanpierreda at gmail.com Thu Jul 26 06:00:53 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 26 Jul 2012 06:00:53 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Thu, Jul 26, 2012 at 5:42 AM, Chris Angelico wrote: >> You omit the one control flow statement that could actually be turned >> into a function, raise. None of the rest could in Python (except >> class), and one of the rest couldn't in any language (def). > > Well, if/while/for could be functions. So could with, probably. Now, > def would be a little tricky... In Haskell, sure. -- Devin From wxjmfauth at gmail.com Thu Jul 26 06:19:36 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 26 Jul 2012 03:19:36 -0700 (PDT) Subject: catch UnicodeDecodeError In-Reply-To: <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> Message-ID: On Thursday, July 26, 2012 9:46:27 AM UTC+2, Jaroslav Dobrek wrote: > On Jul 25, 8:50?pm, Dave Angel <d... at davea.name> wrote: > > On 07/25/2012 08:09 AM, jaroslav.dob... at gmail.com wrote: > > > > > > > > > > > > > > > > > > > > > On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: > > >> Hi Jaroslav, > > > > >> you can catch a UnicodeDecodeError just like any other exception. Can > > >> you provide a full example program that shows your problem? > > > > >> This works fine on my system: > > > > >> import sys > > >> open(&#39;tmp&#39;, &#39;wb&#39;).write(b&#39;\xff\xff&#39;) > > >> try: > > >> ? ? buf = open(&#39;tmp&#39;, &#39;rb&#39;).read() > > >> ? ? buf.decode(&#39;utf-8&#39;) > > >> except UnicodeDecodeError as ude: > > >> ? ? sys.exit(&quot;Found a bad char in file &quot; + &quot;tmp&quot;) > > > > > Thank you. I got it. What I need to do is explicitly decode text. > > > > > But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. > > > > > What I am missing (especially for Python3) is something like: > > > > > try: > > > ? ? for line in sys.stdin: > > > except UnicodeDecodeError: > > > ? ? sys.exit("Encoding problem in line " + str(line_number)) > > > > > I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. > > > > i can't understand your question. ?if the problem is that the system > > doesn't magically produce a variable called line_number, then generate > > it yourself, by counting > > in the loop. > > > That was just a very incomplete and general example. > > My problem is solved. What I need to do is explicitly decode text when > reading it. Then I can catch exceptions. I might do this in future > programs. > > I dislike about this solution that it complicates most programs > unnecessarily. In programs that open, read and process many files I > don't want to explicitly decode and encode characters all the time. I > just want to write: > > for line in f: > > or something like that. Yet, writing this means to *implicitly* decode > text. And, because the decoding is implicit, you cannot say > > try: > for line in f: # here text is decoded implicitly > do_something() > except UnicodeDecodeError(): > do_something_different() > > This isn't possible for syntactic reasons. > > The problem is that vast majority of the thousands of files that I > process are correctly encoded. But then, suddenly, there is a bad > character in a new file. (This is so because most files today are > generated by people who don't know that there is such a thing as > encodings.) And then I need to rewrite my very complex program just > because of one single character in one single file. In my mind you are taking the problem the wrong way. Basically there is no "real UnicodeDecodeError", you are just wrongly attempting to read a file with the wrong codec. Catching a UnicodeDecodeError will not correct the basic problem, it will "only" show, you are using a wrong codec. There is still the possibility, you have to deal with an ill-formed utf-8 codding, but I doubt it is the case. Do not forget, a "bit of text" has only a meaning if you know its coding. In short, all your files are most probably ok, you do not read them correctly. >>> b'abc\xeadef'.decode('utf-8') Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'utf-8' codec can't decode byte 0xea in position 3: invalid continuation byte >>> # but >>> b'abc\xeadef'.decode('cp1252') 'abc?def' >>> b'abc\xeadef'.decode('mac-roman') 'abc?def' >>> b'abc\xeadef'.decode('iso-8859-1') 'abc?def' jmf From jaroslav.dobrek at gmail.com Thu Jul 26 06:51:34 2012 From: jaroslav.dobrek at gmail.com (Jaroslav Dobrek) Date: Thu, 26 Jul 2012 03:51:34 -0700 (PDT) Subject: catch UnicodeDecodeError References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> Message-ID: <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> > And the cool thing is: you can! :) > > In Python 2.6 and later, the new Py3 open() function is a bit more hidden, > but it's still available: > > ? ? from io import open > > ? ? filename = "somefile.txt" > ? ? try: > ? ? ? ? with open(filename, encoding="utf-8") as f: > ? ? ? ? ? ? for line in f: > ? ? ? ? ? ? ? ? process_line(line) ?# actually, I'd use "process_file(f)" > ? ? except IOError, e: > ? ? ? ? print("Reading file %s failed: %s" % (filename, e)) > ? ? except UnicodeDecodeError, e: > ? ? ? ? print("Some error occurred decoding file %s: %s" % (filename, e)) Thanks. I might use this in the future. > > try: > > ? ? for line in f: # here text is decoded implicitly > > ? ? ? ?do_something() > > except UnicodeDecodeError(): > > ? ? do_something_different() > > > This isn't possible for syntactic reasons. > > Well, you'd normally want to leave out the parentheses after the exception > type, but otherwise, that's perfectly valid Python code. That's how these > things work. You are right. Of course this is syntactically possible. I was too rash, sorry. In confused it with some other construction I once tried. I can't remember it right now. But the code above (without the brackets) is semantically bad: The exception is not caught. > > The problem is that vast majority of the thousands of files that I > > process are correctly encoded. But then, suddenly, there is a bad > > character in a new file. (This is so because most files today are > > generated by people who don't know that there is such a thing as > > encodings.) And then I need to rewrite my very complex program just > > because of one single character in one single file. > > Why would that be the case? The places to change should be very local in > your code. This is the case in a program that has many different functions which open and parse different types of files. When I read and parse a directory with such different types of files, a program that uses for line in f: will not exit with any hint as to where the error occurred. I just exits with a UnicodeDecodeError. That means I have to look at all functions that have some variant of for line in f: in them. And it is not sufficient to replace the "for line in f" part. I would have to transform many functions that work in terms of lines into functions that work in terms of decoded bytes. That is why I usually solve the problem by moving fles around until I find the bad file. Then I recode or repair the bad file manually. From jaroslav.dobrek at gmail.com Thu Jul 26 07:04:08 2012 From: jaroslav.dobrek at gmail.com (Jaroslav Dobrek) Date: Thu, 26 Jul 2012 04:04:08 -0700 (PDT) Subject: catch UnicodeDecodeError References: bf64e06c-086b-4fef-8046-f88e52fbafd3@googlegroups.com Message-ID: <975bc0b0-691e-4760-a7be-6a1d211ef874@s1g2000vbj.googlegroups.com> On Jul 26, 12:19?pm, wxjmfa... at gmail.com wrote: > On Thursday, July 26, 2012 9:46:27 AM UTC+2, Jaroslav Dobrek wrote: > > On Jul 25, 8:50?pm, Dave Angel <d... at davea.name> wrote: > > > On 07/25/2012 08:09 AM, jaroslav.dob... at gmail.com wrote: > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > On Wednesday, July 25, 2012 1:35:09 PM UTC+2, Philipp Hagemeister wrote: > > > >> Hi Jaroslav, > > > > > > >> you can catch a UnicodeDecodeError just like any other exception. Can > > > >> you provide a full example program that shows your problem? > > > > > > >> This works fine on my system: > > > > > > >> import sys > > > >> open(&#39;tmp&#39;, &#39;wb&#39;).write(b&#39;\xff\xff&#39;) > > > >> try: > > > >> ? ? buf = open(&#39;tmp&#39;, &#39;rb&#39;).read() > > > >> ? ? buf.decode(&#39;utf-8&#39;) > > > >> except UnicodeDecodeError as ude: > > > >> ? ? sys.exit(&quot;Found a bad char in file &quot; + &quot;tmp&quot;) > > > > > > > Thank you. I got it. What I need to do is explicitly decode text. > > > > > > > But I think trial and error with moving files around will in most cases be faster. Usually, such a problem occurs with some (usually complex) program that I wrote quite a long time ago. I don't like editing old and complex programs that work under all normal circumstances. > > > > > > > What I am missing (especially for Python3) is something like: > > > > > > > try: > > > > ? ? for line in sys.stdin: > > > > except UnicodeDecodeError: > > > > ? ? sys.exit("Encoding problem in line " + str(line_number)) > > > > > > > I got the point that there is no such thing as encoding-independent lines. But if no line ending can be found, then the file simply has one single line. > > > > > > i can't understand your question. ?if the problem is that the system > > > doesn't magically produce a variable called line_number, then generate > > > it yourself, by counting > > > in the loop. > > > That was just a very incomplete and general example. > > > My problem is solved. What I need to do is explicitly decode text when > > reading it. Then I can catch exceptions. I might do this in future > > programs. > > > I dislike about this solution that it complicates most programs > > unnecessarily. In programs that open, read and process many files I > > don't want to explicitly decode and encode characters all the time. I > > just want to write: > > > for line in f: > > > or something like that. Yet, writing this means to *implicitly* decode > > text. And, because the decoding is implicit, you cannot say > > > try: > > ? ? for line in f: # here text is decoded implicitly > > ? ? ? ?do_something() > > except UnicodeDecodeError(): > > ? ? do_something_different() > > > This isn't possible for syntactic reasons. > > > The problem is that vast majority of the thousands of files that I > > process are correctly encoded. But then, suddenly, there is a bad > > character in a new file. (This is so because most files today are > > generated by people who don't know that there is such a thing as > > encodings.) And then I need to rewrite my very complex program just > > because of one single character in one single file. > > In my mind you are taking the problem the wrong way. > > Basically there is no "real UnicodeDecodeError", you are > just wrongly attempting to read a file with the wrong > codec. Catching a UnicodeDecodeError will not correct > the basic problem, it will "only" show, you are using > a wrong codec. > There is still the possibility, you have to deal with an > ill-formed utf-8 codding, but I doubt it is the case. I participate in projects in which all files (raw text files, xml files, html files, ...) are supposed to be encoded in utf-8. I get many different files from many different people. They are almost always ancoded in utf-8. But sometimes a whole file or, more frequently, parts of a file are not encoded in utf-8. The reason is that most of the files stem from the internet. Files or strings are downloaded and, if possible, recoded. And they are often simply concatenated into larger strings or files. I think the most straightforward thing to do is to assume that I get utf-8 and raise an error if some file or character proves to be something different. From stefan_ml at behnel.de Thu Jul 26 07:15:37 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 Jul 2012 13:15:37 +0200 Subject: catch UnicodeDecodeError In-Reply-To: <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> Message-ID: Jaroslav Dobrek, 26.07.2012 12:51: >>> try: >>> for line in f: # here text is decoded implicitly >>> do_something() >>> except UnicodeDecodeError(): >>> do_something_different() > > the code above (without the brackets) is semantically bad: The > exception is not caught. Sure it is. Just to repeat myself: if the above doesn't catch the exception, then the exception did not originate from the place where you think it did. Again: look at the traceback. >>> The problem is that vast majority of the thousands of files that I >>> process are correctly encoded. But then, suddenly, there is a bad >>> character in a new file. (This is so because most files today are >>> generated by people who don't know that there is such a thing as >>> encodings.) And then I need to rewrite my very complex program just >>> because of one single character in one single file. >> >> Why would that be the case? The places to change should be very local in >> your code. > > This is the case in a program that has many different functions which > open and parse different > types of files. When I read and parse a directory with such different > types of files, a program that > uses > > for line in f: > > will not exit with any hint as to where the error occurred. I just > exits with a UnicodeDecodeError. ... that tells you the exact code line where the error occurred. No need to look around. Stefan From ulrich.eckhardt at dominolaser.com Thu Jul 26 07:45:23 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 26 Jul 2012 13:45:23 +0200 Subject: from future import pass_function In-Reply-To: <50110d59$0$11120$c3e8da3@news.astraweb.com> References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> Message-ID: Am 26.07.2012 11:26, schrieb Steven D'Aprano: > On Thu, 26 Jul 2012 08:59:30 +0200, Ulrich Eckhardt wrote: >> Am 26.07.2012 04:38, schrieb Steven D'Aprano: >>> (Actually, I reckon that what is driving this idea is that the OP is a >>> beginner, and he's got a syntax error a few times from writing >>> "pass()", and so he thought it would be easier to force other people to >>> change tens or hundreds of thousands of Python programs to use "pass()" >>> instead of "pass" than to just learn to stop putting parentheses after >>> it. >> >> So, and in order to force people to write parens or break their code I >> have considered the possibility of importing that feature from >> __future__ for those people that want it? Seriously, Steven, as much as >> I like your regular contributions here, this time you had better logged >> off and taken a walk, because you come across as _very_ arrogant here. > > *shrug* I'm just being honest. As you admitted, you hadn't really given > the idea a lot of thought. Your examples didn't show any difference > except a pair of parentheses () after the pass. I made two guesses on > what motivated your suggestion, based on the information I had in front > of me at the time. > > By the way, you trimmed out my comment where I admit to also having come > up with changes to Python without giving any thought to the consequences. > My guesses as to your motive for wanting to change "pass" were not based > on your thoughts, which are hidden to me, but on the way I used to think. I didn't say "Pass should be a function!" but asked "What do you think?". You are assuming lots of things about my goals and jumping to conclusions like that I'm complaining about the stupid Python syntax, that I'm a frustrated noob, that I want someone to fix that syntax, but that is not the case! I'm engaging in a discussion here exactly in order to test the idea I had. > It took me a long time to learn that, for an established language like > Python, change is nearly always for the worse, and any change that > requires changing existing code better have a very good excuse. ...so what do you do when you have an idea? You think about it on your own, right? I do so, too, but I also engage in discussions with others. See? BTW: I think you missed the implications of this thread's topic and the snide remark about forcing people to change their code, i.e. that no existing code has to change (apart from the Python implementation, of course), even if pass was made a function! Uli From sp at abusix.org Thu Jul 26 07:55:45 2012 From: sp at abusix.org (Simon Pirschel) Date: Thu, 26 Jul 2012 13:55:45 +0200 Subject: append in IMAP4 from imaplib very slow In-Reply-To: <50110D14.7020906@abusix.com> References: <5010314F.80001@abusix.com> <5010B7B5.5040206@tim.thechases.com> <5010F689.8090701@abusix.com> <50110D14.7020906@abusix.com> Message-ID: <50113041.4010501@abusix.com> On 07/26/2012 11:25 AM, Simon Pirschel wrote: > Ok, forget about the EXISTS and RECENT response. The server will > response this way if you selected a mailbox, which I did in the Python > code but not in the Perl code. I disabled selecting the mailbox in > Python and there is no difference in the runtime. So, this isn't the > issue. I solved the issue. The bad performance is caused by the socketopt socket.TCP_NODELAY set to 0 by default. Request timing with socket.TCP_NODELAY=0: 0.0501310825348 seconds Request timing with socket.TCP_NODELAY=1: 0.0027711391449 seconds This is a huge difference. Setting TCP_NODELAY=1 will bring the runtime from 3:30 minutes down to 14 seconds! Not Perl speed, but close. Simon -------------- next part -------------- An HTML attachment was scrubbed... URL: From jaroslav.dobrek at gmail.com Thu Jul 26 07:58:03 2012 From: jaroslav.dobrek at gmail.com (jaroslav.dobrek at gmail.com) Date: Thu, 26 Jul 2012 04:58:03 -0700 (PDT) Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> Message-ID: > that tells you the exact code line where the error occurred. No need to > look around. You are right: try: for line in f: do_something() except UnicodeDecodeError: do_something_different() does exactly what one would expect it to do. Thank you very much for pointing this out and sorry for all the posts. This is one of the days when nothing seems to work and when I don't seem to able to read the simplest error message. From jaroslav.dobrek at gmail.com Thu Jul 26 07:58:03 2012 From: jaroslav.dobrek at gmail.com (jaroslav.dobrek at gmail.com) Date: Thu, 26 Jul 2012 04:58:03 -0700 (PDT) Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> Message-ID: > that tells you the exact code line where the error occurred. No need to > look around. You are right: try: for line in f: do_something() except UnicodeDecodeError: do_something_different() does exactly what one would expect it to do. Thank you very much for pointing this out and sorry for all the posts. This is one of the days when nothing seems to work and when I don't seem to able to read the simplest error message. From phihag at phihag.de Thu Jul 26 08:17:44 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Thu, 26 Jul 2012 14:17:44 +0200 Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> Message-ID: <50113568.9030006@phihag.de> On 07/26/2012 01:15 PM, Stefan Behnel wrote: >> exits with a UnicodeDecodeError. > ... that tells you the exact code line where the error occurred. Which property of a UnicodeDecodeError does include that information? On cPython 2.7 and 3.2, I see only start and end, both of which refer to the number of bytes read so far. I used the followin test script: e = None try: b'a\xc3\xa4\nb\xff0'.decode('utf-8') except UnicodeDecodeError as ude: e = ude print(e.start) # 5 for this input, 3 for the input b'a\nb\xff0' print(dir(e)) But even if you would somehow determine a line number, this would only work if the actual encoding uses 0xa for newline. Most encodings (101 out of 108 applicable ones in cPython 3.2) do include 0x0a in their representation of '\n', but multi-byte encodings routinely include 0x0a bytes in their representation of non-newline characters. Therefore, the most you can do is calculate an upper bound for the line number. - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From stefan_ml at behnel.de Thu Jul 26 08:24:40 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 Jul 2012 14:24:40 +0200 Subject: catch UnicodeDecodeError In-Reply-To: <50113568.9030006@phihag.de> References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> <38f5cdaf-c021-4ccd-8fcb-c68b21d3aeb2@w24g2000vby.googlegroups.com> <17bf754d-b1e9-4bb7-bf42-190325ee969a@q29g2000vby.googlegroups.com> <50113568.9030006@phihag.de> Message-ID: Philipp Hagemeister, 26.07.2012 14:17: > On 07/26/2012 01:15 PM, Stefan Behnel wrote: >>> exits with a UnicodeDecodeError. >> ... that tells you the exact code line where the error occurred. > > Which property of a UnicodeDecodeError does include that information? > > On cPython 2.7 and 3.2, I see only start and end, both of which refer to > the number of bytes read so far. Read again: "*code* line". The OP was apparently failing to see that the error did not originate in the source code lines that he had wrapped with a try-except statement but somewhere else, thus leading to the misguided impression that the exception was not properly caught by the except clause. Stefan From gandalf at shopzeus.com Thu Jul 26 08:26:16 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 26 Jul 2012 14:26:16 +0200 Subject: Generating valid identifiers Message-ID: <50113768.6070008@shopzeus.com> I have a program that creates various database objects in PostgreSQL. There is a DOM, and for each element in the DOM, a database object is created (schema, table, field, index and tablespace). I do not want this program to generate very long identifiers. It would increase SQL parsing time, and don't look good. Let's just say that the limit should be 32 characters. But I also want to recognize the identifiers when I look at their modified/truncated names. So I have come up with this solution: - I have restricted original identifiers not to contain the dollar sign. They can only contain [A-Z] or [a-z] or [0-9] and the underscore. Here is a valid example: "group1_group2_group3_some_field_name" - I'm trying to use a hash function to reduce the length of the identifier when it is too long: class Connection(object): # ... more code here @classmethod def makename(cls, basename): if len(basename)>32: h = hashlib.sha256() h.update(basename) tail = base64.b64encode(h.digest(),"_$")[:10] return basename[:30]+"$"+tail else: return basename Here is the result: print repr(Connection.makename("some_field_name")) 'some_field_name' print repr(Connection.makename("group1_group2_group3_some_field_name")) 'group1_group2_group3_some_fiel$AyQVQUXoyf' So, if the identifier is too long, then I use a modified version, that should be unique, and similar to the original name. Let's suppose that nobody wants to crack this modified hash on purpose. And now, the questions: * Would it be a problem to use CRC32 instead of SHA? (Since security is not a problem, and CRC32 is faster.) * I'm truncating the digest value to 10 characters. Is it safe enough? I don't want to use more than 10 characters, because then it wouldn't be possible to recognize the original name. * Can somebody think of a better algorithm, that would give a bigger chance of recognizing the original identifier from the modified one? Thanks, Laszlo From phihag at phihag.de Thu Jul 26 08:43:28 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Thu, 26 Jul 2012 14:43:28 +0200 Subject: catch UnicodeDecodeError In-Reply-To: References: <04f7ff8d-9881-4a04-ab2e-b5573b5f3cd1@googlegroups.com> Message-ID: <50113B70.8020207@phihag.de> On 07/26/2012 02:24 PM, Stefan Behnel wrote: > Read again: "*code* line". The OP was apparently failing to see that > the error did not originate in the source code lines that he had > wrapped with a try-except statement but somewhere else, thus leading to the misguided impression that the exception was not properly caught by the except clause. Oops, over a dozen posts and I still haven't grasped the OP's problem. Sorry! and thanks for noting that. - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From storchaka at gmail.com Thu Jul 26 09:34:17 2012 From: storchaka at gmail.com (Serhiy Storchaka) Date: Thu, 26 Jul 2012 16:34:17 +0300 Subject: the meaning of =?UTF-8?B?csOvxbjClS4uLi4uLi7Dr8W4?= In-Reply-To: <500d7285$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500d0632$0$1504$c3e8da3$76491128@news.astraweb.com> <500d7285$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 23.07.12 18:49, Steven D'Aprano wrote: > ? for <= > ? for >= I insist on the use of ? and ? too. From arnodel at gmail.com Thu Jul 26 10:21:32 2012 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 26 Jul 2012 15:21:32 +0100 Subject: Generating valid identifiers In-Reply-To: <50113768.6070008@shopzeus.com> References: <50113768.6070008@shopzeus.com> Message-ID: On 26 July 2012 13:26, Laszlo Nagy wrote: [...] > I do not want this program to generate very long identifiers. It would > increase SQL parsing time, and don't look good. Let's just say that the > limit should be 32 characters. But I also want to recognize the identifiers > when I look at their modified/truncated names. [...] > print repr(Connection.makename("group1_group2_group3_some_field_name")) > 'group1_group2_group3_some_fiel$AyQVQUXoyf' >>> len('group1_group2_group3_some_fiel$AyQVQUXoyf') 41 You've exceeded 32 characters! Perhaps you could change: return basename[:30]+"$"+tail to: return basename[:21]+"$"+tail But then you'd get something like this for your long identifier: group1_group2_group3_$AyQVQUXoyf which seems to miss out on a crucial bit: namely the field name. Also it's hard to imagine a way to keep things readable when we don't know what the original identifiers look like :) -- Arnaud From tjreedy at udel.edu Thu Jul 26 10:30:11 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jul 2012 10:30:11 -0400 Subject: append in IMAP4 from imaplib very slow In-Reply-To: <50113041.4010501@abusix.com> References: <5010314F.80001@abusix.com> <5010B7B5.5040206@tim.thechases.com> <5010F689.8090701@abusix.com> <50110D14.7020906@abusix.com> <50113041.4010501@abusix.com> Message-ID: On 7/26/2012 7:55 AM, Simon Pirschel wrote: > On 07/26/2012 11:25 AM, Simon Pirschel wrote: >> Ok, forget about the EXISTS and RECENT response. The server will >> response this way if you selected a mailbox, which I did in the Python >> code but not in the Perl code. I disabled selecting the mailbox in >> Python and there is no difference in the runtime. So, this isn't the >> issue. > > I solved the issue. The bad performance is caused by the socketopt > socket.TCP_NODELAY set to 0 by default. > > Request timing with socket.TCP_NODELAY=0: 0.0501310825348 seconds > Request timing with socket.TCP_NODELAY=1: 0.0027711391449 seconds > > This is a huge difference. Setting TCP_NODELAY=1 will bring the runtime > from 3:30 minutes down to 14 seconds! Not Perl speed, but close. Do you think this warrants a change in our docs, if not the code? -- Terry Jan Reedy From tjreedy at udel.edu Thu Jul 26 10:38:28 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jul 2012 10:38:28 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: On 7/26/2012 2:39 AM, Ulrich Eckhardt wrote: > I have seen code that just created a list comprehension to iterate over > something but was discarding the results. If you mean, discard the resulting list, that is probably bad code as it should not create the list in the first place. A generator expression or for loop will iterate without creating an unneeded list. > That could be a case for a "do nothing" function. Such code does do something within the comprehension. > Just having a function that does nothing Not possible. None is the default return. Python does not have proceedures, and that is not going to change, especially for a null proceedure. -- Terry Jan Reedy From subhabangalore at gmail.com Thu Jul 26 10:47:20 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Thu, 26 Jul 2012 07:47:20 -0700 (PDT) Subject: HMM and CRF Package In-Reply-To: References: Message-ID: On Thursday, July 26, 2012 1:28:50 AM UTC+5:30, Terry Reedy wrote: > On 7/25/2012 11:58 AM, subhabangalore at gmail.com wrote: > > As most of the libraries give so many bindings and conditions best way > is to make it. Not very tough, I made earlier, but as some files were > lost so was thinking instead of a remake if ready versions work. Or may > look change from Python 3 to previous version so when 3 will be > supported solution. But can I install both Python 3 and Python2.x or > call 2.x from 3.x? > > You can have multiple versions of Python installed. Just be careful on > *nix to use altinstall so as to not disturb the system install used by > the system. > > Pythonx.y can only use code that works with x.y ;=). However, any Python > process can use any other program via the subprocess module. You just > have to work out the data transfer. > > -- > Terry Jan Reedy Dear Terry, Thanks for your reply. I had downloaded it too, but going tools I felt it is better to repair or rebuild them, as most of them have many bindings. And making is not a big effort when numpy,scipy,matplotlib are there. Regards, Subhabrata Banerjee. From subhabangalore at gmail.com Thu Jul 26 10:47:20 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Thu, 26 Jul 2012 07:47:20 -0700 (PDT) Subject: HMM and CRF Package In-Reply-To: References: Message-ID: On Thursday, July 26, 2012 1:28:50 AM UTC+5:30, Terry Reedy wrote: > On 7/25/2012 11:58 AM, subhabangalore at gmail.com wrote: > > As most of the libraries give so many bindings and conditions best way > is to make it. Not very tough, I made earlier, but as some files were > lost so was thinking instead of a remake if ready versions work. Or may > look change from Python 3 to previous version so when 3 will be > supported solution. But can I install both Python 3 and Python2.x or > call 2.x from 3.x? > > You can have multiple versions of Python installed. Just be careful on > *nix to use altinstall so as to not disturb the system install used by > the system. > > Pythonx.y can only use code that works with x.y ;=). However, any Python > process can use any other program via the subprocess module. You just > have to work out the data transfer. > > -- > Terry Jan Reedy Dear Terry, Thanks for your reply. I had downloaded it too, but going tools I felt it is better to repair or rebuild them, as most of them have many bindings. And making is not a big effort when numpy,scipy,matplotlib are there. Regards, Subhabrata Banerjee. From solipsis at pitrou.net Thu Jul 26 10:48:35 2012 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 26 Jul 2012 14:48:35 +0000 (UTC) Subject: ssl: add =?utf-8?b?bXNnX2NhbGxiYWNr?= References: <35c62d1b461a1b016ff18a3ba2f7936e@localhost> Message-ID: Hi, Thi?baud Weksteen weksteen.fr> writes: > > I wrote a patch for Python 3.2.3 to expose the function > SSL_CTX_set_msg_callback in the module _ssl. > [...] > > Let me know your opinion on that. Does it worth being included? Yes, it sounds useful. Your patch will have to be written against the default branch, although I'm not sure it makes a difference here (see the devguide: http://docs.python.org/devguide/ for more information). Please open an issue at http://bugs.python.org and post your patch there. Thanks Antoine. -- Software development and contracting: http://pro.pitrou.net From tjreedy at udel.edu Thu Jul 26 10:51:21 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Jul 2012 10:51:21 -0400 Subject: Generating valid identifiers In-Reply-To: <50113768.6070008@shopzeus.com> References: <50113768.6070008@shopzeus.com> Message-ID: On 7/26/2012 8:26 AM, Laszlo Nagy wrote: > I have a program that creates various database objects in PostgreSQL. > There is a DOM, and for each element in the DOM, a database object is > created (schema, table, field, index and tablespace). > > I do not want this program to generate very long identifiers. It would > increase SQL parsing time and don't look good. Let's just say that the > limit should be 32 characters. If I controlled all the component names, I would try to limit their lengths so that the sum of lengths was limited to the limit. -- Terry Jan Reedy From rustompmody at gmail.com Thu Jul 26 11:01:56 2012 From: rustompmody at gmail.com (rusi) Date: Thu, 26 Jul 2012 08:01:56 -0700 (PDT) Subject: from future import pass_function References: Message-ID: <68e1df81-19d1-4a36-b447-e01d59dc4c8f@lq16g2000pbb.googlegroups.com> On Jul 25, 1:40?pm, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, > there could be a pass() function that does and returns nothing. > > Example: > ? ? def pass(): > ? ? ? ? return Since many have said NO but I see no good reasons for this no yet, here's mine: tl;dr version: Do-nothing statements are easy just do nothing, ie pass. Do-nothing expressions are hard. In the fully generic context they are impossible to implement. Longer version: Consider the if expression and the if statement. The if statement can have its else part elided in which case it defaults to pass. The if expression cannot so elide. Why? Consider the expression: (exp if cond) # no else Now in "x + (exp if cond)" if cond is false it should presumably be 0 However in "x * (exp if cond)" it should presumably be 1? And in the first case if x were a list should it not be [] ? Now consider your suggestion: def pass(): return is identical to def pass(): return None So you are saying that None can serve as a "generic zero"? Of course as you know (no suggestion that you are a noob on my part!!) Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0+3 3 >>> None+3 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' >>> None+[1,2,3] Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'NoneType' and 'list' >>> So now you (may) retort but these have nothing to do with what you asked. You see what youve asked for is moving pass from the statement world to the expression world. The meaning of a do-nothing statement is easy to give. The meaning of a do-nothing expression is hard because we are obliged to specify a type for expressions and the only value that can possibly belong to all types is the error-value (what denotational semantics calls bottom ? ) A more laymanish example: I have a multiplication I want one of the operands to be a 1, ie the identity I substitute it with the nearest available value ie 0 And out goes the baby with the bathwater! So to come back to your proposal: > there could be a pass() function that does and returns nothing. does nothing: easy returns nothing: impossible (None is not "nothing", its more like "error") From steve+comp.lang.python at pearwood.info Thu Jul 26 11:21:17 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Jul 2012 15:21:17 GMT Subject: from future import pass_function References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> Message-ID: <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 26 Jul 2012 13:45:23 +0200, Ulrich Eckhardt wrote: > I didn't say "Pass should be a function!" but asked "What do you > think?". You are assuming lots of things about my goals and jumping to > conclusions like that I'm complaining about the stupid Python syntax, > that I'm a frustrated noob, that I want someone to fix that syntax, but > that is not the case! I'm engaging in a discussion here exactly in order > to test the idea I had. Fair point. I underestimated you. But go back and re-read your first post, and see if you can understand *why* I underestimated you. You really didn't give any sign that you had given this question much detailed thought. Perhaps if you had mentioned that you had not decided whether this was a good idea and was looking for arguments both for and against, this tone of this discussion would have been very different. >> It took me a long time to learn that, for an established language like >> Python, change is nearly always for the worse, and any change that >> requires changing existing code better have a very good excuse. > > ...so what do you do when you have an idea? You think about it on your > own, right? I do so, too, but I also engage in discussions with others. > See? BTW: I think you missed the implications of this thread's topic and > the snide remark about forcing people to change their code, i.e. that no > existing code has to change (apart from the Python implementation, of > course), even if pass was made a function! I think that you misunderstand the purpose of from __future__ import. It is a *temporary* measure, always. Features which are not backward compatible are FIRST introduced as __future__ features, and THEN a release or two later, they become mandatory. (Unless they are dropped, which has not happened yet.) There have been seven __future__ features as of Python 3.2: absolute_import (enabled in 2.5, mandatory in 2.7) division (enabled in 2.2, mandatory in 3.0) generators (enabled in 2.2, mandatory in 2.3) nested_scopes (enabled in 2.1, mandatory in 2.2) print_function (enabled in 2.6, mandatory in 3.0) unicode_literals (enabled in 2.6, mandatory in 3.0) with_statement (enabled in 2.5, mandatory in 2.6) In any case, I acknowledge that I was wrong about your motivation. I made a guess based on the limited information I had, and based on my own history, and you tell me my guess was wrong. I accept that. -- Steven From steve+comp.lang.python at pearwood.info Thu Jul 26 11:30:09 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Jul 2012 15:30:09 GMT Subject: Generating valid identifiers References: Message-ID: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 26 Jul 2012 14:26:16 +0200, Laszlo Nagy wrote: > I do not want this program to generate very long identifiers. It would > increase SQL parsing time, Will that increase in SQL parsing time be more, or less, than the time it takes to generate CRC32 or SHA hashsums and append them to a truncated identifier? > * Would it be a problem to use CRC32 instead of SHA? (Since security is > not a problem, and CRC32 is faster.) What happens if you get a collision? That is, you have two different long identifiers: a.b.c.d...something a.b.c.d...anotherthing which by bad luck both hash to the same value: a.b.c.d.$AABB99 a.b.c.d.$AABB99 (or whatever). > * I'm truncating the digest value to 10 characters. Is it safe enough? > I don't want to use more than 10 characters, because then it wouldn't be > possible to recognize the original name. > * Can somebody think of a > better algorithm, that would give a bigger chance of recognizing the > original identifier from the modified one? Rather than truncating the most significant part of the identifier, the field name, you should truncate the least important part, the middle. a.b.c.d.e.f.g.something goes to: a.b...g.something or similar. -- Steven From __peter__ at web.de Thu Jul 26 11:43:33 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Jul 2012 17:43:33 +0200 Subject: Generating valid identifiers References: <50113768.6070008@shopzeus.com> Message-ID: Laszlo Nagy wrote: > I do not want this program to generate very long identifiers. It would > increase SQL parsing time, and don't look good. Let's just say that the > limit should be 32 characters. But I also want to recognize the > identifiers when I look at their modified/truncated names. Reality check: the shortened identifiers will look worse, parsing time is negligable -- and it will be hard to recognize the mangled identifiers. From joel.goldstick at gmail.com Thu Jul 26 12:55:18 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 26 Jul 2012 12:55:18 -0400 Subject: from future import pass_function In-Reply-To: <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Jul 26, 2012 at 11:21 AM, Steven D'Aprano wrote: > On Thu, 26 Jul 2012 13:45:23 +0200, Ulrich Eckhardt wrote: > >> I didn't say "Pass should be a function!" but asked "What do you >> think?". You are assuming lots of things about my goals and jumping to >> conclusions like that I'm complaining about the stupid Python syntax, >> that I'm a frustrated noob, that I want someone to fix that syntax, but >> that is not the case! I'm engaging in a discussion here exactly in order >> to test the idea I had. > > Fair point. I underestimated you. But go back and re-read your first > post, and see if you can understand *why* I underestimated you. You > really didn't give any sign that you had given this question much > detailed thought. > > Perhaps if you had mentioned that you had not decided whether this was a > good idea and was looking for arguments both for and against, this tone > of this discussion would have been very different. > > > >>> It took me a long time to learn that, for an established language like >>> Python, change is nearly always for the worse, and any change that >>> requires changing existing code better have a very good excuse. >> >> ...so what do you do when you have an idea? You think about it on your >> own, right? I do so, too, but I also engage in discussions with others. >> See? BTW: I think you missed the implications of this thread's topic and >> the snide remark about forcing people to change their code, i.e. that no >> existing code has to change (apart from the Python implementation, of >> course), even if pass was made a function! > > I think that you misunderstand the purpose of from __future__ import. It > is a *temporary* measure, always. Features which are not backward > compatible are FIRST introduced as __future__ features, and THEN a > release or two later, they become mandatory. (Unless they are dropped, > which has not happened yet.) > > There have been seven __future__ features as of Python 3.2: > > absolute_import (enabled in 2.5, mandatory in 2.7) > division (enabled in 2.2, mandatory in 3.0) > generators (enabled in 2.2, mandatory in 2.3) > nested_scopes (enabled in 2.1, mandatory in 2.2) > print_function (enabled in 2.6, mandatory in 3.0) > unicode_literals (enabled in 2.6, mandatory in 3.0) > with_statement (enabled in 2.5, mandatory in 2.6) > > > In any case, I acknowledge that I was wrong about your motivation. I made > a guess based on the limited information I had, and based on my own > history, and you tell me my guess was wrong. I accept that. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list This is the silliest thread I've ever seen in this group. I should abstain, but what the heck: If you want a function that does nothing, write one. Maybe like this: def do_nothing(): return Then, where you previous wrote pass in your code you can replace it with this thing. But really, not being a language meta-maven myself, somewhere above in this thread it was pointed out that pass is a syntax construction that is necessary in the very seldom case where you create a block of code that has no instructions. Instead of braces for every block, you get to skip that in python and just put pass in this extraordinary little case. While I've come to the point in my python coding knowledge to get my day to day work done proficiently, I'm amazed each time I delve deeper into how profoundly well this language was thought out. No offence to all the well meaning participants here, but this looks like trolling -- Joel Goldstick From ramit.prasad at jpmorgan.com Thu Jul 26 13:19:37 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 26 Jul 2012 17:19:37 +0000 Subject: from future import pass_function In-Reply-To: References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> > No offence to all the well meaning participants here, but this looks like trolling I thought Ranting Rick had sole dominion over trolling? Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Thu Jul 26 13:33:56 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 27 Jul 2012 03:33:56 +1000 Subject: from future import pass_function In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Jul 27, 2012 at 3:19 AM, Prasad, Ramit wrote: >> No offence to all the well meaning participants here, but this looks like trolling > > I thought Ranting Rick had sole dominion over trolling? Certainly not. We are well endowed with trolls here (Xah Lee isn't prolific, but is certainly effective), plus we have some regular posters who'll cover the trolls' tea breaks on occasion (myself, sometimes, and Steven D'Aprano). Now where did I put my asbestos suit... the Aprano is going to be at me pretty hard for this... *dives for cover without it* ChrisA From l.kotek at seznam.cz Thu Jul 26 14:08:52 2012 From: l.kotek at seznam.cz (=?utf-8?B?bC5rb3Rla0BzZXpuYW0uY3o=?=) Date: Thu, 26 Jul 2012 20:08:52 +0200 Subject: =?utf-8?B?UmU6IFB5dGhvbi1saXN0IERpZ2VzdCwgVm9sIDEwNiwgSXNzdWUgMTcw?= Message-ID: <3WjhRn1hrpzPPc@mail.python.org> Ve.,zaxfa? Odeslzvan? z telefonu HTC ----- Reply message ----- Od: python-list-request at python.org Komu: P?edm?t: Python-list Digest, Vol 106, Issue 170 Datum: ?t, 7. 26, 2012 14:10 z-- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Thu Jul 26 14:08:59 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 26 Jul 2012 20:08:59 +0200 Subject: Generating valid identifiers In-Reply-To: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <501187BB.4030207@shopzeus.com> >> * Would it be a problem to use CRC32 instead of SHA? (Since security is >> not a problem, and CRC32 is faster.) > What happens if you get a collision? > > That is, you have two different long identifiers: > > a.b.c.d...something > a.b.c.d...anotherthing > > which by bad luck both hash to the same value: > > a.b.c.d.$AABB99 > a.b.c.d.$AABB99 > > (or whatever). Yes, that was the question. How do I avoid that? (Of course I can avoid that by using a full sha256 hash value.) >> * Can somebody think of a >> better algorithm, that would give a bigger chance of recognizing the >> original identifier from the modified one? > Rather than truncating the most significant part of the identifier, the > field name, you should truncate the least important part, the middle. > > a.b.c.d.e.f.g.something > > goes to: > > a.b...g.something > > or similar. Yes, this is a good idea. Thank you. From emile at fenx.com Thu Jul 26 14:10:19 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 26 Jul 2012 11:10:19 -0700 Subject: Generating valid identifiers In-Reply-To: <50113768.6070008@shopzeus.com> References: <50113768.6070008@shopzeus.com> Message-ID: On 7/26/2012 5:26 AM Laszlo Nagy said... > I have a program that creates various database objects in PostgreSQL. > There is a DOM, and for each element in the DOM, a database object is > created (schema, table, field, index and tablespace). > > I do not want this program to generate very long identifiers. It would > increase SQL parsing time, and don't look good. Let's just say that the > limit should be 32 characters. But I also want to recognize the > identifiers when I look at their modified/truncated names. I had a similar problem with one customer where their legacy green screen app allowed only 40 characters max for the product description, but the marketing description lengths routinely ran out to 75 or so characters. In that situation I reviewed the source marketing descriptions and prepped a utility to translate common longer words or phrases to one of a selection of shortened abbreviations. I then cycled through best fitting substitutions to get as close as reasonable to the 40 character limit which generally resulted in recognizable descriptions in the legacy environment that matched by being directly derived from the longer marketing names. YMMV, Emile From rosuav at gmail.com Thu Jul 26 14:14:17 2012 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 27 Jul 2012 04:14:17 +1000 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Fri, Jul 27, 2012 at 4:01 AM, Dennis Lee Bieber wrote: > On Thu, 26 Jul 2012 19:42:11 +1000, Chris Angelico > declaimed the following in gmane.comp.python.general: > >> Well, if/while/for could be functions. So could with, probably. Now, >> def would be a little tricky... >> > And how would a function "if" perform It'd be much more similar to the ternary operator. Currently there's no way to pass an unevaluated expression to a Python function, but the concept isn't impossible. It's just more suited to functional languages (someone mentioned Haskell) than to imperative ones. > Now, how does the language differentiate between a loop and an if? > > if(conditional): > do something and continue with next statement > > turns into > True: > do something and continue with next statement > > while > > while(conditional): > do something and go back to the test > > turns into > True: > do something and go back to the test Oh THAT's easily solved. A while loop is an if with a goto! Okay, was that sufficiently incendiary? Have fun! :) ChrisA From ckaynor at zindagigames.com Thu Jul 26 14:38:47 2012 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Thu, 26 Jul 2012 11:38:47 -0700 Subject: from future import pass_function In-Reply-To: References: Message-ID: On Thu, Jul 26, 2012 at 11:01 AM, Dennis Lee Bieber wrote: > On Thu, 26 Jul 2012 19:42:11 +1000, Chris Angelico > declaimed the following in gmane.comp.python.general: > > > > Well, if/while/for could be functions. So could with, probably. Now, > > def would be a little tricky... > > > And how would a function "if" perform > > if(conditional): > would become > True: > or > False: > > What determines that branching is desired? The colon? (then what > does the colon on "def x():" perform?) > > Or take "while"... > > while condition: #implies a loop > > while(condition): #as a function implies a return value so again we > have > > True: > or > False: > > Now, how does the language differentiate between a loop and an if? > Easy, the colon specifies a magic argument to the function which is the executable block. In this way, the if function takes in a conditional, then, based on whether the conditional is true, executes the code block or not. A while loop is the same, but it just executes the block multiple times. Additionally, the function's closure is set to the current scope. Now, the real problem comes in how to write those functions - they require themselves to be defined to be functional... > > if(conditional): > do something and continue with next statement > > turns into > True: > do something and continue with next statement > > while > > while(conditional): > do something and go back to the test > > turns into > True: > do something and go back to the test > > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Jul 26 15:28:26 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 26 Jul 2012 13:28:26 -0600 Subject: Generating valid identifiers In-Reply-To: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Jul 26, 2012 at 9:30 AM, Steven D'Aprano wrote: > What happens if you get a collision? > > That is, you have two different long identifiers: > > a.b.c.d...something > a.b.c.d...anotherthing > > which by bad luck both hash to the same value: > > a.b.c.d.$AABB99 > a.b.c.d.$AABB99 > > (or whatever). The odds of a given pair of identifiers having the same digest to 10 hex digits are 1 in 16^10, or approximately 1 in a trillion. If you bought one lottery ticket a day at those odds, you would win approximately once every 3 billion years. But it's not enough just to have a hash collision, they also have to match exactly in the first 21 (or 30, or whatever) characters of their actual names, and they have to both be long enough to invoke the truncating scheme in the first place. The Oracle backend for Django uses this same approach with an MD5 sum to ensure that identifiers will be no more than 30 characters long (a hard limit imposed by Oracle). It actually truncates the hash to 4 digits, though, not 10. This hasn't caused any problems that I'm aware of. From ethan at stoneleaf.us Thu Jul 26 15:31:01 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 26 Jul 2012 12:31:01 -0700 Subject: ANN: dbf.py 0.94.003 Message-ID: <50119AF5.6020904@stoneleaf.us> A few more bug fixes, and I actually included the documentation this time. :) It can be found at http://python.org/pypi/dbf, and has been tested on CPythons 2.4 - 2.7, and PyPy 1.8. dbf v0.94.003 ============= dbf (also known as python dbase) is a module for reading/writing dBase III, FP, VFP, and Clipper .dbf database files. It's an ancient format that still finds lots of use (the most common I'm aware of is retrieving legacy data so it can be stored in a newer database system; other uses include GIS, stand-alone programs such as Family History, Personal Finance, etc.). Highlights ---------- Table -- represents a single .dbf/.dbt (or .fpt) file combination and provides access to records; suports the sequence access and 'with' protocols. Temporary tables can also live entirely in memory. Record -- repesents a single record/row in the table, with field access returning native or custom data types; supports the sequence, mapping, attribute access (with the field names as the attributes), and 'with' protocols. Updates to a record object are reflected on disk either immediately (using gather() or write()), or at the end of a 'with' statement. Fields: dBase III (Null not supported) Character --> unicode Date --> datetime.date or None Logical --> bool or None Memo --> unicode or None Numeric --> int/float depending on field definition or None Float --> same as numeric Clipper (Null not supported) Character --> unicode (character fields can be up to 65,519) Foxpro (Null supported) General --> str (treated as binary) Picture --> str (treated as binary) Visual Foxpro (Null supported) Currency --> decimal.Decimal douBle --> float Integer --> int dateTime --> datetime.datetime If a field is uninitialized (Date, Logical, Numeric, Memo, General, Picture) then None is returned for the value. Custom data types: Null --> used to support Null values Char --> unicode type that auto-trims trailing whitespace, and ignores trailing whitespace for comparisons Date --> date object that allows for no date DateTime --> datetime object that allows for no datetime Time --> time object that allows for no time Logical --> adds Unknown state to bool's: instead of True/False/None, values are Truth, Falsth, and Unknown, with appropriate tri-state logic; while bool(None) is False, bool(Unknown) raises a TypeError; __index__ of Unknown is 2 Quantum --> similar to Logical, but implements boolean algebra (I think) Whirlwind Tour -------------- import datetime import dbf table = dbf.Table(':test:', 'name C(25); age N(3,0); birth D; qualified L') table.open() for datum in ( ('Spanky', 7, dbf.Date.fromymd('20010315'), False), ('Spunky', 23, dbf.Date(1989, 07, 23), True), ('Sparky', 99, dbf.Date(), dbf.Unknown), ): table.append(datum) for record in table: print record print '--------' print record[0:3] print record['name':'birth'] print [record.name, record.age, record.birth] print '--------' custom = table.new( filename='test_on_disk', default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical), ) with custom: # automatically opened and closed for record in table: custom.append(record) for record in custom: dbf.write(record, name=record.name.upper()) print record print '--------' print record[0:3] print record['name':'birth'] print [record.name, record.age, record.birth] print '--------' table.close() From ian.g.kelly at gmail.com Thu Jul 26 16:00:58 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 26 Jul 2012 14:00:58 -0600 Subject: Generating valid identifiers In-Reply-To: References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Jul 26, 2012 at 1:28 PM, Ian Kelly wrote: > The odds of a given pair of identifiers having the same digest to 10 > hex digits are 1 in 16^10, or approximately 1 in a trillion. If you > bought one lottery ticket a day at those odds, you would win > approximately once every 3 billion years. But it's not enough just to > have a hash collision, they also have to match exactly in the first 21 > (or 30, or whatever) characters of their actual names, and they have > to both be long enough to invoke the truncating scheme in the first > place. > > The Oracle backend for Django uses this same approach with an MD5 sum > to ensure that identifiers will be no more than 30 characters long (a > hard limit imposed by Oracle). It actually truncates the hash to 4 > digits, though, not 10. This hasn't caused any problems that I'm > aware of. As a side note, the odds of having at least one hash collision among multiple tables are known as the birthday problem. At 4 hex digits there are 65536 possible digests, and it turns out that at 302 tables there is a >50% chance that at least one pair of those names have the same 4-digit digest. That doesn't mean you should be concerned if you have 302 tables in your Django Oracle database, though, because those colliding tables also have to match completely in the first 26 characters of their generated names, which is not that common. If a collision ever did occur, the resolution would be simple: manually set the name of one of the offending tables in the model definition. With 16 ** 10 possible digests, the probability of collision hits 50% at 1234605 tables. From john_ladasky at sbcglobal.net Thu Jul 26 16:48:07 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 26 Jul 2012 13:48:07 -0700 (PDT) Subject: from future import pass_function In-Reply-To: References: Message-ID: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> On Wednesday, July 25, 2012 1:40:45 AM UTC-7, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, > there could be a pass() function that does and returns nothing. I had very similar thoughts about eight months ago, and posted them here: https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A I'm no computer science guru, but the idea that pass should be a function rather than a statement continues to appeal to me. As you can see, I actually wrote just such a function so that I could use it as an argument in my code. From john_ladasky at sbcglobal.net Thu Jul 26 16:55:39 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 26 Jul 2012 13:55:39 -0700 (PDT) Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> On Wednesday, July 25, 2012 9:32:33 PM UTC-7, Ethan Furman wrote: > What code does `pass` run? When do we pass parameters to `pass`? When > do we need to override `pass`? > > Answers: None. Never. Still waiting for a reply from the OP for a use > case. When I brought up this same issue some months ago... https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A ...it wasn't because I wanted to pass parameters to "pass", it was because I wanted to define a do-nothing function as an optional behavior within another function. In other words, I wanted to pass "pass." From john_ladasky at sbcglobal.net Thu Jul 26 16:55:39 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 26 Jul 2012 13:55:39 -0700 (PDT) Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> On Wednesday, July 25, 2012 9:32:33 PM UTC-7, Ethan Furman wrote: > What code does `pass` run? When do we pass parameters to `pass`? When > do we need to override `pass`? > > Answers: None. Never. Still waiting for a reply from the OP for a use > case. When I brought up this same issue some months ago... https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A ...it wasn't because I wanted to pass parameters to "pass", it was because I wanted to define a do-nothing function as an optional behavior within another function. In other words, I wanted to pass "pass." From ethan at stoneleaf.us Thu Jul 26 17:03:24 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 26 Jul 2012 14:03:24 -0700 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <500D383A.9090500@phihag.de> <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5011B09C.1090608@stoneleaf.us> Steven D'Aprano wrote: > Python's promise is much stronger than merely "deterministic": while it > does not promise what order the keys will be returned, it does promise > that whatever that order turns out to be, they will returned in the same > order as the matching values (unless you modify the dict while iterating). or modify the dict between iterations. ~Ethan~ From ethan at stoneleaf.us Thu Jul 26 17:06:03 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 26 Jul 2012 14:06:03 -0700 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: References: <500D383A.9090500@phihag.de> <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5011B13B.202@stoneleaf.us> Chris Angelico wrote: > On Tue, Jul 24, 2012 at 1:20 AM, Steven D'Aprano > wrote: >> (Although if you think about the implementation of dicts as hash tables, >> it does seem likely that it is trivial to enforce this -- one would have >> to work *harder* to break that promise than to keep it.) > > However, it would be quite reasonable to implement a dict as a splay > tree, and have values() return them nearest-first. This would mean > that just reading from the dictionary could change the order of > values(), yet it wouldn't make the implementation non-conformant. Yes, it would. The docs say that .keys(), .values(), etc., will maintain order unless the dict is modified in between calls. ~Ethan~ From drsalists at gmail.com Thu Jul 26 17:13:19 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 26 Jul 2012 21:13:19 +0000 Subject: dict: keys() and values() order guaranteed to be same? In-Reply-To: <5011B13B.202@stoneleaf.us> References: <500D383A.9090500@phihag.de> <500d6bb2$0$29978$c3e8da3$5496439d@news.astraweb.com> <5011B13B.202@stoneleaf.us> Message-ID: On Thu, Jul 26, 2012 at 9:06 PM, Ethan Furman wrote: > Chris Angelico wrote: > >> On Tue, Jul 24, 2012 at 1:20 AM, Steven D'Aprano >> > >> wrote: >> >>> (Although if you think about the implementation of dicts as hash tables, >>> it does seem likely that it is trivial to enforce this -- one would have >>> to work *harder* to break that promise than to keep it.) >>> >> >> However, it would be quite reasonable to implement a dict as a splay >> tree, and have values() return them nearest-first. This would mean >> that just reading from the dictionary could change the order of >> values(), yet it wouldn't make the implementation non-conformant. >> > > Yes, it would. The docs say that .keys(), .values(), etc., will maintain > order unless the dict is modified in between calls. > > ~Ethan~ > -- > http://mail.python.org/**mailman/listinfo/python-list > On the other hand, it's a somewhat far-out thing to guarantee. If some things were relaxed a bit for the benefit of alternative implementations, I'd think this could be one of the things. I certainly wouldn't want to write code that depends on such a behavior, if nothing else because someday I might want to use a dict-like-object that doesn't provide such a guarantee. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhrivnak at hrivnak.org Thu Jul 26 17:15:51 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Thu, 26 Jul 2012 17:15:51 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: It's not uncommon for "pass" to be referred to as a control statement, although I see your point that it isn't exerting as much control over the flow of execution as others. As further evidence, this doc categorizes it as a "statement" within "flow control tools": http://docs.python.org/tutorial/controlflow.html Michael On Thu, Jul 26, 2012 at 2:42 AM, Ulrich Eckhardt wrote: > pass is not a control statement, it is just a placeholder to make it > explicit that there is nothing else to be expected here. > > Uli > -- > http://mail.python.org/mailman/listinfo/python-list From ian.g.kelly at gmail.com Thu Jul 26 17:18:28 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 26 Jul 2012 15:18:28 -0600 Subject: from future import pass_function In-Reply-To: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> References: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> Message-ID: On Thu, Jul 26, 2012 at 2:48 PM, John Ladasky wrote: > On Wednesday, July 25, 2012 1:40:45 AM UTC-7, Ulrich Eckhardt wrote: >> Hi! >> >> I just had an idea, it occurred to me that the pass statement is pretty >> similar to the print statement, and similarly to the print() function, >> there could be a pass() function that does and returns nothing. > > I had very similar thoughts about eight months ago, and posted them here: > > https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A > > I'm no computer science guru, but the idea that pass should be a function rather than a statement continues to appeal to me. As you can see, I actually wrote just such a function so that I could use it as an argument in my code. As long as 1) the name can't be reassigned (like None) and 2) the compiler is able to optimize it out when used by itself as a statement (to avoid incurring the expense of a common but pointless name lookup), then I kind of agree. The added complexity of those two restrictions detracts a bit from the appeal to elegance, though. From mhrivnak at hrivnak.org Thu Jul 26 17:20:32 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Thu, 26 Jul 2012 17:20:32 -0400 Subject: from future import pass_function In-Reply-To: References: Message-ID: In case the rest of the email didn't make it obvious, everything you quoted me on was sarcasm. I know those things can't be done, and I explained why they can't and shouldn't be done. Michael On Thu, Jul 26, 2012 at 5:16 AM, Devin Jeanpierre wrote: > On Thu, Jul 26, 2012 at 1:20 AM, Michael Hrivnak wrote: >> If we want pass(), then why not break() and continue()? And also >> def() and class()? for(), while(), if(), with(), we can make them all >> callable objects! > > No, you actually can't. > > You omit the one control flow statement that could actually be turned > into a function, raise. None of the rest could in Python (except > class), and one of the rest couldn't in any language (def). > > -- Devin From ethan at stoneleaf.us Thu Jul 26 17:23:02 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 26 Jul 2012 14:23:02 -0700 Subject: from future import pass_function In-Reply-To: <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> Message-ID: <5011B536.7060503@stoneleaf.us> John Ladasky wrote: > On Wednesday, July 25, 2012 9:32:33 PM UTC-7, Ethan Furman wrote: > >> What code does `pass` run? When do we pass parameters to `pass`? When >> do we need to override `pass`? >> >> Answers: None. Never. Still waiting for a reply from the OP for a use >> case. > > When I brought up this same issue some months ago... > > https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A > > ...it wasn't because I wanted to pass parameters to "pass", it was because I wanted to define a do-nothing function as an optional behavior within another function. In other words, I wanted to pass "pass." That's a reasonable thing to want, and quite easily accomplished by passing `lambda: None` or `lambda *args, **kwargs: None` instead. I don't think this is difficult to do, nor common enough to justify making every other `pass` a time-consuming do-nothing operation, instead of just a do-nothing operation ~Ethan~ From john_ladasky at sbcglobal.net Thu Jul 26 18:20:03 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 26 Jul 2012 15:20:03 -0700 (PDT) Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> Message-ID: On Thursday, July 26, 2012 2:23:02 PM UTC-7, Ethan Furman wrote: > That's a reasonable thing to want, and quite easily accomplished by > passing `lambda: None` or `lambda *args, **kwargs: None` instead. That's the same solution that Steven D'Aprano proposed the last time we had this discussion. Which, I agree, is reasonable (although I continue to have a certain instinctive aversion to lambda). From john_ladasky at sbcglobal.net Thu Jul 26 18:20:03 2012 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 26 Jul 2012 15:20:03 -0700 (PDT) Subject: from future import pass_function In-Reply-To: References: <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <6ef13dc9-ad5c-4ed7-9b5c-36f98cd90bb1@googlegroups.com> Message-ID: On Thursday, July 26, 2012 2:23:02 PM UTC-7, Ethan Furman wrote: > That's a reasonable thing to want, and quite easily accomplished by > passing `lambda: None` or `lambda *args, **kwargs: None` instead. That's the same solution that Steven D'Aprano proposed the last time we had this discussion. Which, I agree, is reasonable (although I continue to have a certain instinctive aversion to lambda). From ethan at stoneleaf.us Thu Jul 26 18:35:51 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 26 Jul 2012 15:35:51 -0700 Subject: from future import pass_function In-Reply-To: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> References: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> Message-ID: <5011C647.10106@stoneleaf.us> John Ladasky wrote: > I had very similar thoughts about eight months ago, and posted them here: > > https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A > > I'm no computer science guru, but the idea that pass should be a function rather than a statement continues to appeal to me. As you can see, I actually wrote just such a function so that I could use it as an argument in my code. I would have called `no_op` or `nop` -- `pass` does just what it says: it passes and does zero work. Your _pass does do work, just useless work. Sometimes that's necessary, but I wouldn't call it `_pass`. ~Ethan~ From mailing at franzoni.eu Thu Jul 26 19:03:01 2012 From: mailing at franzoni.eu (Alan Franzoni) Date: Fri, 27 Jul 2012 01:03:01 +0200 Subject: codecs.register_error for "strict", unicode.encode() and str.decode() Message-ID: <5011CCA5.408@franzoni.eu> Hello, I think I'm missing some piece here. I'm trying to register a default error handler for handling exceptions for preventing encoding/decoding errors (I know how this works and that making this global is probably not a good practice, but I found this strange behaviour while writing a proof of concept of how to let Python work in a more forgiving way). What I discovered is that register_error() for "strict" seems to work in the way I expect for string decoding, not for unicode encoding. That's what happens on Mac, Python 2.7.1 from Apple: melquiades:tmp alan$ cat minimal_test_encode.py # -*- coding: utf-8 -*- import codecs def handle_encode(e): return ("ASD", e.end) codecs.register_error("strict", handle_encode) print u"?".encode("ascii") melquiades:tmp alan$ python minimal_test_encode.py Traceback (most recent call last): File "minimal_test_encode.py", line 10, in u"?".encode("ascii") UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 0: ordinal not in range(128) OTOH this works properly: melquiades:tmp alan$ cat minimal_test_decode.py # -*- coding: utf-8 -*- import codecs def handle_decode(e): return (u"ASD", e.end) codecs.register_error("strict", handle_decode) print "?".decode("ascii") melquiades:tmp alan$ python minimal_test_decode.py ASDASD What piece am I missing? The doc at http://docs.python.org/library/codecs.html says " For encoding /error_handler/ will be called with a UnicodeEncodeError instance, which contains information about the location of the error.", is there any reason why the standard "strict" handler cannot be replaced? Thanks for any clue. File links: https://dl.dropbox.com/u/249926/minimal_test_decode.py https://dl.dropbox.com/u/249926/minimal_test_encode.py -- Alan Franzoni contact me at public@[mysurname].eu From breamoreboy at yahoo.co.uk Thu Jul 26 19:23:04 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Jul 2012 00:23:04 +0100 Subject: from future import pass_function In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> Message-ID: On 26/07/2012 18:19, Prasad, Ramit wrote: >> No offence to all the well meaning participants here, but this looks like trolling > > I thought Ranting Rick had sole dominion over trolling? Incorrect. Yes he can be a PITA but when he writes about tkinter/idle he appears to know what he's talking about. I much prefer that to The World's Leading Expert On Writing Documentation aka Xah Lee who must spend his entire life sittng down as his voice is so muffled. > > Ramit > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Thu Jul 26 19:25:01 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Jul 2012 00:25:01 +0100 Subject: from future import pass_function In-Reply-To: References: <500fd986$0$29978$c3e8da3$5496439d@news.astraweb.com> <5010adb8$0$29978$c3e8da3$5496439d@news.astraweb.com> <50110d59$0$11120$c3e8da3@news.astraweb.com> <5011606c$0$29978$c3e8da3$5496439d@news.astraweb.com> <5B80DD153D7D744689F57F4FB69AF4741658DF5E@SCACMX008.exchad.jpmchase.net> Message-ID: On 26/07/2012 18:33, Chris Angelico wrote: > On Fri, Jul 27, 2012 at 3:19 AM, Prasad, Ramit > wrote: >>> No offence to all the well meaning participants here, but this looks like trolling >> >> I thought Ranting Rick had sole dominion over trolling? > > Certainly not. We are well endowed with trolls here (Xah Lee isn't > prolific, but is certainly effective), plus we have some regular > posters who'll cover the trolls' tea breaks on occasion (myself, > sometimes, and Steven D'Aprano). > > Now where did I put my asbestos suit... the Aprano is going to be at > me pretty hard for this... Are you nuts, asbestos? My tin hat, camouflage net and trenching tool are very much safer :) > > *dives for cover without it* > > ChrisA > -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Thu Jul 26 19:34:23 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 27 Jul 2012 00:34:23 +0100 Subject: pexcept module In-Reply-To: <003001cd6a58$d11d5840$735808c0$@teledna.com> References: <003001cd6a58$d11d5840$735808c0$@teledna.com> Message-ID: On 25/07/2012 12:29, Pritam Das wrote: > Is dere any good tutorial for pexcept module. > google and ye shall find. > > Regards, > > Pritam Das > -- Cheers. Mark Lawrence. From simoncropper at fossworkflowguides.com Thu Jul 26 21:22:11 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 27 Jul 2012 11:22:11 +1000 Subject: ANN: dbf.py 0.94.003 In-Reply-To: <50119AF5.6020904@stoneleaf.us> References: <50119AF5.6020904@stoneleaf.us> Message-ID: <5011ED43.1050809@fossworkflowguides.com> On 27/07/12 05:31, Ethan Furman wrote: > A few more bug fixes, and I actually included the documentation this > time. :) It can be found at http://python.org/pypi/dbf, and has been > tested on CPythons 2.4 - 2.7, and PyPy 1.8. [snip] Ethan, That's great. Can you comment on the ultimate aim of the project? Is this package primarily a "universal dbf translator" that allows the data stored in DBFs (which I might add I have many in legacy VFP applications and GIS Shapefiles) to be accessed and extracted or is the module being designed to be used interactively to extract data from and update tables? I remember on the last thread that someone mentioned that indexes are not supported. I presume then that moving around a table with a couple of million records might be a tad slow. Have you tested the package on large datasets, both DBFs with a large number of records as well as a large number of fields? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From d at davea.name Thu Jul 26 21:48:48 2012 From: d at davea.name (Dave Angel) Date: Thu, 26 Jul 2012 21:48:48 -0400 Subject: pexcept module In-Reply-To: <003001cd6a58$d11d5840$735808c0$@teledna.com> References: <003001cd6a58$d11d5840$735808c0$@teledna.com> Message-ID: <5011F380.1010702@davea.name> On 07/25/2012 07:29 AM, Pritam Das wrote: > Is dere any good tutorial for pexcept module. > > As far as I can tell, there's no such module in the standard library. If you're talking about some 3r4 party product, it'd be polite to specify which one. Try: http://pexpect.sourceforge.net/pexpect.html But I have no idea if that's the one you want, nor if there's any tutorial. Usually tutorials for obscure modules are available from the author, or not at all. -- DaveA From steve+comp.lang.python at pearwood.info Thu Jul 26 21:54:07 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Jul 2012 01:54:07 GMT Subject: Generating valid identifiers References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5011f4be$0$29978$c3e8da3$5496439d@news.astraweb.com> On Thu, 26 Jul 2012 13:28:26 -0600, Ian Kelly wrote: > The odds of a given pair of identifiers having the same digest to 10 hex > digits are 1 in 16^10, or approximately 1 in a trillion. Unless an attacker can select the field names, in which case they may be able to improve those odds significantly. In the case of MD5, they can possibly improve those odds to 1 in 1, since MD5 is vulnerable to collision attacks. Not so for some (all?) of the SHA hashes, at least not yet, but they're much more expensive to calculate. If the OP sticks with his intention to use CRC32, the odds won't be anywhere near that low. CRC32 is neither collision-resistant nor cryptographically random, and only generates eight hex digits, not ten. -- Steven From tjreedy at udel.edu Fri Jul 27 00:21:56 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Jul 2012 00:21:56 -0400 Subject: from future import pass_function In-Reply-To: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> References: <5571fa66-edf7-4fb4-8ae4-87ad70c32abc@googlegroups.com> Message-ID: On 7/26/2012 4:48 PM, John Ladasky wrote: > I had very similar thoughts about eight months ago, and posted them > here: > > https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/CB_5fek2b8A > > I'm no computer science guru, but the idea that pass should be a > function rather than a statement continues to appeal to me. A do nothing statement is standard in statement based languages. It is not going away. > can see, I actually wrote just such a function so that I could use it > as an argument in my code. For one time use: lambda:None For multiple use: def none: pass # same as return None in this context A function needs a lot more meat than that to be added as a builtin. --- Terry Jan Reedy From ulrich.eckhardt at dominolaser.com Fri Jul 27 02:39:22 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Fri, 27 Jul 2012 08:39:22 +0200 Subject: from future import pass_function In-Reply-To: References: Message-ID: Am 26.07.2012 09:50, schrieb Mark Lawrence: > And if we could persuade the BDFL to introduce braces, we could have {() > and }() What do you mean "persuade"? Braces work perfectly: def foo(): {} Uli From __peter__ at web.de Fri Jul 27 03:16:48 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jul 2012 09:16:48 +0200 Subject: codecs.register_error for "strict", unicode.encode() and str.decode() References: <5011CCA5.408@franzoni.eu> Message-ID: Alan Franzoni wrote: > Hello, > I think I'm missing some piece here. > > I'm trying to register a default error handler for handling exceptions > for preventing encoding/decoding errors (I know how this works and that > making this global is probably not a good practice, but I found this > strange behaviour while writing a proof of concept of how to let Python > work in a more forgiving way). > > What I discovered is that register_error() for "strict" seems to work in > the way I expect for string decoding, not for unicode encoding. > > That's what happens on Mac, Python 2.7.1 from Apple: > > melquiades:tmp alan$ cat minimal_test_encode.py > # -*- coding: utf-8 -*- > > import codecs > > def handle_encode(e): > return ("ASD", e.end) > > codecs.register_error("strict", handle_encode) > > print u"?".encode("ascii") > > melquiades:tmp alan$ python minimal_test_encode.py > Traceback (most recent call last): > File "minimal_test_encode.py", line 10, in > u"?".encode("ascii") > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in > position 0: ordinal not in range(128) > > > OTOH this works properly: > > melquiades:tmp alan$ cat minimal_test_decode.py > # -*- coding: utf-8 -*- > > import codecs > > def handle_decode(e): > return (u"ASD", e.end) > > codecs.register_error("strict", handle_decode) > > print "?".decode("ascii") > > melquiades:tmp alan$ python minimal_test_decode.py > ASDASD > > > What piece am I missing? The doc at > http://docs.python.org/library/codecs.html says " For > encoding /error_handler/ will be called with a UnicodeEncodeError > > instance, which contains information about the location of the error.", is > there any reason why the standard "strict" handler cannot be replaced? The error handling for the standard erorrs "strict", "replace", "ignore", and "xmlcharrefreplace" is hardwired, see function unicode_encode_ucs1 in Lib/unicodeobject.c: if (known_errorHandler==-1) { if ((errors==NULL) || (!strcmp(errors, "strict"))) known_errorHandler = 1; ... switch (known_errorHandler) { case 1: /* strict */ raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason); goto onError; You need another gun to shoot yourself in the foot ;) From gandalf at shopzeus.com Fri Jul 27 03:28:56 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 27 Jul 2012 09:28:56 +0200 Subject: Generating valid identifiers In-Reply-To: References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50124338.1030002@shopzeus.com> > As a side note, the odds of having at least one hash collision among > multiple tables are known as the birthday problem. At 4 hex digits > there are 65536 possible digests, and it turns out that at 302 tables > there is a >50% chance that at least one pair of those names have the > same 4-digit digest. That doesn't mean you should be concerned if you > have 302 tables in your Django Oracle database, though, because those > colliding tables also have to match completely in the first 26 > characters of their generated names, which is not that common. If a > collision ever did occur, the resolution would be simple: manually set > the name of one of the offending tables in the model definition. > > With 16 ** 10 possible digests, the probability of collision hits 50% > at 1234605 tables. Thank you for the precise explanation. :-) Well, if Django and Oracle uses this, then it can't be a very bad idea. :-) From gandalf at shopzeus.com Fri Jul 27 03:34:48 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 27 Jul 2012 09:34:48 +0200 Subject: Generating valid identifiers In-Reply-To: <5011f4be$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> <5011f4be$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50124498.6060100@shopzeus.com> > Unless an attacker can select the field names, in which case they may be > able to improve those odds significantly. In the case of MD5, they can > possibly improve those odds to 1 in 1, since MD5 is vulnerable to > collision attacks. Not so for some (all?) of the SHA hashes, at least not > yet, but they're much more expensive to calculate. > > If the OP sticks with his intention to use CRC32, the odds won't be > anywhere near that low. CRC32 is neither collision-resistant nor > cryptographically random, and only generates eight hex digits, not ten. > > I'm not affraid of attackers. As I said, nobody will want to "crack" the hash. This is for an in-house project. Only the dba can create new database objects. If the dba wants to do something wrong, he can simply delete whole database. He doesn't need to crack any hash value. :-) So yes, CRC32 is not collision-resistant, and not cryptographically random. But in my case, sha256 is not collision resistant either (because I'm using the first few chars of the digest value only). And cryptographic randomness is not a requirement. Given these circumstances, maybe using CRC32 would be fine too. I wonder what kind of hash Django uses for Oracle. From andrea.crotti.0 at gmail.com Fri Jul 27 05:36:34 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Fri, 27 Jul 2012 10:36:34 +0100 Subject: regexps to objects Message-ID: I have some complex input to parse (with regexps), and I would like to create nice objects directy from them. The re module doesn't of course try to conver to any type, so I was playing around to see if it's worth do something as below, where I assign a constructor to every regexp and build an object from the result.. Do you think it makes sense in general or how do you cope with this problem? import re from time import strptime TIME_FORMAT_INPUT = '%m/%d/%Y %H:%M:%S' def time_string_to_obj(timestring): return strptime(timestring, TIME_FORMAT_INPUT) REGEXPS = { 'num': ('\d+', int), 'date': ('[0-9/]+ [0-9:]+', time_string_to_obj), } def reg_to_obj(reg, st): reg, constr = reg found = re.match(reg, st) return constr(found.group()) if __name__ == '__main__': print reg_to_obj(REGEXPS['num'], '100') print reg_to_obj(REGEXPS['date'], '07/24/2012 06:23:13') From gandalf at shopzeus.com Fri Jul 27 05:59:28 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 27 Jul 2012 11:59:28 +0200 Subject: Generating valid identifiers In-Reply-To: References: <50116281$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50126680.4080308@shopzeus.com> > With 16 ** 10 possible digests, the probability of collision hits 50% at 1234605 tables Actually, I'm using base64 encoding. So it is 64**10. I guess using 6 characters will enough. From __peter__ at web.de Fri Jul 27 06:24:41 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jul 2012 12:24:41 +0200 Subject: regexps to objects References: Message-ID: andrea crotti wrote: > I have some complex input to parse (with regexps), and I would like to > create nice objects directy from them. > The re module doesn't of course try to conver to any type, so I was > playing around to see if it's worth do something as below, where I > assign a constructor to every regexp and build an object from the > result.. > > Do you think it makes sense in general or how do you cope with this > problem? > > import re > from time import strptime > TIME_FORMAT_INPUT = '%m/%d/%Y %H:%M:%S' > > def time_string_to_obj(timestring): > return strptime(timestring, TIME_FORMAT_INPUT) > > > REGEXPS = { > 'num': ('\d+', int), > 'date': ('[0-9/]+ [0-9:]+', time_string_to_obj), > } > > > def reg_to_obj(reg, st): > reg, constr = reg > found = re.match(reg, st) > return constr(found.group()) > > > if __name__ == '__main__': > print reg_to_obj(REGEXPS['num'], '100') > print reg_to_obj(REGEXPS['date'], '07/24/2012 06:23:13') There is an undocumented Scanner class in the re module: >>> from datetime import datetime >>> from re import Scanner >>> sc = Scanner([ ... ("[0-9/]+ [0-9:]+", lambda self, s: datetime.strptime(s, "%m/%d/%Y %H: %M:%S")), ... (r"\d+", lambda self, s: int(s)), ... ("\s+", lambda self, s: None)]) >>> sc.scan("07/24/2012 06:23:13") ([datetime.datetime(2012, 7, 24, 6, 23, 13)], '') >>> sc.scan("07/24/2012 06:23:13 123") ([datetime.datetime(2012, 7, 24, 6, 23, 13), 123], '') However: >>> sc.scan("456 07/24/2012 06:23:13 123") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/re.py", line 322, in scan action = action(self, m.group()) File "", line 2, in File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime (data_string, format)) ValueError: time data '456 07' does not match format '%m/%d/%Y %H:%M:%S' From ethan at stoneleaf.us Fri Jul 27 06:50:39 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 27 Jul 2012 03:50:39 -0700 Subject: ANN: dbf.py 0.94.003 In-Reply-To: <5011ED43.1050809@fossworkflowguides.com> References: <50119AF5.6020904@stoneleaf.us> <5011ED43.1050809@fossworkflowguides.com> Message-ID: <5012727F.9050908@stoneleaf.us> Simon Cropper wrote: > On 27/07/12 05:31, Ethan Furman wrote: >> A few more bug fixes, and I actually included the documentation this >> time. :) It can be found at http://python.org/pypi/dbf, and has been >> tested on CPythons 2.4 - 2.7, and PyPy 1.8. > > [snip] > > Ethan, > > That's great. > > Can you comment on the ultimate aim of the project? To provide read/write access to the dbf format, from dBase III to dBase 7, including memos and index files. Currently supports dBase III, FoxPro, Clipper, and Visual Foxpro (but not autoincrement nor varchar). > Is this package primarily a "universal dbf translator" that allows the > data stored in DBFs (which I might add I have many in legacy VFP > applications and GIS Shapefiles) to be accessed and extracted or is the > module being designed to be used interactively to extract data from and > update tables? Some folk use it as a dbf translator, some folk use it for interactive work. I use it for both those purposes as well as creating new dbf files which get processed by our in-house software as well as third-party software every day. > I remember on the last thread that someone mentioned that indexes are > not supported. I presume then that moving around a table with a couple > of million records might be a tad slow. Have you tested the package on > large datasets, both DBFs with a large number of records as well as a > large number of fields? The largest tables I've had at my disposal so far were about 300,000 records with roughly 50 fields with a total record length of about 1,500. Processing (for me) involves going through every single record, and yes it was a tad slow. This is my most common scenario, and index files would not help at all. For more typical work (for others) of selecting and using a subset of the dbf, an in-memory index can be created -- initial creation can take a few moments, but searches afterwards are quite quick. This is a pure-python implementation, so speed is not the first goal. At some point in the future I would like to create a C accelerator, but that's pretty far down the to-do list. ~Ethan~ From andrea.crotti.0 at gmail.com Fri Jul 27 07:01:03 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Fri, 27 Jul 2012 12:01:03 +0100 Subject: reloading code and multiprocessing In-Reply-To: References: Message-ID: 2012/7/25 andrea crotti : > > I would also like to avoid this in general, but we have many > subprocesses to launch and some of them might take weeks, so we need > to have a process which is always running, because there is never a > point in time where we can just say let's stop everything and start again.. > > Anyway if there are better solutions I'm still glad to hear them, but > I would also like to keep it simple.. > > Another thing which now we need to figure out is how to communicate > with the live process.. For example we might want to submit something > manually, which should pass from the main process. > > The first idea is to have a separate process that opens a socket and > listens for data on a local port, with a defined protocol. > > Then the main process can parse these commands and run them. > Are there easier ways otherwise? So I was trying to do this, removing the module from sys.modules and starting a new process (after modifying the file), but it doesn't work as I expected. The last assertion fails, but how? The pyc file is not generated, the module is actually not in sys.modules, and the function doesn't in the subprocess doesn't fail but still returns the old value. Any idea? old_a = "def ret(): return 0" new_a = "def ret(): return 1" def func_no_import(queue): queue.put(a_glob.ret()) class TestMultiProc(unittest.TestCase): def test_reloading_with_global_import(self): """In this case the import is done before the process are started, so we need to clean sys.modules to make sure we reload everything """ queue = Queue() open(path.join(CUR_DIR, 'old_a.py'), 'w').write(old_a) p1 = Process(target=func_no_import, args=(queue, )) p1.start() p1.join() self.assertEqual(queue.get(), 0) open(path.join(CUR_DIR, 'old_a.py'), 'w').write(new_a) del sys.modules['auto_tester.tests.a_glob'] p2 = Process(target=func_no_import, args=(queue, )) p2.start() p2.join() self.assertEqual(queue.get(), 1) From mariano.difelice at gmail.com Fri Jul 27 08:49:45 2012 From: mariano.difelice at gmail.com (Mariano Di Felice) Date: Fri, 27 Jul 2012 05:49:45 -0700 (PDT) Subject: dynamic setattr Message-ID: <74e41386-a08c-44bb-8793-bcbb2b73fd4c@googlegroups.com> Hi, I have a property file (.ini) that has multiple sections and relative keys, as default structure. Now, I would like to export from my utility class methods getter and setter. I have started as is: class Utility: keys = {"STANDUP": ["st_key1", "st_key2", "st_key3", "st_key4"], "DEFAULT": ["def_key1", "def_key2", "def_key3", "def_key4", "def_key5"]} def __init__(self): for section, keyList in keys .items(): for key in keyList: setattr(self, "get_%s" % key, self.get_value(section, key)) setattr(self, "set_%s" % key, lambda value:self.set_value(section, key, value) ) def get_value(section, key): if file_ini.has_option(section, key): return lambda: file_ini.get(section, key) return lambda: None def set_value(section, key, value): print "set section: %s - key: %s - value: %s" % (section, key, value) if file_ini.has_option(section, key): file_ini.set(section , key ,value) if __name__ == "__main__": utility = Utility() print "key2: %s" % utility.get_def_key2() ## -> value return 100 print "set value 50 to def_key2" utility.set_def_key2(50) print "new value def_key2: %s" % utility.get_def_key2() ## -> value return 100 Well, when in code I set value 50 to def_key2, return value of key st_key4 of STANDUP section!!!! Why? "set section STANDUP - key st_key4 - value: 200" Can anyone help me, please??? Thx in Advance From steve+comp.lang.python at pearwood.info Fri Jul 27 09:46:59 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Jul 2012 13:46:59 GMT Subject: dynamic setattr References: <74e41386-a08c-44bb-8793-bcbb2b73fd4c@googlegroups.com> Message-ID: <50129bd3$0$29978$c3e8da3$5496439d@news.astraweb.com> On Fri, 27 Jul 2012 05:49:45 -0700, Mariano Di Felice wrote: > Hi, > I have a property file (.ini) that has multiple sections and relative > keys, as default structure. Have you looked at Python's standard INI file library? http://docs.python.org/library/configparser.html > Now, I would like to export from my utility class methods getter and > setter. I have started as is: > > class Utility: > > keys = {"STANDUP": ["st_key1", "st_key2", "st_key3", "st_key4"], > "DEFAULT": ["def_key1", "def_key2", "def_key3", > "def_key4", "def_key5"]} This defines a *shared* class attribute. As it is attached to the class, not an instance, every instance will see the same shared dict. > def __init__(self): > for section, keyList in keys .items(): > for key in keyList: As given, this is a SyntaxError. Please do not retype your code from memory, always COPY AND PASTE your actual code. In this case, it is easy to fix the syntax error by fixing the indentation. But what other changes have you made by accident? Your code: def __init__(self): for section, keyList in keys .items(): looks for a *global variable* called keys, *not* the shared class attribute Utility.keys. By design, attributes are not in the function scope. If you want to access an attribute, whether class or instance, you must always refer to them as attributes. def __init__(self): for section, keyList in self.keys.items(): # this will work > setattr(self, "get_%s" % key, self.get_value(section, > key)) > setattr(self, "set_%s" % key, lambda > value:self.set_value(section, key, value) ) What a mess. What is the purpose of this jumble of code? My guess is that you are experienced with Java, and you are trying to adapt Java idioms and patterns to Python. Before you do this, you should read these two articles by a top Python developer who also knows Java backwards: http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html > if __name__ == "__main__": > utility = Utility() > print "key2: %s" % utility.get_def_key2() ## -> value return 100 Again, another SyntaxError. This can be fixed. But the next part cannot. Except for two comments, 100 does not exist in your sample code. Python doesn't magically set values to 100. The code you give cannot possibly return 100 since nowhere in your code does it set anything to 100. If you actually run the code you provide (after fixing the SyntaxErrors), you get this error: py> utility = Utility() Traceback (most recent call last): File "", line 1, in File "", line 5, in __init__ NameError: global name 'keys' is not defined If you fix that and try again, you get this error: py> utility = Utility() Traceback (most recent call last): File "", line 1, in File "", line 7, in __init__ TypeError: get_value() takes exactly 2 arguments (3 given) The results you claim you get are not true. Please read this page and then try again: http://sscce.org/ -- Steven From mariano.difelice at gmail.com Fri Jul 27 09:59:55 2012 From: mariano.difelice at gmail.com (Mariano Di Felice) Date: Fri, 27 Jul 2012 06:59:55 -0700 (PDT) Subject: dynamic setattr In-Reply-To: <50129bd3$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <74e41386-a08c-44bb-8793-bcbb2b73fd4c@googlegroups.com> <50129bd3$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4fa306b2-ce51-4e56-a866-40cb31328760@googlegroups.com> Hi Steven, Sorry for inconvenients. I've posted "unsyntax" example just typing from here, just for exaplain my problem Finally, I don't understand why every set_ set value on wrong section/key. I think setattr syntax is correct, but it doesn't works! About java/python concept, yeah! You all right! But I need a conversion class (as Utility) that expose getter/setter of any keys. Thx! Il giorno venerd? 27 luglio 2012 15:46:59 UTC+2, Steven D'Aprano ha scritto: > On Fri, 27 Jul 2012 05:49:45 -0700, Mariano Di Felice wrote: > > > Hi, > > I have a property file (.ini) that has multiple sections and relative > > keys, as default structure. > > Have you looked at Python's standard INI file library? I already use it! > > http://docs.python.org/library/configparser.html > > > > Now, I would like to export from my utility class methods getter and > > setter. I have started as is: > > > > class Utility: > > > > keys = {"STANDUP": ["st_key1", "st_key2", "st_key3", "st_key4"], > > "DEFAULT": ["def_key1", "def_key2", "def_key3", > > "def_key4", "def_key5"]} > > This defines a *shared* class attribute. As it is attached to the class, > not an instance, every instance will see the same shared dict. > > > > def __init__(self): > > for section, keyList in keys .items(): > > for key in keyList: > > As given, this is a SyntaxError. Please do not retype your code from > memory, always COPY AND PASTE your actual code. > > In this case, it is easy to fix the syntax error by fixing the > indentation. But what other changes have you made by accident? > > Your code: > > def __init__(self): > for section, keyList in keys .items(): > > looks for a *global variable* called keys, *not* the shared class > attribute Utility.keys. By design, attributes are not in the function > scope. If you want to access an attribute, whether class or instance, you > must always refer to them as attributes. > > > def __init__(self): > for section, keyList in self.keys.items(): # this will work > > > > setattr(self, "get_%s" % key, self.get_value(section, > > key)) > > setattr(self, "set_%s" % key, lambda > > value:self.set_value(section, key, value) ) > > > What a mess. What is the purpose of this jumble of code? > > My guess is that you are experienced with Java, and you are trying to > adapt Java idioms and patterns to Python. Before you do this, you should > read these two articles by a top Python developer who also knows Java > backwards: > > http://dirtsimple.org/2004/12/python-is-not-java.html > http://dirtsimple.org/2004/12/java-is-not-python-either.html > > > > > if __name__ == "__main__": > > utility = Utility() > > print "key2: %s" % utility.get_def_key2() ## -> value return 100 > > Again, another SyntaxError. This can be fixed. But the next part cannot. > > Except for two comments, 100 does not exist in your sample code. Python > doesn't magically set values to 100. The code you give cannot possibly > return 100 since nowhere in your code does it set anything to 100. > > If you actually run the code you provide (after fixing the SyntaxErrors), > you get this error: > > py> utility = Utility() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 5, in __init__ > NameError: global name 'keys' is not defined > > > If you fix that and try again, you get this error: > > py> utility = Utility() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 7, in __init__ > TypeError: get_value() takes exactly 2 arguments (3 given) > > > The results you claim you get are not true. > > > Please read this page and then try again: > > http://sscce.org/ > > > > -- > Steven From benoist at ibpc.fr Fri Jul 27 10:26:33 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Fri, 27 Jul 2012 16:26:33 +0200 Subject: argparse limitations Message-ID: Hi, I'm impletting a tool in Python. I'd like this tool to behave like a standard unix tool, as grep for exemple. I chose to use the argparse module to parse the command line and I think I'm getting into several limitations of this module. > First Question. How can I configure the the ArgumentParser to allow the user to give either an input file or to pipe the output from another program? $ mytool.py file.txt $ cat file.txt | mytool.py > Second Question. How can I get the nargs options working with subparser? Cause basically if I've got a positionnal argument with nargs > 1, then the subparsers are recognized as values for the positionnal argument. $ mytool.py file1.txt file2.txt foo Here foo is a command I'd like to pass to mytool but argparse considers it's another input file (as are file1.txt and file2.txt). Any help would be appreciated. Ben. From jeanpierreda at gmail.com Fri Jul 27 10:43:30 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 27 Jul 2012 10:43:30 -0400 Subject: PyCon for students? Message-ID: Hey guys, I recently saw a post saying that PyCon for students' price was dropped to $100. If you are trying to attract students, why not move PyCon to take place during the summer? As far as I know, summer vs spring makes no difference to any members of the general working population (except for teachers and such, who have the same schedule as students), but for students it's the difference between missing a week of school (or, worse, exams), and being able to do whatever because it's the summer vacation. -- Devin From oscar.benjamin at bristol.ac.uk Fri Jul 27 10:43:59 2012 From: oscar.benjamin at bristol.ac.uk (Oscar Benjamin) Date: Fri, 27 Jul 2012 15:43:59 +0100 Subject: argparse limitations In-Reply-To: References: Message-ID: On 27 July 2012 15:26, Benoist Laurent wrote: > Hi, > > I'm impletting a tool in Python. > I'd like this tool to behave like a standard unix tool, as grep for > exemple. > I chose to use the argparse module to parse the command line and I think > I'm getting into several limitations of this module. > > > First Question. > How can I configure the the ArgumentParser to allow the user to give > either an input file or to pipe the output from another program? > > $ mytool.py file.txt $ cat file.txt | mytool.py > A better way to do that last line is: $ mytool.py < file.txt To answer the question, just make the first argument optional defaulting to None. Then you can do: if file1 is None: file1 = sys.stdin > > > > Second Question. > How can I get the nargs options working with subparser? > Cause basically if I've got a positionnal argument with nargs > 1, then > the subparsers are recognized as values for the positionnal argument. > > $ mytool.py file1.txt file2.txt foo > > Here foo is a command I'd like to pass to mytool but argparse considers > it's another input file (as are file1.txt and file2.txt). > I haven't used subparsers in argparse but I imagine that you would call it like: $ mytool.py foo file1.txt file2.txt Cheers, Oscar. > > Any help would be appreciated. > Ben. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Fri Jul 27 10:51:48 2012 From: roy at panix.com (Roy Smith) Date: Fri, 27 Jul 2012 10:51:48 -0400 Subject: Initial nose experience References: Message-ID: In article , Roy Smith wrote: > Lastly, nose, by default, doesn't say much. When things go wrong and > you have no clue what's happening, --verbose and --debug are your > friends. I found another example of nose not saying much, and this one is kind of annoying. Unittest has much richer assertions, and better reporting when they fail. If a nose assertion fails, you just get: ------------------------------------------------------------------ Traceback (most recent call last): File "/home/roy/production/python/lib/python2.6/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/home/roy/songza/pyza/djapi/test_middleware.py", line 48, in test_update_non_json_cookie assert user_list == [9990] AssertionError ------------------------------------------------------------------ Under unittest, it would have printed the value of user_list. Yeah, I know, I can stick a "print user_list" statement into the test, and the output will get suppressed if the test fails. But that means when a test fails, I need to go back and edit the test code, which is a pain. On the other hand, there *is* an incremental efficiency gain of writing: assert x == y instead of assertEqual(x, y) many times. So maybe overall it's a wash. From benoist at ibpc.fr Fri Jul 27 11:19:04 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Fri, 27 Jul 2012 17:19:04 +0200 Subject: argparse limitations In-Reply-To: References: Message-ID: Le Jul 27, 2012 ? 4:43 PM, Oscar Benjamin a ?crit : > > > On 27 July 2012 15:26, Benoist Laurent wrote: > Hi, > > I'm impletting a tool in Python. > I'd like this tool to behave like a standard unix tool, as grep for exemple. > I chose to use the argparse module to parse the command line and I think I'm getting into several limitations of this module. > > > First Question. > How can I configure the the ArgumentParser to allow the user to give either an input file or to pipe the output from another program? > > $ mytool.py file.txt > $ cat file.txt | mytool.py > > A better way to do that last line is: > $ mytool.py < file.txt > > To answer the question, just make the first argument optional defaulting to None. Then you can do: > if file1 is None: > file1 = sys.stdin That's the solution I came to. But I'm not very happy with this since I can definitively not make my program act as a standard unix tool. Any other solution? > > > > > Second Question. > How can I get the nargs options working with subparser? > Cause basically if I've got a positionnal argument with nargs > 1, then the subparsers are recognized as values for the positionnal argument. > > $ mytool.py file1.txt file2.txt foo > > Here foo is a command I'd like to pass to mytool but argparse considers it's another input file (as are file1.txt and file2.txt). > > I haven't used subparsers in argparse but I imagine that you would call it like: > $ mytool.py foo file1.txt file2.txt As far as I know it is not the case. Let's get into the code. parser = argparse.ArgumentParser() parser.add_argument("-i", help="input files", nargs="+") subparsers = parser.add_subparsers() foo_parser = subparser.add_parser("foo") # ... here come some foo parser options bar_parser = subparser.add_parser("bar") # ... here come some bar parser options What argparse expects is the "-i" arguments coming before the subparsers. To summarize, if I adopt your solution to my first question, the I should add the "-i" argument to each subparser. I don't want to since it's ugly and I'd have to write the help myself (which I don't want to). Cheers > > > Cheers, > Oscar. > > > > Any help would be appreciated. > Ben. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jul 27 11:44:44 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jul 2012 17:44:44 +0200 Subject: argparse limitations References: Message-ID: Benoist Laurent wrote: > I'm impletting a tool in Python. > I'd like this tool to behave like a standard unix tool, as grep for > exemple. I chose to use the argparse module to parse the command line and > I think I'm getting into several limitations of this module. > >> First Question. > How can I configure the the ArgumentParser to allow the user to give > either an input file or to pipe the output from another program? > > $ mytool.py file.txt > $ cat file.txt | mytool.py $ echo alpha > in.txt $ cat in.txt | ./mytool.py ALPHA $ cat in.txt | ./mytool.py - out.txt $ cat out.txt ALPHA $ ./mytool.py in.txt ALPHA $ ./mytool.py in.txt out2.txt $ cat out2.txt ALPHA $ cat ./mytool.py #!/usr/bin/env python assert __name__ == "__main__" import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin) parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), default=sys.stdout) args = parser.parse_args() args.outfile.writelines(line.upper() for line in args.infile) Is that good enough? From ian.g.kelly at gmail.com Fri Jul 27 12:26:14 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 27 Jul 2012 10:26:14 -0600 Subject: argparse limitations In-Reply-To: References: Message-ID: On Fri, Jul 27, 2012 at 9:19 AM, Benoist Laurent wrote: > That's the solution I came to. > But I'm not very happy with this since I can definitively not make my > program act as a standard unix tool. > Any other solution? I don't understand; that's pretty much the same way that standard unix tools implement stdin redirection. What specific behavior are you looking for that you're missing with Oscar or Peter's suggestions? > As far as I know it is not the case. > Let's get into the code. > > parser = argparse.ArgumentParser() > parser.add_argument("-i", help="input files", nargs="+") > > subparsers = parser.add_subparsers() > foo_parser = subparser.add_parser("foo") > # ... here come some foo parser options > bar_parser = subparser.add_parser("bar") > # ... here come some bar parser options > > What argparse expects is the "-i" arguments coming before the subparsers. > > To summarize, if I adopt your solution to my first question, the I should > add the "-i" argument to each subparser. > I don't want to since it's ugly and I'd have to write the help myself (which > I don't want to). argparse doesn't really handle well options or arguments with nargs="+" or "*" that come before other non-option arguments or subparser commands. If it sees the input "mytool.py -i one two foo ...", then is the "foo" part of the -i argument (a file to be read), or is it the subparser command? At this point in the parsing it can't really tell the difference, so it tacks it onto the -i list. Potentially it could figure that out later when it reaches the end of the command line, but that would require backtracking over an arbitrarily large part of the command line. Worse, if the string "foo" or "bar" appears more than once in the command line, then the command may really be ambiguous. Usually for this reason arguments with indefinite nargs will be the very last argument so they can simply consume the rest of the command line. Here's an alternate approach that does more or less what you want: parser = argparse.ArgumentParser() parser.add_argument("-i", help="input files", action="append") subparsers = parser.add_subparsers() foo_parser = subparser.add_parser("foo") # ... here come some foo parser options bar_parser = subparser.add_parser("bar") # ... here come some bar parser options >>> parser.parse_args(['-i', 'one', '-i', 'two', 'foo']) Namespace(i=['one', 'two']) It may be a bit awkward having to type "-i" once per file in the command line, but it does clear up the ambiguity. From ian.g.kelly at gmail.com Fri Jul 27 12:33:58 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 27 Jul 2012 10:33:58 -0600 Subject: argparse limitations In-Reply-To: References: Message-ID: On Fri, Jul 27, 2012 at 10:26 AM, Ian Kelly wrote: > It may be a bit awkward having to type "-i" once per file in the > command line, but it does clear up the ambiguity. Or you could bite the bullet and make the input files argument part of the subparser, which you may find ugly, but I believe it's more typical of how other tools with subcommands normally work. If one of your subcommands is a "help" command, do you really want that to accept input files? From benoist at ibpc.fr Fri Jul 27 13:08:29 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Fri, 27 Jul 2012 19:08:29 +0200 Subject: argparse limitations In-Reply-To: References: Message-ID: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> Yes basically looks like you get it. I have to further test it but my first impression is that it's correct. So actually the point was to use nargs="?". Thank you very much. Ben Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : > Benoist Laurent wrote: > >> I'm impletting a tool in Python. >> I'd like this tool to behave like a standard unix tool, as grep for >> exemple. I chose to use the argparse module to parse the command line and >> I think I'm getting into several limitations of this module. >> >>> First Question. >> How can I configure the the ArgumentParser to allow the user to give >> either an input file or to pipe the output from another program? >> >> $ mytool.py file.txt >> $ cat file.txt | mytool.py > > $ echo alpha > in.txt > $ cat in.txt | ./mytool.py > ALPHA > $ cat in.txt | ./mytool.py - out.txt > $ cat out.txt > ALPHA > $ ./mytool.py in.txt > ALPHA > $ ./mytool.py in.txt out2.txt > $ cat out2.txt > ALPHA > $ cat ./mytool.py > #!/usr/bin/env python > assert __name__ == "__main__" > > import argparse > import sys > > parser = argparse.ArgumentParser() > parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), > default=sys.stdin) > parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), > default=sys.stdout) > args = parser.parse_args() > > args.outfile.writelines(line.upper() for line in args.infile) > > Is that good enough? > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhrivnak at hrivnak.org Fri Jul 27 15:46:11 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Fri, 27 Jul 2012 15:46:11 -0400 Subject: PyCon for students? In-Reply-To: References: Message-ID: Having a conference during the summer is generally more expensive, because you have to compete with tourists for lodging and such. For this reason, summer-time conventions are often in places where nobody wants to be during the summer, like Phoenix. That said, Santa Clara probably isn't a cheap location in March, and they could probably find a non-scorching and non-touristy city that's no more expensive during the summer. So it's a balance between wanting a location that is affordable vs. a location that will give extra incentive for people to attend. Also, professional python devs like to take their vacations during the summer too, so there is potential for conflict with that. Lastly, the main conference is Friday-Sunday, and I think many students could make that work. It also probably overlaps with a lot of spring breaks. Michael P.S. Instead of doing "whatever" during the summer, many students have important internships that they don't want to skip out on any more than regular classes. On Fri, Jul 27, 2012 at 10:43 AM, Devin Jeanpierre wrote: > Hey guys, > > I recently saw a post saying that PyCon for students' price was > dropped to $100. If you are trying to attract students, why not move > PyCon to take place during the summer? As far as I know, summer vs > spring makes no difference to any members of the general working > population (except for teachers and such, who have the same schedule > as students), but for students it's the difference between missing a > week of school (or, worse, exams), and being able to do whatever > because it's the summer vacation. > > -- Devin > -- > http://mail.python.org/mailman/listinfo/python-list From todd.tabern at gmail.com Fri Jul 27 21:23:33 2012 From: todd.tabern at gmail.com (todd.tabern at gmail.com) Date: Fri, 27 Jul 2012 18:23:33 -0700 (PDT) Subject: Search and replace text in XML file? Message-ID: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> I'm looking to search an entire XML file for specific text and replace that text, while maintaining the structure of the XML file. The text occurs within multiple nodes throughout the file. I basically need to replace every occurrence C:\Program Files with C:\Program Files (x86), regardless of location. For example, that text appears within: C:\Program Files\\Map Data\Road_Centerlines.shp and also within: C:\Program Files\Templates\RoadNetwork.rtx ...among others. I've tried some non-python methods and they all ruined the XML structure. I've been Google searching all day and can only seem to find solutions that look for a specific node and replace the whole string between the tags. I've been looking at using minidom to achieve this but I just can't seem to figure out the right method. My end goal, once I have working code, is to compile an exe that can work on machines without python, allowing a user can click in order to perform the XML modification. Thanks in advance. From jason at powerpull.net Fri Jul 27 22:07:48 2012 From: jason at powerpull.net (Jason Friedman) Date: Fri, 27 Jul 2012 20:07:48 -0600 Subject: Search and replace text in XML file? In-Reply-To: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: > I'm looking to search an entire XML file for specific text and replace that text, while maintaining the structure of the XML file. The text occurs within multiple nodes throughout the file. > I basically need to replace every occurrence C:\Program Files with C:\Program Files (x86), regardless of location. For example, that text appears within: > C:\Program Files\\Map Data\Road_Centerlines.shp > and also within: > C:\Program Files\Templates\RoadNetwork.rtx > ...among others. > I've tried some non-python methods and they all ruined the XML structure. I've been Google searching all day and can only seem to find solutions that look for a specific node and replace the whole string between the tags. > I've been looking at using minidom to achieve this but I just can't seem to figure out the right method. > My end goal, once I have working code, is to compile an exe that can work on machines without python, allowing a user can click in order to perform the XML modification. Is it as simple as this? $ cat my.xml C:\Program Files\\Map Data\Road_Centerlines.shp and also within: C:\Program Files\Templates\RoadNetwork.rtx $ python3 Python 3.2.3 (default, May 3 2012, 15:51:42) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> for line in open("my.xml"): ... print(line.replace("C:\Program Files", "C:\Program Files (x86)"), end="") ... C:\Program Files (x86)\\Map Data\Road_Centerlines.shp and also within: C:\Program Files (x86)\Templates\RoadNetwork.rtx This solution assumes that you have no tags containing the string "C:\Program Files". From tjreedy at udel.edu Sat Jul 28 03:17:45 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 28 Jul 2012 03:17:45 -0400 Subject: Search and replace text in XML file? In-Reply-To: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: On 7/27/2012 9:23 PM, todd.tabern at gmail.com wrote: > I'm looking to search an entire XML file for specific text and > replace that text, while maintaining the structure of the XML file. For a one-off project, or for experimentation, I would use a proper text-editor* and run through with search/replace. For automation, use Jason's suggestion of .replace, perhaps on a line-by-line basis. * By definition, such only make changes you request. Notepad++ is one such on Windows. You do not want a word or document processor, or, for simple xml oblivious text substitutions, an xml processor. Such things often make changes of various sorts. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Sat Jul 28 04:29:12 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 28 Jul 2012 09:29:12 +0100 Subject: Search and replace text in XML file? In-Reply-To: References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: On 28/07/2012 08:17, Terry Reedy wrote: > On 7/27/2012 9:23 PM, todd.tabern at gmail.com wrote: >> I'm looking to search an entire XML file for specific text and >> replace that text, while maintaining the structure of the XML file. > > For a one-off project, or for experimentation, I would use a proper > text-editor* and run through with search/replace. For automation, use > Jason's suggestion of .replace, perhaps on a line-by-line basis. > > * By definition, such only make changes you request. Notepad++ is one > such on Windows. You do not want a word or document processor, or, for > simple xml oblivious text substitutions, an xml processor. Such things > often make changes of various sorts. > I highly recommend the use of notepad++. If anyone knows of a better text editor for Windows please let me know :) -- Cheers. Mark Lawrence. From rosuav at gmail.com Sat Jul 28 11:51:48 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 29 Jul 2012 01:51:48 +1000 Subject: OT: Text editors (was Re: Search and replace text in XML file?) Message-ID: On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: > I highly recommend the use of notepad++. If anyone knows of a better text > editor for Windows please let me know :) My current preference is SciTE, available on Linux and Windows both. It's configured using Lua, has lexers (and thus syntax highlighters and auto-indenters) for a huge list of languages (including Python, or I wouldn't mention it), and isn't RAM-hungry. It's not bug-free (but what isn't), and has a few limitations (eg it only really supports UTF-8), but I've found it excellent as both text editor and pseudo-IDE. ChrisA From python at mrabarnett.plus.com Sat Jul 28 12:01:19 2012 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 28 Jul 2012 17:01:19 +0100 Subject: Search and replace text in XML file? In-Reply-To: References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: <50140CCF.3010406@mrabarnett.plus.com> On 28/07/2012 09:29, Mark Lawrence wrote: > On 28/07/2012 08:17, Terry Reedy wrote: >> On 7/27/2012 9:23 PM, todd.tabern at gmail.com wrote: >>> I'm looking to search an entire XML file for specific text and >>> replace that text, while maintaining the structure of the XML file. >> >> For a one-off project, or for experimentation, I would use a proper >> text-editor* and run through with search/replace. For automation, use >> Jason's suggestion of .replace, perhaps on a line-by-line basis. >> >> * By definition, such only make changes you request. Notepad++ is one >> such on Windows. You do not want a word or document processor, or, for >> simple xml oblivious text substitutions, an xml processor. Such things >> often make changes of various sorts. >> > > I highly recommend the use of notepad++. If anyone knows of a better > text editor for Windows please let me know :) > My own preference is EditPad. I liked EditPad Lite so much that I bought EditPad Pro. From alister.ware at ntlworld.com Sat Jul 28 13:17:36 2012 From: alister.ware at ntlworld.com (Alister) Date: Sat, 28 Jul 2012 17:17:36 GMT Subject: OT: Text editors (was Re: Search and replace text in XML file?) References: Message-ID: On Sun, 29 Jul 2012 01:51:48 +1000, Chris Angelico wrote: > On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence > wrote: >> I highly recommend the use of notepad++. If anyone knows of a better >> text editor for Windows please let me know :) > > My current preference is SciTE, available on Linux and Windows both. > It's configured using Lua, has lexers (and thus syntax highlighters and > auto-indenters) for a huge list of languages (including Python, or I > wouldn't mention it), and isn't RAM-hungry. It's not bug-free (but what > isn't), and has a few limitations (eg it only really supports UTF-8), > but I've found it excellent as both text editor and pseudo-IDE. > > ChrisA I like Geany at present, although i have not tried too many others -- Nothing increases your golf score like witnesses. From theology at gmail.com Sat Jul 28 13:20:05 2012 From: theology at gmail.com (Zeth) Date: Sat, 28 Jul 2012 18:20:05 +0100 Subject: PyCon UK 2012 - Call for talks Message-ID: <50141F45.4030106@gmail.com> PyCon UK 2012 - Call for talks Please forward this email to relevant lists, social networks, etc. PyCon UK 2012, the UK's official Python conference, returns from the 28th September to 1st October, Coventry UK. This volunteer run and organised conference includes sprints, training, open space and social events. For more information please see our site at pyconuk.org and our wiki at pyconuk.net If you would like to share your expertise, tell us your horror stories or pimp your project, please consider giving a talk at PyConUK. Your talk should reflect at least one of our four themes ( http://pyconuk.net/Themes ). When planning your talk, it should be no more than 40 minutes. Please email us the following: Your name A contact number A one paragraph biography The title of your talk A short one paragraph abstract Which theme (or themes) your talk can be categorised under. If we accept your talk, we would also require a longer abstract in order to create a wiki page. To submit a talk, please email submit at pyconuk.net before Tuesday 14th August 2012. If you have already given us your talks, and had confirmation from John or Zeth, then ignore this message, but we still need the data in the wiki if it is not already there. Best Wishes, PyCon UK Team From wxjmfauth at gmail.com Sat Jul 28 13:43:58 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 28 Jul 2012 10:43:58 -0700 (PDT) Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: Message-ID: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> On Saturday, July 28, 2012 5:51:48 PM UTC+2, Chris Angelico wrote: ... and has a few limitations (eg it only really supports > > UTF-8), ?! It's my daily plain text editor (Windows) since ? (I don't remember). And I'm using it for utf-8, utf-16 and cp1252 (my favorite coding) without problems. jmf From wxjmfauth at gmail.com Sat Jul 28 13:43:58 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 28 Jul 2012 10:43:58 -0700 (PDT) Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: Message-ID: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> On Saturday, July 28, 2012 5:51:48 PM UTC+2, Chris Angelico wrote: ... and has a few limitations (eg it only really supports > > UTF-8), ?! It's my daily plain text editor (Windows) since ? (I don't remember). And I'm using it for utf-8, utf-16 and cp1252 (my favorite coding) without problems. jmf From rosuav at gmail.com Sat Jul 28 13:47:24 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 29 Jul 2012 03:47:24 +1000 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> Message-ID: On Sun, Jul 29, 2012 at 3:43 AM, wrote: > On Saturday, July 28, 2012 5:51:48 PM UTC+2, Chris Angelico wrote: > > ... and has a few limitations (eg it only really supports >> >> UTF-8), > > ?! > > It's my daily plain text editor (Windows) since ? (I don't remember). > And I'm using it for utf-8, utf-16 and cp1252 (my favorite coding) > without problems. Okay, I must have misunderstood something then. Was under the impression that it had some internals where it worked only in bytes, and that things wouldn't always work if you used anything other than UTF-8. It's not an issue for me, since UTF-8 suits me just fine, so I've never looked into it. Apologies for the Elmer FUD! ChrisA From python.list at tim.thechases.com Sat Jul 28 14:29:44 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 28 Jul 2012 13:29:44 -0500 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: Message-ID: <50142F98.9020900@tim.thechases.com> On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: > I highly recommend the use of notepad++. If anyone knows of a > better text editor for Windows please let me know :) I'll advocate for Vim which is crazy-powerful and works nicely on just about any platform I touch. Others will advocate for Emacs, which I can't say fits the way my brain works but it's also powerful and loved by many. The ubiquity of these two platforms makes a worthwhile investment of time spent in learning at least one if not both. -tkc From wxjmfauth at gmail.com Sat Jul 28 15:23:34 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 28 Jul 2012 12:23:34 -0700 (PDT) Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> Message-ID: <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> On Saturday, July 28, 2012 7:47:24 PM UTC+2, Chris Angelico wrote: > On Sun, Jul 29, 2012 at 3:43 AM, wrote: > > > On Saturday, July 28, 2012 5:51:48 PM UTC+2, Chris Angelico wrote: > > > > > > ... and has a few limitations (eg it only really supports > > >> > > >> UTF-8), > > > > > > ?! > > > > > > It's my daily plain text editor (Windows) since ? (I don't remember). > > > And I'm using it for utf-8, utf-16 and cp1252 (my favorite coding) > > > without problems. > > > > Okay, I must have misunderstood something then. Was under the > > impression that it had some internals where it worked only in bytes, > > and that things wouldn't always work if you used anything other than > > UTF-8. It's not an issue for me, since UTF-8 suits me just fine, so > > I've never looked into it. Apologies for the Elmer FUD! > > > > ChrisA No problem. Important is just to say SciTE works fine with many codings. Having said this, I think there is probably some confusion between the scintilla widget and the editor, the application, SciTE using scintilla. In the Python world, the ported "scintilla widget", wxStyleTextCtrl in wxPython and QScintilla in PyQt are working internally in utf-8 and the api's, at least in wxPython, work with a byte arithmetic (annoying). If I used the PyQt version, I do not remember the status with Qt. I prefer the QPlainTextEdit widget. For info: http://scintilla.org/ jmf From wxjmfauth at gmail.com Sat Jul 28 15:23:34 2012 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 28 Jul 2012 12:23:34 -0700 (PDT) Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> Message-ID: <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> On Saturday, July 28, 2012 7:47:24 PM UTC+2, Chris Angelico wrote: > On Sun, Jul 29, 2012 at 3:43 AM, wrote: > > > On Saturday, July 28, 2012 5:51:48 PM UTC+2, Chris Angelico wrote: > > > > > > ... and has a few limitations (eg it only really supports > > >> > > >> UTF-8), > > > > > > ?! > > > > > > It's my daily plain text editor (Windows) since ? (I don't remember). > > > And I'm using it for utf-8, utf-16 and cp1252 (my favorite coding) > > > without problems. > > > > Okay, I must have misunderstood something then. Was under the > > impression that it had some internals where it worked only in bytes, > > and that things wouldn't always work if you used anything other than > > UTF-8. It's not an issue for me, since UTF-8 suits me just fine, so > > I've never looked into it. Apologies for the Elmer FUD! > > > > ChrisA No problem. Important is just to say SciTE works fine with many codings. Having said this, I think there is probably some confusion between the scintilla widget and the editor, the application, SciTE using scintilla. In the Python world, the ported "scintilla widget", wxStyleTextCtrl in wxPython and QScintilla in PyQt are working internally in utf-8 and the api's, at least in wxPython, work with a byte arithmetic (annoying). If I used the PyQt version, I do not remember the status with Qt. I prefer the QPlainTextEdit widget. For info: http://scintilla.org/ jmf From hamilton at nothere.com Sat Jul 28 17:43:48 2012 From: hamilton at nothere.com (hamilton) Date: Sat, 28 Jul 2012 15:43:48 -0600 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> Message-ID: On 7/28/2012 1:23 PM, wxjmfauth at gmail.com wrote: > For info: http://scintilla.org/ Just did a quick check on scintilla. This looks like a single file editor. Is there a project like capability in there that I did not notice ? Thanks hamilton From timr at probo.com Sat Jul 28 18:32:31 2012 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jul 2012 15:32:31 -0700 Subject: Search and replace text in XML file? References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: todd.tabern at gmail.com wrote: > >I basically need to replace every occurrence C:\Program Files with >C:\Program Files (x86), regardless of location. For example, that >text appears within: >C:\Program Files\\Map Data\Road_Centerlines.shp >and also within: >C:\Program Files\Templates\RoadNetwork.rtx >...among others. >I've tried some non-python methods and they all ruined the XML structure. I don't see how that's possible. XML doesn't have any character counts, and it doesn't care about extra white space. A rock-stupid editor substitution should have been able to do this in two seconds. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rosuav at gmail.com Sat Jul 28 18:42:05 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 29 Jul 2012 08:42:05 +1000 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> Message-ID: On Sun, Jul 29, 2012 at 7:43 AM, hamilton wrote: > On 7/28/2012 1:23 PM, wxjmfauth at gmail.com wrote: >> >> For info: http://scintilla.org/ > > > Just did a quick check on scintilla. > > This looks like a single file editor. > > Is there a project like capability in there that I did not notice ? Scintilla is a text editing widget; SciTE is a Scintilla-based Text Editor (and is by the same author). The editor wraps up Scintilla with facilities for handling multiple files simultaneously (multiple buffers/tabbed display/whatever you want to call it). ChrisA From aclark at aclark.net Sat Jul 28 19:15:44 2012 From: aclark at aclark.net (Alex Clark) Date: Sat, 28 Jul 2012 19:15:44 -0400 Subject: ANN: pythonpackages.com beta Message-ID: Hi Python folks, I am reaching out to various Python-related programming communities in order to offer new help packaging your software. If you have ever struggled with packaging and releasing Python software (e.g. to PyPI), please check out this service: - http://pythonpackages.com The basic idea is to automate packaging by checking out code, testing, and uploading (e.g. to PyPI) all through the web, as explained in this introduction: - http://docs.pythonpackages.com/en/latest/introduction.html Also, I will be available to answer your Python packaging questions most days/nights in #pythonpackages on irc.freenode.net. Hope to meet/talk with all of you soon. Alex -- Alex Clark ? http://pythonpackages.com/ONE_CLICK From james.pye at gmail.com Sat Jul 28 19:25:05 2012 From: james.pye at gmail.com (jwp) Date: Sat, 28 Jul 2012 16:25:05 -0700 (PDT) Subject: How to represent dates BC In-Reply-To: References: Message-ID: On Tuesday, July 24, 2012 2:55:29 AM UTC-7, Laszlo Nagy wrote: > >>> conn.getqueryvalue("select '1311-03-14 BC'::date") > What is the good representation here? Should I implement my own date Do your datetime formatting in postgres: "select '1311-03-14 BC'::date::text" PG does have a have a reasonable set of functions for working with datetime. If you need something more complicated than a simple cast to text, I'd suggest creating a function: CREATE OR REPLACE FUNCTION fmt_my_dates(date) RETURNS text LANGUAGE SQL AS $$ SELECT EXTRACT(.. FROM $1)::text || ... $$; From james.pye at gmail.com Sat Jul 28 19:25:05 2012 From: james.pye at gmail.com (jwp) Date: Sat, 28 Jul 2012 16:25:05 -0700 (PDT) Subject: How to represent dates BC In-Reply-To: References: Message-ID: On Tuesday, July 24, 2012 2:55:29 AM UTC-7, Laszlo Nagy wrote: > >>> conn.getqueryvalue("select '1311-03-14 BC'::date") > What is the good representation here? Should I implement my own date Do your datetime formatting in postgres: "select '1311-03-14 BC'::date::text" PG does have a have a reasonable set of functions for working with datetime. If you need something more complicated than a simple cast to text, I'd suggest creating a function: CREATE OR REPLACE FUNCTION fmt_my_dates(date) RETURNS text LANGUAGE SQL AS $$ SELECT EXTRACT(.. FROM $1)::text || ... $$; From hamilton at nothere.com Sat Jul 28 22:33:07 2012 From: hamilton at nothere.com (hamilton) Date: Sat, 28 Jul 2012 20:33:07 -0600 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> Message-ID: On 7/28/2012 4:42 PM, Chris Angelico wrote: > On Sun, Jul 29, 2012 at 7:43 AM, hamilton wrote: >> On 7/28/2012 1:23 PM, wxjmfauth at gmail.com wrote: >>> >>> For info: http://scintilla.org/ >> >> >> Just did a quick check on scintilla. >> >> This looks like a single file editor. >> >> Is there a project like capability in there that I did not notice ? > > Scintilla is a text editing widget; SciTE is a Scintilla-based Text > Editor (and is by the same author). The editor wraps up Scintilla with > facilities for handling multiple files simultaneously (multiple > buffers/tabbed display/whatever you want to call it). > > ChrisA > Ok, so the answer is no. Thanks From rosuav at gmail.com Sat Jul 28 22:37:43 2012 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 29 Jul 2012 12:37:43 +1000 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: <70f3e677-550b-4727-8292-fda143a4e8c0@googlegroups.com> <2cc0a214-f349-473d-8acb-dcbd10f5a782@googlegroups.com> Message-ID: On Sun, Jul 29, 2012 at 12:33 PM, hamilton wrote: > Ok, so the answer is no. In terms of the editor, it's fine; you need only worry about Scintilla itself if you're aiming to incorporate it in your own program. ChrisA From ben+python at benfinney.id.au Sun Jul 29 01:08:58 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 29 Jul 2012 15:08:58 +1000 Subject: OT: Text editors References: Message-ID: <87pq7fqhlh.fsf@benfinney.id.au> Tim Chase writes: > On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: > > I highly recommend the use of notepad++. If anyone knows of a > > better text editor for Windows please let me know :) I highly recommend not tying your editor skills to a single OS, especially one as ornery for programmers as Windows. > I'll advocate for Vim which is crazy-powerful and works nicely on > just about any platform I touch. > > Others will advocate for Emacs, which I can't say fits the way my > brain works but it's also powerful and loved by many. Right. I'm in Tim's position, but reversed: my preference is for Emacs but Vim is a fine choice also. They are mature, well-supported with regular updates and a massive library of plug-ins for different uses, have a huge community to help you, and work on all major programming OSen. > The ubiquity of these two platforms makes a worthwhile investment of > time spent in learning at least one if not both. I use both frequently in my work for different things, and they are good for pretty much any task involving manipulation of text. Learn one of Emacs or Vim well, and you won't need to worry about text editors again. -- \ ?All opinions are not equal. Some are a very great deal more | `\ robust, sophisticated, and well supported in logic and argument | _o__) than others.? ?Douglas Adams | Ben Finney From rustompmody at gmail.com Sun Jul 29 01:36:56 2012 From: rustompmody at gmail.com (rusi) Date: Sat, 28 Jul 2012 22:36:56 -0700 (PDT) Subject: OT: Text editors References: <87pq7fqhlh.fsf@benfinney.id.au> Message-ID: <6a2a69db-8275-4bbd-b4bb-0d94cb6118a6@re8g2000pbc.googlegroups.com> On Jul 29, 10:08?am, Ben Finney wrote: > Tim Chase writes: > > On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: > > > I highly recommend the use of notepad++. ?If anyone knows of a > > > better text editor for Windows please let me know :) I would have bet Mark was ribbing the folks on this list. Maybe you were not Mark? [Well you did say notepad++ not notepad] But to get a bit more serious... > > I highly recommend not tying your editor skills to a single OS, > especially one as ornery for programmers as Windows. > > > I'll advocate for Vim which is crazy-powerful and works nicely on > > just about any platform I touch. > > > Others will advocate for Emacs, which I can't say fits the way my > > brain works but it's also powerful and loved by many. > > Right. I'm in Tim's position, but reversed: my preference is for Emacs > but Vim is a fine choice also. They are mature, well-supported with > regular updates and a massive library of plug-ins for different uses, > have a huge community to help you, and work on all major programming > OSen. > > > The ubiquity of these two platforms makes a worthwhile investment of > > time spent in learning at least one if not both. > > I use both frequently in my work for different things, and they are good > for pretty much any task involving manipulation of text. > > Learn one of Emacs or Vim well, and you won't need to worry about text > editors again. Just curious about your emacs+python usage. Do you use the emacs builtin python mode or the separate python-mode? Do you use pdb? Any other special setups? How about ipython? [Personal note: Ive been using and teaching python with emacs for over 10 years now. But I am getting increasing 'funny looks' for not (for example) using eclipse.] From ben+python at benfinney.id.au Sun Jul 29 04:24:38 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 29 Jul 2012 18:24:38 +1000 Subject: OT: Text editors References: <87pq7fqhlh.fsf@benfinney.id.au> <6a2a69db-8275-4bbd-b4bb-0d94cb6118a6@re8g2000pbc.googlegroups.com> Message-ID: <87lii3q8jd.fsf@benfinney.id.au> rusi writes: > Do you use the emacs builtin python mode or the separate python-mode? I'm not sure. I have both installed. I try to keep my Emacs setup portable across different machines, so I'm probably using the built-in mode. > Do you use pdb? Occasionally, but I haven't learned how to do that in Emacs. > Any other special setups? GNU Screen and Emacs are the foundation of my programming environment. > How about ipython? Never really liked it nor saw a need for it. I use the Python interactive console, with GNU readline so I get history preserved and tab-completion. > But I am getting increasing 'funny looks' for not (for example) using > eclipse.] Unless those funny looks are accompanied by compelling reasons to invest a whole lot of effort into learning a rather slow and complex program, then it seems you can ignore them. -- \ ?The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything.? ?Aahz | _o__) | Ben Finney From subhabangalore at gmail.com Sun Jul 29 05:27:18 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 29 Jul 2012 02:27:18 -0700 (PDT) Subject: Python Error Message-ID: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Dear Group, I was trying to convert the list to a set, with the following code: set1=set(list1) the code was running fine, but all on a sudden started to give the following error, set1=set(list1) TypeError: unhashable type: 'list' please let me know how may I resolve. And sometimes some good running program gives error all on a sudden with no parameter changed, how may I debug it? Thanking You in Advance, Regards, Subhabrata Banerjee. From breamoreboy at yahoo.co.uk Sun Jul 29 06:28:17 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 29 Jul 2012 11:28:17 +0100 Subject: OT: Text editors In-Reply-To: <87pq7fqhlh.fsf@benfinney.id.au> References: <87pq7fqhlh.fsf@benfinney.id.au> Message-ID: On 29/07/2012 06:08, Ben Finney wrote: > Tim Chase writes: > >> On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: >>> I highly recommend the use of notepad++. If anyone knows of a >>> better text editor for Windows please let me know :) > > I highly recommend not tying your editor skills to a single OS, > especially one as ornery for programmers as Windows. > >> I'll advocate for Vim which is crazy-powerful and works nicely on >> just about any platform I touch. >> >> Others will advocate for Emacs, which I can't say fits the way my >> brain works but it's also powerful and loved by many. > > Right. I'm in Tim's position, but reversed: my preference is for Emacs > but Vim is a fine choice also. They are mature, well-supported with > regular updates and a massive library of plug-ins for different uses, > have a huge community to help you, and work on all major programming > OSen. > >> The ubiquity of these two platforms makes a worthwhile investment of >> time spent in learning at least one if not both. > > I use both frequently in my work for different things, and they are good > for pretty much any task involving manipulation of text. > > Learn one of Emacs or Vim well, and you won't need to worry about text > editors again. > Point taken, snag being I've never used any nix box in anger. This thread reminds of the good 'ole days when I were a lad using TPU on VMS. Have we got any VMS aficionados here? -- Cheers. Mark Lawrence. From __peter__ at web.de Sun Jul 29 07:08:57 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Jul 2012 13:08:57 +0200 Subject: Python Error References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: subhabangalore at gmail.com wrote: > Dear Group, > > I was trying to convert the list to a set, with the following code: > > set1=set(list1) > > the code was running fine, but all on a sudden started to give the > following error, > > set1=set(list1) > TypeError: unhashable type: 'list' > > please let me know how may I resolve. > > And sometimes some good running program gives error all on a sudden with > no parameter changed, how may I debug it? Add a print statement before the offending line: print list1 set1 = set(list1) You will see that list1 contains another list, e. g. this works... >>> list1 = ["alpha", "beta"] >>> set(list1) set(['alpha', 'beta']) ...while this doesn't: >>> list1 = ["alpha", ["beta"]] >>> set(list1) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' From python.list at tim.thechases.com Sun Jul 29 07:47:25 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 29 Jul 2012 06:47:25 -0500 Subject: OT: Text editors In-Reply-To: References: <87pq7fqhlh.fsf@benfinney.id.au> Message-ID: <501522CD.6020302@tim.thechases.com> On 07/29/12 05:28, Mark Lawrence wrote: > On 29/07/2012 06:08, Ben Finney wrote: >> Tim Chase writes: >> Learn one of Emacs or Vim well, and you won't need to worry >> about text editors again. > > Point taken, snag being I've never used any nix box in anger. > This thread reminds of the good 'ole days when I were a lad using > TPU on VMS. Have we got any VMS aficionados here? Though I'm personally far more vitriolic about VMS vs $OS (had a few souring experiences with VMS in college) than I am regarding Vim vs. Emacs, you can get Vim for at least OpenVMS: http://www.vim.org/download.php#others I presume sources compile fairly well on other flavors of VMS if needed, and I'd expect Emacs can do likewise[1] -tkc [1] http://www.emacswiki.org/emacs/EmacsOnVMS From subhabangalore at gmail.com Sun Jul 29 08:30:15 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 29 Jul 2012 05:30:15 -0700 (PDT) Subject: Python Error In-Reply-To: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> On Sunday, July 29, 2012 2:57:18 PM UTC+5:30, (unknown) wrote: > Dear Group, > > > > I was trying to convert the list to a set, with the following code: > > > > set1=set(list1) > > > Dear Peter, Thanks for the answer. But my list does not contain another list that is the issue. Intriguing. Thinking what to do. Regards, Subhabrata. > the code was running fine, but all on a sudden started to give the following error, > > > > set1=set(list1) > > TypeError: unhashable type: 'list' > > > > please let me know how may I resolve. > > > > And sometimes some good running program gives error all on a sudden with no parameter changed, how may I debug it? > > > > Thanking You in Advance, > > > > Regards, > > Subhabrata Banerjee. From t at jollybox.de Sun Jul 29 08:45:21 2012 From: t at jollybox.de (Thomas Jollans) Date: Sun, 29 Jul 2012 14:45:21 +0200 Subject: Python Error In-Reply-To: <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> Message-ID: <50153061.6050905@jollybox.de> On 07/29/2012 02:30 PM, subhabangalore at gmail.com wrote: > Thanks for the answer. But my list does not contain another list that is the issue. Intriguing. Thinking what to do. What does your list contain? Can you reproduce the issue in a few self-contained lines of code that you can show us, that we can test ourselves? From iftecan2000 at gmail.com Sun Jul 29 08:52:40 2012 From: iftecan2000 at gmail.com (Ifthikhan Nazeem) Date: Sun, 29 Jul 2012 14:52:40 +0200 Subject: Python Error In-Reply-To: <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> Message-ID: Hi, Have you tried printing the list which is passed onto the set. The items in the list passed should be hashable and possibly there are objects which are not hashable. On Sun, Jul 29, 2012 at 2:30 PM, wrote: > On Sunday, July 29, 2012 2:57:18 PM UTC+5:30, (unknown) wrote: > > Dear Group, > > > > > > > > I was trying to convert the list to a set, with the following code: > > > > > > > > set1=set(list1) > > > > > > > Dear Peter, > Thanks for the answer. But my list does not contain another list that is > the issue. Intriguing. Thinking what to do. > Regards, > Subhabrata. > > the code was running fine, but all on a sudden started to give the > following error, > > > > > > > > set1=set(list1) > > > > TypeError: unhashable type: 'list' > > > > > > > > please let me know how may I resolve. > > > > > > > > And sometimes some good running program gives error all on a sudden with > no parameter changed, how may I debug it? > > > > > > > > Thanking You in Advance, > > > > > > > > Regards, > > > > Subhabrata Banerjee. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spam at capuchin.co.uk Sun Jul 29 09:36:34 2012 From: spam at capuchin.co.uk (Robert Marshall) Date: Sun, 29 Jul 2012 14:36:34 +0100 Subject: OT: Text editors References: <87pq7fqhlh.fsf@benfinney.id.au> Message-ID: <87txwqd6zh.fsf@capuchin.co.uk> On Sun, 29 Jul 2012, python.list at tim.thechases.com wrote: > On 07/29/12 05:28, Mark Lawrence wrote: >> On 29/07/2012 06:08, Ben Finney wrote: >>> Tim Chase writes: >>> Learn one of Emacs or Vim well, and you won't need to worry >>> about text editors again. >> >> Point taken, snag being I've never used any nix box in anger. >> This thread reminds of the good 'ole days when I were a lad using >> TPU on VMS. Have we got any VMS aficionados here? > > Though I'm personally far more vitriolic about VMS vs $OS (had a few > souring experiences with VMS in college) than I am regarding Vim vs. > Emacs, you can get Vim for at least OpenVMS: > > http://www.vim.org/download.php#others > > I presume sources compile fairly well on other flavors of VMS if > needed, and I'd expect Emacs can do likewise[1] > I used to use tpu (used to have piles of tpu macros..) and I first got used to emacs by using its tpu mode - I see that still exists so you can use emacs and pretend it is really tpu! Robert -- La grenouille songe..dans son ch?teau d'eau Links and things http://rmstar.blogspot.com/ From breamoreboy at yahoo.co.uk Sun Jul 29 09:53:44 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 29 Jul 2012 14:53:44 +0100 Subject: Python Error In-Reply-To: <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> Message-ID: On 29/07/2012 13:30, subhabangalore at gmail.com wrote: > On Sunday, July 29, 2012 2:57:18 PM UTC+5:30, (unknown) wrote: >> Dear Group, >> >> I was trying to convert the list to a set, with the following code: >> >> set1=set(list1) >> > Dear Peter, > Thanks for the answer. But my list does not contain another list that is the issue. Intriguing. Thinking what to do. > Regards, > Subhabrata. Can you loop round the list and print each entry and its type, that should give you some clues? >> the code was running fine, but all on a sudden started to give the following error, >> >> set1=set(list1) >> >> TypeError: unhashable type: 'list' >> >> please let me know how may I resolve. >> >> And sometimes some good running program gives error all on a sudden with no parameter changed, how may I debug it? >> >> Thanking You in Advance, >> >> Regards, >> >> Subhabrata Banerjee. > -- Cheers. Mark Lawrence. From jae at jaerhard.com Sun Jul 29 09:57:48 2012 From: jae at jaerhard.com (=?iso-8859-1?B?SvxyZ2VuIEEu?= Erhard) Date: Sun, 29 Jul 2012 15:57:48 +0200 Subject: Python Error In-Reply-To: References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: <20120729135748.GA20880@jaerhard.com> On Sun, Jul 29, 2012 at 01:08:57PM +0200, Peter Otten wrote: > subhabangalore at gmail.com wrote: > > > Dear Group, > > > > I was trying to convert the list to a set, with the following code: > > > > set1=set(list1) > > > > the code was running fine, but all on a sudden started to give the > > following error, > > > > set1=set(list1) > > TypeError: unhashable type: 'list' > > > > Add a print statement before the offending line: > > print list1 > set1 = set(list1) > > You will see that list1 contains another list, e. g. this works... > Peter's right, but instead of a print before the line, put a try/except around it, like try: set1 = set(list1) except TypeError: print list1 raise This way, only the *actual* error triggers any output. With a general print before, you can get a lot of unnecessary output. Grits, J From steve+comp.lang.python at pearwood.info Sun Jul 29 10:01:17 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Jul 2012 14:01:17 GMT Subject: Python Error References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> Message-ID: <5015422c$0$29978$c3e8da3$5496439d@news.astraweb.com> On Sun, 29 Jul 2012 05:30:15 -0700, subhabangalore wrote: > Dear Peter, > Thanks for the answer. But my list does not contain another list that is > the issue. Intriguing. That is not what the error message says. You said that this line of code: set1=set(list1) gives this error: TypeError: unhashable type: 'list' Almost certainly, either you are mistaken about the line of code which gives the error, or you are mistaken about the error, or you are mistaken that your list does not contain any lists. > Thinking what to do. Exactly what Peter suggested: print the list before you try to convert it to a set, and see what it actually contains. It will also help you to read this page and try to follow its advice: http://sscce.org/ -- Steven From tokauf at googlemail.com Sun Jul 29 10:04:03 2012 From: tokauf at googlemail.com (tokauf at googlemail.com) Date: Sun, 29 Jul 2012 07:04:03 -0700 (PDT) Subject: newbie: write new file (from a server) Message-ID: Hi, I have a client. He sends file content (as bytes) to my server. The server receives this content as bytes and decodes it to string. Then the server opens a file (filename comes from client) try to write the file-content to the new file. It works but there are parts of the client file content in the new file. I tested it: the whole content from client comes to the server. Can anybody help me? My server code: ------------------------- import socketserver class MyTCPServer(socketserver.BaseRequestHandler): def handle(self): s = '' li = [] addr = self.client_address[0] print("[{}] Connected! ".format(addr)) while True: bytes = self.request.recv(4096) if bytes: s = bytes.decode("utf8") print(s) li = s.split("~") with open(li[0], 'w') as fp: fp.write(li[1]) #... main ...................................................... if __name__ == "__main__": server = socketserver.ThreadingTCPServer(("", 12345), MyTCPServer) server.serve_forever() -------------------------------- o-o Thomas From breamoreboy at yahoo.co.uk Sun Jul 29 10:15:42 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 29 Jul 2012 15:15:42 +0100 Subject: OT: Text editors In-Reply-To: <87txwqd6zh.fsf@capuchin.co.uk> References: <87pq7fqhlh.fsf@benfinney.id.au> <87txwqd6zh.fsf@capuchin.co.uk> Message-ID: On 29/07/2012 14:36, Robert Marshall wrote: > On Sun, 29 Jul 2012, python.list at tim.thechases.com wrote: > >> On 07/29/12 05:28, Mark Lawrence wrote: >>> On 29/07/2012 06:08, Ben Finney wrote: >>>> Tim Chase writes: >>>> Learn one of Emacs or Vim well, and you won't need to worry >>>> about text editors again. >>> >>> Point taken, snag being I've never used any nix box in anger. >>> This thread reminds of the good 'ole days when I were a lad using >>> TPU on VMS. Have we got any VMS aficionados here? >> >> Though I'm personally far more vitriolic about VMS vs $OS (had a few >> souring experiences with VMS in college) than I am regarding Vim vs. >> Emacs, you can get Vim for at least OpenVMS: >> >> http://www.vim.org/download.php#others >> >> I presume sources compile fairly well on other flavors of VMS if >> needed, and I'd expect Emacs can do likewise[1] >> > > I used to use tpu (used to have piles of tpu macros..) and I first got used > to emacs by using its tpu mode - I see that still exists so you can use > emacs and pretend it is really tpu! > > Robert > Well knock me down with a feather, clevor Trevor[1], might have to give that a go, thanks. [1] Ian Dury and the Blockheads album New Boots and Panties, song called Clevor Trevor for those of you who clearly lack a suitable education :) -- Cheers. Mark Lawrence. From tokauf at googlemail.com Sun Jul 29 10:16:01 2012 From: tokauf at googlemail.com (Thomas Kaufmann) Date: Sun, 29 Jul 2012 07:16:01 -0700 (PDT) Subject: newbie: write content in a file (server-side) Message-ID: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> Hi, I send from a client file content to my server (as bytes). So far so good. The server receives this content complete. Ok. Then I want to write this content to a new file. It works too. But in the new file are only the first part of the whole content. What's the problem. o-o Thomas Here's my server code: import socketserver class MyTCPServer(socketserver.BaseRequestHandler): def handle(self): s = '' li = [] addr = self.client_address[0] print("[{}] Connected! ".format(addr)) while True: bytes = self.request.recv(4096) if bytes: s = bytes.decode("utf8") print(s) li = s.split("~") with open(li[0], 'w') as fp: fp.write(li[1]) #... main ...................................................... if __name__ == "__main__": server = socketserver.ThreadingTCPServer(("", 12345), MyTCPServer) server.serve_forever() From roy at panix.com Sun Jul 29 10:23:59 2012 From: roy at panix.com (Roy Smith) Date: Sun, 29 Jul 2012 10:23:59 -0400 Subject: Python Error References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: In article <81818a9c-60d3-48da-9345-0c0dfd5b25e7 at googlegroups.com>, subhabangalore at gmail.com wrote: > set1=set(list1) > > the code was running fine, but all on a sudden started to give the following > error, > > set1=set(list1) > TypeError: unhashable type: 'list' First, make sure you understand what the error means. All the elements of a set must be hashable. Lists are not hashable because they are mutable. So, what the error is telling you is that some element of list1 is itself a list, and therefore not hashable, and thus the set can't be created. I would start by printing list1. If the list is long (or contains deeply nested structures), just doing "print list1" may result in something that is difficult to read. In that case, try using pprint (see the pprint module) to get a nicer display. If it's still not obvious, pull out the bigger guns. Try something like: for item in list1: try: hash(item) except TypeError: print "This one can't be hashed: %s" % item > And sometimes some good running program gives error all on a sudden with no > parameter changed Well, *something* changed. Assuming nothing truly bizarre like a stray Higgs Boson flipping a bit in your computer's memory, what you need to do is figure out what that is. Did you change your code in any way (having everything under version control helps here)? If not the code, then what changed about the input? If you're sure that both the code and the input are unchanged, that leaves something in the environment. Did your python interpreter get upgraded to a newer version? Or your operating system? PYTHONPATH? Depending on what your program is doing, it could be something time based. A different time zone, perhaps? Did daylight savings time just go into or out of effect where you are? Does it only fail on Sunday? From arnodel at gmail.com Sun Jul 29 10:24:14 2012 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 29 Jul 2012 15:24:14 +0100 Subject: OT: Text editors In-Reply-To: <6a2a69db-8275-4bbd-b4bb-0d94cb6118a6@re8g2000pbc.googlegroups.com> References: <87pq7fqhlh.fsf@benfinney.id.au> <6a2a69db-8275-4bbd-b4bb-0d94cb6118a6@re8g2000pbc.googlegroups.com> Message-ID: On 29 July 2012 06:36, rusi wrote: > Just curious about your emacs+python usage. > Do you use the emacs builtin python mode or the separate python-mode? > Do you use pdb? > Any other special setups? One thing that I find very useful is to configure flymake to use pyflakes. Very useful to get feedback on unused imports / unused variables / undefined variables (which means you spot typos on variable names straight away). For instructions, see e.g. http://www.plope.com/Members/chrism/flymake-mode -- Arnaud From subhabangalore at gmail.com Sun Jul 29 10:36:39 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 29 Jul 2012 07:36:39 -0700 (PDT) Subject: Python Error In-Reply-To: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: <35b4e1bf-0f99-4c9d-bd40-8f44ba100510@googlegroups.com> On Sunday, July 29, 2012 2:57:18 PM UTC+5:30, (unknown) wrote: > Dear Group, > > > > I was trying to convert the list to a set, with the following code: > > > > set1=set(list1) > > > > the code was running fine, but all on a sudden started to give the following error, > > > > set1=set(list1) > > TypeError: unhashable type: 'list' > > > > please let me know how may I resolve. > > > > And sometimes some good running program gives error all on a sudden with no parameter changed, how may I debug it? > > > > Thanking You in Advance, > > > > Regards, > > Subhabrata Banerjee. Dear Group, Thank you for your kind time and reply. True as Steven pointed the error should be specific. I tested. Put comment mark before the set assignment, printed the list as Peter suggested, taken the print of the list, but no it is not my problem, as you suggested what is contained in the list, I am taking out the values and then assigning blank list and appending the processed values in the list. If this kind of problems happen, --rare but in my 6 yrs Python experience happened sometimes--then I take a new window, rewrite or copy the earlier code module by module, give a new method name--believe it or not--- works. Regards, Subhabrata. From subhabangalore at gmail.com Sun Jul 29 10:41:47 2012 From: subhabangalore at gmail.com (subhabangalore at gmail.com) Date: Sun, 29 Jul 2012 07:41:47 -0700 (PDT) Subject: Python Error In-Reply-To: References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: On Sunday, July 29, 2012 7:53:59 PM UTC+5:30, Roy Smith wrote: > In article <81818a9c-60d3-48da-9345-0c0dfd5b25e7 at googlegroups.com>, > > subhabangalore at gmail.com wrote: > > > > > set1=set(list1) > > > > > > the code was running fine, but all on a sudden started to give the following > > > error, > > > > > > set1=set(list1) > > > TypeError: unhashable type: 'list' > > > > First, make sure you understand what the error means. All the elements > > of a set must be hashable. Lists are not hashable because they are > > mutable. So, what the error is telling you is that some element of > > list1 is itself a list, and therefore not hashable, and thus the set > > can't be created. > > > > I would start by printing list1. If the list is long (or contains > > deeply nested structures), just doing "print list1" may result in > > something that is difficult to read. In that case, try using pprint > > (see the pprint module) to get a nicer display. > > > > If it's still not obvious, pull out the bigger guns. Try something like: > > > > for item in list1: > > try: > > hash(item) > > except TypeError: > > print "This one can't be hashed: %s" % item > > > > > And sometimes some good running program gives error all on a sudden with no > > > parameter changed > > > > Well, *something* changed. Assuming nothing truly bizarre like a stray > > Higgs Boson flipping a bit in your computer's memory, what you need to > > do is figure out what that is. Did you change your code in any way > > (having everything under version control helps here)? If not the code, > > then what changed about the input? > > > > If you're sure that both the code and the input are unchanged, that > > leaves something in the environment. Did your python interpreter get > > upgraded to a newer version? Or your operating system? PYTHONPATH? > > > > Depending on what your program is doing, it could be something time > > based. A different time zone, perhaps? Did daylight savings time just > > go into or out of effect where you are? Does it only fail on Sunday? Hi Roy, Sorry I overlooked your answer. It fails generally on Sunday. True. How you got it? I recently downloaded Python2.7 64 bit -while I am working on Python3.2.1 64 bit Windows 7 SP1. Regards, Subhabrata Banerjee. From emile at fenx.com Sun Jul 29 10:42:24 2012 From: emile at fenx.com (Emile van Sebille) Date: Sun, 29 Jul 2012 07:42:24 -0700 Subject: Python Error In-Reply-To: <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <86285e84-bc6e-4527-9af5-c29f8c9716c0@googlegroups.com> Message-ID: On 7/29/2012 5:30 AM subhabangalore at gmail.com said... > On Sunday, July 29, 2012 2:57:18 PM UTC+5:30, (unknown) wrote: >> Dear Group, >> I was trying to convert the list to a set, with the following code: >> set1=set(list1) > Thanks for the answer. But my list does not contain another list that is the issue. Intriguing. Thinking what to do. Now you need to identify the type of the object that is causing python to misreport the unhashable type causing the error as the error you're getting says list and you say there isn't one. So, now we have a python bug. >>> set ([1,2,3]) set([1, 2, 3]) >>> set ([1,2,[]]) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' >>> set ([1,2,{}]) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'dict' > the code was running fine, but all on a sudden started to give the following error, > > > > set1=set(list1) > > TypeError: unhashable type: 'list' Try adding the following: for ii in list1: try: set([ii]) except: print "this causes an error type (val): %s (%s)" (type(ii),ii) Either it's a python bug or there really is a list in there. Emile From rosuav at gmail.com Sun Jul 29 11:12:19 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 30 Jul 2012 01:12:19 +1000 Subject: Python Error In-Reply-To: <35b4e1bf-0f99-4c9d-bd40-8f44ba100510@googlegroups.com> References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> <35b4e1bf-0f99-4c9d-bd40-8f44ba100510@googlegroups.com> Message-ID: On Mon, Jul 30, 2012 at 12:36 AM, wrote: > If this kind of problems happen, --rare but in my 6 yrs Python experience happened sometimes--then I take a new window, rewrite or copy the earlier code module by module, give a new method name--believe it or not--- works. If that solves your problem, it may be that you inadvertently shadowed a built-in - maybe you assigned to "set" or "list" or something. ChrisA From __peter__ at web.de Sun Jul 29 11:16:11 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Jul 2012 17:16:11 +0200 Subject: newbie: write content in a file (server-side) References: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> Message-ID: Thomas Kaufmann wrote: > I send from a client file content to my server (as bytes). So far so good. > The server receives this content complete. Ok. Then I want to write this > content to a new file. It works too. But in the new file are only the > first part of the whole content. > > What's the problem. > Here's my server code: > while True: > bytes = self.request.recv(4096) > if bytes: > s = bytes.decode("utf8") > print(s) > li = s.split("~") > with open(li[0], 'w') as fp: > fp.write(li[1]) - Do you ever want to leave the loop? - You calculate a new filename on every iteration of the while loop -- probably not what you intended to do. - The "w" argument tells Python to overwrite the file if it exists. You either need to keep the file open (move the with... out of the loop) or open it with "a". - You may not receive the complete file name on the first iteration of the while loop. - The bytes buffer can contain incomplete characters, e. g.: >>> data = b"\xc3\xa4" >>> data.decode("utf-8") '?' >>> data[:1].decode("utf-8") Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: unexpected end of data From lipska at yahoo.co.uk Sun Jul 29 12:01:00 2012 From: lipska at yahoo.co.uk (lipska the kat) Date: Sun, 29 Jul 2012 17:01:00 +0100 Subject: Is Python a commercial proposition ? Message-ID: Pythoners Firstly, thanks to those on the tutor list who answered my questions. I'm trying to understand where Python fits into the set of commonly available, commercially used languages of the moment. My most recent experience is with Java. The last project I was involved with included 6775 java source files containing 1,145,785 lines of code. How do I know this? because I managed to cobble together a python script that walks the source tree and counts the lines of code. It ignores block and line comments and whitespace lines so I'm fairly confident it's an accurate total. It doesn't include web interface files (mainly .jsp and HTML) or configuration files (XML, properties files and what have you). In fact it was remarkably easy to do this in python which got me thinking about how I could use the language in a commercial environment. I was first attracted to python by it's apparent 'Object Orientedness' I soon realised however that by looking at it in terms of the language I know best I wasn't comparing like with like. Once I had 'rebooted the bioware' I tried to approach python with an open mind and I have to say it's growing on me. The questions I have are ... How is python used in the real world. What sized projects are people involved with Are applications generally written entirely in python or is it more often used for a subset of functionality. I hope this is an acceptable question for this group Many thanks Lipska -- Lipska the Kat: Troll hunter, sandbox destroyer and farscape dreamer of Aeryn Sun From python at mrabarnett.plus.com Sun Jul 29 12:22:52 2012 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 29 Jul 2012 17:22:52 +0100 Subject: OT: Text editors In-Reply-To: References: <87pq7fqhlh.fsf@benfinney.id.au> <87txwqd6zh.fsf@capuchin.co.uk> Message-ID: <5015635C.2010400@mrabarnett.plus.com> On 29/07/2012 15:15, Mark Lawrence wrote: > On 29/07/2012 14:36, Robert Marshall wrote: >> On Sun, 29 Jul 2012, python.list at tim.thechases.com wrote: >> >>> On 07/29/12 05:28, Mark Lawrence wrote: >>>> On 29/07/2012 06:08, Ben Finney wrote: >>>>> Tim Chase writes: >>>>> Learn one of Emacs or Vim well, and you won't need to worry >>>>> about text editors again. >>>> >>>> Point taken, snag being I've never used any nix box in anger. >>>> This thread reminds of the good 'ole days when I were a lad using >>>> TPU on VMS. Have we got any VMS aficionados here? >>> >>> Though I'm personally far more vitriolic about VMS vs $OS (had a few >>> souring experiences with VMS in college) than I am regarding Vim vs. >>> Emacs, you can get Vim for at least OpenVMS: >>> >>> http://www.vim.org/download.php#others >>> >>> I presume sources compile fairly well on other flavors of VMS if >>> needed, and I'd expect Emacs can do likewise[1] >>> >> >> I used to use tpu (used to have piles of tpu macros..) and I first got used >> to emacs by using its tpu mode - I see that still exists so you can use >> emacs and pretend it is really tpu! >> >> Robert >> > > Well knock me down with a feather, clevor Trevor[1], might have to give > that a go, thanks. > > [1] Ian Dury and the Blockheads album New Boots and Panties, song called > Clevor Trevor for those of you who clearly lack a suitable education :) > There appears to be some confusion about the spelling, but it might be "Clevor Trever". From mhrivnak at hrivnak.org Sun Jul 29 13:13:41 2012 From: mhrivnak at hrivnak.org (Michael Hrivnak) Date: Sun, 29 Jul 2012 13:13:41 -0400 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: http://www.djangosites.org/ Instagram, Pinterest, Washington Post, and The Onion all use djangoto run their websites. http://stackoverflow.com/questions/1906795/what-are-some-famous-websites-built-in-django Django is of course a very highly-regarded web framework written in python, but there are other good python frameworks out there with strong user bases. Python is used frequently on the server side of web applications for sites of all sizes, with the UI generally being done in javascript. It's also used heavily for administrative purposes such as: - Operating system installer: http://fedoraproject.org/wiki/Anaconda - Software repository management: http://pulpproject.org/ - Software package installation: http://en.wikipedia.org/wiki/Ubuntu_Software_Center - Cloud computing: http://en.wikipedia.org/wiki/OpenStack You can write web applications that scale automatically on hosting services like: - Google App Engine: https://developers.google.com/appengine/ - OpenShift: http://openshift.redhat.com/ - Heroku: http://www.heroku.com/ In sum, python is used widely for a variety of purposes by some of the largest enterprises down to very small projects. Michael On Sun, Jul 29, 2012 at 12:01 PM, lipska the kat wrote: > Pythoners > > Firstly, thanks to those on the tutor list who answered my questions. > > I'm trying to understand where Python fits into the set of commonly > available, commercially used languages of the moment. > > My most recent experience is with Java. The last project I was involved with > included 6775 java source files containing 1,145,785 lines of code. How do I > know this? because I managed to cobble together a python script that walks > the source tree and counts the lines of code. It ignores block and line > comments and whitespace lines so I'm fairly confident it's an accurate > total. It doesn't include web interface files (mainly .jsp and HTML) or > configuration files (XML, properties files and what have you). In fact it > was remarkably easy to do this in python which got me thinking about how I > could use the language in a commercial environment. > > I was first attracted to python by it's apparent 'Object Orientedness' I > soon realised however that by looking at it in terms of the language I know > best I wasn't comparing like with like. Once I had 'rebooted the bioware' I > tried to approach python with an open mind and I have to say it's growing on > me. > > The questions I have are ... > > How is python used in the real world. > What sized projects are people involved with > Are applications generally written entirely in python or is it more often > used for a subset of functionality. > > I hope this is an acceptable question for this group > > Many thanks > > Lipska > > -- > Lipska the Kat: Troll hunter, sandbox destroyer > and farscape dreamer of Aeryn Sun > -- > http://mail.python.org/mailman/listinfo/python-list From amangill.coldfire at gmail.com Sun Jul 29 13:37:14 2012 From: amangill.coldfire at gmail.com (coldfire) Date: Sun, 29 Jul 2012 10:37:14 -0700 (PDT) Subject: How To AutoLogin to Website And Navigate thereafter Message-ID: Can Some one help me or guide me the coding for automatic login to a website while keeping the session alive and navigating further into website for screen scraping using python. I understand the scraping part but unable to Understand the Login part using any of the Lib Urllib,Urlib2,BeautifulSoup,Mechanize,Re,requests,cookiejar etc Thanks for the help. From breamoreboy at yahoo.co.uk Sun Jul 29 13:43:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 29 Jul 2012 18:43:32 +0100 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: On 29/07/2012 17:01, lipska the kat wrote: > Pythoners > > Firstly, thanks to those on the tutor list who answered my questions. > > I'm trying to understand where Python fits into the set of commonly > available, commercially used languages of the moment. > > My most recent experience is with Java. The last project I was involved > with included 6775 java source files containing 1,145,785 lines of code. > How do I know this? because I managed to cobble together a python script > that walks the source tree and counts the lines of code. It ignores > block and line comments and whitespace lines so I'm fairly confident > it's an accurate total. It doesn't include web interface files (mainly > .jsp and HTML) or configuration files (XML, properties files and what > have you). In fact it was remarkably easy to do this in python which got > me thinking about how I could use the language in a commercial environment. > > I was first attracted to python by it's apparent 'Object Orientedness' I > soon realised however that by looking at it in terms of the language I > know best I wasn't comparing like with like. Once I had 'rebooted the > bioware' I tried to approach python with an open mind and I have to say > it's growing on me. > > The questions I have are ... > > How is python used in the real world. > What sized projects are people involved with > Are applications generally written entirely in python or is it more > often used for a subset of functionality. > > I hope this is an acceptable question for this group You are hard pushed to find anything here that's unacceptable, that's why I like reading this list so much. > > Many thanks > > Lipska > There's a list of companies who use python on www.python.org top right of the page. You may have heard of one or two of them. -- Cheers. Mark Lawrence. From stefan_ml at behnel.de Sun Jul 29 13:49:51 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 29 Jul 2012 19:49:51 +0200 Subject: counting source lines (was: Is Python a commercial proposition ?) In-Reply-To: References: Message-ID: lipska the kat, 29.07.2012 18:01: > My most recent experience is with Java. The last project I was involved > with included 6775 java source files containing 1,145,785 lines of code. > How do I know this? because I managed to cobble together a python script > that walks the source tree and counts the lines of code. It ignores block > and line comments and whitespace lines so I'm fairly confident it's an > accurate total. It doesn't include web interface files (mainly ..jsp and > HTML) or configuration files (XML, properties files and what have you). In > fact it was remarkably easy to do this in python Just a comment on this part. An even easier way to count source lines is by using the tool "SLOCCount". It also works with various languages. Stefan From bschaffer13 at gmail.com Sun Jul 29 13:50:00 2012 From: bschaffer13 at gmail.com (Brandon Schaffer) Date: Sun, 29 Jul 2012 11:50:00 -0600 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: Another common use is to create automated regression testing frameworks, and other automation tools. I see posting for python developers for this type of thing all the time on stack overflow careers. On Sun, Jul 29, 2012 at 11:43 AM, Mark Lawrence wrote: > On 29/07/2012 17:01, lipska the kat wrote: >> >> Pythoners >> >> Firstly, thanks to those on the tutor list who answered my questions. >> >> I'm trying to understand where Python fits into the set of commonly >> available, commercially used languages of the moment. >> >> My most recent experience is with Java. The last project I was involved >> with included 6775 java source files containing 1,145,785 lines of code. >> How do I know this? because I managed to cobble together a python script >> that walks the source tree and counts the lines of code. It ignores >> block and line comments and whitespace lines so I'm fairly confident >> it's an accurate total. It doesn't include web interface files (mainly >> .jsp and HTML) or configuration files (XML, properties files and what >> have you). In fact it was remarkably easy to do this in python which got >> me thinking about how I could use the language in a commercial >> environment. >> >> I was first attracted to python by it's apparent 'Object Orientedness' I >> soon realised however that by looking at it in terms of the language I >> know best I wasn't comparing like with like. Once I had 'rebooted the >> bioware' I tried to approach python with an open mind and I have to say >> it's growing on me. >> >> The questions I have are ... >> >> How is python used in the real world. >> What sized projects are people involved with >> Are applications generally written entirely in python or is it more >> often used for a subset of functionality. >> >> I hope this is an acceptable question for this group > > > You are hard pushed to find anything here that's unacceptable, that's why I > like reading this list so much. > >> >> Many thanks >> >> Lipska >> > > There's a list of companies who use python on www.python.org top right of > the page. You may have heard of one or two of them. > > -- > Cheers. > > Mark Lawrence. > > -- > http://mail.python.org/mailman/listinfo/python-list From amc96 at cam.ac.uk Sun Jul 29 13:55:36 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Sun, 29 Jul 2012 18:55:36 +0100 Subject: OT: Text editors (was Re: Search and replace text in XML file?) In-Reply-To: References: Message-ID: On 28/07/2012 16:51, Chris Angelico wrote: > On Sat, Jul 28, 2012 at 6:29 PM, Mark Lawrence wrote: >> I highly recommend the use of notepad++. If anyone knows of a better text >> editor for Windows please let me know :) > > My current preference is SciTE, available on Linux and Windows both. > It's configured using Lua, has lexers (and thus syntax highlighters > and auto-indenters) for a huge list of languages (including Python, or > I wouldn't mention it), and isn't RAM-hungry. It's not bug-free (but > what isn't), and has a few limitations (eg it only really supports > UTF-8), but I've found it excellent as both text editor and > pseudo-IDE. > > ChrisA > I use emacs, which is also available for windows (http://ftp.gnu.org/gnu/emacs/windows/ et al) As my work requires mixing between windows, various *NIXes, GUIs and terminals, having a common text editor across all is fantastically useful. ~Andrew From python.list at tim.thechases.com Sun Jul 29 14:28:52 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 29 Jul 2012 13:28:52 -0500 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: <501580E4.6030200@tim.thechases.com> On 07/29/12 12:13, Michael Hrivnak wrote: > - Operating system installer: http://fedoraproject.org/wiki/Anaconda > - Software repository management: http://pulpproject.org/ > - Software package installation: > http://en.wikipedia.org/wiki/Ubuntu_Software_Center > - Cloud computing: http://en.wikipedia.org/wiki/OpenStack I'll include both the Bazaar and Mercurial DVCS tools which are mostly Python (I understand some inner loops drop to C, but both have the option to fall back to a pure Python implementation). -tkc From amc96 at cam.ac.uk Sun Jul 29 14:34:46 2012 From: amc96 at cam.ac.uk (Andrew Cooper) Date: Sun, 29 Jul 2012 19:34:46 +0100 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: On 29/07/2012 17:01, lipska the kat wrote: > Pythoners > > Firstly, thanks to those on the tutor list who answered my questions. > > I'm trying to understand where Python fits into the set of commonly > available, commercially used languages of the moment. > > My most recent experience is with Java. The last project I was involved > with included 6775 java source files containing 1,145,785 lines of code. > How do I know this? because I managed to cobble together a python script > that walks the source tree and counts the lines of code. It ignores > block and line comments and whitespace lines so I'm fairly confident > it's an accurate total. It doesn't include web interface files (mainly > .jsp and HTML) or configuration files (XML, properties files and what > have you). In fact it was remarkably easy to do this in python which got > me thinking about how I could use the language in a commercial environment. > > I was first attracted to python by it's apparent 'Object Orientedness' I > soon realised however that by looking at it in terms of the language I > know best I wasn't comparing like with like. Once I had 'rebooted the > bioware' I tried to approach python with an open mind and I have to say > it's growing on me. > > The questions I have are ... > > How is python used in the real world. > What sized projects are people involved with > Are applications generally written entirely in python or is it more > often used for a subset of functionality. Python is used extensively in XenServer, although arguably more of a glue between components. The installer is entirely python, whereas the running product uses it more for scripts and toolstack plugins. Behind the scenes, our regression test framework is entirely python, which performs several thousand machine hours of tests a night, from simple tests such as "verify the installer runs correctly and verify settings are preserved across upgrade from an older version" to "set up a pool of 4 servers, kill the master server (by removing its power), and verify that the remaining 3 fail over and one gets promoted to master" ~Andrew > > I hope this is an acceptable question for this group > > Many thanks > > Lipska > From subtitle.indo at gmail.com Sun Jul 29 14:37:54 2012 From: subtitle.indo at gmail.com (subin) Date: Mon, 30 Jul 2012 01:37:54 +0700 Subject: concurrent.futures vs gevent Message-ID: Hi, It will be my first post here. I just found a great presentation here https://ep2012.europython.eu/conference/talks/concurrentfutures-is-here. As non native english, i can't fully understand all of the material presented there. I have some doubt, i hope someone here can give clarification. Could concurrent.futures be a (partly) replacement of gevent? I guess not, because gevent provide lightweight thread via greenlet, while concurrent.futures only provide multiprocessing across different processor) (not lightweight). Thanks From stefan_ml at behnel.de Sun Jul 29 14:38:19 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 29 Jul 2012 20:38:19 +0200 Subject: Is Python a commercial proposition ? In-Reply-To: <501580E4.6030200@tim.thechases.com> References: <501580E4.6030200@tim.thechases.com> Message-ID: Tim Chase, 29.07.2012 20:28: > On 07/29/12 12:13, Michael Hrivnak wrote: >> - Operating system installer: http://fedoraproject.org/wiki/Anaconda >> - Software repository management: http://pulpproject.org/ >> - Software package installation: >> http://en.wikipedia.org/wiki/Ubuntu_Software_Center >> - Cloud computing: http://en.wikipedia.org/wiki/OpenStack > > I'll include both the Bazaar and Mercurial DVCS tools which are > mostly Python (I understand some inner loops drop to C, but both > have the option to fall back to a pure Python implementation). I find it perfectly reasonable to use C code (and other kinds of low-level code) in Python tools and applications. In fact, easy interfacing with low-level code is one of (C)Python's major selling points. Stefan From tjreedy at udel.edu Sun Jul 29 15:38:50 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 29 Jul 2012 15:38:50 -0400 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: On 7/29/2012 12:01 PM, lipska the kat wrote: > I'm trying to understand where Python fits into the set of commonly > available, commercially used languages of the moment. Ever heard of a little startup called Google? It was built with C, Java, ... and Python. I believe Youtube is scripted in Python. > Are applications generally written entirely in python > or is it more often used for a subset of functionality. Even if the direct application is in Python, if it runs on CPython, it probably uses modules coded or re-coded in C, and it certainly used builtin functions and classes coded in C. The first 'killer app' for Python, in the 1990s, was its use as a glue language for interactive and batch scientific/numerical computation mostly done in compiled Fortran. -- Terry Jan Reedy From Bernd-Waterkamp at web.de Sun Jul 29 15:43:22 2012 From: Bernd-Waterkamp at web.de (Bernd Waterkamp) Date: Sun, 29 Jul 2012 21:43:22 +0200 Subject: Is Python a commercial proposition ? References: Message-ID: <15p2u6797fkt7$.1ku8k9avgkior.dlg@40tude.net> Michael Hrivnak schrieb: > Python is used frequently on the server side of web applications for > sites of all sizes, with the UI generally being done in javascript. Two large companies with lots of python code are dropbox and youtube: http://highscalability.com/blog/2011/3/14/6-lessons-from-dropbox-one-million-files-saved-every-15-minu.html http://highscalability.com/blog/2012/3/26/7-years-of-youtube-scalability-lessons-in-30-minutes.html > It's also used heavily for administrative purposes such as: > > - Operating system installer: http://fedoraproject.org/wiki/Anaconda > - Software repository management: http://pulpproject.org/ > - Software package installation: > http://en.wikipedia.org/wiki/Ubuntu_Software_Center > - Cloud computing: http://en.wikipedia.org/wiki/OpenStack - Frameworks/tools like func, fabric or ipython are used in medium and large networks/"clouds". - Python is also used a lot for admin tasks instead of shell scripts. - I know IBM WebSphere is not the favorite choice as an application server for most Java programmers *g*, but it uses Jython for the admin CLI. python and python based tools are used for engineering and scientific computing - some random examples: numpy, Sage, matplotlib, NetworkX. Regards, Bernd From aled.r.evans at gmail.com Sun Jul 29 15:54:42 2012 From: aled.r.evans at gmail.com (Aled Evans) Date: Sun, 29 Jul 2012 12:54:42 -0700 (PDT) Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: On Sunday, July 29, 2012 5:01:00 PM UTC+1, lipska the kat wrote: > Pythoners > > > > Firstly, thanks to those on the tutor list who answered my questions. > > > > I'm trying to understand where Python fits into the set of commonly > > available, commercially used languages of the moment. > > > > My most recent experience is with Java. The last project I was involved > > with included 6775 java source files containing 1,145,785 lines of code. > > How do I know this? because I managed to cobble together a python script > > that walks the source tree and counts the lines of code. It ignores > > block and line comments and whitespace lines so I'm fairly confident > > it's an accurate total. It doesn't include web interface files (mainly > > .jsp and HTML) or configuration files (XML, properties files and what > > have you). In fact it was remarkably easy to do this in python which got > > me thinking about how I could use the language in a commercial environment. > > > > I was first attracted to python by it's apparent 'Object Orientedness' I > > soon realised however that by looking at it in terms of the language I > > know best I wasn't comparing like with like. Once I had 'rebooted the > > bioware' I tried to approach python with an open mind and I have to say > > it's growing on me. > > > > The questions I have are ... > > > > How is python used in the real world. > > What sized projects are people involved with > > Are applications generally written entirely in python or is it more > > often used for a subset of functionality. > > > > I hope this is an acceptable question for this group > > > > Many thanks > > > > Lipska > > > > -- > > Lipska the Kat: Troll hunter, sandbox destroyer > > and farscape dreamer of Aeryn Sun If you check Google's job listings: http://www.google.com/about/jobs/teams/engineering/ On the software side of things you'll see very few listings that don't ask for coding in Python as a requirement or, at the very least, an advantageous skill to have. I'd say slowly, but surely, many people are coming around the fact that Python is not only as powerful as Java and other high-level languages, but it's also easier to read and write. That, and people (that I've spoken to, at least), find it far more fun to code in Python! From mail at paultjuh.org Sun Jul 29 16:54:46 2012 From: mail at paultjuh.org (=?utf-8?Q?Paul_van_der_Linden?=) Date: Sun, 29 Jul 2012 22:54:46 +0200 Subject: Is Python a commercial proposition ? Message-ID: Scripting is one of the strong sides of python. I use it al the time to quickly write a script to analyze something or automate. That is probably the reason it is used to glue (script) things together and is embedded in some programs (like Maya and such). At the company we're using python and django for websites, from small micro sites till big enterprise sites. Currently I'm working on a highly configurable application to control a maya render cluster. You can also use it for testing and even frontend testing. I think you can use python for almost everything, tough I think it's less suitable for non-web gui applications. lipska the kat schreef: Pythoners Firstly, thanks to those on the tutor list who answered my questions. I'm trying to understand where Python fits into the set of commonly available, commercially used languages of the moment. My most recent experience is with Java. The last project I was involved with included 6775 java source files containing 1,145,785 lines of code. How do I know this? because I managed to cobble together a python script that walks the source tree and counts the lines of code. It ignores block and line comments and whitespace lines so I'm fairly confident it's an accurate total. It doesn't include web interface files (mainly .jsp and HTML) or configuration files (XML, properties files and what have you). In fact it was remarkably easy to do this in python which got me thinking about how I could use the language in a commercial environment. I was first attracted to python by it's apparent 'Object Orientedness' I soon realised however that by looking at it in terms of the language I know best I wasn't comparing like with like. Once I had 'rebooted the bioware' I tried to approach python with an open mind and I have to say it's growing on me. The questions I have are ... How is python used in the real world. What sized projects are people involved with Are applications generally written entirely in python or is it more often used for a subset of functionality. I hope this is an acceptable question for this group Many thanks Lipska -- Lipska the Kat: Troll hunter, sandbox destroyer and farscape dreamer of Aeryn Sun -- http://mail.python.org/mailman/listinfo/python-list From invalid at invalid.invalid Sun Jul 29 17:41:13 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 29 Jul 2012 21:41:13 +0000 (UTC) Subject: OT: Text editors References: <87pq7fqhlh.fsf@benfinney.id.au> Message-ID: On 2012-07-29, Mark Lawrence wrote: > Point taken, snag being I've never used any nix box in anger. This > thread reminds of the good 'ole days when I were a lad using TPU on > VMS. Have we got any VMS aficionados here? It's been a long time, but I used eve/tpu as my main editor for several years back when I did embedded SW development on VMS. I was an ex-Unix user, so I used DECShell a lot -- even though it was painfully slow. The entire Unix philosophy is based on the assumption that process creation is inexpensive, and I was told process creation on VMS was _very_ expensive, so Bourne shell scripts that would have taken second under Unix took minutes under VMS. -- Grant From PointedEars at web.de Sun Jul 29 17:47:41 2012 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 29 Jul 2012 23:47:41 +0200 Subject: Is Python a commercial proposition ? References: Message-ID: <15834089.9i7QP8sP0p@PointedEars.de> Michael Hrivnak wrote: > Python is used frequently on the server side of web applications for > sites of all sizes, with the UI generally being done in javascript. There is no javascript. -- PointedEars Please do not Cc: me. / Bitte keine Kopien per E-Mail. From solipsis at pitrou.net Sun Jul 29 17:49:28 2012 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 29 Jul 2012 21:49:28 +0000 (UTC) Subject: ANN: pathlib 0.7 Message-ID: Hello, pathlib 0.7 has been released with the following changes: - Add '**' (recursive) patterns to Path.glob(). - Fix openat() support after the API refactoring in Python 3.3 beta1. - Add a *target_is_directory* argument to Path.symlink_to() pathlib offers a set of classes to handle filesystem paths. It offers the following advantages over using string objects: * No more cumbersome use of os and os.path functions. Everything can be done easily through operators, attribute accesses, and method calls. * Embodies the semantics of different path types. For example, comparing Windows paths ignores casing. * Well-defined semantics, eliminating any warts or ambiguities (forward vs. backward slashes, etc.). PyPI download page at http://pypi.python.org/pypi/pathlib/ Documentation at http://pathlib.readthedocs.org/en/latest/ Code and issue tracker at https://bitbucket.org/pitrou/pathlib/ Regards Antoine Pitrou. -- Software development and contracting: http://pro.pitrou.net From esj at harvee.org Sun Jul 29 19:21:49 2012 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 29 Jul 2012 19:21:49 -0400 Subject: simplified Python parsing question Message-ID: <5015C58D.4040101@harvee.org> as some folks may remember, I have been working on making Python and its tool base more accessible to disabled programmers. I've finally come up with a really simple technique which should solve 80% of the problem. What I need to figure out is how to find a spot in the code where a symbol exists and potentially, it's rough type (class name, instance, etc.). This is really a much bigger question that I want to get into right now but I'm looking just to build a demo to back up a storyboard plus video. When you are sitting on or in a name, you look to the left or look to the right what would you see that would tell you that you have gone past the end of that name. For example a = b + c if you are sitting on a, the boundaries are beginning of line and =, if you are sitting on b, the boundaries are = and +, if you are sitting on c, the boundaries are + and end of line. a call the region between those boundaries the symbol region. if this example is clear to you, what you suggest for a method of finding a whole statement, or a whole symbol region? note, doesn't have to be perfect or complete solution, just good enough to let me do a moderately complex demo and seek funding accessibility world to build a complete environment. I appreciate the help because I believe that once this is working, it'll make a significant difference in the ability for disabled programmers to write code again as well as be able to integrate within existing development team and their naming conventions. Looking forward to responses. --- eric first draft write up of technique https://docs.google.com/document/d/1In11apApKozw_UOPAhVz0ePqns72_6652Dra34xWp4E/edit From rodrick.brown at gmail.com Sun Jul 29 20:12:42 2012 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Sun, 29 Jul 2012 20:12:42 -0400 Subject: Is Python a commercial proposition ? In-Reply-To: References: Message-ID: <-1016624622349492799@unknownmsgid> Sent from my iPhone On Jul 29, 2012, at 12:07 PM, lipska the kat wrote: > Pythoners > > Firstly, thanks to those on the tutor list who answered my questions. > > I'm trying to understand where Python fits into the set of commonly available, commercially used languages of the moment. Python is a glue language much like Perl was 10 years ago. Until the GIL is fixed I doubt anyone will seriously look at Python as an option for large enterprise standalone application development. I work in financials and the majority of our apps are developed in C++ and Java yet all the tools that startup, deploy and conduct rigorous unit testing are implemented in Python or Shell scripts that wrap Python scripts. Python definitely has its place in the enterprise however not so much for serious stand alone app development. I'm starting to see Python used along side many statistical and analytical tools like R, SPlus, and Mathlab for back testing and prototype work, in a lot of cases I've seen quants and traders implement models in Python to back test and if successful converted to Java or C++. From steve+comp.lang.python at pearwood.info Sun Jul 29 20:44:04 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 30 Jul 2012 00:44:04 GMT Subject: Extracting bit fields from an IEEE-784 float Message-ID: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> I wish to extract the bit fields from a Python float, call it x. First I cast the float to 8-bytes: s = struct.pack('=d', x) i = struct.unpack('=q', s)[0] Then I extract the bit fields from the int, e.g. to grab the sign bit: (i & 0x8000000000000000) >> 63 Questions: 1) Are there any known implementations or platforms where Python floats are not C doubles? If so, what are they? 2) If the platform byte-order is reversed, do I need to take any special action? I don't think I do, because even though the float is reversed, so will be the bit mask. Is this correct? 3) Any other problems with the way I am doing this? Thanks in advance, Steven From bahamutzero8825 at gmail.com Sun Jul 29 20:52:22 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 29 Jul 2012 19:52:22 -0500 Subject: Is Python a commercial proposition ? In-Reply-To: <-1016624622349492799@unknownmsgid> References: <-1016624622349492799@unknownmsgid> Message-ID: <5015DAC6.6060803@gmail.com> On 7/29/2012 7:12 PM, Rodrick Brown wrote: > Python is a glue language much like Perl was 10 years ago. Until the > GIL is fixed I doubt anyone will seriously look at Python as an option > for large enterprise standalone application development. The GIL is neither a bug to be fixed nor an inherent part of the language. It is a design choice for CPython. There are reasons the CPython devs have no intention of removing the GIL (at least in the near future). A recent outline of these reasons (written by one of the CPython devs) is here: http://python-notes.boredomandlaziness.org/en/latest/python3/questions_and_answers.html#but-but-surely-fixing-the-gil-is-more-important-than-fixing-unicode -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From dan at tombstonezero.net Sun Jul 29 21:08:14 2012 From: dan at tombstonezero.net (Dan Sommers) Date: Sun, 29 Jul 2012 18:08:14 -0700 Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: <20120730010814.GB1400@particle> On 2012-07-30 at 00:44:04 +0000, Steven D'Aprano wrote: > I wish to extract the bit fields from a Python float, call it x. First I > cast the float to 8-bytes: > > s = struct.pack('=d', x) > i = struct.unpack('=q', s)[0] > > Then I extract the bit fields from the int, e.g. to grab the sign bit: > > (i & 0x8000000000000000) >> 63 > 3) Any other problems with the way I am doing this? No, but perhaps this would be clearer: import math sign = math.copysign(1.0, x) There are solutions that use math.frexp, too, but IMO they're more obtuse. HTH, Dan From chris at gonnerman.org Sun Jul 29 21:26:53 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Sun, 29 Jul 2012 20:26:53 -0500 Subject: PyPI question, or, maybe I'm just stupid In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: <5015E2DD.2050209@gonnerman.org> I've been making some minor updates to the PollyReports module I announced a while back, and I've noticed that when I upload it to PyPI, my changelog (CHANGES.txt) doesn't appear to be integrated into the site at all. Do I have to put the changes into the README, or have I missed something here? It seems that there should be some automatic method whereby PyPI users could easily see what I've changed without downloading it first. From drsalists at gmail.com Sun Jul 29 21:33:01 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 29 Jul 2012 18:33:01 -0700 Subject: Is Python a commercial proposition ? In-Reply-To: <5015DAC6.6060803@gmail.com> References: <-1016624622349492799@unknownmsgid> <5015DAC6.6060803@gmail.com> Message-ID: On Sun, Jul 29, 2012 at 5:52 PM, Andrew Berg wrote: > On 7/29/2012 7:12 PM, Rodrick Brown wrote: > > Python is a glue language much like Perl was 10 years ago. Until the > > GIL is fixed I doubt anyone will seriously look at Python as an option > > for large enterprise standalone application development. > The GIL is neither a bug to be fixed nor an inherent part of the > language. It is a design choice for CPython. There are reasons the > CPython devs have no intention of removing the GIL (at least in the near > future). A recent outline of these reasons (written by one of the > CPython devs) is here: > > > http://python-notes.boredomandlaziness.org/en/latest/python3/questions_and_answers.html#but-but-surely-fixing-the-gil-is-more-important-than-fixing-unicode It's a nice document, though it seems to use the phrase "shared memory" in a novel (to me) way, and literally says that multiprocessing doesn't use "shared memory" even though it does (at least in the sense of the phrase that I'm accustomed to). I suppose you could call what I usually refer to as "shared memory", instead "System V shared memory". It's hidden from the user to a large extent, but when multiprocessing passes objects from one process to another, I believe it's doing so via System V shared memory. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rodrick.brown at gmail.com Sun Jul 29 22:31:00 2012 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Sun, 29 Jul 2012 22:31:00 -0400 Subject: Is Python a commercial proposition ? In-Reply-To: <5015DAC6.6060803@gmail.com> References: <-1016624622349492799@unknownmsgid> <5015DAC6.6060803@gmail.com> Message-ID: <-9130812546080764300@unknownmsgid> On Jul 29, 2012, at 8:54 PM, Andrew Berg wrote: > On 7/29/2012 7:12 PM, Rodrick Brown wrote: >> Python is a glue language much like Perl was 10 years ago. Until the >> GIL is fixed I doubt anyone will seriously look at Python as an option >> for large enterprise standalone application development. > The GIL is neither a bug to be fixed nor an inherent part of the > language. It is a design choice for CPython. There are reasons the > CPython devs have no intention of removing the GIL (at least in the near > future). A recent outline of these reasons (written by one of the > CPython devs) is here: > > http://python-notes.boredomandlaziness.org/en/latest/python3/questions_and_answers.html#but-but-surely-fixing-the-gil-is-more-important-than-fixing-unicode Hence the reason why no one will seriously look at Python for none glue work or simple web apps. When it comes to designing complex applications that need to exploit large multicore systems Python just isn't an option. Its still not possible to be a pure Python developer and find gainful employment today. > -- > CPython 3.3.0b1 | Windows NT 6.1.7601.17803 > -- > http://mail.python.org/mailman/listinfo/python-list From no.email at nospam.invalid Sun Jul 29 23:03:00 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Sun, 29 Jul 2012 20:03:00 -0700 Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> <5015DAC6.6060803@gmail.com> Message-ID: <7xy5m2vtln.fsf@ruckus.brouhaha.com> Rodrick Brown writes: > Hence the reason why no one will seriously look at Python for none > glue work or simple web apps. When it comes to designing complex > applications that need to exploit large multicore systems Python just > isn't an option. That's wrong, I've run multicore apps in Python, by just using separate processes. There was no GIL issue, just separate processes for each core. The cpython interpreter is so slow that the GIL is usually not the bottleneck anyway. For lots of applications this just doesn't matter since the app is either not cpu-intensive or (in my case) all the work is done in native libraries. > Its still not possible to be a pure Python developer and find gainful > employment today. Certainly any serious programmer should be good in multiple languages, and in fact I got to write a little bit of C code at work a few months ago, but it wasn't really needed. The program is all Python. From steve+comp.lang.python at pearwood.info Sun Jul 29 23:33:32 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 30 Jul 2012 03:33:32 GMT Subject: simplified Python parsing question References: Message-ID: <5016008b$0$11120$c3e8da3@news.astraweb.com> On Sun, 29 Jul 2012 19:21:49 -0400, Eric S. Johansson wrote: > When you are sitting on or in a name, you look to the left or look to > the right what would you see that would tell you that you have gone past > the end of that name. For example Have you read the docs? It gives full details of the Python syntax. http://docs.python.org/reference/index.html For example: http://docs.python.org/reference/simple_stmts.html#assignment-statements See also: http://docs.python.org/library/language.html http://effbot.org/zone/simple-top-down-parsing.htm http://nedbatchelder.com/text/python-parsers.html Here's a Python parser using the pyparsing library. It's a bit old (written for Python 2.4) but it shouldn't be hard to update it to new syntax: http://pyparsing.wikispaces.com/file/view/pythonGrammarParser.py -- Steven From ben+python at benfinney.id.au Mon Jul 30 00:00:48 2012 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 30 Jul 2012 14:00:48 +1000 Subject: PyPI question, or, maybe I'm just stupid References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: <87fw89rj7z.fsf@benfinney.id.au> Chris Gonnerman writes: > I've been making some minor updates to the PollyReports module Your post is showing up as a reply to a thread about IEEE-784 floats, because you created your message as a reply. Consequently, it's rather confusing why you suddenly start talking about PollyReports. If you want to attract attention to an unrelated topic, it's best if you don't reply to an existing thread; instead, start a new thread by composing a new message to the forum. -- \ ?I'd take the awe of understanding over the awe of ignorance | `\ any day.? ?Douglas Adams | _o__) | Ben Finney From tjreedy at udel.edu Mon Jul 30 01:17:22 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Jul 2012 01:17:22 -0400 Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: On 7/29/2012 8:44 PM, Steven D'Aprano wrote: > I wish to extract the bit fields from a Python float, call it x. First I > cast the float to 8-bytes: > > s = struct.pack('=d', x) > i = struct.unpack('=q', s)[0] > > Then I extract the bit fields from the int, e.g. to grab the sign bit: > > (i & 0x8000000000000000) >> 63 > > > Questions: > > 1) Are there any known implementations or platforms where Python floats > are not C doubles? If so, what are they? CPython floats are C doubles, which should be IEEE doubles. Other implementations have a different to probably the same thing. > 2) If the platform byte-order is reversed, do I need to take any special > action? I don't think I do, because even though the float is reversed, so > will be the bit mask. Is this correct? The math modules functions to disassemble floats will not care. -- Terry Jan Reedy From james.pye at gmail.com Mon Jul 30 01:18:23 2012 From: james.pye at gmail.com (jwp) Date: Sun, 29 Jul 2012 22:18:23 -0700 (PDT) Subject: ANN: visage (interfaces) Message-ID: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> Hi, I just pushed this up to pypi/github, and I hoped to acquire some c.l.py opinions. It's experimental at this point, and might get scrapped. visage is a loosely coupled interface registry. weakrefs make it cake to implement. Basically, zope.interface, but where the interfaces are referenced by an identifier instead of the defining Interface class. Also, ABC registration is performed when the Interface becomes available so that isinstance/issubclass checks can be performed on Implementation instances/classes. FWICT, pyprotocols allows for something like this, but while introducing many "interesting concepts". (; Currently, visage has no concept of adaption, but I'm suspecting that it could be built *on top* of the existing foundation. Personally, I'd prefer to reference interfaces by an identifier. Notably, the idea of having to pull in a dependency in order to perform local tests that have no need for the formal Interface class is reason enough for me to use something like this instead of the existing solutions. Sure, to each their own.? What's c.l.py's perspective on managing interfaces and implementations? Fuck it, ship it? =) From james.pye at gmail.com Mon Jul 30 01:32:41 2012 From: james.pye at gmail.com (jwp) Date: Sun, 29 Jul 2012 22:32:41 -0700 (PDT) Subject: ANN: visage (interfaces) In-Reply-To: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> References: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> Message-ID: <52f2e8b7-4d91-4034-a263-d657bfedcc45@googlegroups.com> On Sunday, July 29, 2012 10:18:23 PM UTC-7, jwp wrote: > I just pushed this up to pypi/github, and I hoped to acquire some c.l.py opinions. http://github.com/jwp/py-visage From stefan_ml at behnel.de Mon Jul 30 02:07:00 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 30 Jul 2012 08:07:00 +0200 Subject: Is Python a commercial proposition ? In-Reply-To: <-1016624622349492799@unknownmsgid> References: <-1016624622349492799@unknownmsgid> Message-ID: Rodrick Brown, 30.07.2012 02:12: > On Jul 29, 2012, at 12:07 PM, lipska the kat wrote: >> I'm trying to understand where Python fits into the set of commonly available, commercially used languages of the moment. > > Python is a glue language much like Perl was 10 years ago. Until the > GIL is fixed Enough people have commented on this piece of FUD already. > I doubt anyone will seriously look at Python as an option > for large enterprise standalone application development. I know enough examples to recognise this as nonsense. You mentioned working in "financials" and even there I know at least one not-so-small bank that's been developing their internal (EAI and business process) code in Python for almost a decade now. And their developers are quite happy with it, certainly happier than many of the Java developers I've met in other banks. Still, you may still get away with the above statement by providing a sufficiently narrow definition of "standalone". By my definition, there isn't much "standalone" code out there. Most code I know interfaces with a couple of external tools, libraries or backends, usually written in languages I don't have to care about because they provide a language independent interface. Stefan From esj at harvee.org Mon Jul 30 02:17:33 2012 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 30 Jul 2012 02:17:33 -0400 Subject: simplified Python parsing question In-Reply-To: <5016008b$0$11120$c3e8da3@news.astraweb.com> References: <5016008b$0$11120$c3e8da3@news.astraweb.com> Message-ID: <501626FD.9070404@harvee.org> On 7/29/2012 11:33 PM, Steven D'Aprano wrote: > On Sun, 29 Jul 2012 19:21:49 -0400, Eric S. Johansson wrote: > >> When you are sitting on or in a name, you look to the left or look to >> the right what would you see that would tell you that you have gone past >> the end of that name. For example > Have you read the docs? It gives full details of the Python syntax. Yes I have. I was hoping for a different perspective because what I'm trying to do is middle out parsing. Top-down when the scanner focus moves from left to right and bottom up when the scanner focus moves from right to left. sounds kind of odd when I describe it that way but both the cursor is on the middle of a name string and I need to look to either end of that name string before can do a conversion to a symbol string, I have to look at both ends in different ways. If you've read the documentation I've provided, would it be a better example to use for describing some of the issues. Here's a very rough draft of a storyboard https://docs.google.com/presentation/d/1fuKyo9AE6i9ZdX2lucwK0v_W5Kx9M3Mezavm40wzCo8/edit the first 13-14 slides are the working content for the storyboard. the rest is mostly "memory" of things I was thinking about so if it doesn't make sense or seems wrong, don't give me grief. :-) > Here's a Python parser using the pyparsing library. It's a bit old > (written for Python 2.4) but it shouldn't be hard to update it to new > syntax: > > http://pyparsing.wikispaces.com/file/view/pythonGrammarParser.py > thanks for the reference. I'll take a look at it as well. From ulrich.eckhardt at dominolaser.com Mon Jul 30 02:42:58 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 30 Jul 2012 08:42:58 +0200 Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: Am 30.07.2012 02:44, schrieb Steven D'Aprano: > I wish to extract the bit fields from a Python float, call it x. First I > cast the float to 8-bytes: > > s = struct.pack('=d', x) > i = struct.unpack('=q', s)[0] > > Then I extract the bit fields from the int, e.g. to grab the sign bit: > > (i & 0x8000000000000000) >> 63 > > > Questions: > > 1) Are there any known implementations or platforms where Python floats > are not C doubles? If so, what are they? The struct docs refer to C's double type, so it depends on that type probably. However, regardless of C's double type, the same docs refer to the IEEE form when packed into a byte array. Is it just the representation you are after or some specific behaviour? > 2) If the platform byte-order is reversed, do I need to take any special > action? I don't think I do, because even though the float is reversed, so > will be the bit mask. Is this correct? Yes, the code is fine. If you have doubts, I have a big-endian system at home (Linux/PowerPC) where I could run tests. > 3) Any other problems with the way I am doing this? Python docs refer to IEEE-754, not 784? Typo? Uli From vikas.choudhary at yahoo.co.in Mon Jul 30 03:05:41 2012 From: vikas.choudhary at yahoo.co.in (Vikas Kumar Choudhary) Date: Mon, 30 Jul 2012 15:05:41 +0800 (SGT) Subject: Linux shell to python Message-ID: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Dear friends, I just joined the group. I was trying porting from bash shell to python. let me know if someone has tried to implement (grep and PIPE) ?shell commands in python `lspci | grep Q | grep ?"$isp_str1" | grep "$isp_str2" | cut -c1-7' ? I tried to use python subprocess and OS.Popen modules. Thanks & Regard's Vikas Kumar Choudhary (Yahoo,MSN-Hotmail,Skype) Messenger = vikas.choudhary Please?Add Me in Your Messenger List for Better Communication P??Please consider the environment before printing this e-mail Do not print this email unless it is absolutely necessary. Save papers, Save tree. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Note: This e-mail is confidential and may also be privileged, this is for the intended recipients only. If you are not the intended recipient, please delete the message and notify me immediately; you should not copy or use it for any purpose, nor disclose its contents to any other person. Notice:? All email and instant messages (including attachments) sent to or from This E-mail id , may be retained, monitored and/or reviewed, or authorized law enforcement personnel, without further notice or consent. ---------------------------------------------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Jul 30 03:40:04 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 30 Jul 2012 17:40:04 +1000 Subject: Linux shell to python In-Reply-To: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: On Mon, Jul 30, 2012 at 5:05 PM, Vikas Kumar Choudhary wrote: > > I was trying porting from bash shell to python. > > let me know if someone has tried to implement (grep and PIPE) shell commands in python `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' Welcome! While it's technically possible to do exactly that in Python (using subprocess as you describe), there's usually a more efficient and cleaner method of achieving the same goal. With a port such as you describe, it's probably best to go right back to the conceptual level and work out what exactly you're trying to do, and then look at implementing that in Python. You'll end up with much cleaner code at the end of it. For an initial guess, I would say that you'll use subprocess to invoke lspci, but then everything else will be done in Python directly. ChrisA From rosuav at gmail.com Mon Jul 30 03:52:55 2012 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 30 Jul 2012 17:52:55 +1000 Subject: Is Python a commercial proposition ? In-Reply-To: References: <-1016624622349492799@unknownmsgid> Message-ID: On Mon, Jul 30, 2012 at 4:07 PM, Stefan Behnel wrote: > Still, you may still get away with the above statement by providing a > sufficiently narrow definition of "standalone". By my definition, there > isn't much "standalone" code out there. Most code I know interfaces with a > couple of external tools, libraries or backends, usually written in > languages I don't have to care about because they provide a language > independent interface. Agreed, and the flip-side of that is that there aren't many mono-language developers either. Sure, it'd be possible to make a career of nothing but Objective-C, writing apps for Apple to make all the money off, but even then you'll probably benefit from knowing some glue languages. Python's an excellent glue language, but it's also fine for huge applications. Yes, it can't multithread across cores if you use CPython and are CPU-bound. That's actually a pretty specific limitation, and taking out any component of that eliminates the GIL as a serious problem. ChrisA From dickinsm at gmail.com Mon Jul 30 03:57:15 2012 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 30 Jul 2012 00:57:15 -0700 (PDT) Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: <48341117-060e-492a-b476-4d2ac58ba590@googlegroups.com> On Monday, July 30, 2012 1:44:04 AM UTC+1, Steven D'Aprano wrote: > 1) Are there any known implementations or platforms where Python floats > are not C doubles? If so, what are they? Well, IronPython is presumably using .NET Doubles, while Jython will be using Java Doubles---in either case, that's specified to be the IEEE 754 binary64 type. For CPython, and I guess PyPy too, we're using C doubles, which in theory are in whatever format the platform provides, but in practice are always IEEE 754 binary64 again. So you're pretty safe assuming IEEE 754 binary64 format. If you ever meet a current Python running on a system that *doesn't* use IEEE 754 for its C doubles, please let me know---there are a lot of interesting questions that would come up in that case. > 2) If the platform byte-order is reversed, do I need to take any special > > action? I don't think I do, because even though the float is reversed, so > > will be the bit mask. Is this correct? True; on almost all current platforms, the endianness of int types matches the endianness of float types. But to be safe, why not use ' 3) Any other problems with the way I am doing this? You might consider whether you want to use ' Message-ID: <87fw89wr39.fsf@handshake.de> "Eric S. Johansson" writes: > When you are sitting on or in a name, you look to the left or look to > the right what would you see that would tell you that you have gone > past the end of that name. For example > > a = b + c > > if you are sitting on a, the boundaries are beginning of line and =, > if you are sitting on b, the boundaries are = and +, if you are > sitting on c, the boundaries are + and end of line. a call the region > between those boundaries the symbol region. Check the lexical definitions. They essentially define, what a "symbol region" is. In essence, you have names, operators, literals whitespace and comments -- each with quite a simple definition. From dieter at handshake.de Mon Jul 30 05:20:58 2012 From: dieter at handshake.de (Dieter Maurer) Date: Mon, 30 Jul 2012 11:20:58 +0200 Subject: PyPI question, or, maybe I'm just stupid References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> <5015E2DD.2050209@gonnerman.org> Message-ID: <87boixwqo5.fsf@handshake.de> Chris Gonnerman writes: > I've been making some minor updates to the PollyReports module I > announced a while back, and I've noticed that when I upload it to > PyPI, my changelog (CHANGES.txt) doesn't appear to be integrated into > the site at all. Do I have to put the changes into the README, or > have I missed something here? It seems that there should be some > automatic method whereby PyPI users could easily see what I've changed > without downloading it first. "CHANGES.txt" is not automatically presented. If necessary, you must integrate it into the "long description". However, personally, I am not interested in all the details (typically found in "CHANGES.txt") but some (often implicit) information is sufficient for me: something like "major API change", "minor bug fixes". Thus, think carefully what you put on the overview page. I find it very stupid to see several window scrolls of changes for a package but to learn how to install the package, I have to download its source... From gandalf at shopzeus.com Mon Jul 30 05:25:28 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 30 Jul 2012 11:25:28 +0200 Subject: simplified Python parsing question In-Reply-To: <5015C58D.4040101@harvee.org> References: <5015C58D.4040101@harvee.org> Message-ID: <50165308.5060708@shopzeus.com> > I appreciate the help because I believe that once this is working, > it'll make a significant difference in the ability for disabled > programmers to write code again as well as be able to integrate within > existing development team and their naming conventions. Did you try to use pygments? http://pygments.org/docs/api/ It already contains a lexer for Python source code. You can create a Lexer (pygments.lexer.Lexer) then call its get_tokens method. Then you can use this to identify statements: http://docs.python.org/reference/simple_stmts.html Fortunately, almost all statements begin with a keyword. There are some exceptions: expression statement assignment statement I would first tokenize the code, then divide it by statement keywords. Finally, you just need to find expression/assignment statements in the remaining sections. (Maybe there is a better way to do it.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tokauf at googlemail.com Mon Jul 30 05:50:12 2012 From: tokauf at googlemail.com (Thomas Kaufmann) Date: Mon, 30 Jul 2012 02:50:12 -0700 (PDT) Subject: newbie: write content in a file (server-side) In-Reply-To: References: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> Message-ID: <99c41e29-5e7d-44c8-a0f5-eeb74af6bb49@googlegroups.com> Am Sonntag, 29. Juli 2012 17:16:11 UTC+2 schrieb Peter Otten: > Thomas Kaufmann wrote: > > > > > I send from a client file content to my server (as bytes). So far so good. > > > The server receives this content complete. Ok. Then I want to write this > > > content to a new file. It works too. But in the new file are only the > > > first part of the whole content. > > > > > > What's the problem. > > > > > Here's my server code: > > > > > while True: > > > bytes = self.request.recv(4096) > > > if bytes: > > > s = bytes.decode("utf8") > > > print(s) > > > li = s.split("~") > > > with open(li[0], 'w') as fp: > > > fp.write(li[1]) > > > > - Do you ever want to leave the loop? > > > > - You calculate a new filename on every iteration of the while loop -- > > probably not what you intended to do. > > > > - The "w" argument tells Python to overwrite the file if it exists. You > > either need to keep the file open (move the with... out of the loop) or open > > it with "a". > > > > - You may not receive the complete file name on the first iteration of the > > while loop. > > > > - The bytes buffer can contain incomplete characters, e. g.: > > > > >>> data = b"\xc3\xa4" > > >>> data.decode("utf-8") > > '?' > > >>> data[:1].decode("utf-8") > > Traceback (most recent call last): > > File "", line 1, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: > > unexpected end of data Thanks Peter. It helps;-). From tokauf at googlemail.com Mon Jul 30 05:50:12 2012 From: tokauf at googlemail.com (Thomas Kaufmann) Date: Mon, 30 Jul 2012 02:50:12 -0700 (PDT) Subject: newbie: write content in a file (server-side) In-Reply-To: References: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> Message-ID: <99c41e29-5e7d-44c8-a0f5-eeb74af6bb49@googlegroups.com> Am Sonntag, 29. Juli 2012 17:16:11 UTC+2 schrieb Peter Otten: > Thomas Kaufmann wrote: > > > > > I send from a client file content to my server (as bytes). So far so good. > > > The server receives this content complete. Ok. Then I want to write this > > > content to a new file. It works too. But in the new file are only the > > > first part of the whole content. > > > > > > What's the problem. > > > > > Here's my server code: > > > > > while True: > > > bytes = self.request.recv(4096) > > > if bytes: > > > s = bytes.decode("utf8") > > > print(s) > > > li = s.split("~") > > > with open(li[0], 'w') as fp: > > > fp.write(li[1]) > > > > - Do you ever want to leave the loop? > > > > - You calculate a new filename on every iteration of the while loop -- > > probably not what you intended to do. > > > > - The "w" argument tells Python to overwrite the file if it exists. You > > either need to keep the file open (move the with... out of the loop) or open > > it with "a". > > > > - You may not receive the complete file name on the first iteration of the > > while loop. > > > > - The bytes buffer can contain incomplete characters, e. g.: > > > > >>> data = b"\xc3\xa4" > > >>> data.decode("utf-8") > > '?' > > >>> data[:1].decode("utf-8") > > Traceback (most recent call last): > > File "", line 1, in > > UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: > > unexpected end of data Thanks Peter. It helps;-). From tokauf at googlemail.com Mon Jul 30 05:51:18 2012 From: tokauf at googlemail.com (Thomas Kaufmann) Date: Mon, 30 Jul 2012 02:51:18 -0700 (PDT) Subject: newbie: write content in a file (server-side) In-Reply-To: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> References: <98f9b4a6-b797-40f3-a919-89c2d4fb4496@googlegroups.com> Message-ID: <8767e4fe-6734-4715-8765-f1b58eabd622@googlegroups.com> Am Sonntag, 29. Juli 2012 16:16:01 UTC+2 schrieb Thomas Kaufmann: > Hi, > > > > I send from a client file content to my server (as bytes). So far so good. > > The server receives this content complete. Ok. Then I want to write this content to a new file. It works too. But in the new file are only the first part of the whole content. > > > > What's the problem. > > > > o-o > > > > Thomas > > > > Here's my server code: > > > > > > > > import socketserver > > > > class MyTCPServer(socketserver.BaseRequestHandler): > > > > def handle(self): > > > > s = '' > > li = [] > > addr = self.client_address[0] > > print("[{}] Connected! ".format(addr)) > > while True: > > > > bytes = self.request.recv(4096) > > if bytes: > > s = bytes.decode("utf8") > > print(s) > > li = s.split("~") > > with open(li[0], 'w') as fp: > > fp.write(li[1]) > > > > #... main ...................................................... > > > > if __name__ == "__main__": > > > > server = socketserver.ThreadingTCPServer(("", 12345), MyTCPServer) > > server.serve_forever() Thanks a lot. It helps. From esj at harvee.org Mon Jul 30 05:57:40 2012 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 30 Jul 2012 05:57:40 -0400 Subject: simplified Python parsing question In-Reply-To: <50165308.5060708@shopzeus.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> Message-ID: <50165A94.5050906@harvee.org> On 7/30/2012 5:25 AM, Laszlo Nagy wrote: > > Did you try to use pygments? > > http://pygments.org/docs/api/ > thanks, I'll take a look. > > I would first tokenize the code, then divide it by statement keywords. > Finally, you just need to find expression/assignment statements in the > remaining sections. (Maybe there is a better way to do it.) > > > yeah the problem is also little more complicated than simple parsing of Python code. For example, one example (from the white paper) *meat space blowback = Friends and family [well-meaning attempt] *could that be parsed by the tools you mention? I suspect not but this is what I need to generate using speech recognition because it's easily spoken. A more complex example might be something like new base = OS path-base name (old path) or if OS base exists (current path): new base name = OS path base name(current path) What's particularly cute here is that using the translation technique I can actually describe the full object method path with a minimum of speaking overhead. Python is great. :-) But the questions remain, will these tools are stuff like this? From phihag at phihag.de Mon Jul 30 06:35:38 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 30 Jul 2012 12:35:38 +0200 Subject: Linux shell to python In-Reply-To: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: <5016637A.7060008@phihag.de> On 07/30/2012 09:05 AM, Vikas Kumar Choudhary wrote: > `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' The rough Python equivalent would be import subprocess [ l.partition(' ')[0] # or l[:7], if you want to copy it verbatim for l in subprocess.check_output(['lspci']).splitlines() if 'Q' in l and isp_str1 in l and isp_str2 in l ] You can also just paste the whole pipeline with the shell=True parameter. That's not recommended though, and it's hard to correctly quote strings. - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From python.list at tim.thechases.com Mon Jul 30 07:09:03 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 30 Jul 2012 06:09:03 -0500 Subject: Is Python a commercial proposition ? In-Reply-To: <-9130812546080764300@unknownmsgid> References: <-1016624622349492799@unknownmsgid> <5015DAC6.6060803@gmail.com> <-9130812546080764300@unknownmsgid> Message-ID: <50166B4F.3040209@tim.thechases.com> On 07/29/12 21:31, Rodrick Brown wrote: > Its still not possible to be a pure Python developer and find > gainful employment today. I'm not sure where you get your facts, but unless you define "pure" in a super-narrow way, it's just flat-out wrong. I've been employed doing primarily Python for the past 7+ years. Yes, there's been some SQL involved; yes, I've done code-reviews for somebody else's C# (the nice thing about C-like languages is they all read mostly the same); yes, some of the web apps have required knowing ECMAScript, HTML, XML, CSS, etc. But the day to day is mostly coding in Python. And the several recruiters that have contacted me in the past week or two about additional Python positions seem to think there are pure Python jobs available. Maybe you intended to write "not possible to be a poor Python developer and find gainful employment today" which could surely be the case, as I've met LOTS of programmers (Python and otherwise) that I'd never consider hiring because of their poor skills/understanding of their tools. -tkc From zhangshaohua20101010 at gmail.com Mon Jul 30 07:09:50 2012 From: zhangshaohua20101010 at gmail.com (=?UTF-8?B?5byg5bCR5Y2O?=) Date: Mon, 30 Jul 2012 04:09:50 -0700 (PDT) Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: <8f988469-5d04-4d89-9856-b37b5fbe79e1@googlegroups.com> you can use commands.getstatusoutput(command), the shell command special charactor (like "$ and so on )should be escaped! ? 2012?7?30????UTC+8??3?40?04??Chris Angelico??? > On Mon, Jul 30, 2012 at 5:05 PM, Vikas Kumar Choudhary > > wrote: > > > > > > I was trying porting from bash shell to python. > > > > > > let me know if someone has tried to implement (grep and PIPE) shell commands in python `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' > > > > Welcome! > > > > While it's technically possible to do exactly that in Python (using > > subprocess as you describe), there's usually a more efficient and > > cleaner method of achieving the same goal. With a port such as you > > describe, it's probably best to go right back to the conceptual level > > and work out what exactly you're trying to do, and then look at > > implementing that in Python. You'll end up with much cleaner code at > > the end of it. > > > > For an initial guess, I would say that you'll use subprocess to invoke > > lspci, but then everything else will be done in Python directly. > > > > ChrisA From duncan.booth at invalid.invalid Mon Jul 30 07:15:06 2012 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Jul 2012 11:15:06 GMT Subject: Python Error References: <81818a9c-60d3-48da-9345-0c0dfd5b25e7@googlegroups.com> Message-ID: J?rgen A. Erhard wrote: > Peter's right, but instead of a print before the line, put a > try/except around it, like > > try: > set1 = set(list1) > except TypeError: > print list1 > raise > > This way, only the *actual* error triggers any output. With a general > print before, you can get a lot of unnecessary output. > > Grits, J > Or even better: try: set1 = set(list1) except TypeError: print list1 import pdb; pdb.set_trace() raise Then the error will print the value of list1 and drop you into the debugger so you can examine what's going on in more detail. -- Duncan Booth http://kupuguy.blogspot.com From jae+python at jaerhard.com Mon Jul 30 07:31:30 2012 From: jae+python at jaerhard.com (=?iso-8859-1?B?SvxyZ2VuIEEu?= Erhard) Date: Mon, 30 Jul 2012 13:31:30 +0200 Subject: Linux shell to python In-Reply-To: <5016637A.7060008@phihag.de> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <5016637A.7060008@phihag.de> Message-ID: <20120730113130.GA7968@jaerhard.com> On Mon, Jul 30, 2012 at 12:35:38PM +0200, Philipp Hagemeister wrote: > On 07/30/2012 09:05 AM, Vikas Kumar Choudhary wrote: > > `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' > > The rough Python equivalent would be > > import subprocess > [ l.partition(' ')[0] # or l[:7], if you want to copy it verbatim > for l in subprocess.check_output(['lspci']).splitlines() > if 'Q' in l and isp_str1 in l and isp_str2 in l > ] Ouch. A list comprehension spanning more than one line is bad code pretty much every time. But you did qualify it as "rough" :D Grits, J From __peter__ at web.de Mon Jul 30 07:58:56 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jul 2012 13:58:56 +0200 Subject: Linux shell to python References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: Vikas Kumar Choudhary wrote: > let me know if someone has tried to implement (grep and PIPE) shell > commands in python `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" > | cut -c1-7' > > I tried to use python subprocess and OS.Popen modules. subprocess is the way to go. > I was trying porting from bash shell to python. Here's an example showing how to translate a shell pipe: http://docs.python.org/library/subprocess.html#replacing-shell-pipeline But even if you can port the shell script literally I recommend a more structured approach: import subprocess import itertools def parse_data(lines): for not_empty, group in itertools.groupby(lines, key=bool): if not_empty: triples = (line.partition(":") for line in group) pairs = ((left, right.strip()) for left, sep, right in triples) yield dict(pairs) if __name__ == "__main__": def get(field): return entry.get(field, "").lower() output = subprocess.Popen(["lspci", "-vmm"], stdout=subprocess.PIPE).communicate()[0] for entry in parse_data(output.splitlines()): if "nvidia" in get("Vendor") and "usb" in get("Device"): print entry["Slot"] print entry["Device"] print From phihag at phihag.de Mon Jul 30 07:59:15 2012 From: phihag at phihag.de (Philipp Hagemeister) Date: Mon, 30 Jul 2012 13:59:15 +0200 Subject: Linux shell to python In-Reply-To: <20120730113130.GA7968@jaerhard.com> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <5016637A.7060008@phihag.de> <20120730113130.GA7968@jaerhard.com> Message-ID: <50167713.2080400@phihag.de> On 07/30/2012 01:31 PM, J?rgen A. Erhard wrote: > On Mon, Jul 30, 2012 at 12:35:38PM +0200, Philipp Hagemeister wrote: >> import subprocess >> [ l.partition(' ')[0] # or l[:7], if you want to copy it verbatim >> for l in subprocess.check_output(['lspci']).splitlines() >> if 'Q' in l and isp_str1 in l and isp_str2 in l >> ] > > Ouch. A list comprehension spanning more than one line is bad code > pretty much every time. I didn't want to introduce a separate function, but as requested, here's the function version: def pciIds(searchWords=['Q', isp_str1, isp_str2]): for l in subprocess.check_output(['lspci']).splitlines(): if all(sw in l for sw in searchWords): yield l.partition(' ')[0] You could also separate the processing, like this: lines = subprocess.check_output(['lspci']).splitlines() lines = [l for l in lines if 'Q' in l and isp_str1 in l and isp_str2 in l] # Or: lines = filter(lambda l: 'Q' in l and isp_str1 in l and isp_str2 in l, lines) [l.partition(' ')[0] for l in lines] # Or: map(lambda l: l.partition(' ')[0], lines) But personally, I have no problem with three-line list comprehensions. Can you elaborate why the list comprehension version is bad code? Or more to the point, how would *you* write it? - Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: OpenPGP digital signature URL: From chris at gonnerman.org Mon Jul 30 08:46:16 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Mon, 30 Jul 2012 07:46:16 -0500 Subject: [Python] Re: PyPI question, or, maybe I'm just stupid In-Reply-To: <87fw89rj7z.fsf@benfinney.id.au> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> <87fw89rj7z.fsf@benfinney.id.au> Message-ID: <50168218.90306@gonnerman.org> On 07/29/2012 11:00 PM, Ben Finney wrote: > Your post is showing up as a reply to a thread about IEEE-784 floats, > because you created your message as a reply. Consequently, it's rather > confusing why you suddenly start talking about PollyReports. If you > want to attract attention to an unrelated topic, it's best if you > don't reply to an existing thread; instead, start a new thread by > composing a new message to the forum. My apologies. I did not consider that headers I can't see might be being sent along. From chris at gonnerman.org Mon Jul 30 08:50:26 2012 From: chris at gonnerman.org (Chris Gonnerman) Date: Mon, 30 Jul 2012 07:50:26 -0500 Subject: [Python] Re: PyPI question, or, maybe I'm just stupid Message-ID: <50168312.6080900@gonnerman.org> On 07/30/2012 04:20 AM, Dieter Maurer wrote: > "CHANGES.txt" is not automatically presented. > If necessary, you must integrate it into the "long description". > > However, personally, I am not interested in all the details (typically > found in "CHANGES.txt") but some (often implicit) information is > sufficient for me: something like "major API change", "minor bug > fixes". Thus, think carefully what you put on the overview page. I see your point. I'm just lazy, I guess. I already put a description of what I've changed into git, so why, I muse, must I also edit the overview page separately? I was hoping there was an automatic way that "setup.py sdist upload" could handle it for me. > I find it very stupid to see several window scrolls of changes for > a package but to learn how to install the package, I have to download its > source... Not sure I get this. The installation procedure for PollyReports is the same as for, what, 99% of Python source packages? sudo python setup.py install What else are you saying I should do? -- Chris. From roy at panix.com Mon Jul 30 09:06:17 2012 From: roy at panix.com (Roy Smith) Date: Mon, 30 Jul 2012 09:06:17 -0400 Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> Message-ID: In article , Chris Angelico wrote: > Python's an excellent glue language, but it's also fine for huge > applications. Yes, it can't multithread across cores if you use > CPython and are CPU-bound. That's actually a pretty specific > limitation, and taking out any component of that eliminates the GIL as > a serious problem. These days, I'm working on a fairly large web application (songza.com). The business/application logic is written entirely in Python (mostly as two django apps). That's what we spend 80% of our developer time writing. As for scale, we're currently running on 80 cores worth of AWS servers for the front end. Another 50 or so cores for the database and other backend functions. Yesterday (Sunday, so a slow day), we served 27 million HTTP requests; we're not facebook-sized, but it's not some little toy application either. Every time we look at performance, we can't hardly measure the time it takes to run the Python code. Overall, we spend (way) more time waiting on network I/O than anything else. Other than I/O, our biggest performance issue is slow database queries, and making more queries than we really need to. The engineering work to improve performance involves restructuring our data representation in the database, caching (at multiple levels), or eliminating marginal features which cost more than they're worth. None of this would be any different if we used C++, except that we'd spend so much time writing and debugging code that we'd have no time left to think about the really important stuff. As far as the GIL is concerned, it's just not an issue for us. We run lots of server processes. Perhaps not as elegant as running fewer multi-threaded processes, but it works just fine, is easy to implement, and we never have to worry about all the horrors of getting memory management right in a multi-threaded C++ application. From maniandram01 at gmail.com Mon Jul 30 09:27:04 2012 From: maniandram01 at gmail.com (maniandram01 at gmail.com) Date: Mon, 30 Jul 2012 06:27:04 -0700 (PDT) Subject: py2c - an open source Python to C/C++ is looking for developers Message-ID: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> I created py2c ( http://code.google.com/p/py2c )- an open source Python to C/C++ translator! py2c is looking for developers! To join create a posting in the py2c-discuss Google Group or email me! Thanks PS:I hope this is the appropiate group for this message. From lipska at yahoo.co.uk Mon Jul 30 09:37:27 2012 From: lipska at yahoo.co.uk (lipska the kat) Date: Mon, 30 Jul 2012 14:37:27 +0100 Subject: Is Python a commercial proposition ? In-Reply-To: References: <-1016624622349492799@unknownmsgid> Message-ID: On 30/07/12 14:06, Roy Smith wrote: > In article, > Chris Angelico wrote: > >> Python's an excellent glue language, but it's also fine for huge >> applications. Yes, it can't multithread across cores if you use >> CPython and are CPU-bound. That's actually a pretty specific >> limitation, and taking out any component of that eliminates the GIL as >> a serious problem. > > These days, I'm working on a fairly large web application (songza.com). > The business/application logic is written entirely in Python (mostly as > two django apps). That's what we spend 80% of our developer time > writing. > snip "We are very sorry to say that due to licensing constraints we cannot allow access to Songza for listeners located outside of the United States." Arse :-( Lipska -- Lipska the Kat: Troll hunter, sandbox destroyer and farscape dreamer of Aeryn Sun From invalid at invalid.invalid Mon Jul 30 10:09:38 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 30 Jul 2012 14:09:38 +0000 (UTC) Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> Message-ID: On 2012-07-30, Stefan Behnel wrote: > Still, you may still get away with the above statement by providing a > sufficiently narrow definition of "standalone". By my definition, there > isn't much "standalone" code out there. Most code I know interfaces with a > couple of external tools, libraries or backends, usually written in > languages I don't have to care about because they provide a language > independent interface. It's not really relevent to this discussion, but there is _lots_ of stand-alone code out there. It runs in sub-one-dollar microcontrollers that are programmed in assembly language or in C without external libraries (sometimes not even the "libc" that's included in the C language definition). Those microcontrollers are everywhere in toys, appliances, and all sorts of other "non-computer" things. -- Grant Edwards grant.b.edwards Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON gmail.com TEXTILE production of the INDONESIAN archipelago? From invalid at invalid.invalid Mon Jul 30 10:16:05 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 30 Jul 2012 14:16:05 +0000 (UTC) Subject: Extracting bit fields from an IEEE-784 float References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: On 2012-07-30, Steven D'Aprano wrote: > 1) Are there any known implementations or platforms where Python floats > are not C doubles? If so, what are they? And the question you didn't ask: are there any platforms where a C double isn't IEEE-754? The last ones I worked on that where the FP format wasn't IEEE were the DEC VAX and TI's line if 32-bit floating-point DSPs. I don't think Python runs on the latter, but it might on the former. -- Grant Edwards grant.b.edwards Yow! I was born in a at Hostess Cupcake factory gmail.com before the sexual revolution! From roy at panix.com Mon Jul 30 10:28:51 2012 From: roy at panix.com (Roy Smith) Date: Mon, 30 Jul 2012 10:28:51 -0400 Subject: Extracting bit fields from an IEEE-784 float References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: In article , Grant Edwards wrote: > The last ones I worked on that where the FP format wasn't IEEE were > the DEC VAX According to http://en.wikipedia.org/wiki/Vax#History, the last VAX was produced 7 years ago. I'm sure there's still more than a few chugging away in corporate data centers and manufacturing floors, but as an architecture, it's pretty much a dead parrot. IEEE floating point is as near to a universal standard as it gets in the computer world. About the only thing that has it beat for market penetration and longevity are 2's complement integers and 8-bit bytes. From breamoreboy at yahoo.co.uk Mon Jul 30 10:50:04 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 30 Jul 2012 15:50:04 +0100 Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: On 30/07/2012 15:16, Grant Edwards wrote: > On 2012-07-30, Steven D'Aprano wrote: > >> 1) Are there any known implementations or platforms where Python floats >> are not C doubles? If so, what are they? > > And the question you didn't ask: are there any platforms where a C > double isn't IEEE-754? > > The last ones I worked on that where the FP format wasn't IEEE were > the DEC VAX and TI's line if 32-bit floating-point DSPs. I don't > think Python runs on the latter, but it might on the former. > Support for Python on VMS has been dropped for v3.3 see http://bugs.python.org/issue11918 -- Cheers. Mark Lawrence. From gandalf at shopzeus.com Mon Jul 30 10:59:12 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 30 Jul 2012 16:59:12 +0200 Subject: simplified Python parsing question In-Reply-To: <50165A94.5050906@harvee.org> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> Message-ID: <5016A140.7010106@shopzeus.com> > > yeah the problem is also little more complicated than simple parsing > of Python code. For example, one example (from the white paper) > > *meat space blowback = Friends and family [well-meaning attempt] > > *could that be parsed by the tools you mention? It is not valid Python code. Pygments is able to tokenize code that is not valid Python code. Because it is not parsing, it is just tokenizing. But if you put a bunch of random tokens into a file, then of course you will never be able to split that into statements. Probably, you will need to process ident/dedent tokens, identify the "level" of the satement. And then you can tell what file, class, inner class, method you are staying in. Inside one "level" or code block, you could try to divide the code into statements. Otherwise, I have no idea how a blind person could navigate in a Python source. In fact I have no idea how they use regular programs. So I'm affraid I cannot help too much with this. :-( From sabri.pllana at gmail.com Mon Jul 30 11:02:19 2012 From: sabri.pllana at gmail.com (SP) Date: Mon, 30 Jul 2012 08:02:19 -0700 (PDT) Subject: CfP: 5th International Workshop on Multi-Core Computing Systems (MuCoCoS) Message-ID: *********************************************************************** Paper submission deadline: September 9, 2012 *********************************************************************** 5th International Workshop on Multi-Core Computing Systems (MuCoCoS) 2012 Focus: Performance Portability and Tuning Salt Lake City, Utah, November 16, 2012 In conjunction with the Supercomputing Conference SC12 *********************************************************************** Workshop proceedings are published by the IEEE *********************************************************************** CONTEXT The pervasiveness of homogeneous and heterogeneous multi-core and many-core processors, in a large spectrum of systems from embedded and general-purpose to high-end computing systems, poses major challenges to software industry. In general, there is no guarantee that software developed for a particular architecture will be executable (that is functional) on another architecture. Furthermore, ensuring that the software preserves some aspects of performance behavior (such as temporal or energy efficiency) across different such architectures is an open research issue. Therefore, this workshop focuses on novel solutions for functional and performance portability as well as automatic tuning across different architectures. Following the successful organization of MuCoCoS 2008 (Barcelona, Spain), MuCoCoS 2009 (Fukuoka, Japan), MuCoCoS 2010 (Krakow, Poland), MuCoCoS 2011 (Seoul, Korea), this year MuCoCoS will be organized at Salt Lake City, Utah, November 16, 2012, in conjunction with the Supercomputing Conference SC12. MuCoCoS 2012 focuses on Performance Portability and Tuning. TOPICS OF INTEREST - The topics of the workshop include but are not limited to: :: Performance measurement, modeling, analysis and tuning :: Portable programming models, languages and compilation techniques :: Tunable algorithms and data structures :: Run-time systems and hardware support mechanisms for auto- tuning :: Case studies highlighting performance portability and tuning SUBMISSION GUIDELINES - The papers should be prepared using the IEEE format, and no longer than 10 pages. Submitted papers will be carefully evaluated based on originality, significance to workshop topics, technical soundness, and presentation quality. - Submission of the paper implies that should the paper be accepted, at least one of the authors will register and present the paper at the workshop. Papers will be published as a part of the SC12 digital proceedings. These are IEEE digital library proceedings that will be available online. - Please submit your paper (as PDF) electronically using the online submission system. (https://www.easychair.org/account/signin.cgi?conf=mucocos2012) SPECIAL JOURNAL ISSUE Authors of the best MuCoCoS papers will be invited to submit their extended workshop papers to a special issue of Computing journal (? Springer) that will be developed for this workshop. IMPORTANT DATES - Submission: September 9, 2012 - Notification: October 14, 2012 - Registration: October 17, 2012 - Workshop: November 16, 2012 WORKSHOP CO-CHAIRS - Sabri Pllana, University of Vienna, Austria - Jacob Barhen, Oak Ridge National Laboratory, US From andrea.crotti.0 at gmail.com Mon Jul 30 11:08:39 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 30 Jul 2012 16:08:39 +0100 Subject: py2c - an open source Python to C/C++ is looking for developers In-Reply-To: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> References: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> Message-ID: 2012/7/30 : > I created py2c ( http://code.google.com/p/py2c )- an open source Python to C/C++ translator! > py2c is looking for developers! > To join create a posting in the py2c-discuss Google Group or email me! > Thanks > PS:I hope this is the appropiate group for this message. > -- > http://mail.python.org/mailman/listinfo/python-list It looks like a very very hard task, and really useful or for exercise? The first few lines I've seen there are the dangerous * imports and LazyStrin looks like a typo.. from ast import * import functools from c_types import * from lazystring import * #constant data empty = LazyStrin ordertuple = ((Or,),(And From esj at harvee.org Mon Jul 30 11:40:50 2012 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 30 Jul 2012 11:40:50 -0400 Subject: simplified Python parsing question In-Reply-To: <5016A140.7010106@shopzeus.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> Message-ID: <5016AB02.4060505@harvee.org> On 7/30/2012 10:59 AM, Laszlo Nagy wrote: > >> >> yeah the problem is also little more complicated than simple parsing of >> Python code. For example, one example (from the white paper) >> >> *meat space blowback = Friends and family [well-meaning attempt] >> >> *could that be parsed by the tools you mention? > > It is not valid Python code. Pygments is able to tokenize code that is not > valid Python code. Because it is not parsing, it is just tokenizing. But if > you put a bunch of random tokens into a file, then of course you will never be > able to split that into statements. If you have been reading the papers, you would understand what I'm doing. I'm trying to take Python code with speech recognition friendly symbols and translate the symbols into a code friendly form. My conjecture is that you can change your perspective on the code and look for the edge that would normally be used to define start of a symbol, you should be able to define the name string. Another possibility is looking at the region which just contains letters numbers and spaces and outside and use that as your definition of a name string. It would probably help to verify that each word is found in a dictionary although that adds extra complexity if you are trying to increase the dictionary at the same time as the translation table. I'm beginning to think for the first generation I should just use regular expressions looking forwards and backwards and try to enumerate the possible cases. > > Probably, you will need to process ident/dedent tokens, identify the "level" > of the satement. And then you can tell what file, class, inner class, method > you are staying in. Inside one "level" or code block, you could try to divide > the code into statements. I was starting in that direction so that is good confirmation > > Otherwise, I have no idea how a blind person could navigate in a Python > source. In fact I have no idea how they use regular programs. So I'm affraid I > cannot help too much with this. :-( I'm sorry, I am, and I'm trying to help, hand disabled programmers. There are more disability than blindness and after almost 20 years of encountering this shortsightedness, I do get a little cranky at times. :-) > > From invalid at invalid.invalid Mon Jul 30 11:47:51 2012 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 30 Jul 2012 15:47:51 +0000 (UTC) Subject: Extracting bit fields from an IEEE-784 float References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: On 2012-07-30, Mark Lawrence wrote: > On 30/07/2012 15:16, Grant Edwards wrote: >> On 2012-07-30, Steven D'Aprano wrote: >> >>> 1) Are there any known implementations or platforms where Python floats >>> are not C doubles? If so, what are they? >> >> And the question you didn't ask: are there any platforms where a C >> double isn't IEEE-754? >> >> The last ones I worked on that where the FP format wasn't IEEE were >> the DEC VAX and TI's line if 32-bit floating-point DSPs. I don't >> think Python runs on the latter, but it might on the former. >> > > Support for Python on VMS has been dropped for v3.3 see > http://bugs.python.org/issue11918 I imagine that VAXes running Unix went extinct in the wild long before VAXes running VMS. -- Grant Edwards grant.b.edwards Yow! Did YOU find a at DIGITAL WATCH in YOUR box gmail.com of VELVEETA? From dickinsm at gmail.com Mon Jul 30 12:14:32 2012 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 30 Jul 2012 09:14:32 -0700 (PDT) Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: <84e263f3-29ad-4e18-b5f4-65306abbae08@googlegroups.com> On Monday, July 30, 2012 3:16:05 PM UTC+1, Grant Edwards wrote: > The last ones I worked on that where the FP format wasn't IEEE were > > the DEC VAX and TI's line if 32-bit floating-point DSPs. I don't > > think Python runs on the latter, but it might on the former. For current hardware, there's also IBM big iron: the IBM System z10 apparently has hardware support for IBM's hexadecimal floating-point format in addition to IEEE 754 binary *and* decimal floating-point. But IIUC, a typical Linux installation on one of these machines uses the IEEE 754 stuff, not the hexadecimal bits. So unlikely to be an issue for Python. -- Mark From rustompmody at gmail.com Mon Jul 30 12:25:22 2012 From: rustompmody at gmail.com (rusi) Date: Mon, 30 Jul 2012 09:25:22 -0700 (PDT) Subject: Is Python a commercial proposition ? References: Message-ID: <851e1b02-5d76-49cd-b8a2-489625d5d1b4@g4g2000pbn.googlegroups.com> On Jul 29, 9:01?pm, lipska the kat wrote: > Pythoners > > Firstly, thanks to those on the tutor list who answered my questions. > > I'm trying to understand where Python fits into the set of commonly > available, commercially used languages of the moment. > > My most recent experience is with Java. The last project I was involved > with included 6775 java source files containing 1,145,785 lines of code. > How do I know this? because I managed to cobble together a python script > that walks the source tree and counts the lines of code. It ignores > block and line comments and whitespace lines so I'm fairly confident > it's an accurate total. It doesn't include web interface files (mainly > .jsp and HTML) or configuration files (XML, properties files and what > have you). In fact it was remarkably easy to do this in python which got > me thinking about how I could use the language in a commercial environment. > > I was first attracted to python by it's apparent 'Object Orientedness' I > soon realised however that by looking at it in terms of the language I > know best I wasn't comparing like with like. Once I had 'rebooted the > bioware' I tried to approach python with an open mind and I have to say > it's growing on me. > > The questions I have are ... > > How is python used in the real world. > What sized projects are people involved with > Are applications generally written entirely in python or is it more > often used for a subset of functionality. I think when people talk of scripting this area tends to get missed: (Or if someone mentioned it, I missed it :-) ) http://wiki.python.org/moin/AppsWithPythonScripting From maxthemouse at googlemail.com Mon Jul 30 12:42:24 2012 From: maxthemouse at googlemail.com (MaxTheMouse) Date: Mon, 30 Jul 2012 09:42:24 -0700 (PDT) Subject: py2c - an open source Python to C/C++ is looking for developers References: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> Message-ID: On Jul 30, 7:27?am, maniandra... at gmail.com wrote: > I created py2c (http://code.google.com/p/py2c)- an open source Python to C/C++ translator! > py2c is looking for developers! > To join create a posting in the py2c-discuss Google Group or email me! > Thanks > PS:I hope this is the appropiate group for this message. Out of curiosity. What is the difference between this and Shedskin? Shedskin being a (restricted) python-to-C++ compiler. (http://code.google.com/p/ shedskin/) Is the goal to be able to handle any python code or a subset? Cheers, Adam From drsalists at gmail.com Mon Jul 30 12:52:21 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 30 Jul 2012 16:52:21 +0000 Subject: Extracting bit fields from an IEEE-784 float In-Reply-To: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: On Mon, Jul 30, 2012 at 12:44 AM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > I wish to extract the bit fields from a Python float, call it x. First I > cast the float to 8-bytes: > > s = struct.pack('=d', x) > i = struct.unpack('=q', s)[0] > > Then I extract the bit fields from the int, e.g. to grab the sign bit: > > (i & 0x8000000000000000) >> 63 > > > Questions: > > 1) Are there any known implementations or platforms where Python floats > are not C doubles? If so, what are they? > Last I heard, DEC Alpha chips did not use IEEE floating point. > 2) If the platform byte-order is reversed, do I need to take any special > action? I don't think I do, because even though the float is reversed, so > will be the bit mask. Is this correct? > > 3) Any other problems with the way I am doing this? > It gives me the heebie jeebies. Why go to all the trouble and incur the lack of portability to esoteric platforms, when you can just use arithmetic expressions? It's fancy, and it'll probably almost always work, but it's probably not so wise. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at paultjuh.org Mon Jul 30 12:55:29 2012 From: mail at paultjuh.org (=?utf-8?Q?Paul_van_der_Linden?=) Date: Mon, 30 Jul 2012 18:55:29 +0200 Subject: Linux shell to python In-Reply-To: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: You can do this with one subprocess.Popen and some python commands. The alternative is to pipe some subprocess.Popen commands together. Or for the quick way out (but I think you better stick with bash scripting then): http://pypi.python.org/pypi/sarge/ Don't know about it's stability/ubs/etc, never used it. ? -----Original message----- From:Vikas Kumar Choudhary Sent:Mon 30-07-2012 09:34 Subject:Linux shell to python To:python-list at python.org; Dear friends, I just joined the group. I was trying porting from bash shell to python. ?let me know if someone has tried to implement (grep and PIPE) ?shell commands in python `lspci | grep Q | grep ?"$isp_str1" | grep "$isp_str2" | cut -c1-7' ?I tried to use python subprocess and OS.Popen modules. Thanks & Regard's Vikas Kumar Choudhary (Yahoo,MSN-Hotmail,Skype) Messenger = vikas.choudhary Please?Add Me in Your Messenger List for Better Communication P??Please consider the environment before printing this e-mail Do not print this email unless it is absolutely necessary. Save papers, Save tree. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Note: This e-mail is confidential and may also be privileged, this is for the intended recipients only. If you are not the intended recipient, please delete the message and notify me immediately; you should not copy or use it for any purpose, nor disclose its contents to any other person. Notice:? All email and instant messages (including attachments) sent to or from This E-mail id , may be retained, monitored and/or reviewed, or authorized law enforcement personnel, without further notice or consent. ---------------------------------------------------------------------------------------------------------------------- ? -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at paultjuh.org Mon Jul 30 13:13:43 2012 From: mail at paultjuh.org (=?utf-8?Q?Paul_van_der_Linden?=) Date: Mon, 30 Jul 2012 19:13:43 +0200 Subject: simplified Python parsing question In-Reply-To: <50165A94.5050906@harvee.org> References: <50165A94.5050906@harvee.org> Message-ID: Another possibility is to use the ast module of python: http://docs.python.org/library/ast.html The only problem with that module, is that everything you parse must be correct, otherwise it throws an exception, I don't know if that's a problem for your project? ? -----Original message----- From:Eric S. Johansson Sent:Mon 30-07-2012 12:00 Subject:Re: simplified Python parsing question To:python-list at python.org; On 7/30/2012 5:25 AM, Laszlo Nagy wrote: > > Did you try to use pygments? > > http://pygments.org/docs/api/ > thanks, I'll take a look. > > I would first tokenize the code, then divide it by statement keywords. > Finally, you just need to find expression/assignment statements in the > remaining sections. (Maybe there is a better way to do it.) > > > yeah the problem is also little more complicated than simple parsing of Python code. For example, one example (from the white paper) *meat space blowback = Friends and family [well-meaning attempt] *could that be parsed by the tools you mention? I suspect not but this is what I need to generate using speech recognition because it's easily spoken. A more complex example might be something like new base = OS path-base name (old path) or if OS base exists (current path): new base name = OS path base name(current path) What's particularly cute here is that using the translation technique I can actually describe the full object method path with a minimum of speaking overhead. Python is great. :-) But the questions remain, will these tools are stuff like this? -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Jul 30 13:36:28 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 30 Jul 2012 10:36:28 -0700 Subject: Is Python a commercial proposition ? In-Reply-To: <-1016624622349492799@unknownmsgid> References: <-1016624622349492799@unknownmsgid> Message-ID: On 7/29/2012 5:12 PM Rodrick Brown said... > Until the > GIL is fixed I doubt anyone will seriously look at Python as an option > for large enterprise standalone application development. See openERP -- http://www.openerp.com/ -- they've been actively converting SAP accounts and have recently absorbed a couple SAP resellers. Emile From kroger at pedrokroger.net Mon Jul 30 14:01:32 2012 From: kroger at pedrokroger.net (Pedro Kroger) Date: Mon, 30 Jul 2012 15:01:32 -0300 Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. Message-ID: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> Pyknon is a simple music library for Python hackers. With Pyknon you can generate Midi files quickly and reason about musical proprieties. It works with Python 2.7 and 3.2. Pyknon is very simple to use, here's a basic example to create 4 notes and save into a MIDI file:: from pyknon.genmidi import Midi from pyknon.music import NoteSeq notes1 = NoteSeq("D4 F#8 A Bb4") midi = Midi(1, tempo=90) midi.seq_notes(notes1, track=0) midi.write("demo.mid") It's available on PyPI and its homepage is http://kroger.github.com/pyknon/ Best regards, Pedro ----- http://pedrokroger.net http://musicforgeeksandnerds.com From ramit.prasad at jpmorgan.com Mon Jul 30 14:26:32 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 30 Jul 2012 18:26:32 +0000 Subject: Is Python a commercial proposition ? In-Reply-To: <-1016624622349492799@unknownmsgid> References: <-1016624622349492799@unknownmsgid> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416594013@SCACMX008.exchad.jpmchase.net> > I work in financials and the majority of our apps are developed in C++ > and Java yet all the tools that startup, deploy and conduct rigorous > unit testing are implemented in Python or Shell scripts that wrap > Python scripts. > > Python definitely has its place in the enterprise however not so much > for serious stand alone app development. > > I'm starting to see Python used along side many statistical and > analytical tools like R, SPlus, and Mathlab for back testing and > prototype work, in a lot of cases I've seen quants and traders > implement models in Python to back test and if successful converted to > Java or C++. Maybe this is true in *your* experience but *my* experience is very different. I have seen Python modules become modules that end up rewritten in C for performance reasons but I consider that part of the power of Python and an argument *for* Python. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Mon Jul 30 14:33:23 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Jul 2012 11:33:23 -0700 Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. In-Reply-To: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> Message-ID: <5016D373.1090809@stoneleaf.us> Pedro Kroger wrote: > Pyknon is a simple music library for Python hackers. Sounds cool. How is 'Pyknon' pronounced? > It's available on PyPI and its homepage is > http://kroger.github.com/pyknon/ I would suggest you change the theme -- using Firefox 3.6 the page is very difficult to read. ~Ethan~ From kroger at pedrokroger.net Mon Jul 30 14:37:00 2012 From: kroger at pedrokroger.net (Pedro Kroger) Date: Mon, 30 Jul 2012 15:37:00 -0300 Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. In-Reply-To: <5016D373.1090809@stoneleaf.us> References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> <5016D373.1090809@stoneleaf.us> Message-ID: <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> On Jul 30, 2012, at 3:33 PM, Ethan Furman wrote: > Pedro Kroger wrote: >> Pyknon is a simple music library for Python hackers. > > Sounds cool. How is 'Pyknon' pronounced? I pronounce it similarly as google translate does: http://translate.google.com/#English|English|Pyknon It's a musical Greek term, but since it's a Python package, I think it's acceptable to pronounce the Py part as "pie" ;-) >> It's available on PyPI and its homepage is >> http://kroger.github.com/pyknon/ > > I would suggest you change the theme -- using Firefox 3.6 the page is very difficult to read. Thanks for the report. Do you mind if I ask why you are using such an old version? (It looks fine with Firefox 14.0.1) Cheers, Pedro ----- http://pedrokroger.net http://musicforgeeksandnerds.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Jul 30 14:47:42 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 30 Jul 2012 18:47:42 +0000 Subject: [Python] Re: PyPI question, or, maybe I'm just stupid In-Reply-To: <50168312.6080900@gonnerman.org> References: <50168312.6080900@gonnerman.org> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416594076@SCACMX008.exchad.jpmchase.net> > > However, personally, I am not interested in all the details (typically > > found in "CHANGES.txt") but some (often implicit) information is > > sufficient for me: something like "major API change", "minor bug > > fixes". Thus, think carefully what you put on the overview page. > I see your point. I'm just lazy, I guess. I already put a description > of what I've changed into git, so why, I muse, must I also edit the > overview page separately? I was hoping there was an automatic way that > "setup.py sdist upload" could handle it for me. Even if you could include commit messages I would not recommend it. Commit messages are for developers of _your_ package not users. It is like leaving a memo (cough or message) for future developers. As a user, I want to know that you added a feature AAA. I do *not* want to know that in order to add AAA you also had to modify BBB and create CCC. Maybe you had to revert BBB because it conflicted with DDD and then you refactored some code and added/updated comments. Finally you managed to fix BBB (maybe also modifying DDD?) and so the feature AAA is now available. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Mon Jul 30 14:58:18 2012 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 30 Jul 2012 11:58:18 -0700 Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. In-Reply-To: <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> <5016D373.1090809@stoneleaf.us> <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> Message-ID: <5016D94A.2020703@stoneleaf.us> Pedro Kroger wrote: > > On Jul 30, 2012, at 3:33 PM, Ethan Furman > wrote: > >> Pedro Kroger wrote: >>> Pyknon is a simple music library for Python hackers. >> >> Sounds cool. How is 'Pyknon' pronounced? > > I pronounce it similarly as google translate does: So the 'k' is pronounced. Okay. >> I would suggest you change the theme -- using Firefox 3.6 the page is >> very difficult to read. > > Thanks for the report. Do you mind if I ask why you are using such an > old version? > (It looks fine with Firefox 14.0.1) That version works for me -- I don't like upgrading to a new version of bugs if I don't have to. ;) I checked the page on a coworker's machine who does have a recent version, and it is a little better, but it is still very faint (thin grey letters on a white background is hard to read). With version 3 the thin grey letters are also broken, making it even worse. ~Ethan~ From ramit.prasad at jpmorgan.com Mon Jul 30 15:32:47 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 30 Jul 2012 19:32:47 +0000 Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. In-Reply-To: <5016D94A.2020703@stoneleaf.us> References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> <5016D373.1090809@stoneleaf.us> <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> <5016D94A.2020703@stoneleaf.us> Message-ID: <5B80DD153D7D744689F57F4FB69AF47416594155@SCACMX008.exchad.jpmchase.net> > >> I would suggest you change the theme -- using Firefox 3.6 the page is > >> very difficult to read. > > > > Thanks for the report. Do you mind if I ask why you are using such an > > old version? > > (It looks fine with Firefox 14.0.1) > > > That version works for me -- I don't like upgrading to a new version of > bugs if I don't have to. ;) Why do you prefer to keep your old security holes? Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From roy at panix.com Mon Jul 30 16:50:44 2012 From: roy at panix.com (Roy Smith) Date: Mon, 30 Jul 2012 16:50:44 -0400 Subject: Extracting bit fields from an IEEE-784 float References: <5015d8d4$0$11120$c3e8da3@news.astraweb.com> Message-ID: In article , Grant Edwards wrote: > I imagine that VAXes running Unix went extinct in the wild long before > VAXes running VMS. Of course they did. VMS is all about vendor lock-in. People who continue to run VAXen don't do so because they're wedded to the hardware. They do so because they're wedded to some specific VMS application (and the business processes which depend on it). From barry at barrys-emacs.org Mon Jul 30 17:26:20 2012 From: barry at barrys-emacs.org (Barry Scott) Date: Mon, 30 Jul 2012 22:26:20 +0100 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> Message-ID: <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> lspci gets all its information from the files in /sys/bus/pci/devices. You can use os.listdir() to list all the files in the folder and then open the files you want to get the data you need. And of course you can write list comprehensions on as many lines as it take to make the code maintainable. Barry On 30 Jul 2012, at 17:55, Paul van der Linden wrote: > You can do this with one subprocess.Popen and some python commands. > The alternative is to pipe some subprocess.Popen commands together. > Or for the quick way out (but I think you better stick with bash scripting then): http://pypi.python.org/pypi/sarge/ > Don't know about it's stability/ubs/etc, never used it. > > -----Original message----- > From: Vikas Kumar Choudhary > Sent: Mon 30-07-2012 09:34 > Subject: Linux shell to python > To: python-list at python.org; > Dear friends, > > I just joined the group. > I was trying porting from bash shell to python. > > > let me know if someone has tried to implement (grep and PIPE) shell commands in python `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' > > I tried to use python subprocess and OS.Popen modules. > > Thanks & Regard's > > Vikas Kumar Choudhary > > > (Yahoo,MSN-Hotmail,Skype) Messenger = vikas.choudhary > Please Add Me in Your Messenger List for Better Communication > P Please consider the environment before printing this e-mail > Do not print this email unless it is absolutely necessary. > Save papers, Save tree. > -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > Note: This e-mail is confidential and may also be privileged, this is for the intended recipients only. If you are not the intended recipient, please delete the message and notify me immediately; you should not copy or use it for any purpose, nor disclose its contents to any other person. > > Notice: All email and instant messages (including attachments) sent to or from This E-mail id , may be retained, monitored and/or reviewed, or authorized law enforcement personnel, without further notice or consent. > ---------------------------------------------------------------------------------------------------------------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From mauriceling at gmail.com Mon Jul 30 17:36:19 2012 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Mon, 30 Jul 2012 14:36:19 -0700 (PDT) Subject: [ANN] New paper published (Volume 7 of The Python Papers) - High-Speed Data Shredding using Python Message-ID: <45451cd3-41c6-4d07-9aaf-8a9a9093efd4@googlegroups.com> Link: http://ojs.pythonpapers.org/index.php/tpp/article/view/243 Abstract In recent years, backup and restore is a common topic in data storage. However, there?s hardly anybody mention about safe data deletion. Common data destruction methodology requires the wipe operation to fill the disk with zeros, then with random data, and then with zeros again. Three passes are normally sufficient for ordinary home users. On the down side, such algorithms will take many hours to delete a 2TB hard disk. Although current Linux utility tools gives most users more than enough security and data protections, we had developed a cross-platform standalone application that could expunge all confidential data stored in flash drive or hard disk. The data shredding software is written in Python, and it could overwrite existing data using user-defined wipe algorithm. This software project also explores the technical approaches to digital data destruction using various methodologies defined in different standards, which includes a selection of military-grade procedures proposed by information security specialists. The application operates with no limitations to the capacity of the storage media connected to the computer system, it can rapidly and securely erase any magnetic mediums, optical disks or solid-state memories found in the computer or embedded system. Not only does the software comply with the IEEE T10/T13 specifications, it also binds to the number of connectivity limited by the SAS/SATA buses. From mauriceling at gmail.com Mon Jul 30 17:37:38 2012 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Mon, 30 Jul 2012 14:37:38 -0700 (PDT) Subject: [ANN] New paper published (Volume 7 of The Python Papers) - Designing and Testing PyZMQ Applications Message-ID: <21bbf232-4a8b-4b98-a5a2-b40b5656c8d5@googlegroups.com> Link: http://ojs.pythonpapers.org/index.php/tpp/article/view/242 Abstract PyZMQ is a powerful and easy-to-use network layer. While ZeroMQ and PyZMQ are quite well documented and good introductory tutorials exist, no best-practice guide on how to design and especially to test larger or more complex PyZMQ applications could be found. This article shows a possible way to design, document and test real-world applications. The approach presented in this article was used for the development of a distributed simulation framework and proved to work quite well in this scenario. From drsalists at gmail.com Mon Jul 30 18:56:48 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 30 Jul 2012 22:56:48 +0000 Subject: Linux shell to python In-Reply-To: <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On Mon, Jul 30, 2012 at 9:26 PM, Barry Scott wrote: > lspci gets all its information from the files in /sys/bus/pci/devices. > > You can use os.listdir() to list all the files in the folder and then open > the files you want to get the data you need. > Gee, wouldn't it be more portable to parse lspci? I wouldn't put it past the (Linux) kernel devs to move the pseudo-filesystems around again... > And of course you can write list comprehensions on as many lines as > it take to make the code maintainable. > Sigh, and I'm also not keen on multi-line list comprehensions, specifically because I think they tend to make less readable code. It also becomes a mess when you need to insert print statements to get some visibility into what's going on. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Jul 30 19:14:25 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 30 Jul 2012 16:14:25 -0700 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On 7/30/2012 3:56 PM Dan Stromberg said... > > On Mon, Jul 30, 2012 at 9:26 PM, Barry Scott And of course you can write list comprehensions on as many lines as > it take to make the code maintainable. > > Sigh, and I'm also not keen on multi-line list comprehensions, > specifically because I think they tend to make less readable code. It > also becomes a mess when you need to insert print statements to get some > visibility into what's going on. I tend to write long one-liners then convert them to loops the first time I need to see what's going on. Premature optimization otherwise. :) Emile From drsalists at gmail.com Mon Jul 30 19:46:14 2012 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 30 Jul 2012 23:46:14 +0000 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On Mon, Jul 30, 2012 at 11:14 PM, Emile van Sebille wrote: > On 7/30/2012 3:56 PM Dan Stromberg said... > > >> On Mon, Jul 30, 2012 at 9:26 PM, Barry Scott > > > And of course you can write list comprehensions on as many lines as >> it take to make the code maintainable. >> >> Sigh, and I'm also not keen on multi-line list comprehensions, >> specifically because I think they tend to make less readable code. It >> also becomes a mess when you need to insert print statements to get some >> visibility into what's going on. >> > > I tend to write long one-liners then convert them to loops the first time > I need to see what's going on. > > Premature optimization otherwise. :) > Premature optimization of what? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Mon Jul 30 20:16:32 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 30 Jul 2012 17:16:32 -0700 (PDT) Subject: py2c - an open source Python to C/C++ is looking for developers References: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> Message-ID: <1409e6f3-b265-4329-9618-c06f8098fef3@t1g2000pbl.googlegroups.com> On Jul 31, 2:42?am, MaxTheMouse wrote: > What is the difference between this and Shedskin? Shedskin being a > (restricted) python-to-C++ compiler. (http://code.google.com/p/ > shedskin/) Is the goal to be able to handle any python code or a > subset? There's also Nuitka, which is an unrestricted compiler, I believe: http://nuitka.net/pages/overview.html Is this a completely independent project, or are there plans to leverage off of PyPy's toolchain, for example? From wuwei23 at gmail.com Mon Jul 30 20:45:47 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 30 Jul 2012 17:45:47 -0700 (PDT) Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> <5015DAC6.6060803@gmail.com> Message-ID: <8eb14d3b-c096-4a91-ab52-aea0f1afe1fb@po9g2000pbb.googlegroups.com> On Jul 30, 12:31?pm, Rodrick Brown wrote: > Its still not possible to be a pure Python developer and find gainful > employment today. I have been working as a "pure" Python developer for six+ years now (in that the bulk of my coding is done in Python, with some interface behaviour in JS). On average, every two months I'm contacted by a recruiter or an employer wanting me for my Python experience. I've worked for government, education and private industry, and the only time I didn't get paid was my last week working for a start-up. So I'm pretty confident that I'm "gainfully" employed. From wuwei23 at gmail.com Mon Jul 30 21:09:10 2012 From: wuwei23 at gmail.com (alex23) Date: Mon, 30 Jul 2012 18:09:10 -0700 (PDT) Subject: ANN: visage (interfaces) References: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> <52f2e8b7-4d91-4034-a263-d657bfedcc45@googlegroups.com> Message-ID: <41ef7b32-05e0-4cec-92ab-1ae0fce6171b@n16g2000vbn.googlegroups.com> On Jul 30, 3:18?pm, jwp wrote: > What's c.l.py's perspective on managing interfaces and implementations? I've been working with Plone for the past year and have become a big fan of interfaces. I must admit I _do_ like zope.interface's adaptation, but your's looks lighter in a way that could be handy for a side project, so I may have some more concrete feedback soon :) BTW I think if you rename the ReStructured Text docs to .rst github will automatically render them. From james.pye at gmail.com Mon Jul 30 21:41:19 2012 From: james.pye at gmail.com (jwp) Date: Mon, 30 Jul 2012 18:41:19 -0700 (PDT) Subject: ANN: visage (interfaces) In-Reply-To: <41ef7b32-05e0-4cec-92ab-1ae0fce6171b@n16g2000vbn.googlegroups.com> References: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> <52f2e8b7-4d91-4034-a263-d657bfedcc45@googlegroups.com> <41ef7b32-05e0-4cec-92ab-1ae0fce6171b@n16g2000vbn.googlegroups.com> Message-ID: <68308a21-ee64-4714-b52e-bb5a43b4a229@googlegroups.com> On Monday, July 30, 2012 6:09:10 PM UTC-7, alex23 wrote: > a side project, so I may have some more concrete feedback soon :) =) > BTW I think if you rename the ReStructured Text docs to .rst github > > will automatically render them. Did not know that. Gonna go do a lot of git mv's now. Thanks. From steve+comp.lang.python at pearwood.info Mon Jul 30 21:54:51 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Jul 2012 01:54:51 GMT Subject: simplified Python parsing question References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> Message-ID: <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 30 Jul 2012 11:40:50 -0400, Eric S. Johansson wrote: > If you have been reading the papers, you would understand what I'm > doing. That is the second time, at least, that you have made a comment like that. Understand that most people are not going to follow links to find out whether or not they are interested in what you have to say. If you can't give a brief explanation of what you are doing in your email or news post, many people aren't going to read on. Perhaps they intend to but are too busy, or they have email access but web access is restricted, or they've already got 200 tabs open in their browser and don't want any more (I'm not exaggerating, I know people like that). People use email because it is a "push" technology -- you don't have to go out and look for information, it gets pushed into your inbox. Clicking on links is a "pull" technology -- you have to make the explicit decision to click the link, open a browser, go out to the Internet and read who knows what. That requires a different frame of mind. Expect to lose some of your audience every time you require them to follow a link. And *especially* so if that it a link to Google Docs, instead of an normal web page. Google Docs is, in my opinion, a nasty piece of rubbish that doesn't run on any of my browsers. As far as I'm concerned, I'd rather download a Word doc, because at least I can open that in OpenOffice or Abiword and read it. Something in Google Docs might as well be locked in a safe as far as I'm concerned. -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 30 22:06:20 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Jul 2012 02:06:20 GMT Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> Message-ID: <50173d9c$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 30 Jul 2012 14:09:38 +0000, Grant Edwards wrote: > On 2012-07-30, Stefan Behnel wrote: > >> Still, you may still get away with the above statement by providing a >> sufficiently narrow definition of "standalone". By my definition, there >> isn't much "standalone" code out there. Most code I know interfaces >> with a couple of external tools, libraries or backends, usually written >> in languages I don't have to care about because they provide a language >> independent interface. > > It's not really relevent to this discussion, but there is _lots_ of > stand-alone code out there. It runs in sub-one-dollar microcontrollers > that are programmed in assembly language or in C without external > libraries (sometimes not even the "libc" that's included in the C > language definition). Those microcontrollers are everywhere in toys, > appliances, and all sorts of other "non-computer" things. And at that level, you aren't going to write your app in Python anyway, and not because of the GIL. (These microcontrollers are unlikely to have multiple cores -- why the hell does your microwave oven need two cores?) It seems to me that those who claim that the GIL is a serious barrier to Python's use in the enterprise are mostly cargo-cult programmers, parroting what they've heard from other cargo-cultists. It really is astonishing the amount of misinformation and outright wrong-headed ignorance that counts as accepted wisdom in the enterprise. -- Steven From steve+comp.lang.python at pearwood.info Mon Jul 30 22:09:03 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Jul 2012 02:09:03 GMT Subject: ANN: visage (interfaces) References: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> <52f2e8b7-4d91-4034-a263-d657bfedcc45@googlegroups.com> <41ef7b32-05e0-4cec-92ab-1ae0fce6171b@n16g2000vbn.googlegroups.com> <68308a21-ee64-4714-b52e-bb5a43b4a229@googlegroups.com> Message-ID: <50173e3f$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 30 Jul 2012 18:41:19 -0700, jwp wrote: >> BTW I think if you rename the ReStructured Text docs to .rst github >> will automatically render them. > > Did not know that. Gonna go do a lot of git mv's now. Do *one* and see if github actually does render it. Then do the rest. -- Steven From esj at harvee.org Mon Jul 30 22:11:50 2012 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 30 Jul 2012 22:11:50 -0400 Subject: simplified Python parsing question In-Reply-To: <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <50173EE6.3030702@harvee.org> On 7/30/2012 9:54 PM, Steven D'Aprano wrote: > On Mon, 30 Jul 2012 11:40:50 -0400, Eric S. Johansson wrote: > >> If you have been reading the papers, you would understand what I'm >> doing. > That is the second time, at least, that you have made a comment like that. Actually, it's probably more like the forth hundred time. :-) I apologize, I was wrong and I would back up and start over again if I could > > Understand that most people are not going to follow links to find out > whether or not they are interested in what you have to say. If you can't > give a brief explanation of what you are doing in your email or news > post, many people aren't going to read on. Perhaps they intend to but are > too busy, or they have email access but web access is restricted, or > they've already got 200 tabs open in their browser and don't want any > more (I'm not exaggerating, I know people like that). accept criticism. I'm still working on an elevator pitch for this concept. I've been living with the technology and all its variations for about 10 years and it's not easy to explain to someone who is not disabled. People with working hands don't understand how isolating and, sometimes humiliating software can be. advocates like myself sometimes get a little tired of saying the same thing over and over and over again and people who are disabled just don't care. So you find yourself using shorthand because you going to be ignored anyway > > People use email because it is a "push" technology -- you don't have to > go out and look for information, it gets pushed into your inbox. Clicking > on links is a "pull" technology -- you have to make the explicit decision > to click the link, open a browser, go out to the Internet and read who > knows what. That requires a different frame of mind. Expect to lose some > of your audience every time you require them to follow a link. Okay, this implies the need to really work on more of an elevator/summary speech. Thank you for your input. I appreciate it > > And *especially* so if that it a link to Google Docs, instead of an > normal web page. Google Docs is, in my opinion, a nasty piece of rubbish > that doesn't run on any of my browsers. As far as I'm concerned, I'd > rather download a Word doc, because at least I can open that in > OpenOffice or Abiword and read it. Something in Google Docs might as well > be locked in a safe as far as I'm concerned. the ability for multiple people to work on the same document at the same time is really important. Can't do that with Word or Libre office. revision tracking in traditional word processors are unpleasant to work with especially if your hands are broken. It would please me greatly if you would be willing to try an experiment. live my life for a while. Sit in a chair and tell somebody what to type and where to move the mouse without moving your hands. keep your hands gripping the arms or the sides of the chair. The rule is you can't touch the keyboard you can't touch the mice, you can't point at the screen. I suspect you would have a hard time surviving half a day with these limitations. no embarrassment in that, most people wouldn't make it as far as a half a day. I've had to live with it since 1994. Not trying to brag, just pointing out the facts. I'm going to try again from a different angle in a different thread. I will take your advice to heart and I would appreciate some feedback on how well I do satisfying the issues you have described From steve+comp.lang.python at pearwood.info Mon Jul 30 22:25:29 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Jul 2012 02:25:29 GMT Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> <5016D373.1090809@stoneleaf.us> <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> <5016D94A.2020703@stoneleaf.us> Message-ID: <50174218$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 30 Jul 2012 19:32:47 +0000, Prasad, Ramit wrote: >> >> I would suggest you change the theme -- using Firefox 3.6 the page >> >> is very difficult to read. >> > >> > Thanks for the report. Do you mind if I ask why you are using such an >> > old version? >> > (It looks fine with Firefox 14.0.1) Firefox 3.6 is not "such an old version". It is the currently supported version in RHEL and Centos, and under the rebranded name Iceweasel, Debian Squeeze. >> That version works for me -- I don't like upgrading to a new version of >> bugs if I don't have to. ;) > > Why do you prefer to keep your old security holes? I don't. But in my experience, the risk of security breaches is *much* less than the chance that the new version will break functionality, introduce bugs, have a worse user interface, and generally be a step backwards rather than forward. Security fixes are orthogonal to new features and UI changes. Any software which forces you to take unwanted new features and accept UI degradation in order to get security fixes is doing the wrong thing, and almost certainly adding new security holes as fast as they remove them. When it comes to browsers, I would rather rely on dedicated security features like NoScript that has a stable UI and continual functional improvements, than to get on the Firefox upgrade treadmill. When I upgrade my OS, I'll get a new major release of Firefox. With luck, all the kinks will be ironed out by then. Until then, Firefox 3.6 is stable and works. Besides, it is amazing what a better browsing experience you get by disabling 99% of all Flash and 95% of all Javascript. Python is one of the few cases where I can implicitly trust that each upgrade is an actual *upgrade*, not a downgrade with a higher version number like KDE 3 -> KDE 4, or a sidegrade, like Firefox. -- Steven From simoncropper at fossworkflowguides.com Mon Jul 30 22:38:39 2012 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Tue, 31 Jul 2012 12:38:39 +1000 Subject: [ANN] New paper published (Volume 7 of The Python Papers) - High-Speed Data Shredding using Python In-Reply-To: <45451cd3-41c6-4d07-9aaf-8a9a9093efd4@googlegroups.com> References: <45451cd3-41c6-4d07-9aaf-8a9a9093efd4@googlegroups.com> Message-ID: <5017452F.5060900@fossworkflowguides.com> On 31/07/12 07:36, mauriceling at acm.org wrote: > Link: http://ojs.pythonpapers.org/index.php/tpp/article/view/243 > > Abstract > > In recent years, backup and restore is a common topic in data storage. However, there?s hardly anybody mention about safe data deletion. Common data destruction methodology requires the wipe operation to fill the disk with zeros, then with random data, and then with zeros again. Three passes are normally sufficient for ordinary home users. On the down side, such algorithms will take many hours to delete a 2TB hard disk. Although current Linux utility tools gives most users more than enough security and data protections, we had developed a cross-platform standalone application that could expunge all confidential data stored in flash drive or hard disk. The data shredding software is written in Python, and it could overwrite existing data using user-defined wipe algorithm. This software project also explores the technical approaches to digital data destruction using various methodologies defined in different standards, which includes a selection of military-grade procedures proposed by information security specialists. The application operates with no limitations to the capacity of the storage media connected to the computer system, it can rapidly and securely erase any magnetic mediums, optical disks or solid-state memories found in the computer or embedded system. Not only does the software comply with the IEEE T10/T13 specifications, it also binds to the number of connectivity limited by the SAS/SATA buses. > The paper is very interesting. Funny though I found it very hard to find a name of the application developed -- I presume it is the successor of CBL Data Shredder -- or if it is foss or proprietary package? Does the application have a project page? -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Python http://www.fossworkflowguides.com/scripting From esj at harvee.org Mon Jul 30 22:44:00 2012 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 30 Jul 2012 22:44:00 -0400 Subject: toggle name, With explanations Message-ID: <50174670.7090505@harvee.org> the wonderful responses I received from people like Lazlo, Paul, and Stephen has given me some ideas about a different approach. First, here's explanation of what I'm doing I'm developing a method which will enable hand disabled developers such as myself to create and manipulate symbols identical to those created by non-disabled developers. the input mechanism will be speech recognition maximizing the use of ordinary continuous English dictation and a minimal set of commands to activate this method. Subsequent work will produce a speech user interface for navigation code and tools such as debuggers bypassing the interference and constraints created by GUIs. The core concept is any string of a natural language words can be transformed into a symbol by storing the matchup between the natural language word string and the symbol string in a database. in other words, a dictionary which has paired keys and one key can return the other. in my original request I was thinking about parsing the environment and looking for the transition between code and symbol or natural language word string but unfortunately, that technique breaks because the characters around the region of interest may not be complete or correct code. So I thought about trying to look at the other way. If you find a string of characters that you don't look like a symbol or look like a string of natural in words, when the characters stop looking like that, then that defines the limits of the region of interest. example: s.pack(side=Tkinter.R^IGHT, fill=Tkinter.Y) the carrot marks the current position. If I was to say this point, "toggle word", I would first look to the left and the right and look forward the character string stopped looking like a symbol or a natural language word string.in this example, I would find the string "RIGHT". If I didn't find anything, I would look one more character to the left and see if there was a "." present, do the same search again this time solely to the left and I would have the string "TKinter.RIGHT". The database would have the in tree and replace it with "TK interpreter right" so I could edit the string with speech recognition. s.pack(side=TK interpreter^ right, fill=Tkinter.Y) Then using the same basic technique as I described above, I looked left and right for a series of symbols, in this case they are actually words, until I reach something that is not a symbol. The end result is used a key for the database which would return "Tkinter.RIGHT" It looks like if I'm correct, this is a much simpler way of doing what I wanted to do (extract symbols and natural language word strings). 1) can you see any holes in this logic? 2) what would you recommend for regular expressions. The reason I ask is that if you have spaces in the string, you only want want alphanumeric sequences, if you have alphanumeric plus symbol special characters, you don't want spaces. I'm not sure how strict that precondition should be. I'm going to need to think about it more. Opinions would be welcome. I think this works for almost any language too which is really important in the disabled programmer community. I appreciate your patience. Sometimes the overhead of communicating using speech recognition with tools don't work well with speech recognition such as Thunderbird makes the whole process of writing almost more difficult than it's worth. Working on tools like this is incremental progress I need to make in order to be able to bring speech recognition-based accessibility to the Python world. --- eric From python.list at tim.thechases.com Mon Jul 30 22:54:41 2012 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 30 Jul 2012 21:54:41 -0500 Subject: OT: accessibility (was "Re: simplified Python parsing question") In-Reply-To: <50173EE6.3030702@harvee.org> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> <50173EE6.3030702@harvee.org> Message-ID: <501748F1.2060903@tim.thechases.com> On 07/30/12 21:11, Eric S. Johansson wrote: > the ability for multiple people to work on the same document at > the same time is really important. Can't do that with Word or > Libre office. revision tracking in traditional word processors > are unpleasant to work with especially if your hands are broken. If you're developing, I might recommend using text-based storage and actual revision-control software. Hosting HTML (or Restructured Text, or plain-text, or LaTeX) documents on a shared repository such as GitHub or Bitbucket provides nicely for accessible documentation as well as much more powerful revision control. > It would please me greatly if you would be willing to try an > experiment. live my life for a while. Sit in a chair and tell > somebody what to type and where to move the mouse without moving > your hands. keep your hands gripping the arms or the sides of > the chair. The rule is you can't touch the keyboard you can't > touch the mice, you can't point at the screen. I suspect you > would have a hard time surviving half a day with these > limitations. no embarrassment in that, most people wouldn't make > it as far as a half a day. I've tried a similar experiment and am curious on your input device. Eye-tracking/dwell-clicking? A sip/puff joystick? Of the various input methods I tried, I found that Dasher[1] was the most intuitive, had a fairly high input rate and accuracy (both initially, and in terms of correcting mistakes I'd made). It also had the ability to generate dictionaries/vocabularies that made more appropriate/weighted suggestions which might help in certain contexts (e.g. pre-load a Python grammar allowing for choosing full atoms in a given context). -tkc [1] http://en.wikipedia.org/wiki/Dasher http://www.inference.phy.cam.ac.uk/dasher/ From james.pye at gmail.com Mon Jul 30 23:10:06 2012 From: james.pye at gmail.com (jwp) Date: Mon, 30 Jul 2012 20:10:06 -0700 (PDT) Subject: ANN: visage (interfaces) In-Reply-To: <50173e3f$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <0ac6c039-9cad-4cef-86d8-25e597996225@googlegroups.com> <52f2e8b7-4d91-4034-a263-d657bfedcc45@googlegroups.com> <41ef7b32-05e0-4cec-92ab-1ae0fce6171b@n16g2000vbn.googlegroups.com> <68308a21-ee64-4714-b52e-bb5a43b4a229@googlegroups.com> <50173e3f$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Monday, July 30, 2012 7:09:03 PM UTC-7, Steven D'Aprano wrote: > Do *one* and see if github actually does render it. Then do the rest. Did it for one project. It does render it. =) Naturally, sphinx autodoc links don't work. =( Come-on github, use dat fundin' From no.email at nospam.invalid Tue Jul 31 00:45:51 2012 From: no.email at nospam.invalid (Paul Rubin) Date: Mon, 30 Jul 2012 21:45:51 -0700 Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> <50173d9c$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7x62941qtc.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > And at that level, you aren't going to write your app in Python anyway, > and not because of the GIL. (These microcontrollers are unlikely to have > multiple cores -- why the hell does your microwave oven need two cores?) http://greenarrays.com ;-) > It seems to me that those who claim that the GIL is a serious barrier to > Python's use in the enterprise are mostly cargo-cult programmers, I would say, it puts a crimp into Python's versatility but there are still lots of areas where it's not a serious issue. A real compiler (PyPy) will help Python performance far more than multi-core currently can. From stefan_ml at behnel.de Tue Jul 31 01:23:54 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Jul 2012 07:23:54 +0200 Subject: py2c - an open source Python to C/C++ is looking for developers In-Reply-To: <1409e6f3-b265-4329-9618-c06f8098fef3@t1g2000pbl.googlegroups.com> References: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> <1409e6f3-b265-4329-9618-c06f8098fef3@t1g2000pbl.googlegroups.com> Message-ID: alex23, 31.07.2012 02:16: > On Jul 31, 2:42 am, MaxTheMouse wrote: >> What is the difference between this and Shedskin? Shedskin being a >> (restricted) python-to-C++ compiler. (http://code.google.com/p/ >> shedskin/) Is the goal to be able to handle any python code or a >> subset? > > There's also Nuitka, which is an unrestricted compiler, I believe: > http://nuitka.net/pages/overview.html Not to forget Cython, which is the only Python-to-C compiler that is in widespread use. > Is this a completely independent project, or are there plans to > leverage off of PyPy's toolchain, for example? >From a look at the source code, it seems hard to bring it together with anything. It looks very monolithic. Stefan From stefan_ml at behnel.de Tue Jul 31 01:27:01 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Jul 2012 07:27:01 +0200 Subject: Is Python a commercial proposition ? In-Reply-To: <7x62941qtc.fsf@ruckus.brouhaha.com> References: <-1016624622349492799@unknownmsgid> <50173d9c$0$29978$c3e8da3$5496439d@news.astraweb.com> <7x62941qtc.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin, 31.07.2012 06:45: > A real compiler (PyPy) will help Python performance far more than > multi-core currently can. That's too general a statement to be meaningful. Stefan From dieter at handshake.de Tue Jul 31 01:54:05 2012 From: dieter at handshake.de (Dieter Maurer) Date: Tue, 31 Jul 2012 07:54:05 +0200 Subject: [Python] Re: PyPI question, or, maybe I'm just stupid References: <50168312.6080900@gonnerman.org> Message-ID: <87sjc8o4qq.fsf@handshake.de> Chris Gonnerman writes: > On 07/30/2012 04:20 AM, Dieter Maurer wrote: > ... >> I find it very stupid to see several window scrolls of changes for >> a package but to learn how to install the package, I have to download its >> source... > Not sure I get this. The installation procedure for PollyReports is > the same as for, what, 99% of Python source packages? > > sudo python setup.py install > > What else are you saying I should do? This remark was not targeted at "PollyReports" but (in general) at packages with non-trivial installation procedures which nevertheless state on the overview page "for installation read the separate installation instructions (in the source distribution)". As a side note: playing well with python package managers ("easy_install", "pip", "zc.buildout", ...) could make it even simpler than "sudo python setup.py install". From poushali0198 at gmail.com Tue Jul 31 02:06:50 2012 From: poushali0198 at gmail.com (Poushali Ghosh) Date: Mon, 30 Jul 2012 23:06:50 -0700 (PDT) Subject: if you are able to access the internet at your spare time and wish to earn some $100 - $200 per month, then you are landed at the right place. this community is for you only !!! Message-ID: welcome to online jobs. ------------------------------------------ the job in which you can earn ! the job in which you can work from anywhere ! the job in which you can work at your convinient ! ------------------------------------------ here, you can find lot of earning oppurtunities like email earnings, forum earnings, discussion earnings & much more. all you need to do is some response kind of work. as per your well and wish you can work on your earning programs at your comfortable timings. your earnings will be paid to you through the cheques from the companies. visit homepage for more details : http://ernmoneyonli9.blogspot.in From ian.g.kelly at gmail.com Tue Jul 31 02:23:33 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 31 Jul 2012 00:23:33 -0600 Subject: OT: accessibility (was "Re: simplified Python parsing question") In-Reply-To: <501748F1.2060903@tim.thechases.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> <50173EE6.3030702@harvee.org> <501748F1.2060903@tim.thechases.com> Message-ID: On Mon, Jul 30, 2012 at 8:54 PM, Tim Chase wrote: > I've tried a similar experiment and am curious on your input device. > Eye-tracking/dwell-clicking? A sip/puff joystick? Of the various > input methods I tried, I found that Dasher[1] was the most > intuitive, had a fairly high input rate and accuracy (both > initially, and in terms of correcting mistakes I'd made). It also > had the ability to generate dictionaries/vocabularies that made more > appropriate/weighted suggestions which might help in certain > contexts (e.g. pre-load a Python grammar allowing for choosing full > atoms in a given context). A microphone with voice recognition software is described in the storyboard. From steve+comp.lang.python at pearwood.info Tue Jul 31 02:29:34 2012 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Jul 2012 06:29:34 GMT Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> <50173d9c$0$29978$c3e8da3$5496439d@news.astraweb.com> <7x62941qtc.fsf@ruckus.brouhaha.com> Message-ID: <50177b4d$0$29867$c3e8da3$5496439d@news.astraweb.com> On Mon, 30 Jul 2012 21:45:51 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> And at that level, you aren't going to write your app in Python anyway, >> and not because of the GIL. (These microcontrollers are unlikely to >> have multiple cores -- why the hell does your microwave oven need two >> cores?) > > http://greenarrays.com ;-) > >> It seems to me that those who claim that the GIL is a serious barrier >> to Python's use in the enterprise are mostly cargo-cult programmers, > > I would say, it puts a crimp into Python's versatility but there are > still lots of areas where it's not a serious issue. Of course it's a crimp. Nobody likes the GIL for its own sake, and nobody likes the fact that it does slow CPython down under some circumstances. It's not like the Python devs scheme behind closed doors on how to make Python slower. If somebody came up with a way to remove the GIL without the harmful side-effects, or volunteered to do the enormous amount of work needed, the devs would be as enthusiastic for it as anyone else. Recognising that there are *some* applications where Python isn't suitable (for whatever reason, not just because of the GIL) is simply common sense. There are a whole lot of factors leading to the choice of a compiler. "Can use all available cores on a CPU" is only one of many. [rant] But to hear some people talk, CPU-bound multi-threaded apps are the only "serious" enterprise apps, and further more, there is no possible way to make a program fast enough *except* threads, hence no possible way that Python is suitable except by removing the GIL. Do they consider that perhaps there are alternatives to threads? Or that there already are Python implementations that don't include the GIL, running on big enterprise-friendly platforms like Java and .NET? No they do not. If Python didn't have the GIL, they'd find some other excuse to dismiss it for "serious" work. And that is why I consider that anyone repeating without nuance the canard that the GIL makes Python unsuitable for serious enterprise work is a cargo-cultist. [/rant] And now I have to go yell at some kids who are on my lawn. -- Steven From vitrun at gmail.com Tue Jul 31 02:39:18 2012 From: vitrun at gmail.com (Yzr) Date: Tue, 31 Jul 2012 14:39:18 +0800 Subject: on django deployment Message-ID: Hi, guys: which solution is better, concerning memory usage and concurrency when deploying django ? 1) nginx + uWSGI + django 2) nginx + tornado + django thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Jul 31 03:15:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 31 Jul 2012 08:15:32 +0100 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On 31/07/2012 02:20, Dennis Lee Bieber wrote: > On Mon, 30 Jul 2012 22:56:48 +0000, Dan Stromberg > declaimed the following in gmane.comp.python.general: > > >> Sigh, and I'm also not keen on multi-line list comprehensions, specifically >> because I think they tend to make less readable code. It also becomes a >> mess when you need to insert print statements to get some visibility into >> what's going on. > > Cleanly splitting the list-comp by > > [ result-computation > for-item-selection-clause > if-filter-clause ] > > isn't that unreadable... But anyone doing > > [ result- > -computation for-item- > -selection-clause if- > -filter- > -clause ] > > should be pecked to death by a dead parrot. > Any particular species? -- Cheers. Mark Lawrence. From rosuav at gmail.com Tue Jul 31 04:05:49 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 31 Jul 2012 18:05:49 +1000 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On Tue, Jul 31, 2012 at 5:15 PM, Mark Lawrence wrote: > On 31/07/2012 02:20, Dennis Lee Bieber wrote: >> >> should be pecked to death by a dead parrot. >> > > Any particular species? I'm sure that, if you're in Norway, you could find an appropriate bird. But for those of us for whom that's not an option, I'd be content to nail the programmer's feet to the cage and then return him whence he came as a faulty model. Unfortunately local law enforcement would want in on that deal. ChrisA From benoist at ibpc.fr Tue Jul 31 05:39:36 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Tue, 31 Jul 2012 11:39:36 +0200 Subject: argparse limitations In-Reply-To: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> Message-ID: Well sorry about that but it seems I was wrong. It was Friday evening and I guess I've not been careful. Actually when you specify nargs="?", the doc says "One argument will be consumed from the command line if possible, and produced as a single item". So you can't pass several arguments to the program. So, to rephrase the question, how can I get a argument parser that parses the command-line just as Unix grep would do? i.e. $ echo 42 > foo.txt $ echo 172 >> foo.txt $ cp foo.txt bar.txt $ $ grep 42 foo.txt 42 $ grep 42 foo.txt bar.txt foo.txt:42 bar.txt:42 $ cat foo.txt | grep 42 42 $ grep -c 42 foo.txt 1 Cheers, Ben Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : > > > Yes basically looks like you get it. > I have to further test it but my first impression is that it's correct. > > So actually the point was to use nargs="?". > > Thank you very much. > Ben > > > > Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : > >> Benoist Laurent wrote: >> >>> I'm impletting a tool in Python. >>> I'd like this tool to behave like a standard unix tool, as grep for >>> exemple. I chose to use the argparse module to parse the command line and >>> I think I'm getting into several limitations of this module. >>> >>>> First Question. >>> How can I configure the the ArgumentParser to allow the user to give >>> either an input file or to pipe the output from another program? >>> >>> $ mytool.py file.txt >>> $ cat file.txt | mytool.py >> >> $ echo alpha > in.txt >> $ cat in.txt | ./mytool.py >> ALPHA >> $ cat in.txt | ./mytool.py - out.txt >> $ cat out.txt >> ALPHA >> $ ./mytool.py in.txt >> ALPHA >> $ ./mytool.py in.txt out2.txt >> $ cat out2.txt >> ALPHA >> $ cat ./mytool.py >> #!/usr/bin/env python >> assert __name__ == "__main__" >> >> import argparse >> import sys >> >> parser = argparse.ArgumentParser() >> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), >> default=sys.stdin) >> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), >> default=sys.stdout) >> args = parser.parse_args() >> >> args.outfile.writelines(line.upper() for line in args.infile) >> >> Is that good enough? >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > -- > http://mail.python.org/mailman/listinfo/python-list -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Jul 31 05:55:57 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 31 Jul 2012 10:55:57 +0100 Subject: argparse limitations In-Reply-To: References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> Message-ID: On Jul 31, 2012 10:32 AM, "Benoist Laurent" wrote: > > Well sorry about that but it seems I was wrong. > It was Friday evening and I guess I've not been careful. > > Actually when you specify nargs="?", the doc says "One argument will be consumed from the command line if possible, and produced as a single item". > So you can't pass several arguments to the program. Right below that in the docs it explains about using nargs='*' and nargs='+'. One of those will do what you want. Oscar. > > So, to rephrase the question, how can I get a argument parser that parses the command-line just as Unix grep would do? > i.e. > > $ echo 42 > foo.txt > $ echo 172 >> foo.txt > $ cp foo.txt bar.txt > $ > $ grep 42 foo.txt > 42 > $ grep 42 foo.txt bar.txt > foo.txt:42 > bar.txt:42 > $ cat foo.txt | grep 42 > 42 > $ grep -c 42 foo.txt > 1 > > > Cheers, > Ben > > > > > Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : > >> >> >> Yes basically looks like you get it. >> I have to further test it but my first impression is that it's correct. >> >> So actually the point was to use nargs="?". >> >> Thank you very much. >> Ben >> >> >> >> Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : >> >>> Benoist Laurent wrote: >>> >>>> I'm impletting a tool in Python. >>>> >>>> I'd like this tool to behave like a standard unix tool, as grep for >>>> >>>> exemple. I chose to use the argparse module to parse the command line and >>>> >>>> I think I'm getting into several limitations of this module. >>>> >>>> >>>>> First Question. >>>> >>>> How can I configure the the ArgumentParser to allow the user to give >>>> >>>> either an input file or to pipe the output from another program? >>>> >>>> >>>> $ mytool.py file.txt >>>> >>>> $ cat file.txt | mytool.py >>> >>> >>> $ echo alpha > in.txt >>> $ cat in.txt | ./mytool.py >>> ALPHA >>> $ cat in.txt | ./mytool.py - out.txt >>> $ cat out.txt >>> ALPHA >>> $ ./mytool.py in.txt >>> ALPHA >>> $ ./mytool.py in.txt out2.txt >>> $ cat out2.txt >>> ALPHA >>> $ cat ./mytool.py >>> #!/usr/bin/env python >>> assert __name__ == "__main__" >>> >>> import argparse >>> import sys >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), >>> default=sys.stdin) >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), >>> default=sys.stdout) >>> args = parser.parse_args() >>> >>> args.outfile.writelines(line.upper() for line in args.infile) >>> >>> Is that good enough? >>> >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> -- >> Benoist Laurent >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 >> Institut de Biologie Physico-Chimique >> 13, rue Pierre et Marie Curie >> F-75005 Paris >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ulrich.eckhardt at dominolaser.com Tue Jul 31 06:36:14 2012 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 31 Jul 2012 12:36:14 +0200 Subject: NameError vs AttributeError Message-ID: Hi! Using Python 2.7, I stumbled across the fact that 'self.xy' raises an AttributeError if self doesn't have an 'xy' as attribute, but 'xy' will instead raise a NameError. To some extent, these two are very similar, namely that the name 'xy' couldn't be resolved in a certain context, but they don't have a common baseclass. I guess one of the reasons is behind the way that Python handles variable lookup, the plain 'xy' will find local and global names while 'self.xy' will only look into onself. However, this vague idea is far from enough to explain it to someone else. Can someone help me out? Uli From benoist at ibpc.fr Tue Jul 31 06:37:29 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Tue, 31 Jul 2012 12:37:29 +0200 Subject: argparse limitations In-Reply-To: References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> Message-ID: Really sorry about that. So, for the community, below is the full code for a tool that behaves like a Unix standard tool. It takes in argument the files to process and a command. """Just to setup a command-line parser that acts just like a unix standard tool.""" import argparse import sys def define_options(): parser = argparse.ArgumentParser() parser.add_argument("fname", help="input file", nargs="*") # create subparsers subparsers = parser.add_subparsers(dest="cmd", metavar="command") # create the parser for the "foo" command get_parser = subparsers.add_parser("foo", help="foo help") get_parser.add_argument("-n", help="number of foo to print", type=int, default=10) # create the parser for the "bar" command sum_parser = subparsers.add_parser("bar", help="bar help") return parser if __name__ == '__main__': args = define_options().parse_args() if not args.fname: content = sys.stdin.read() # do something else: for fname in args.fname: with(open(fname, "rt")) as f: content = f.read() # do somet Benoist Le Jul 31, 2012 ? 11:55 AM, Oscar Benjamin a ?crit : > > On Jul 31, 2012 10:32 AM, "Benoist Laurent" wrote: > > > > Well sorry about that but it seems I was wrong. > > It was Friday evening and I guess I've not been careful. > > > > Actually when you specify nargs="?", the doc says "One argument will be consumed from the command line if possible, and produced as a single item". > > So you can't pass several arguments to the program. > > Right below that in the docs it explains about using nargs='*' and nargs='+'. One of those will do what you want. > > Oscar. > > > > > So, to rephrase the question, how can I get a argument parser that parses the command-line just as Unix grep would do? > > i.e. > > > > $ echo 42 > foo.txt > > $ echo 172 >> foo.txt > > $ cp foo.txt bar.txt > > $ > > $ grep 42 foo.txt > > 42 > > $ grep 42 foo.txt bar.txt > > foo.txt:42 > > bar.txt:42 > > $ cat foo.txt | grep 42 > > 42 > > $ grep -c 42 foo.txt > > 1 > > > > > > Cheers, > > Ben > > > > > > > > > > Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : > > > >> > >> > >> Yes basically looks like you get it. > >> I have to further test it but my first impression is that it's correct. > >> > >> So actually the point was to use nargs="?". > >> > >> Thank you very much. > >> Ben > >> > >> > >> > >> Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : > >> > >>> Benoist Laurent wrote: > >>> > >>>> I'm impletting a tool in Python. > >>>> > >>>> I'd like this tool to behave like a standard unix tool, as grep for > >>>> > >>>> exemple. I chose to use the argparse module to parse the command line and > >>>> > >>>> I think I'm getting into several limitations of this module. > >>>> > >>>> > >>>>> First Question. > >>>> > >>>> How can I configure the the ArgumentParser to allow the user to give > >>>> > >>>> either an input file or to pipe the output from another program? > >>>> > >>>> > >>>> $ mytool.py file.txt > >>>> > >>>> $ cat file.txt | mytool.py > >>> > >>> > >>> $ echo alpha > in.txt > >>> $ cat in.txt | ./mytool.py > >>> ALPHA > >>> $ cat in.txt | ./mytool.py - out.txt > >>> $ cat out.txt > >>> ALPHA > >>> $ ./mytool.py in.txt > >>> ALPHA > >>> $ ./mytool.py in.txt out2.txt > >>> $ cat out2.txt > >>> ALPHA > >>> $ cat ./mytool.py > >>> #!/usr/bin/env python > >>> assert __name__ == "__main__" > >>> > >>> import argparse > >>> import sys > >>> > >>> parser = argparse.ArgumentParser() > >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), > >>> default=sys.stdin) > >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), > >>> default=sys.stdout) > >>> args = parser.parse_args() > >>> > >>> args.outfile.writelines(line.upper() for line in args.infile) > >>> > >>> Is that good enough? > >>> > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >>> > >> > >> -- > >> Benoist Laurent > >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 > >> Institut de Biologie Physico-Chimique > >> 13, rue Pierre et Marie Curie > >> F-75005 Paris > >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > > Benoist Laurent > > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > > Institut de Biologie Physico-Chimique > > 13, rue Pierre et Marie Curie > > F-75005 Paris > > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.ware at ntlworld.com Tue Jul 31 06:53:41 2012 From: alister.ware at ntlworld.com (Alister) Date: Tue, 31 Jul 2012 10:53:41 GMT Subject: Linux shell to python References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: On Tue, 31 Jul 2012 08:15:32 +0100, Mark Lawrence wrote: > On 31/07/2012 02:20, Dennis Lee Bieber wrote: >> On Mon, 30 Jul 2012 22:56:48 +0000, Dan Stromberg >> declaimed the following in gmane.comp.python.general: >> >> >>> Sigh, and I'm also not keen on multi-line list comprehensions, >>> specifically because I think they tend to make less readable code. It >>> also becomes a mess when you need to insert print statements to get >>> some visibility into what's going on. >> >> Cleanly splitting the list-comp by >> >> [ result-computation >> for-item-selection-clause if-filter-clause ] >> >> isn't that unreadable... But anyone doing >> >> [ result- >> -computation for-item- -selection-clause if- -filter- >> -clause ] >> >> should be pecked to death by a dead parrot. >> >> > Any particular species? as has already been hinted - Norwegian Blue -- Question: Is it better to abide by the rules until they're changed or help speed the change by breaking them? From benoist at ibpc.fr Tue Jul 31 07:03:47 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Tue, 31 Jul 2012 13:03:47 +0200 Subject: argparse limitations In-Reply-To: References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> Message-ID: <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> Finally. The code I proposed doesn't work in this case: if you add any positional argument to one of the subparsers, then the parsing doesn't work anymore. The reason seems to be that argparse thinks the last argument of the first parser is the last but one argument. Hence, if a subparser takes some arguments, it fails. Example: if the "-n" argument of the foo parser is set mandatory (so becomes "n" instead of "-n") python toto.py foo.txt bar.txt foo 10 usage: toto.py [-h] [fname [fname ...]] command ... toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 'bar') Any solution? Cheers, Ben Le Jul 31, 2012 ? 12:37 PM, Benoist Laurent a ?crit : > Really sorry about that. > > So, for the community, below is the full code for a tool that behaves like a Unix standard tool. > It takes in argument the files to process and a command. > > """Just to setup a command-line parser that acts just like a unix > standard tool.""" > > import argparse > import sys > > def define_options(): > parser = argparse.ArgumentParser() > parser.add_argument("fname", help="input file", nargs="*") > > # create subparsers > subparsers = parser.add_subparsers(dest="cmd", metavar="command") > > # create the parser for the "foo" command > get_parser = subparsers.add_parser("foo", help="foo help") > get_parser.add_argument("-n", help="number of foo to print", > type=int, default=10) > > # create the parser for the "bar" command > sum_parser = subparsers.add_parser("bar", help="bar help") > > return parser > > > if __name__ == '__main__': > args = define_options().parse_args() > > if not args.fname: > content = sys.stdin.read() > # do something > else: > for fname in args.fname: > with(open(fname, "rt")) as f: > content = f.read() > # do somet > > > Benoist > > > > Le Jul 31, 2012 ? 11:55 AM, Oscar Benjamin a ?crit : > >> >> On Jul 31, 2012 10:32 AM, "Benoist Laurent" wrote: >> > >> > Well sorry about that but it seems I was wrong. >> > It was Friday evening and I guess I've not been careful. >> > >> > Actually when you specify nargs="?", the doc says "One argument will be consumed from the command line if possible, and produced as a single item". >> > So you can't pass several arguments to the program. >> >> Right below that in the docs it explains about using nargs='*' and nargs='+'. One of those will do what you want. >> >> Oscar. >> >> > >> > So, to rephrase the question, how can I get a argument parser that parses the command-line just as Unix grep would do? >> > i.e. >> > >> > $ echo 42 > foo.txt >> > $ echo 172 >> foo.txt >> > $ cp foo.txt bar.txt >> > $ >> > $ grep 42 foo.txt >> > 42 >> > $ grep 42 foo.txt bar.txt >> > foo.txt:42 >> > bar.txt:42 >> > $ cat foo.txt | grep 42 >> > 42 >> > $ grep -c 42 foo.txt >> > 1 >> > >> > >> > Cheers, >> > Ben >> > >> > >> > >> > >> > Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : >> > >> >> >> >> >> >> Yes basically looks like you get it. >> >> I have to further test it but my first impression is that it's correct. >> >> >> >> So actually the point was to use nargs="?". >> >> >> >> Thank you very much. >> >> Ben >> >> >> >> >> >> >> >> Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : >> >> >> >>> Benoist Laurent wrote: >> >>> >> >>>> I'm impletting a tool in Python. >> >>>> >> >>>> I'd like this tool to behave like a standard unix tool, as grep for >> >>>> >> >>>> exemple. I chose to use the argparse module to parse the command line and >> >>>> >> >>>> I think I'm getting into several limitations of this module. >> >>>> >> >>>> >> >>>>> First Question. >> >>>> >> >>>> How can I configure the the ArgumentParser to allow the user to give >> >>>> >> >>>> either an input file or to pipe the output from another program? >> >>>> >> >>>> >> >>>> $ mytool.py file.txt >> >>>> >> >>>> $ cat file.txt | mytool.py >> >>> >> >>> >> >>> $ echo alpha > in.txt >> >>> $ cat in.txt | ./mytool.py >> >>> ALPHA >> >>> $ cat in.txt | ./mytool.py - out.txt >> >>> $ cat out.txt >> >>> ALPHA >> >>> $ ./mytool.py in.txt >> >>> ALPHA >> >>> $ ./mytool.py in.txt out2.txt >> >>> $ cat out2.txt >> >>> ALPHA >> >>> $ cat ./mytool.py >> >>> #!/usr/bin/env python >> >>> assert __name__ == "__main__" >> >>> >> >>> import argparse >> >>> import sys >> >>> >> >>> parser = argparse.ArgumentParser() >> >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), >> >>> default=sys.stdin) >> >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), >> >>> default=sys.stdout) >> >>> args = parser.parse_args() >> >>> >> >>> args.outfile.writelines(line.upper() for line in args.infile) >> >>> >> >>> Is that good enough? >> >>> >> >>> >> >>> -- >> >>> http://mail.python.org/mailman/listinfo/python-list >> >>> >> >> >> >> -- >> >> Benoist Laurent >> >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 >> >> Institut de Biologie Physico-Chimique >> >> 13, rue Pierre et Marie Curie >> >> F-75005 Paris >> >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >> >> >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> > >> > >> > -- >> > Benoist Laurent >> > Laboratoire de Biochimie Theorique / CNRS UPR 9080 >> > Institut de Biologie Physico-Chimique >> > 13, rue Pierre et Marie Curie >> > F-75005 Paris >> > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >> > >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > -- > http://mail.python.org/mailman/listinfo/python-list -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Jul 31 07:45:51 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 31 Jul 2012 12:45:51 +0100 Subject: argparse limitations In-Reply-To: <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> Message-ID: On 31 July 2012 12:03, Benoist Laurent wrote: > Finally. > > The code I proposed doesn't work in this case: if you add any positional > argument to one of the subparsers, then the parsing doesn't work anymore. > The reason seems to be that argparse thinks the last argument of the first > parser is the last but one argument. > Hence, if a subparser takes some arguments, it fails. > > Example: if the "-n" argument of the foo parser is set mandatory (so > becomes "n" instead of "-n") > > python toto.py foo.txt bar.txt foo 10 > usage: toto.py [-h] [fname [fname ...]] command ... > toto.py: error: argument command: invalid choice: '10' (choose from 'foo', > 'bar') > What about: $ python toto.py foo.txt bar.txt foo -n 10 Note that contrary to what you said above, your program does not work like a "standard unix tool". A standard command line program to do what you want would normally look like $ python toto.py foo -n 10 foo.txt bar.txt or perhaps $ python toto.py foo foo.txt bar.txt -n 10 so that the algorithm for differentiating the command 'foo' from the filenames is well defined. How do you propose that your user enters a filename 'foo'? Oscar. > > Any solution? > > Cheers, > Ben > > > > Le Jul 31, 2012 ? 12:37 PM, Benoist Laurent a ?crit : > > Really sorry about that. > > So, for the community, below is the full code for a tool that behaves like > a Unix standard tool. > It takes in argument the files to process and a command. > > """Just to setup a command-line parser that acts just like a unix > standard tool.""" > > import argparse > import sys > > def define_options(): > parser = argparse.ArgumentParser() > parser.add_argument("fname", help="input file", nargs="*") > > # create subparsers > subparsers = parser.add_subparsers(dest="cmd", metavar="command") > > # create the parser for the "foo" command > get_parser = subparsers.add_parser("foo", help="foo help") > get_parser.add_argument("-n", help="number of foo to print", > type=int, default=10) > > # create the parser for the "bar" command > sum_parser = subparsers.add_parser("bar", help="bar help") > > return parser > > > if __name__ == '__main__': > args = define_options().parse_args() > > if not args.fname: > content = sys.stdin.read() > # do something > else: > for fname in args.fname: > with(open(fname, "rt")) as f: > content = f.read() > # do somet > > > Benoist > > > > Le Jul 31, 2012 ? 11:55 AM, Oscar Benjamin a ?crit : > > > On Jul 31, 2012 10:32 AM, "Benoist Laurent" wrote: > > > > Well sorry about that but it seems I was wrong. > > It was Friday evening and I guess I've not been careful. > > > > Actually when you specify nargs="?", the doc says "One argument will be > consumed from the command line if possible, and produced as a single item". > > So you can't pass several arguments to the program. > > Right below that in the docs it explains about using nargs='*' and > nargs='+'. One of those will do what you want. > > Oscar. > > > > > So, to rephrase the question, how can I get a argument parser that > parses the command-line just as Unix grep would do? > > i.e. > > > > $ echo 42 > foo.txt > > $ echo 172 >> foo.txt > > $ cp foo.txt bar.txt > > $ > > $ grep 42 foo.txt > > 42 > > $ grep 42 foo.txt bar.txt > > foo.txt:42 > > bar.txt:42 > > $ cat foo.txt | grep 42 > > 42 > > $ grep -c 42 foo.txt > > 1 > > > > > > Cheers, > > Ben > > > > > > > > > > Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : > > > >> > >> > >> Yes basically looks like you get it. > >> I have to further test it but my first impression is that it's correct. > >> > >> So actually the point was to use nargs="?". > >> > >> Thank you very much. > >> Ben > >> > >> > >> > >> Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : > >> > >>> Benoist Laurent wrote: > >>> > >>>> I'm impletting a tool in Python. > >>>> > >>>> I'd like this tool to behave like a standard unix tool, as grep for > >>>> > >>>> exemple. I chose to use the argparse module to parse the command line > and > >>>> > >>>> I think I'm getting into several limitations of this module. > >>>> > >>>> > >>>>> First Question. > >>>> > >>>> How can I configure the the ArgumentParser to allow the user to give > >>>> > >>>> either an input file or to pipe the output from another program? > >>>> > >>>> > >>>> $ mytool.py file.txt > >>>> > >>>> $ cat file.txt | mytool.py > >>> > >>> > >>> $ echo alpha > in.txt > >>> $ cat in.txt | ./mytool.py > >>> ALPHA > >>> $ cat in.txt | ./mytool.py - out.txt > >>> $ cat out.txt > >>> ALPHA > >>> $ ./mytool.py in.txt > >>> ALPHA > >>> $ ./mytool.py in.txt out2.txt > >>> $ cat out2.txt > >>> ALPHA > >>> $ cat ./mytool.py > >>> #!/usr/bin/env python > >>> assert __name__ == "__main__" > >>> > >>> import argparse > >>> import sys > >>> > >>> parser = argparse.ArgumentParser() > >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), > >>> default=sys.stdin) > >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), > >>> default=sys.stdout) > >>> args = parser.parse_args() > >>> > >>> args.outfile.writelines(line.upper() for line in args.infile) > >>> > >>> Is that good enough? > >>> > >>> > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >>> > >> > >> -- > >> Benoist Laurent > >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 > >> Institut de Biologie Physico-Chimique > >> 13, rue Pierre et Marie Curie > >> F-75005 Paris > >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > > Benoist Laurent > > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > > Institut de Biologie Physico-Chimique > > 13, rue Pierre et Marie Curie > > F-75005 Paris > > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From esj at harvee.org Tue Jul 31 07:56:03 2012 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 31 Jul 2012 07:56:03 -0400 Subject: OT: accessibility (was "Re: simplified Python parsing question") In-Reply-To: <501748F1.2060903@tim.thechases.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> <50173EE6.3030702@harvee.org> <501748F1.2060903@tim.thechases.com> Message-ID: <5017C7D3.3080301@harvee.org> On 7/30/2012 10:54 PM, Tim Chase wrote: > On 07/30/12 21:11, Eric S. Johansson wrote: >> the ability for multiple people to work on the same document at >> the same time is really important. Can't do that with Word or >> Libre office. revision tracking in traditional word processors >> are unpleasant to work with especially if your hands are broken. > If you're developing, I might recommend using text-based storage and > actual revision-control software. Hosting HTML (or Restructured > Text, or plain-text, or LaTeX) documents on a shared repository such > as GitHub or Bitbucket provides nicely for accessible documentation > as well as much more powerful revision control. But then you hit a second layer of "doesn't really work nice with speech recognition". Using a markup language can actually be more difficult than using a WYSIWYG editor. For example, with a soft word, I can do most of the basics using speech commands and I have what's called "Select-and-Say" editing capability in the buffer. Can't do that with any other editor. They are not integrated with NaturallySpeaking. A few years ago I created a small scale framework for speech recognition users (akasha). You use the domain specific market notation to be able to construct Web applications. Instead of using classic HTML models, it used things that were more appropriate to speech driven environment. unlike with HTML, which you cannot write using speech recognition and a boatload of effort, akasha was 95% speakable using out-of-the-box speech recognition. This also brings me to the concept of how the design for speech recognition use. Modifying an existing user interface or creating a new one either through a speakable data format and minimal application changes or by the application and grammar to a recognition engine and manipulating something that isn't speakable. From experience, outside of the first model works well if you are looking for relatively easy and very high marks accessibility, the second is required if you are operating within a team and need to integrate with everybody else. Unfortunately, the second technique points out just how badly designed most software is and that led me to the concept of no-UI (not unlike no SQL) which is more controversial than I want to get into right now. > >> It would please me greatly if you would be willing to try an >> experiment. live my life for a while. Sit in a chair and tell >> somebody what to type and where to move the mouse without moving >> your hands. keep your hands gripping the arms or the sides of >> the chair. The rule is you can't touch the keyboard you can't >> touch the mice, you can't point at the screen. I suspect you >> would have a hard time surviving half a day with these >> limitations. no embarrassment in that, most people wouldn't make >> it as far as a half a day. > I've tried a similar experiment and am curious on your input device. > Eye-tracking/dwell-clicking? A sip/puff joystick? Of the various > input methods I tried, I found that Dasher[1] was the most > intuitive, had a fairly high input rate and accuracy (both > initially, and in terms of correcting mistakes I'd made). It also > had the ability to generate dictionaries/vocabularies that made more > appropriate/weighted suggestions which might help in certain > contexts (e.g. pre-load a Python grammar allowing for choosing full > atoms in a given context). Just ordinary speech recognition. NaturallySpeaking. Part of my hand problem is that I no longer have good fine motor control which sucks because I used to enjoy drawing with pencils and juggling. I've tried dasher and I don't have find enough motor control to make it work very well. Sometimes I play games with my girlfriend at fly or die and the user interfaces for the various game controllers is simple enough that my hands only get in the way some of the time. Or at least that's what say when she is beating me soundly at billiards. :-) Some of the ideas you've mentioned have been thought in another contexts. The problem is that when it comes to working with code, you have two problems. Creation of code and editing code. Which do you do more? If you're like most of us, it is editing. That's why I made the toggle words feature something that would toggle both from a string name to a codename and vice versa.the future version of this and, this is where I'm going to need a lot of help from the Python community, would translate the statement in a buffer to a particular two-dimensional form and place it into a special window that NaturallySpeaking can operate on. The reason for covering it from the one-dimensional string of a statement to a two-dimensional form is to make it easier to disambiguate different features using speech. The idea isn't fully fleshed out because I want to get through this one first and actually be able to start writing code again. From roy at panix.com Tue Jul 31 08:04:57 2012 From: roy at panix.com (Roy Smith) Date: Tue, 31 Jul 2012 08:04:57 -0400 Subject: Is Python a commercial proposition ? References: <-1016624622349492799@unknownmsgid> <50173d9c$0$29978$c3e8da3$5496439d@news.astraweb.com> <7x62941qtc.fsf@ruckus.brouhaha.com> <50177b4d$0$29867$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <50177b4d$0$29867$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > Do they consider that perhaps there are alternatives to threads? There's basically two reasons people use threads. First is because it's a convenient way to multiplex short-lived tasks on a single processor. What people tend to forget is that we managed to do that before there were threads. Event loops still work perfectly fine. For an interesting example, http://www.gevent.org/. Second is because we have multiple long-lived, compute-bound tasks and want to be able to take advantage of multiple processors. For that, multiprocessing works just fine most of the time. And multiprocess has the advantage over multithreading in that the processes can run on different machines, so you're not limited by the number of cores you can get on a single CPU. What multiprocessing doesn't give you is fine-grain task switching. So we're left with the set of jobs which consist of many (but not more than the number of cores on one CPU) compute-bound tasks, that we know how to parallelize, and require fine-grain task switching. Sure, that's an important set of jobs, but there's a whole huge world of computing that doesn't fit into that box. From rmorgan466 at gmail.com Tue Jul 31 08:13:04 2012 From: rmorgan466 at gmail.com (Rita) Date: Tue, 31 Jul 2012 08:13:04 -0400 Subject: profiling and optimizing Message-ID: hello, I recently inherented a large python process and everything is lovely. As a learning experience I would like to optimize the code so I ran it thru the profiler python -m cProfile myscript.py It seems majority of the time is taking in the deep copy but that seems to come from a function (or functions) in the code. Is there a way to optimize that? perhaps have a C implementation of the deep copy? Would that be feasible? -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Jul 31 08:21:08 2012 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 31 Jul 2012 22:21:08 +1000 Subject: profiling and optimizing In-Reply-To: References: Message-ID: On Tue, Jul 31, 2012 at 10:13 PM, Rita wrote: > It seems majority of the time is taking in the deep copy but that seems to > come from a function (or functions) in the code. Is there a way to optimize > that? Why is the program deep-copying things? Rather than making deepcopy faster, consider doing it less. Normally I would first ask: Does the program even NEED optimization? Often the answer is no, because it's already fast enough - for instance, if it spends all its time waiting for the internet, there's little point reducing its CPU footprint. However, that point is moot in this instance, since you're doing the profiling/optimization for education rather than performance :) Have fun with it! Chris Angelico From stefan_ml at behnel.de Tue Jul 31 08:22:23 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Jul 2012 14:22:23 +0200 Subject: profiling and optimizing In-Reply-To: References: Message-ID: Rita, 31.07.2012 14:13: > I recently inherented a large python process and everything is lovely. As a > learning experience I would like to optimize the code so I ran it thru the > profiler > > python -m cProfile myscript.py > > It seems majority of the time is taking in the deep copy but that seems to > come from a function (or functions) in the code. Is there a way to optimize > that? perhaps have a C implementation of the deep copy? Would that > be feasible? Those approaches would be my second (or maybe even later) step. The first one would be to check if the deep copy is really necessary, and if so, if it is really necessary to do it over the full depth of the entire object graph. Stefan From oscar.benjamin at bristol.ac.uk Tue Jul 31 08:23:19 2012 From: oscar.benjamin at bristol.ac.uk (Oscar Benjamin) Date: Tue, 31 Jul 2012 13:23:19 +0100 Subject: profiling and optimizing In-Reply-To: References: Message-ID: On 31 July 2012 13:13, Rita wrote: > hello, > > I recently inherented a large python process and everything is lovely. As > a learning experience I would like to optimize the code so I ran it thru > the profiler > > python -m cProfile myscript.py > > It seems majority of the time is taking in the deep copy but that seems to > come from a function (or functions) in the code. Is there a way to optimize > that? perhaps have a C implementation of the deep copy? Would that > be feasible? > I think you'll need to provide more information to get an answer to your question. Why are you copying? What are you copying? Do you need a deep-copy? I don't really know what you're doing but my first approach would be to try and reduce or eliminate the deep copies rather than implement them in c. Oscar. > > > > > > > -- > --- Get your facts first, then you can distort them as you please.-- > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Jul 31 08:46:27 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Jul 2012 14:46:27 +0200 Subject: py2c - an open source Python to C/C++ is looking for developers In-Reply-To: References: <16816fd5-c6b4-49df-baf0-e0bfb0d999df@googlegroups.com> <1409e6f3-b265-4329-9618-c06f8098fef3@t1g2000pbl.googlegroups.com> Message-ID: Stefan Behnel, 31.07.2012 07:23: > From a look at the source code, it seems hard to bring it together with > anything. It looks very monolithic. Hmm, sorry, I mixed it up with "2c.py", which is yet another of those Python-to-C compilers with an all too similar name. https://code.google.com/p/2c-python/ There are a couple of others here: http://wiki.python.org/moin/PythonImplementations Seeing the number of those compilers, almost none of which is commonly used and/or still alive as a project, the question really is: why another one? I mean, it's totally fine as a hobby educational project, sure, and I really don't want to discourage anyone from going through this to have fun. But apart from "just for fun", what is the goal that would make this particular compiler different from the others? And also different enough to merit its own source base, instead of basing it on one of the existing projects? I don't consider "source is harder to read than to write" a good answer to this in general. Stefan From benoist at ibpc.fr Tue Jul 31 08:51:13 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Tue, 31 Jul 2012 14:51:13 +0200 Subject: argparse limitations In-Reply-To: References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> Message-ID: <88DC1003-262D-421B-AB1F-126CEC4765DE@ibpc.fr> Le Jul 31, 2012 ? 1:45 PM, Oscar Benjamin a ?crit : > > > On 31 July 2012 12:03, Benoist Laurent wrote: > Finally. > > The code I proposed doesn't work in this case: if you add any positional argument to one of the subparsers, then the parsing doesn't work anymore. > The reason seems to be that argparse thinks the last argument of the first parser is the last but one argument. > Hence, if a subparser takes some arguments, it fails. > > Example: if the "-n" argument of the foo parser is set mandatory (so becomes "n" instead of "-n") > > python toto.py foo.txt bar.txt foo 10 > usage: toto.py [-h] [fname [fname ...]] command ... > toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 'bar') > > What about: > > $ python toto.py foo.txt bar.txt foo -n 10 > > Note that contrary to what you said above, your program does not work like a "standard unix tool". A standard command line program to do what you want would normally look like You're right. But then, using argparse, I would have to add the same argument to all my subparsers since argparse does the work sequentially: once it recognized the start of a subparser, everything that follows have to be an argument of this subparser. Hence, arguments (therefore options) from the main parser are not recognized anymore. > > $ python toto.py foo -n 10 foo.txt bar.txt Same remark as above: if I want the command line to look like this, then I would have setup each subparser with all the main program options. > > or perhaps > > $ python toto.py foo foo.txt bar.txt -n 10 > > so that the algorithm for differentiating the command 'foo' from the filenames is well defined. How do you propose that your user enters a filename 'foo'? Well I guess it is a intrinsec limitation: I think it's quite natural that the user can't enter a filename named as a command. > > Oscar. > > > > Any solution? > > Cheers, > Ben > > > > Le Jul 31, 2012 ? 12:37 PM, Benoist Laurent a ?crit : > >> Really sorry about that. >> >> So, for the community, below is the full code for a tool that behaves like a Unix standard tool. >> It takes in argument the files to process and a command. >> >> """Just to setup a command-line parser that acts just like a unix >> standard tool.""" >> >> import argparse >> import sys >> >> def define_options(): >> parser = argparse.ArgumentParser() >> parser.add_argument("fname", help="input file", nargs="*") >> >> # create subparsers >> subparsers = parser.add_subparsers(dest="cmd", metavar="command") >> >> # create the parser for the "foo" command >> get_parser = subparsers.add_parser("foo", help="foo help") >> get_parser.add_argument("-n", help="number of foo to print", >> type=int, default=10) >> >> # create the parser for the "bar" command >> sum_parser = subparsers.add_parser("bar", help="bar help") >> >> return parser >> >> >> if __name__ == '__main__': >> args = define_options().parse_args() >> >> if not args.fname: >> content = sys.stdin.read() >> # do something >> else: >> for fname in args.fname: >> with(open(fname, "rt")) as f: >> content = f.read() >> # do somet >> >> >> Benoist >> >> >> >> Le Jul 31, 2012 ? 11:55 AM, Oscar Benjamin a ?crit : >> >>> >>> On Jul 31, 2012 10:32 AM, "Benoist Laurent" wrote: >>> > >>> > Well sorry about that but it seems I was wrong. >>> > It was Friday evening and I guess I've not been careful. >>> > >>> > Actually when you specify nargs="?", the doc says "One argument will be consumed from the command line if possible, and produced as a single item". >>> > So you can't pass several arguments to the program. >>> >>> Right below that in the docs it explains about using nargs='*' and nargs='+'. One of those will do what you want. >>> >>> Oscar. >>> >>> > >>> > So, to rephrase the question, how can I get a argument parser that parses the command-line just as Unix grep would do? >>> > i.e. >>> > >>> > $ echo 42 > foo.txt >>> > $ echo 172 >> foo.txt >>> > $ cp foo.txt bar.txt >>> > $ >>> > $ grep 42 foo.txt >>> > 42 >>> > $ grep 42 foo.txt bar.txt >>> > foo.txt:42 >>> > bar.txt:42 >>> > $ cat foo.txt | grep 42 >>> > 42 >>> > $ grep -c 42 foo.txt >>> > 1 >>> > >>> > >>> > Cheers, >>> > Ben >>> > >>> > >>> > >>> > >>> > Le Jul 27, 2012 ? 7:08 PM, Benoist Laurent a ?crit : >>> > >>> >> >>> >> >>> >> Yes basically looks like you get it. >>> >> I have to further test it but my first impression is that it's correct. >>> >> >>> >> So actually the point was to use nargs="?". >>> >> >>> >> Thank you very much. >>> >> Ben >>> >> >>> >> >>> >> >>> >> Le Jul 27, 2012 ? 5:44 PM, Peter Otten a ?crit : >>> >> >>> >>> Benoist Laurent wrote: >>> >>> >>> >>>> I'm impletting a tool in Python. >>> >>>> >>> >>>> I'd like this tool to behave like a standard unix tool, as grep for >>> >>>> >>> >>>> exemple. I chose to use the argparse module to parse the command line and >>> >>>> >>> >>>> I think I'm getting into several limitations of this module. >>> >>>> >>> >>>> >>> >>>>> First Question. >>> >>>> >>> >>>> How can I configure the the ArgumentParser to allow the user to give >>> >>>> >>> >>>> either an input file or to pipe the output from another program? >>> >>>> >>> >>>> >>> >>>> $ mytool.py file.txt >>> >>>> >>> >>>> $ cat file.txt | mytool.py >>> >>> >>> >>> >>> >>> $ echo alpha > in.txt >>> >>> $ cat in.txt | ./mytool.py >>> >>> ALPHA >>> >>> $ cat in.txt | ./mytool.py - out.txt >>> >>> $ cat out.txt >>> >>> ALPHA >>> >>> $ ./mytool.py in.txt >>> >>> ALPHA >>> >>> $ ./mytool.py in.txt out2.txt >>> >>> $ cat out2.txt >>> >>> ALPHA >>> >>> $ cat ./mytool.py >>> >>> #!/usr/bin/env python >>> >>> assert __name__ == "__main__" >>> >>> >>> >>> import argparse >>> >>> import sys >>> >>> >>> >>> parser = argparse.ArgumentParser() >>> >>> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), >>> >>> default=sys.stdin) >>> >>> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), >>> >>> default=sys.stdout) >>> >>> args = parser.parse_args() >>> >>> >>> >>> args.outfile.writelines(line.upper() for line in args.infile) >>> >>> >>> >>> Is that good enough? >>> >>> >>> >>> >>> >>> -- >>> >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >>> >> >>> >> -- >>> >> Benoist Laurent >>> >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 >>> >> Institut de Biologie Physico-Chimique >>> >> 13, rue Pierre et Marie Curie >>> >> F-75005 Paris >>> >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >>> >> >>> >> -- >>> >> http://mail.python.org/mailman/listinfo/python-list >>> > >>> > >>> > -- >>> > Benoist Laurent >>> > Laboratoire de Biochimie Theorique / CNRS UPR 9080 >>> > Institut de Biologie Physico-Chimique >>> > 13, rue Pierre et Marie Curie >>> > F-75005 Paris >>> > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >>> > >>> > >>> > -- >>> > http://mail.python.org/mailman/listinfo/python-list >>> > >> >> -- >> Benoist Laurent >> Laboratoire de Biochimie Theorique / CNRS UPR 9080 >> Institut de Biologie Physico-Chimique >> 13, rue Pierre et Marie Curie >> F-75005 Paris >> Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > > -- > Benoist Laurent > Laboratoire de Biochimie Theorique / CNRS UPR 9080 > Institut de Biologie Physico-Chimique > 13, rue Pierre et Marie Curie > F-75005 Paris > Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 > > -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Jul 31 09:04:53 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 31 Jul 2012 14:04:53 +0100 Subject: argparse limitations In-Reply-To: <88DC1003-262D-421B-AB1F-126CEC4765DE@ibpc.fr> References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> <88DC1003-262D-421B-AB1F-126CEC4765DE@ibpc.fr> Message-ID: On 31 July 2012 13:51, Benoist Laurent wrote: > > Le Jul 31, 2012 ? 1:45 PM, Oscar Benjamin a ?crit : > > > > On 31 July 2012 12:03, Benoist Laurent wrote: > >> Finally. >> >> The code I proposed doesn't work in this case: if you add any positional >> argument to one of the subparsers, then the parsing doesn't work anymore. >> The reason seems to be that argparse thinks the last argument of the >> first parser is the last but one argument. >> Hence, if a subparser takes some arguments, it fails. >> >> Example: if the "-n" argument of the foo parser is set mandatory (so >> becomes "n" instead of "-n") >> >> python toto.py foo.txt bar.txt foo 10 >> usage: toto.py [-h] [fname [fname ...]] command ... >> toto.py: error: argument command: invalid choice: '10' (choose from >> 'foo', 'bar') >> > > What about: > > $ python toto.py foo.txt bar.txt foo -n 10 > > Note that contrary to what you said above, your program does not work like > a "standard unix tool". A standard command line program to do what you want > would normally look like > > > You're right. > But then, using argparse, I would have to add the same argument to all my > subparsers since argparse does the work sequentially: once it recognized > the start of a subparser, everything that follows have to be an argument of > this subparser. > Hence, arguments (therefore options) from the main parser are not > recognized anymore. > If the parsing after the subcommand is to be the same for each subcommand, then don't use subparsers. You could just make the first argument be the command name and use one parser for everything. If the parsing is supposed to be different for different subcommands then use subparsers and add the files argument to each subparser; you can make a function to add the common arguments and options if you don't want to duplicate the code. Well I guess it is a intrinsec limitation: I think it's quite natural that > the user can't enter a filename named as a command. > There is an intrinsic limitation on any parser that it must be possible to determine the targets of the arguments uniquely. If you want the parser to scan through and take the first argument matching 'foo' or 'bar' and parse the remaining arguments accordingly then you already have your solution. It just won't work if the user wants to pass in a file called 'foo' or 'bar' (maybe that's acceptable, though). The standard way, however, is to have a parser that takes the first non-option argument as a subcommand name and parses the remaining arguments according to that subcommand. Your command line users are more likely to be able to understand how to use the program if it works that way. Oscar. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jul 31 09:23:56 2012 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Jul 2012 15:23:56 +0200 Subject: profiling and optimizing References: Message-ID: Rita wrote: > I recently inherented a large python process and everything is lovely. As > a learning experience I would like to optimize the code so I ran it thru > the profiler > > python -m cProfile myscript.py > > It seems majority of the time is taking in the deep copy but that seems to > come from a function (or functions) in the code. Is there a way to > optimize that? perhaps have a C implementation of the deep copy? Would > that be feasible? To give what the other respondents said a different angle: if you replace the deep with a shallow copy: do your unit tests start to fail? You don't have any? Add them before you start tinkering with the code ;) From benoist at ibpc.fr Tue Jul 31 09:24:08 2012 From: benoist at ibpc.fr (Benoist Laurent) Date: Tue, 31 Jul 2012 15:24:08 +0200 Subject: argparse limitations In-Reply-To: References: <94FFCC5D-82DC-40A7-B0E5-5244CD93F512@ibpc.fr> <8CB64AAC-CEA3-45BF-A9ED-E372DCABF334@ibpc.fr> <88DC1003-262D-421B-AB1F-126CEC4765DE@ibpc.fr> Message-ID: <4E4315A2-B78B-4AF9-9C18-377D4A5F1F6B@ibpc.fr> > The standard way, however, is to have a parser that takes the first non-option argument as a subcommand name and parses the remaining arguments according to that subcommand. Your command line users are more likely to be able to understand how to use the program if it works that way. I'll do this way. Thank a lot. Ben Le Jul 31, 2012 ? 3:04 PM, Oscar Benjamin a ?crit : > > > On 31 July 2012 13:51, Benoist Laurent wrote: > > Le Jul 31, 2012 ? 1:45 PM, Oscar Benjamin a ?crit : > >> >> >> On 31 July 2012 12:03, Benoist Laurent wrote: >> Finally. >> >> The code I proposed doesn't work in this case: if you add any positional argument to one of the subparsers, then the parsing doesn't work anymore. >> The reason seems to be that argparse thinks the last argument of the first parser is the last but one argument. >> Hence, if a subparser takes some arguments, it fails. >> >> Example: if the "-n" argument of the foo parser is set mandatory (so becomes "n" instead of "-n") >> >> python toto.py foo.txt bar.txt foo 10 >> usage: toto.py [-h] [fname [fname ...]] command ... >> toto.py: error: argument command: invalid choice: '10' (choose from 'foo', 'bar') >> >> What about: >> >> $ python toto.py foo.txt bar.txt foo -n 10 >> >> Note that contrary to what you said above, your program does not work like a "standard unix tool". A standard command line program to do what you want would normally look like > > You're right. > But then, using argparse, I would have to add the same argument to all my subparsers since argparse does the work sequentially: once it recognized the start of a subparser, everything that follows have to be an argument of this subparser. > Hence, arguments (therefore options) from the main parser are not recognized anymore. > > If the parsing after the subcommand is to be the same for each subcommand, then don't use subparsers. You could just make the first argument be the command name and use one parser for everything. > > If the parsing is supposed to be different for different subcommands then use subparsers and add the files argument to each subparser; you can make a function to add the common arguments and options if you don't want to duplicate the code. > > Well I guess it is a intrinsec limitation: I think it's quite natural that the user can't enter a filename named as a command. > > There is an intrinsic limitation on any parser that it must be possible to determine the targets of the arguments uniquely. If you want the parser to scan through and take the first argument matching 'foo' or 'bar' and parse the remaining arguments accordingly then you already have your solution. It just won't work if the user wants to pass in a file called 'foo' or 'bar' (maybe that's acceptable, though). > > The standard way, however, is to have a parser that takes the first non-option argument as a subcommand name and parses the remaining arguments according to that subcommand. Your command line users are more likely to be able to understand how to use the program if it works that way. > > Oscar. -- Benoist Laurent Laboratoire de Biochimie Theorique / CNRS UPR 9080 Institut de Biologie Physico-Chimique 13, rue Pierre et Marie Curie F-75005 Paris Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56 -------------- next part -------------- An HTML attachment was scrubbed... URL: From cyrille.leroux at gmail.com Tue Jul 31 09:36:44 2012 From: cyrille.leroux at gmail.com (cyrille.leroux at gmail.com) Date: Tue, 31 Jul 2012 06:36:44 -0700 (PDT) Subject: docx/lxml Message-ID: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> Hello, I'm trying to use the docx package to generate documents containing some text and tables. I don't want to install any module since I just want my coworkers to copy a directory and run a script, without installing tons of softwares (Just python2.7 which is already installed). First, I downloaded docx package, copied the docx directory I found. Then, I added its path (sys.path.append()) But it complained it missed a lxml package. Ok, I downloaded it, copied the lxml directory. This time, it wanted a etree.py file. I search and found it is generated during installation... But I don't want to install it ! I searched again, and found that anyway, even if I install it to get this file, it will need other libraries... At this point, I already lost too much time, so I quit. It's way too much work for what I have to do. [My questions :] - Do you know any *easy to use*, *easy to deploy* package to generate ".doc like" documents ? - Do you have any suggestion to do it differently (maybe with native packages ?) - As a python newby, I don't understand why you have to go through the pain of installing packages since they should be able to work with just the __init__.py files ? Regards, Cyrille From bouncingcats at gmail.com Tue Jul 31 09:52:12 2012 From: bouncingcats at gmail.com (David) Date: Tue, 31 Jul 2012 23:52:12 +1000 Subject: Is Python a commercial proposition ? In-Reply-To: References: <-1016624622349492799@unknownmsgid> Message-ID: On 30/07/2012, lipska the kat wrote: > On 30/07/12 14:06, Roy Smith wrote: >> >> These days, I'm working on a fairly large web application (songza.com). > > "We are very sorry to say that due to licensing constraints we cannot > allow access to Songza for listeners located outside of the United States." > > Arse :-( A free[1] US proxy could bypass[2] that page ... eg something like http://www.airproxy.ca/ [1] as in beer [2] for research purposes From andrea.crotti.0 at gmail.com Tue Jul 31 09:56:37 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Tue, 31 Jul 2012 14:56:37 +0100 Subject: Pass data to a subprocess Message-ID: I'm having fun in the world of multiprocessing, and I would like some suggestions. For example suppose I want to create many processes and pass them some data to process (also why they are running). I found many nice things (Pipe, Manager and so on), but actually even this seems to work: class MyProcess(Process): def __init__(self): Process.__init__(self) self.ls = [] def __str__(self): return str(self.ls) def add(self, ls): self.ls += ls def run(self): print("running the process in another subprocess") def procs(): mp = MyProcess() mp.start() # with the join we are actually waiting for the end of the running time mp.join() mp.add([1,2,3]) mp.add([2,3,4]) print(mp) Which is a bit surprising, because it means that I can pass data to an object that is running on another process. Is it because of some magic in the background and can I rely on that or simply I didn't understand how it works? From bahamutzero8825 at gmail.com Tue Jul 31 09:59:17 2012 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Tue, 31 Jul 2012 08:59:17 -0500 Subject: Firefox 3.6 [OT] (was: Re: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way.) In-Reply-To: <50174218$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <31A3F10D-C2A8-417E-8501-7E7364315DDD@pedrokroger.net> <5016D373.1090809@stoneleaf.us> <8A8834DA-E80E-434A-902D-25A0AA96B2E9@pedrokroger.net> <5016D94A.2020703@stoneleaf.us> <50174218$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5017E4B5.9000200@gmail.com> On 7/30/2012 9:25 PM, Steven D'Aprano wrote: > I don't. But in my experience, the risk of security breaches is *much* > less than the chance that the new version will break functionality, > introduce bugs, have a worse user interface, and generally be a step > backwards rather than forward. 4.0 sucked. It had a radically new UI and it broke heaps of add-ons and it leaked memory. 5.0 was slightly better, but still sucked because it still leaked memory. 6.0 didn't suck so much because the memory leaks were taken care of, and by this point there were extensions to deal with certain issues (like not having a place for status bar icons). By 7.0, there weren't really any more problems. By no means was the process painless, but I've found the new UI to be a bit better than the old one (at this point - not when 4.0 came out) now that the dust has settled. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 From kroger at pedrokroger.net Tue Jul 31 10:00:25 2012 From: kroger at pedrokroger.net (Pedro Kroger) Date: Tue, 31 Jul 2012 11:00:25 -0300 Subject: docx/lxml In-Reply-To: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> Message-ID: <257377AC-F74F-4D02-B90D-6D3917B89A73@pedrokroger.net> On Jul 31, 2012, at 10:36 AM, cyrille.leroux at gmail.com wrote: > - Do you know any *easy to use*, *easy to deploy* package to generate ".doc like" documents ? > - Do you have any suggestion to do it differently (maybe with native packages ?) > > - As a python newby, I don't understand why you have to go through the pain of installing packages since they should be able to work with just the __init__.py files ? > > Regards, > > Cyrille Hi, May I suggest you use pip and, possibly, virtualenv? pip makes it easy to install Python packages while virtualenv creates an isolated Python environment For instance, I just installed docx and its dependencies with: pip install docx lxml datutils PIL And I did that inside a testing virtualenv, so I wouldn't mess up my Python setup. pip and virtualenv make it really easy and painless to install Python packages. Cheers, Pedro ----- http://pedrokroger.net http://musicforgeeksandnerds.com From andrea.crotti.0 at gmail.com Tue Jul 31 10:12:22 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Tue, 31 Jul 2012 15:12:22 +0100 Subject: Pass data to a subprocess In-Reply-To: References: Message-ID: > > > def procs(): > mp = MyProcess() > # with the join we are actually waiting for the end of the running time > mp.add([1,2,3]) > mp.start() > mp.add([2,3,4]) > mp.join() > print(mp) > I think I got it now, if I already just mix the start before another add, inside the Process.run it won't see the new data that has been added after the start. So this way is perfectly safe only until the process is launched, if it's running I need to use some multiprocess-aware data structure, is that correct? From paul.nospam at rudin.co.uk Tue Jul 31 10:45:49 2012 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Tue, 31 Jul 2012 15:45:49 +0100 Subject: Search and replace text in XML file? References: <5535f70f-4542-451f-8b08-a62b45d15c11@googlegroups.com> Message-ID: <87sjc8yoo2.fsf@no-fixed-abode.cable.virginmedia.net> Terry Reedy writes: > ... a proper text-editor* > * ... Notepad++ is one such on Windows. Surely emacs is the only such on any platform? :) From gandalf at shopzeus.com Tue Jul 31 10:46:08 2012 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 31 Jul 2012 16:46:08 +0200 Subject: Pass data to a subprocess In-Reply-To: References: Message-ID: <5017EFB0.6080608@shopzeus.com> > I think I got it now, if I already just mix the start before another add, inside the Process.run it won't see the new data that has been added after the start. So this way is perfectly safe only until the process is launched, if it's running I need to use some multiprocess-aware data structure, is that correct? Yes. Read this: http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes You can use Queues and Pipes. Actually, these are basic elements of the multiprocessing module and they are well documented. I wonder if you read the documentation at all, before posting questions here. From cyrille.leroux at gmail.com Tue Jul 31 11:01:48 2012 From: cyrille.leroux at gmail.com (Cyrille Leroux) Date: Tue, 31 Jul 2012 08:01:48 -0700 (PDT) Subject: docx/lxml In-Reply-To: References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> Message-ID: <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> On Tuesday, July 31, 2012 4:00:25 PM UTC+2, Pedro Kroger wrote: > On Jul 31, 2012, at 10:36 AM, Cyrille Leroux wrote: > > > > > - Do you know any *easy to use*, *easy to deploy* package to generate ".doc like" documents ? > > > - Do you have any suggestion to do it differently (maybe with native packages ?) > > > > > > - As a python newby, I don't understand why you have to go through the pain of installing packages since they should be able to work with just the __init__.py files ? > > > > > > Regards, > > > > > > Cyrille > > > > Hi, > > > > May I suggest you use pip and, possibly, virtualenv? > > pip makes it easy to install Python packages while virtualenv creates an isolated Python environment > > > > For instance, I just installed docx and its dependencies with: > > > > pip install docx lxml datutils PIL > > > > And I did that inside a testing virtualenv, so I wouldn't mess up my Python setup. > > > > pip and virtualenv make it really easy and painless to install Python packages. > > > > Cheers, > > > > Pedro > > ----- > > http://pedrokroger.net > > http://musicforgeeksandnerds.com Thank you for your quick reply Pedro. I'm giving pip a try : 1/ Linux (debian lenny) - (as root) sh setuptools-0.6c11-py2.7.egg (ok) - (as root) cd pip-1.1 ; python setup.py install (ok) - pip : ImportError : No module named pkg_resources - damn, I guess it's going to be a pain, again - ... then I remember that anyway, I cannot access internet from my session - end of story for linux 2/ Back on Windows (7) - setuptools-0.6c11.win32-py2.7.exe (ok) - (cmd) easy_install.exe pip : AttributeError : 'NoneType' object has no attribute 'clone' Well, I think I'm starting to feel less and less enthusiastic about python... I didn't suspect it would be so difficult to write a basic doc file :) From cyrille.leroux at gmail.com Tue Jul 31 11:01:48 2012 From: cyrille.leroux at gmail.com (Cyrille Leroux) Date: Tue, 31 Jul 2012 08:01:48 -0700 (PDT) Subject: docx/lxml In-Reply-To: References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> Message-ID: <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> On Tuesday, July 31, 2012 4:00:25 PM UTC+2, Pedro Kroger wrote: > On Jul 31, 2012, at 10:36 AM, Cyrille Leroux wrote: > > > > > - Do you know any *easy to use*, *easy to deploy* package to generate ".doc like" documents ? > > > - Do you have any suggestion to do it differently (maybe with native packages ?) > > > > > > - As a python newby, I don't understand why you have to go through the pain of installing packages since they should be able to work with just the __init__.py files ? > > > > > > Regards, > > > > > > Cyrille > > > > Hi, > > > > May I suggest you use pip and, possibly, virtualenv? > > pip makes it easy to install Python packages while virtualenv creates an isolated Python environment > > > > For instance, I just installed docx and its dependencies with: > > > > pip install docx lxml datutils PIL > > > > And I did that inside a testing virtualenv, so I wouldn't mess up my Python setup. > > > > pip and virtualenv make it really easy and painless to install Python packages. > > > > Cheers, > > > > Pedro > > ----- > > http://pedrokroger.net > > http://musicforgeeksandnerds.com Thank you for your quick reply Pedro. I'm giving pip a try : 1/ Linux (debian lenny) - (as root) sh setuptools-0.6c11-py2.7.egg (ok) - (as root) cd pip-1.1 ; python setup.py install (ok) - pip : ImportError : No module named pkg_resources - damn, I guess it's going to be a pain, again - ... then I remember that anyway, I cannot access internet from my session - end of story for linux 2/ Back on Windows (7) - setuptools-0.6c11.win32-py2.7.exe (ok) - (cmd) easy_install.exe pip : AttributeError : 'NoneType' object has no attribute 'clone' Well, I think I'm starting to feel less and less enthusiastic about python... I didn't suspect it would be so difficult to write a basic doc file :) From stefan_ml at behnel.de Tue Jul 31 11:13:12 2012 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 31 Jul 2012 17:13:12 +0200 Subject: docx/lxml In-Reply-To: <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> Message-ID: Cyrille Leroux, 31.07.2012 17:01: > I'm giving pip a try : > > > 1/ Linux (debian lenny) > - (as root) sh setuptools-0.6c11-py2.7.egg (ok) > - (as root) cd pip-1.1 ; python setup.py install (ok) > - pip : ImportError : No module named pkg_resources > - damn, I guess it's going to be a pain, again > - ... then I remember that anyway, I cannot access internet from my session > - end of story for linux > > > 2/ Back on Windows (7) > > - setuptools-0.6c11.win32-py2.7.exe (ok) > - (cmd) easy_install.exe pip : AttributeError : 'NoneType' object has no attribute 'clone' > > Well, I think I'm starting to feel less and less enthusiastic about python... I didn't suspect it would be so difficult to write a basic doc file :) "pip" goes with "distribute", not "setuptools". http://packages.python.org/distribute/ Stefan From andrea.crotti.0 at gmail.com Tue Jul 31 11:26:18 2012 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Tue, 31 Jul 2012 16:26:18 +0100 Subject: Pass data to a subprocess In-Reply-To: <5017EFB0.6080608@shopzeus.com> References: <5017EFB0.6080608@shopzeus.com> Message-ID: 2012/7/31 Laszlo Nagy : >> I think I got it now, if I already just mix the start before another add, >> inside the Process.run it won't see the new data that has been added after >> the start. So this way is perfectly safe only until the process is launched, >> if it's running I need to use some multiprocess-aware data structure, is >> that correct? > > Yes. Read this: > > http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes > > You can use Queues and Pipes. Actually, these are basic elements of the > multiprocessing module and they are well documented. I wonder if you read > the documentation at all, before posting questions here. > > > -- > http://mail.python.org/mailman/listinfo/python-list As I wrote "I found many nice things (Pipe, Manager and so on), but actually even this seems to work:" yes I did read the documentation. I was just surprised that it worked better than I expected even without Pipes and Queues, but now I understand why.. Anyway now I would like to be able to detach subprocesses to avoid the nasty code reloading that I was talking about in another thread, but things get more tricky, because I can't use queues and pipes to communicate with a running process that it's noit my child, correct? From cyrille.leroux at gmail.com Tue Jul 31 11:51:04 2012 From: cyrille.leroux at gmail.com (Cyrille Leroux) Date: Tue, 31 Jul 2012 08:51:04 -0700 (PDT) Subject: docx/lxml In-Reply-To: References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> Message-ID: <5c0560ec-66ef-4be7-912a-ed648fe60af1@googlegroups.com> On Tuesday, July 31, 2012 5:13:12 PM UTC+2, Stefan Behnel wrote: > Cyrille Leroux, 31.07.2012 17:01: > > > I'm giving pip a try : > > > > > > > > > 1/ Linux (debian lenny) > > > - (as root) sh setuptools-0.6c11-py2.7.egg (ok) > > > - (as root) cd pip-1.1 ; python setup.py install (ok) > > > - pip : ImportError : No module named pkg_resources > > > - damn, I guess it's going to be a pain, again > > > - ... then I remember that anyway, I cannot access internet from my session > > > - end of story for linux > > > > > > > > > 2/ Back on Windows (7) > > > > > > - setuptools-0.6c11.win32-py2.7.exe (ok) > > > - (cmd) easy_install.exe pip : AttributeError : 'NoneType' object has no attribute 'clone' > > > > > > Well, I think I'm starting to feel less and less enthusiastic about python... I didn't suspect it would be so difficult to write a basic doc file :) > > > > "pip" goes with "distribute", not "setuptools". > > > > http://packages.python.org/distribute/ > > > > Stefan Ok, I will try it next time then, thank you. In the end, I found a way around. I generated an html file, then, converted it to a doc file. From cyrille.leroux at gmail.com Tue Jul 31 11:51:04 2012 From: cyrille.leroux at gmail.com (Cyrille Leroux) Date: Tue, 31 Jul 2012 08:51:04 -0700 (PDT) Subject: docx/lxml In-Reply-To: References: <40113c57-5978-45a2-b695-8917706fd268@googlegroups.com> <704bbd5d-38fd-4e8d-884b-d09197125c85@googlegroups.com> Message-ID: <5c0560ec-66ef-4be7-912a-ed648fe60af1@googlegroups.com> On Tuesday, July 31, 2012 5:13:12 PM UTC+2, Stefan Behnel wrote: > Cyrille Leroux, 31.07.2012 17:01: > > > I'm giving pip a try : > > > > > > > > > 1/ Linux (debian lenny) > > > - (as root) sh setuptools-0.6c11-py2.7.egg (ok) > > > - (as root) cd pip-1.1 ; python setup.py install (ok) > > > - pip : ImportError : No module named pkg_resources > > > - damn, I guess it's going to be a pain, again > > > - ... then I remember that anyway, I cannot access internet from my session > > > - end of story for linux > > > > > > > > > 2/ Back on Windows (7) > > > > > > - setuptools-0.6c11.win32-py2.7.exe (ok) > > > - (cmd) easy_install.exe pip : AttributeError : 'NoneType' object has no attribute 'clone' > > > > > > Well, I think I'm starting to feel less and less enthusiastic about python... I didn't suspect it would be so difficult to write a basic doc file :) > > > > "pip" goes with "distribute", not "setuptools". > > > > http://packages.python.org/distribute/ > > > > Stefan Ok, I will try it next time then, thank you. In the end, I found a way around. I generated an html file, then, converted it to a doc file. From bigblueswope at gmail.com Tue Jul 31 12:14:38 2012 From: bigblueswope at gmail.com (BJ Swope) Date: Tue, 31 Jul 2012 12:14:38 -0400 Subject: my email In-Reply-To: <1342866979.8152.YahooMailNeo@web193102.mail.sg3.yahoo.com> References: <1342575898.38612.YahooMailNeo@web193103.mail.sg3.yahoo.com> <50061A89.9090200@mrabarnett.plus.com> <1342866979.8152.YahooMailNeo@web193102.mail.sg3.yahoo.com> Message-ID: I would also recommend changing your birthday as well ;) -- "The end of democracy and the defeat of the American Revolution will occur when government falls into the hands of lending institutions and moneyed incorporations." -- Thomas Jefferson The whole world is a comedy to those that think, a tragedy to those that feel. ---Horace Walpole On Sat, Jul 21, 2012 at 6:36 AM, Maria Hanna Carmela Dionisio < mmdionisio1993 at yahoo.com.ph> wrote: > lolz sorry i already change it..just a newbhie, that's why :Dv > ------------------------------ > *From:* MRAB > *To:* python-list at python.org > *Sent:* Wednesday, July 18, 2012 10:08 AM > *Subject:* Re: my email > > On 18/07/2012 02:44, Maria Hanna Carmela Dionisio wrote: > > mmdionisio1993 at yahoo.com.ph > > > > Just a newbhie here :> > > > ...who has just revealed her password! > > [remainder snipped] > -- > http://mail.python.org/mailman/listinfo/python-list > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lipska at yahoo.co.uk Tue Jul 31 13:27:10 2012 From: lipska at yahoo.co.uk (lipska the kat) Date: Tue, 31 Jul 2012 18:27:10 +0100 Subject: Is Python a commercial proposition ? In-Reply-To: References: <-1016624622349492799@unknownmsgid> Message-ID: On 31/07/12 14:52, David wrote: > On 30/07/2012, lipska the kat wrote: >> On 30/07/12 14:06, Roy Smith wrote: >>> >>> These days, I'm working on a fairly large web application (songza.com). >> >> "We are very sorry to say that due to licensing constraints we cannot >> allow access to Songza for listeners located outside of the United States." >> >> Arse :-( > > A free[1] US proxy could bypass[2] that page ... eg something like > http://www.airproxy.ca/ > > [1] as in beer > [2] for research purposes Oooooh that's a bit good isn't it, just for research purposes of course. There's one (as in 1 above) in the pump for you. lipska -- Lipska the Kat: Troll hunter, sandbox destroyer and farscape dreamer of Aeryn Sun From dihedral88888 at googlemail.com Tue Jul 31 15:01:38 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 31 Jul 2012 12:01:38 -0700 (PDT) Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: <92ca88a5-5633-469d-8752-09c6350651ab@googlegroups.com> Mark Lawrence? 2012?7?31????UTC+8??3?15?32???? > On 31/07/2012 02:20, Dennis Lee Bieber wrote: > > > On Mon, 30 Jul 2012 22:56:48 +0000, Dan Stromberg > > > declaimed the following in gmane.comp.python.general: > > > > > > > > >> Sigh, and I'm also not keen on multi-line list comprehensions, specifically > > >> because I think they tend to make less readable code. It also becomes a > > >> mess when you need to insert print statements to get some visibility into > > >> what's going on. > > > > > > Cleanly splitting the list-comp by > > > > > > [ result-computation > > > for-item-selection-clause > > > if-filter-clause ] > > > > > > isn't that unreadable... But anyone doing > > > > > > [ result- > > > -computation for-item- > > > -selection-clause if- > > > -filter- > > > -clause ] > > > > > > should be pecked to death by a dead parrot. > > > > > > > Any particular species? > > > > -- > > Cheers. > > > > Mark Lawrence. For each item in the known list that passes the required conditional test, then use the item to perform the tasks desired as instructed. It is not necessary that a new list has to be constructed in the tasks. A method which can produce a new object always involves some memory management. Therefore, some error handling part should not be missing. From dihedral88888 at googlemail.com Tue Jul 31 15:01:38 2012 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 31 Jul 2012 12:01:38 -0700 (PDT) Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: <92ca88a5-5633-469d-8752-09c6350651ab@googlegroups.com> Mark Lawrence? 2012?7?31????UTC+8??3?15?32???? > On 31/07/2012 02:20, Dennis Lee Bieber wrote: > > > On Mon, 30 Jul 2012 22:56:48 +0000, Dan Stromberg > > > declaimed the following in gmane.comp.python.general: > > > > > > > > >> Sigh, and I'm also not keen on multi-line list comprehensions, specifically > > >> because I think they tend to make less readable code. It also becomes a > > >> mess when you need to insert print statements to get some visibility into > > >> what's going on. > > > > > > Cleanly splitting the list-comp by > > > > > > [ result-computation > > > for-item-selection-clause > > > if-filter-clause ] > > > > > > isn't that unreadable... But anyone doing > > > > > > [ result- > > > -computation for-item- > > > -selection-clause if- > > > -filter- > > > -clause ] > > > > > > should be pecked to death by a dead parrot. > > > > > > > Any particular species? > > > > -- > > Cheers. > > > > Mark Lawrence. For each item in the known list that passes the required conditional test, then use the item to perform the tasks desired as instructed. It is not necessary that a new list has to be constructed in the tasks. A method which can produce a new object always involves some memory management. Therefore, some error handling part should not be missing. From tjreedy at udel.edu Tue Jul 31 16:21:22 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Jul 2012 16:21:22 -0400 Subject: NameError vs AttributeError In-Reply-To: References: Message-ID: On 7/31/2012 6:36 AM, Ulrich Eckhardt wrote: > Hi! > > Using Python 2.7, I stumbled across the fact that 'self.xy' raises an > AttributeError if self doesn't have an 'xy' as attribute, but 'xy' will > instead raise a NameError. To some extent, these two are very similar, > namely that the name 'xy' couldn't be resolved in a certain context, but > they don't have a common baseclass. You have observed a true fact. The two errors both involve non-reconition of identifiers. In most cases, the identifiers are looked-up in a dict. > I guess one of the reasons is behind the way that Python handles > variable lookup, the plain 'xy' will find local and global names while > 'self.xy' will only look into onself. However, this vague idea is far > from enough to explain it to someone else. > > Can someone help me out? 1. Why two separate exceptions: a) operational: two separate exceptions are possible. Name lookup and attribute lookup goes thru separate machinery. Name lookup may go thru local, nonlocal, global (modular) and builtin namespaces. Attribute lookup goes thru instance, class, and superclasses to object. Name lookup is fixed except for nonlocal and global declarations local assignments. Attribute lookup can be over-riden with special methods (and special method lookup skips the instance). b) practical: two separate exceptions are desirable. One catches an exception to do something in the except clause. Name and attribute errors often have different causes and different associated actions. def empty_and_process(poppable, process): try: pop = popable.pop except AttributeError: raise AttributeError("Can only empty_and_process objects with .pop method") Whoops, programming typo raises NameError. It should *not* be caught, rather bug should be fixed. Later usage error gets AttributeError, possibly documented. User decides whether it represents a bug to be fixed (the default) or a control signal to be caught and processed. If one really does want the same action for the different mistakes, "except (NameError, AttributeError):" is easy enough to write. 2. Why no special base exception (NameAttrError ?). Python exceptions started as strings with NO hierarchy. The current class system is still relatively flat. Flat is better than nested because nesting introduces a new entities and new entities should not be introduced without sufficient purpose and each one makes the whole harder to learn and remember. I suspect that if you grepped a large Python code corpus for this particular pair in except statements you would find it rare. --- Another example: KeyError and IndexError are both subscript errors, but there is no SubscriptError superclass, even though both work thru the same mechanism -- __getitem__. The reason is that there is no need for one. In 'x[y]', x is usually intented to be either a sequence or mapping, but not possibly both. In the rare cases when one wants to catch both errors, one can easily enough. To continue the example above, popping an empty list and empty set produce IndexError and KeyError respectively: try: while True: process(pop()) except (KeyError, IndexError): pass # empty collection means we are done -- Terry Jan Reedy From ckaynor at zindagigames.com Tue Jul 31 16:49:25 2012 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Tue, 31 Jul 2012 13:49:25 -0700 Subject: NameError vs AttributeError In-Reply-To: References: Message-ID: On Tue, Jul 31, 2012 at 1:21 PM, Terry Reedy wrote: > Another example: KeyError and IndexError are both subscript errors, but > there is no SubscriptError superclass, even though both work thru the same > mechanism -- __getitem__. The reason is that there is no need for one. In > 'x[y]', x is usually intented to be either a sequence or mapping, but not > possibly both. In the rare cases when one wants to catch both errors, one > can easily enough. To continue the example above, popping an empty list and > empty set produce IndexError and KeyError respectively: > > try: > while True: > process(pop()) > except (KeyError, IndexError): > pass # empty collection means we are done There is a base type for KeyError and IndexError: LookupError. http://docs.python.org/library/exceptions.html#exception-hierarchy > > > -- > Terry Jan Reedy > > > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Jul 31 17:04:44 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Jul 2012 17:04:44 -0400 Subject: Why 'Flat is better than nested' Message-ID: >>> import this prints 'The Zen of Python', a poem by Tim Peters that consists of python proverbs such as "Flat is better than nested." (Others things being equal) why? Because it is a restatement of the principle of parsimony, of not multiplying entities without necessity. Suppose we have a unstructured collection of N items. Organizer comes along and says 'Let there be structure. Let us organize the items as leaf nodes in a hierarchical tree' (which is equivalent to nesting). To do so, we can add as many as N-1 new non-leaf nodes and as many as (about) 2*N - log2(N) parent child relationships. In other words, nearly quadruple the number of entities to learn, discuss, and remember. Well, there had better be a good necessity to do so ;-). And, of course, once new entities *are* conjured up, it is hard to get rid of them. -- Terry Jan Reedy From iftecan2000 at gmail.com Tue Jul 31 17:28:03 2012 From: iftecan2000 at gmail.com (Ifthikhan Nazeem) Date: Tue, 31 Jul 2012 23:28:03 +0200 Subject: Why 'Flat is better than nested' In-Reply-To: References: Message-ID: *as many as (about) 2*N - log2(N) parent child relationships* * * I would like to know how did you come up with the above formula? Forgive my ignorance. -- Thanks and Best Regards, Iftikhan Nazeem *Skype* : iftecan2000 On Tue, Jul 31, 2012 at 11:04 PM, Terry Reedy wrote: > >>> import this > > prints 'The Zen of Python', a poem by Tim Peters that consists of python > proverbs such as "Flat is better than nested." (Others things being equal) > why? Because it is a restatement of the principle of parsimony, of not > multiplying entities without necessity. > > Suppose we have a unstructured collection of N items. Organizer comes > along and says 'Let there be structure. Let us organize the items as leaf > nodes in a hierarchical tree' (which is equivalent to nesting). To do so, > we can add as many as N-1 new non-leaf nodes and as many as (about) 2*N - > log2(N) parent child relationships. In other words, nearly quadruple the > number of entities to learn, discuss, and remember. Well, there had better > be a good necessity to do so ;-). > > And, of course, once new entities *are* conjured up, it is hard to get rid > of them. > > -- > Terry Jan Reedy > > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Jul 31 17:49:05 2012 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 31 Jul 2012 15:49:05 -0600 Subject: Why 'Flat is better than nested' In-Reply-To: References: Message-ID: On Tue, Jul 31, 2012 at 3:28 PM, Ifthikhan Nazeem wrote: > as many as (about) 2*N - log2(N) parent child relationships > > I would like to know how did you come up with the above formula? Forgive my > ignorance. I come up with 2N - 2 myself. If there are N leaf nodes and N - 1 non-leaf nodes, then there are 2N - 1 total nodes, each of which has one parent except for the root. That's 2N - 2 parent-child relationships. From rosuav at gmail.com Tue Jul 31 18:15:57 2012 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 1 Aug 2012 08:15:57 +1000 Subject: simplified Python parsing question In-Reply-To: <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <5015C58D.4040101@harvee.org> <50165308.5060708@shopzeus.com> <50165A94.5050906@harvee.org> <5016A140.7010106@shopzeus.com> <50173aea$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Jul 31, 2012 at 11:54 AM, Steven D'Aprano wrote: > Google Docs is, in my opinion, a nasty piece of rubbish > that doesn't run on any of my browsers. As far as I'm concerned, I'd > rather download a Word doc, because at least I can open that in > OpenOffice or Abiword and read it. Something in Google Docs might as well > be locked in a safe as far as I'm concerned. I go the opposite way. Google Docs works fine in my web browser, but if it's a Word doc, I need to hunt down something that can read it. I've yet to find any browser that can't handle a GDocs "publish" page, but I have plenty of computers that don't have any {Open|Libre|Liber|Libra|whatever the next generation is}-Office installed. Best is to put the information into your email/post. Next best is to have a link to the information. Definitely worst is to force people to download your file and try to read it. ChrisA From barry at barrys-emacs.org Tue Jul 31 18:36:24 2012 From: barry at barrys-emacs.org (Barry Scott) Date: Tue, 31 Jul 2012 23:36:24 +0100 Subject: Linux shell to python In-Reply-To: References: <1343631941.7199.YahooMailNeo@web193104.mail.sg3.yahoo.com> <1826E39D-43C1-4CEB-AEA2-133B95AC0B0B@barrys-emacs.org> Message-ID: <3D06A099-1B06-4B16-A1C1-B9C0624B55D3@barrys-emacs.org> On 30 Jul 2012, at 23:56, Dan Stromberg wrote: > > On Mon, Jul 30, 2012 at 9:26 PM, Barry Scott wrote: > lspci gets all its information from the files in /sys/bus/pci/devices. > > You can use os.listdir() to list all the files in the folder and then open > the files you want to get the data you need. > Gee, wouldn't it be more portable to parse lspci? I wouldn't put it past the (Linux) kernel devs to move the pseudo-filesystems around again... No. The app is less stable the the linux user api gureentee. I have been bitten with app output format changes but the /sys files have been Reliable and far better focused at answering questions. > > And of course you can write list comprehensions on as many lines as > it take to make the code maintainable. > Sigh, and I'm also not keen on multi-line list comprehensions, specifically because I think they tend to make less readable code. It also becomes a mess when you need to insert print statements to get some visibility into what's going on. > With out trading examples of production code this is resolverable. Barry -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncingcats at gmail.com Tue Jul 31 19:31:43 2012 From: bouncingcats at gmail.com (David) Date: Wed, 1 Aug 2012 09:31:43 +1000 Subject: Is Python a commercial proposition ? In-Reply-To: References: <-1016624622349492799@unknownmsgid> Message-ID: On 01/08/2012, lipska the kat wrote: > On 31/07/12 14:52, David wrote: >> >> [1] as in beer >> [2] for research purposes > > There's one (as in 1 above) in the pump for you. Great, more beer => better research => \o/\o/\o/ But, "pump" sounds a bit extreme .. I usually sip contentedly from a glass :p From tjreedy at udel.edu Tue Jul 31 19:57:24 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Jul 2012 19:57:24 -0400 Subject: Why 'Flat is better than nested' In-Reply-To: References: Message-ID: On 7/31/2012 5:49 PM, Ian Kelly wrote: > On Tue, Jul 31, 2012 at 3:28 PM, Ifthikhan Nazeem wrote: >> as many as (about) 2*N - log2(N) parent child relationships >> >> I would like to know how did you come up with the above formula? Forgive my >> ignorance. By non-rigorous experimentation, which did not quite count everything. > I come up with 2N - 2 myself. If there are N leaf nodes and N - 1 > non-leaf nodes, then there are 2N - 1 total nodes, each of which has > one parent except for the root. That's 2N - 2 parent-child > relationships. That looks right. I was trying to think recursively, which in this case is more rather than less complicated. That actually sharpens my original point. N-1 new nodes and 2N-2 new relationships is 3N-3 new entities. The internal node limit of N-1 only applies to full-proper-strict binary trees without one-child internal nodes. Otherwise, a single leaf node could have an indefinite number of ancestors. from https://en.wikipedia.org/wiki/Binary_tree "A full binary tree (sometimes proper binary tree or 2-tree or strictly binary tree) is a tree in which every node other than the leaves has two children." -- Terry Jan Reedy From tjreedy at udel.edu Tue Jul 31 20:14:01 2012 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 31 Jul 2012 20:14:01 -0400 Subject: NameError vs AttributeError In-Reply-To: References: Message-ID: On 7/31/2012 4:49 PM, Chris Kaynor wrote: > On Tue, Jul 31, 2012 at 1:21 PM, Terry Reedy > wrote: > > Another example: KeyError and IndexError are both subscript errors, > but there is no SubscriptError superclass, even though both work > thru the same mechanism -- __getitem__. The reason is that there is > no need for one. In 'x[y]', x is usually intented to be either a > sequence or mapping, but not possibly both. In the rare cases when > one wants to catch both errors, one can easily enough. To continue > the example above, popping an empty list and empty set produce > IndexError and KeyError respectively: > > try: > while True: > process(pop()) > except (KeyError, IndexError): > pass # empty collection means we are done > > There is a base type for KeyError and IndexError: LookupError. > > http://docs.python.org/library/exceptions.html#exception-hierarchy Oh, so there is. Added in 1.5 strictly as a never-directly-raised base class for the above pair, now also directly raised in codecs.lookup. I have not decided if I want to replace the tuple in the code in my book. -- Terry Jan Reedy From dregister at clear.net Tue Jul 31 20:48:55 2012 From: dregister at clear.net (Damon Register) Date: Tue, 31 Jul 2012 20:48:55 -0400 Subject: missing python-config and building python on Windows Message-ID: <50187CF7.3080706@clear.net> I am attempting to build gtk and glade using mingw/msys. It seems that some of the packages require python. I installed 2.7.3 using the installer from python.org. That worked for some of the packages but now I am trying to do one that needs python-config which I don't find in the installation directory. I tried building from source using mingw/msys but that had too many problems so I gave up on that. I thought I might try building with MSVC 2010 since it appears to be supported and I have that at work. There are a few problems with this: 1. though I have looked in a few readme files, I don't see instructions for installing what I have just built using MSVC. Where can I find the instructions for installing after building with MSVC? 2. I have searched the project directory but I don't find python-config. Is this some sort of optional thing that isn't built by default? I tried searching this list and although I find a few questions about it, I don't see an answer to where I can find it. 3. It seems that MSVC doesn't produce the .a library files needed for linking into a mingw built program. Do I have to do that fun trick to create the .a from the dll? Damon Register From peter at www.pjb.com.au Tue Jul 31 23:19:22 2012 From: peter at www.pjb.com.au (Peter Billam) Date: 01 Aug 2012 03:19:22 GMT Subject: [ANN] pyknon: Simple Python library to generate music in a hacker friendly way. References: Message-ID: On 2012-07-30, Pedro Kroger wrote: > Pyknon is a simple music library for Python hackers. With Pyknon > you can generate Midi files quickly and reason about musical > proprieties. It works with Python 2.7 and 3.2. > ... a basic example to create 4 notes and save into a MIDI file: > from pyknon.genmidi import Midi > from pyknon.music import NoteSeq > notes1 = NoteSeq("D4 F#8 A Bb4") > midi = Midi(1, tempo=90) > midi.seq_notes(notes1, track=0) > midi.write("demo.mid") > It's available on PyPI and its homepage is > http://kroger.github.com/pyknon/ > Pedro > http://pedrokroger.net http://musicforgeeksandnerds.com I'll check it out. It probably fits into a whole software ecosystem that you're putting together ... It's a crowded area, e.g. my midi stuff is at: http://www.pjb.com.au/midi/index.html and I'd probably do the above example by: ~> muscript -midi <demo.mid | 3/4 2.0 =1 treble 4 D 8 [F# A] 4 Bb EOT see: http://www.pjb.com.au/muscript/index.html but also relevant would be my MIDI.py, see: http://www.pjb.com.au/midi/MIDI.html which is also available in call-compatible Lua version: http://www.pjb.com.au/comp/lua/MIDI.html and is closely related to the Perl CPAN module. You could consider posting Pyknon to comp.music.midi ; it's very low traffic, but some real gurus lurk there. All the best with your music, Peter -- Peter Billam www.pjb.com.au www.pjb.com.au/comp/contact.html From skippy.hammond at gmail.com Tue Jul 31 23:49:41 2012 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 01 Aug 2012 13:49:41 +1000 Subject: missing python-config and building python on Windows In-Reply-To: <50187CF7.3080706@clear.net> References: <50187CF7.3080706@clear.net> Message-ID: <5018A755.60609@gmail.com> On 1/08/2012 10:48 AM, Damon Register wrote: > I am attempting to build gtk and glade using mingw/msys. It seems that > some > of the packages require python. I installed 2.7.3 using the installer from > python.org. That worked for some of the packages but now I am trying to do > one that needs python-config which I don't find in the installation > directory. > > I tried building from source using mingw/msys but that had too many > problems > so I gave up on that. I thought I might try building with MSVC 2010 since > it appears to be supported and I have that at work. There are a few > problems > with this: > 1. though I have looked in a few readme files, I don't see instructions for > installing what I have just built using MSVC. Where can I find the > instructions for installing after building with MSVC? There is no such process. In general, you can just run directly from the built tree. > 2. I have searched the project directory but I don't find > python-config. Is > this some sort of optional thing that isn't built by default? I tried > searching this list and although I find a few questions about it, I > don't > see an answer to where I can find it. I'm afraid I don't know what python-config is. It appears it might be a reflection of how Python was configured and build on *nix systems - if that is the case then it is expected that one does not exist for Windows (as it doesn't use the *nix build chain). > 3. It seems that MSVC doesn't produce the .a library files needed for > linking > into a mingw built program. Do I have to do that fun trick to > create the > .a from the dll? I'm surprised MSVC *can* build .a files for mingw - but AFAIK, even if MSVC could do that, I believe Python makes no attempt to build with support for linking into mingw programs. Mark