From steve+comp.lang.python at pearwood.info Sat Feb 1 00:23:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Feb 2014 05:23:08 GMT Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> Message-ID: <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> On Fri, 31 Jan 2014 22:16:59 -0500, Terry Reedy wrote: > Creating a painting on canvas has two similar phases. Prepare a generic > blank canvas stretched on a frame and coated with a white undercoat. > Paint a particular picture. Would you say that the second step is not > creating anything? A dubious analogy, since there are artists who would say that attacking the canvas with a knife and setting the remains on fire count as a form of artistic creation :-) "Creation" can mean various things in English. One might argue that the only creation was the guy at the factory who made the canvas, and the people who made the paints. After that comes the preparation stage, followed by the splashing-paint-on-canvas stage. If you want to use "creating" to refer to the splashing-paint stage, then I think the closest analogy in Python is the stuff which happens *after* __init__ is called. Using a class often means modifying it as you go (in much the same way that using a canvas requires modifying it as you go), and it's never *completely* prepared until just before you stop using it. One adds data, modifies the data, moves data from one attribute to another, sets up temporary data attributes, calls methods which modify the instance, and finally get the final answer you want, at which point your task is done and the instance is thrown away. Think of a dict: d = {} # Dict is constructed. for key in data: key = process(key) if condition(): d[key] = something(key) Is all that work also not part of the object construction process? If we write it like this: d = dict(something(key) for key in map(process, data) if condition()) you'd probably call it the constructor. But the two bits of code do the same thing. While we talk about a constructor as if the process of constructing an object was black and white with a clear and obvious dividing line, in practice its often fuzzy, with a lot of grey. (That's one of the objections the functional crowd has with mutable objects.) So to answer your question: no, in context of programming, I would *not* call the putting-paint-to-canvas stage of artist painting to be "creation". I would call it *using* the constructed object (the canvas). Whether that *use* of the canvas happens to be *artistic* creation or mere derivative pap is another story :-) -- Steven From roy at panix.com Sat Feb 1 00:25:04 2014 From: roy at panix.com (Roy Smith) Date: Sat, 01 Feb 2014 00:25:04 -0500 Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <52ec84bc$0$29972$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 31 Jan 2014 22:16:59 -0500, Terry Reedy wrote: > > > Creating a painting on canvas has two similar phases. Prepare a generic > > blank canvas stretched on a frame and coated with a white undercoat. > > Paint a particular picture. Would you say that the second step is not > > creating anything? > > A dubious analogy, since there are artists who would say that attacking > the canvas with a knife and setting the remains on fire count as a form > of artistic creation :-) That's __del__() From rustompmody at gmail.com Sat Feb 1 00:31:31 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 31 Jan 2014 21:31:31 -0800 (PST) Subject: __init__ is the initialiser In-Reply-To: <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <74e0f440-d9ed-4530-8561-3b9444714bbc@googlegroups.com> On Saturday, February 1, 2014 10:53:08 AM UTC+5:30, Steven D'Aprano wrote: > On Fri, 31 Jan 2014 22:16:59 -0500, Terry Reedy wrote: > > Creating a painting on canvas has two similar phases. Prepare a generic > > blank canvas stretched on a frame and coated with a white undercoat. > > Paint a particular picture. Would you say that the second step is not > > creating anything? > A dubious analogy, since there are artists who would say that attacking > the canvas with a knife and setting the remains on fire count as a form > of artistic creation :-) > "Creation" can mean various things in English. One might argue that the > only creation was the guy at the factory who made the canvas, and the > people who made the paints. After that comes the preparation stage, > followed by the splashing-paint-on-canvas stage. > If you want to use "creating" to refer to the splashing-paint stage, then > I think the closest analogy in Python is the stuff which happens *after* > __init__ is called. Using a class often means modifying it as you go (in > much the same way that using a canvas requires modifying it as you go), > and it's never *completely* prepared until just before you stop using it. > One adds data, modifies the data, moves data from one attribute to > another, sets up temporary data attributes, calls methods which modify > the instance, and finally get the final answer you want, at which point > your task is done and the instance is thrown away. Think of a dict: > d = {} # Dict is constructed. > for key in data: > key = process(key) > if condition(): > d[key] = something(key) > Is all that work also not part of the object construction process? If we > write it like this: > d = dict(something(key) for key in map(process, data) if condition()) > you'd probably call it the constructor. But the two bits of code do the > same thing. > While we talk about a constructor as if the process of constructing an > object was black and white with a clear and obvious dividing line, in > practice its often fuzzy, with a lot of grey. (That's one of the > objections the functional crowd has with mutable objects.) > So to answer your question: no, in context of programming, I would *not* > call the putting-paint-to-canvas stage of artist painting to be > "creation". I would call it *using* the constructed object (the canvas). > Whether that *use* of the canvas happens to be *artistic* creation or > mere derivative pap is another story :-) http://en.wikipedia.org/wiki/Four_causes [Replace cause by create(ion) ] From swdunning at cox.net Sat Feb 1 00:04:07 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 31 Jan 2014 22:04:07 -0700 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: Ok cool, thanks Denis! On Jan 31, 2014, at 8:02 PM, Denis McMahon wrote: > On Thu, 30 Jan 2014 21:12:19 -0800, scottwd80 wrote: > >> Here is the question that was asked and below that I'll paste the code I >> have so far. > > The following is a reasonably but not highly obfuscated short solution to > the problem set in python 2.7. With a bit of luck, after each lesson of > your course, you'll be able to understand a bit more of how it works. > > M=60;H=M*60 > def s(h,m,s): return h*H+m*M+s > def hms(s): return (int(s/H),int((s%H)/M),s%M) > (a,b,c)=hms(s(6,52,0)+3*s(0,7,12)+2*s(0,8,15)) > print "{:02d}:{:02d}:{:02d}".format(a,b,c) > > When you can write a short paragraph describing what each line of the > program does, you'll be on your way to understanding a few of the > structures, syntaxes and mechanisms of python. > > Or you could show it to your lecturer or a TA and say it was suggested > that you ask her or him to work through it with you. > > -- > Denis McMahon, denismfmcmahon at gmail.com > -- > https://mail.python.org/mailman/listinfo/python-list From swdunning at cox.net Sat Feb 1 00:18:34 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 31 Jan 2014 22:18:34 -0700 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: Any chance you guys could help with another question I have? Below is a code to a different problem. The only thing I don?t understand is why when calculating the 'discounted price? you have to subtract 1? Thanks again guys! price_per_book = 24.95 discount = .40 quantity = 60 discounted_price = (1-discount) * price_per_book shipping = 3.0 + (60 - 1) * .75 total_price = 60 * discounted_price + shipping print total_price, 'Total price' Scott On Jan 31, 2014, at 8:02 PM, Denis McMahon wrote: > On Thu, 30 Jan 2014 21:12:19 -0800, scottwd80 wrote: > >> Here is the question that was asked and below that I'll paste the code I >> have so far. > > The following is a reasonably but not highly obfuscated short solution to > the problem set in python 2.7. With a bit of luck, after each lesson of > your course, you'll be able to understand a bit more of how it works. > > M=60;H=M*60 > def s(h,m,s): return h*H+m*M+s > def hms(s): return (int(s/H),int((s%H)/M),s%M) > (a,b,c)=hms(s(6,52,0)+3*s(0,7,12)+2*s(0,8,15)) > print "{:02d}:{:02d}:{:02d}".format(a,b,c) > > When you can write a short paragraph describing what each line of the > program does, you'll be on your way to understanding a few of the > structures, syntaxes and mechanisms of python. > > Or you could show it to your lecturer or a TA and say it was suggested > that you ask her or him to work through it with you. > > -- > Denis McMahon, denismfmcmahon at gmail.com > -- > https://mail.python.org/mailman/listinfo/python-list From swdunning at cox.net Sat Feb 1 00:19:24 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 31 Jan 2014 22:19:24 -0700 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: If you?re interested in what the problem is here it is? Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? On Jan 31, 2014, at 10:18 PM, Scott W Dunning wrote: > Any chance you guys could help with another question I have? Below is a code to a different problem. The only thing I don?t understand is why when calculating the 'discounted price? you have to subtract 1? Thanks again guys! > > price_per_book = 24.95 > discount = .40 > quantity = 60 > discounted_price = (1-discount) * price_per_book > shipping = 3.0 + (60 - 1) * .75 > total_price = 60 * discounted_price + shipping > print total_price, 'Total price' > > Scott > > > > On Jan 31, 2014, at 8:02 PM, Denis McMahon wrote: > >> On Thu, 30 Jan 2014 21:12:19 -0800, scottwd80 wrote: >> >>> Here is the question that was asked and below that I'll paste the code I >>> have so far. >> >> The following is a reasonably but not highly obfuscated short solution to >> the problem set in python 2.7. With a bit of luck, after each lesson of >> your course, you'll be able to understand a bit more of how it works. >> >> M=60;H=M*60 >> def s(h,m,s): return h*H+m*M+s >> def hms(s): return (int(s/H),int((s%H)/M),s%M) >> (a,b,c)=hms(s(6,52,0)+3*s(0,7,12)+2*s(0,8,15)) >> print "{:02d}:{:02d}:{:02d}".format(a,b,c) >> >> When you can write a short paragraph describing what each line of the >> program does, you'll be on your way to understanding a few of the >> structures, syntaxes and mechanisms of python. >> >> Or you could show it to your lecturer or a TA and say it was suggested >> that you ask her or him to work through it with you. >> >> -- >> Denis McMahon, denismfmcmahon at gmail.com >> -- >> https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Feb 1 00:44:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Feb 2014 00:44:22 -0500 Subject: Python shell wont open idle or an exisiting py file In-Reply-To: References: <24EAA33389A147D8BC08B029E2209E16@UserPC> Message-ID: On 1/31/2014 8:52 PM, Chris Angelico wrote: > On Sat, Feb 1, 2014 at 12:45 PM, Terry Reedy wrote: >> H:\HP_Documents\0PythonWork\AirplaneKinematics\accel2.py >> caused this message >> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 14: >> invalid start byte > > So... something's interpreting \0 as codepoint U+0000 (which it > shouldn't), storing that in "UTF-8" as 0xC0 0x80 (which it shouldn't), > and then giving it to Python to decode. Right. Which is why it puzzled me. Credit Serhiy for unraveling this and fixing it. > That's a weird little combination bug right there. Which started with Microsoft's decision to reuse the string excape character '\' as a directory separator. -- Terry Jan Reedy From tjreedy at udel.edu Sat Feb 1 00:46:32 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Feb 2014 00:46:32 -0500 Subject: Python shell wont open idle or an exisiting py file In-Reply-To: References: <24EAA33389A147D8BC08B029E2209E16@UserPC> <52EC61FF.4060204@mrabarnett.plus.com> Message-ID: On 1/31/2014 10:36 PM, Chris Angelico wrote: > On Sat, Feb 1, 2014 at 1:54 PM, MRAB wrote: >> I think that some years ago I heard about a variation on UTF-8 >> (Microsoft?) where codepoint U+0000 is encoded as 0xC0 0x80 so that the >> null byte can be used as the string terminator. >> >> I had a look on Wikipedia found this: >> >> http://en.wikipedia.org/wiki/Null-terminated_string > > Yeah, it's a common abuse of UTF-8. It's a violation of spec, but an > understandable one. However, I don't understand why the first part - > why should \0 become U+0000 but (presumably) the \a later on > (...cs\accel...) doesn't become U+0007, etc? Because only \0 has a special meaning in a C string, and Tk is written in C and uses C strings. -- Terry Jan Reedy From ayushidalmia2604 at gmail.com Sat Feb 1 00:50:21 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Fri, 31 Jan 2014 21:50:21 -0800 (PST) Subject: fseek In Compressed Files In-Reply-To: References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> Message-ID: <06185e63-7f49-48b6-a86e-bfa96ed84248@googlegroups.com> On Thursday, January 30, 2014 9:51:28 PM UTC+5:30, Peter Otten wrote: > Serhiy Storchaka wrote: > > > > > 30.01.14 13:28, Peter Otten ???????(??): > > >> Ayushi Dalmia wrote: > > >> > > >>> I need to randomly access a bzip2 or gzip file. How can I set the offset > > >>> for a line and later retreive the line from the file using the offset. > > >>> Pointers in this direction will help. > > >> > > >> with gzip.open(filename) as f: > > >> f.seek(some_pos) > > >> print(f.readline()) > > >> f.seek(some_pos) > > >> print(f.readline()) > > >> > > >> seems to work as expected. Can you tell a bit more about your usecase (if > > >> it isn't covered by that basic example)? > > > > > > I don't recommend to seek backward in compressed file. This is very > > > inefficient operation. > > > > Do you know an efficient way to implement random access for a bzip2 or gzip > > file? Nothing that I know of. From steve+comp.lang.python at pearwood.info Sat Feb 1 00:51:14 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Feb 2014 05:51:14 GMT Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ec8b51$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Feb 2014 15:35:17 +1100, Chris Angelico wrote: > On Sat, Feb 1, 2014 at 2:42 PM, Steven D'Aprano > wrote: >> I've met people who have difficulty with OOP principles, at least at >> first. But once you understand the idea of objects, it isn't that hard >> to understand the idea that: >> >> - first, the object has to be created, or constructed, or allocated >> if you will; >> >> - only then can it be initialised. >> >> Thus, two methods. __new__ constructs (creates, allocates) a new >> object; __init__ initialises it after the event. > > Yes, but if you think in terms of abstractions, they're both just steps > in the conceptual process of "creating the object". If I ask GTK to > create me a Button, I don't care how many steps it has to go through of > allocating memory, allocating other resources, etc, etc, etc. You deleted the part of my post where I suggested that it's only a historical accident that Python has two methods for constructing an object when most OOP languages get by with one. > All I want is to be able to write: > > foobar = Button("Foo Bar") > > and, at the end of it, to have a Button that I can toss onto a window. > That's the job of a constructor - to give me an object in a state that I > can depend on. You're assuming your conclusion. Why is it the job of the constructor, rather than the initialiser? When I buy a house, it is fully constructed, but it's not yet usable -- there's no bed, no fridge, no furniture of any sort, just a bare shell with a roof and some built-in cupboards and perhaps an oven. I have to initialise the house myself with whatever furniture I need. Even if it's a "fully furnished house", I still have to initialise it before I can say it's truly usable, even if that is merely emptying my suitcase into the built-in robes. The curse of the discontinuous mind: we look for hard dividing lines between black and white when what we really have is shades of grey. It's easy to tell when an int is constructed and ready to use, and sure enough it uses __new__ and has a do-nothing __init__. But with mutable objects, say a list, when is it constructed and ready to use? Suppose you want to create a list of items and extract the third smallest item. When is the list constructed and ready to use? - Is it when the memory is allocated for the object? Obviously not, since we can't do anything with it yet. - How about when the object fields are set up and made consistent? (Array is blanked, length set to the correct value, pointer to the class set, etc.) This makes a good candidate, since this is the earliest that the object is in a consistent state. - Is it when the list items are placed into the array? This is also a good candidate, since this is the earliest that the list has the items we expect. Assuming we expect any -- since many lists are created as simply [], then populated later, this isn't exactly black and white either. - Or when it is sorted? Probably not here, although this is the earliest that the user can *actually* use the list for what they wanted it for, namely to extract the third largest value. When does a pile of computer parts become a computer? When the CPU is plugged in? When the mouse is attached? Somewhere in between? We have difficulty drawing dividing lines because our minds are discontinuous but reality is continuous. [...] > The difference between __new__ and __init__ is important when you write > either method, but not when you use the class. It's like writing other > dunder methods. You care about the distinction between __add__ and > __radd__ when you write the methods, but in all other code, all that > matters is that it does what you want: Yes. And your point is? Speaking as an end user, "call the constructor" to refer to: instance = MyClass(arg) is exactly right, because the constructor is called regardless of whether __new__ is called alone, or __new__ and __init__. [...] > The two methods could have been done as a single method, __construct__, > in which you get passed a cls instead of a self, and you call > self=super().__construct__() and then initialize stuff. That would be called __new__ in Python. There's no *need* to use __init__ for anything (except old-style classic classes in Python 2). -- Steven From ayushidalmia2604 at gmail.com Sat Feb 1 00:52:11 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Fri, 31 Jan 2014 21:52:11 -0800 (PST) Subject: fseek In Compressed Files In-Reply-To: References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> Message-ID: <897c196f-0812-43cf-9829-07993263207e@googlegroups.com> On Friday, January 31, 2014 12:16:59 AM UTC+5:30, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > > > On Thursday, January 30, 2014 4:20:26 PM UTC+5:30, Ayushi Dalmia wrote: > > >> Hello, > > >> > > >> > > >> > > >> I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. > > > > > > We are not allowed to use databases! I need to do this without database. > > > > > > > Why do you reply to your own message? Makes it hard for people to > > make sense of your post. > > > > Have you any answers to earlier questions? How big is this file, > > what python version, do you care about performance, code you've > > tried, ... > > > > -- > > DaveA The size of this file will be 10 GB. The version of Python I am using is 2.7.2. Yes, performance is an important issue. From steve+comp.lang.python at pearwood.info Sat Feb 1 00:53:21 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Feb 2014 05:53:21 GMT Subject: Dunder [was Re: __init__ is the initialiser] References: <858utviwgs.fsf@benfinney.id.au> <52ec6183$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ec8bd1$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Feb 2014 15:05:34 +1100, Chris Angelico wrote: > On Sat, Feb 1, 2014 at 1:52 PM, Steven D'Aprano > wrote: >> "Constructor" is three syllables; "ctor" isn't readily pronounceable in >> English at all, rather like Cthulhu. (I can't think of any standard >> English words with a "CT" in them at all, let alone at the start of the >> word). The best I can come up with is "KUH TOR" or possibly "SEE TOR", >> both of which are clumsy, and only save a single syllable. > > May I tactfully suggest that searching the abstract of a dictionary for > the letters 'ct' would be a useful action here. Point taken :-P I did say that *I* couldn't think of any. -- Steven From dan at tombstonezero.net Sat Feb 1 01:30:43 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Sat, 1 Feb 2014 06:30:43 +0000 (UTC) Subject: pytz question: GMT vs. UTC References: <3g6je9h7fp29pebi7aa04tigc50hm3vepj@4ax.com> <52E9BB8C.80000@mrabarnett.plus.com> <52eb287c$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 31 Jan 2014 17:42:30 +1100, Chris Angelico wrote: > On Fri, Jan 31, 2014 at 5:28 PM, Dan Sommers wrote: >> ObPython: My program retrieves temperatures (in Kelvins) from an >> external device (the details of which I am not at liberty to discuss) >> and stores them in the cloud (because that's where all the cool kids >> store data these days), and there's something really weird going on. >> >> $ python ./program.py >> temperature1 is -100 K >> temperature2 is 100 K >> temperature2 is hotter than temperature1 >> >> But everyone knows that -100K is hotter than 100K. I tried converting >> to UTC, but that didn't help. What am I missing? > > I'm sorry, you have completely misunderstood the problem here. You are > storing data in the cloud, which means you're representing everything > with water. It is therefore fundamentally illogical to use any > temperature outside the range [273.15K, 373.15K], because otherwise > your cloud will freeze or boil, and either way, it'll crash badly. I think I found the problem: it's not a water cloud, it's a potassium sulfide cloud, and as its temperatures rose, I lost the special Ks. > Plus, converting to UTC? Puh-leeze. You should be using kilogram > meters per second. It was a momentary lapse of reason. Sorry. Dan From rosuav at gmail.com Sat Feb 1 02:26:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Feb 2014 18:26:48 +1100 Subject: Python shell wont open idle or an exisiting py file In-Reply-To: References: <24EAA33389A147D8BC08B029E2209E16@UserPC> <52EC61FF.4060204@mrabarnett.plus.com> Message-ID: On Sat, Feb 1, 2014 at 4:46 PM, Terry Reedy wrote: > On 1/31/2014 10:36 PM, Chris Angelico wrote: >> >> On Sat, Feb 1, 2014 at 1:54 PM, MRAB wrote: >>> >>> I think that some years ago I heard about a variation on UTF-8 >>> (Microsoft?) where codepoint U+0000 is encoded as 0xC0 0x80 so that the >>> null byte can be used as the string terminator. >>> >>> I had a look on Wikipedia found this: >>> >>> http://en.wikipedia.org/wiki/Null-terminated_string >> >> >> Yeah, it's a common abuse of UTF-8. It's a violation of spec, but an >> understandable one. However, I don't understand why the first part - >> why should \0 become U+0000 but (presumably) the \a later on >> (...cs\accel...) doesn't become U+0007, etc? > > > Because only \0 has a special meaning in a C string, and Tk is written in C > and uses C strings. Eh? I've used \a in C programs (not often but I have used it). It's possible that \0 is the only one that actually bombs anything (because of C0 80 representation). But since \7 and \a both represent 0x07 in a C string, I would expect there to be other problems, if it's interpreting it as source. Ah well! Weird weird. ChrisA From bouncingcats at gmail.com Sat Feb 1 01:13:48 2014 From: bouncingcats at gmail.com (David) Date: Sat, 1 Feb 2014 17:13:48 +1100 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> <8da5d692-1446-4107-9a5a-5efd91f7c051@googlegroups.com> <2B1086E7-5E5F-4227-8F9E-92A37D2DE1D2@cox.net> Message-ID: On 1 February 2014 14:17, David wrote: > > Scott's message quoted above did not reach me, only Chris's quote of > it, so I say: Scott once you begin a discussion on a mailing list like > this one, please make sure that every reply you make goes to > "python-list at python.org" and not to the individual. That way we can > all participate in the discussion, that is best for everyone > especially you. Please disregard the above paragraph Scott. Because 8 messages from you were just delivered to me, including that one, all via the list, some were 5 hours old. Sorry for any confusion I caused due to that delay. From ethan at stoneleaf.us Sat Feb 1 03:28:03 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sat, 01 Feb 2014 00:28:03 -0800 Subject: __init__ is the initialiser In-Reply-To: <52ec8b51$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> <52ec8b51$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ECB013.2070806@stoneleaf.us> On 01/31/2014 09:51 PM, Steven D'Aprano wrote: > On Sat, 01 Feb 2014 15:35:17 +1100, Chris Angelico wrote: >> >> The two methods could have been done as a single method, __construct__, >> in which you get passed a cls instead of a self, and you call >> self=super().__construct__() and then initialize stuff. > > That would be called __new__ in Python. There's no *need* to use __init__ > for anything (except old-style classic classes in Python 2). While there may not be a /need/ for two, having two is quite handy. Having __new__ take care of the nuts and bolts (or foundation, as Terry put it), and being able to further customize with __init__ (where the kitchen goes, how many bedrooms, to follow along with Terry) is quite useful. One of my favorite Enum recipes uses that pattern to have some basic behavior, with some other behavior that is easily overridable/extendable [1]. -- ~Ethan~ [1] http://stackoverflow.com/q/19330460/208880 From tjreedy at udel.edu Sat Feb 1 03:51:48 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Feb 2014 03:51:48 -0500 Subject: Python shell wont open idle or an exisiting py file In-Reply-To: References: <24EAA33389A147D8BC08B029E2209E16@UserPC> <52EC61FF.4060204@mrabarnett.plus.com> Message-ID: On 2/1/2014 2:26 AM, Chris Angelico wrote: > On Sat, Feb 1, 2014 at 4:46 PM, Terry Reedy wrote: >> On 1/31/2014 10:36 PM, Chris Angelico wrote: >>> >>> On Sat, Feb 1, 2014 at 1:54 PM, MRAB wrote: >>>> >>>> I think that some years ago I heard about a variation on UTF-8 >>>> (Microsoft?) where codepoint U+0000 is encoded as 0xC0 0x80 so that the >>>> null byte can be used as the string terminator. >>>> >>>> I had a look on Wikipedia found this: >>>> >>>> http://en.wikipedia.org/wiki/Null-terminated_string >>> >>> >>> Yeah, it's a common abuse of UTF-8. It's a violation of spec, but an >>> understandable one. However, I don't understand why the first part - >>> why should \0 become U+0000 but (presumably) the \a later on >>> (...cs\accel...) doesn't become U+0007, etc? >> >> >> Because only \0 has a special meaning in a C string, I should have added 'to C itself', as the string terminator. >> and Tk is written in C and uses C strings. > > Eh? I've used \a in C programs (not often but I have used it). > > It's possible that \0 is the only one that actually bombs anything > (because of C0 80 representation). \0 can bomb C byte processing by terminating it sooner than it should. Its unexpected replacement bombs utf-8 decoding. > But since \7 and \a both represent > 0x07 in a C string, I would expect there to be other problems, if it's > interpreting it as source. Ah well! Weird weird. While other control codes may have special meaning to a terminal or other device, to do not have special meaning to the operation of C string functions themselves (except possible for a 'getline' function looking for n -- but I do not remember is the C stdlib has any such functions). I am speaking from my memory of C. I have not looked at the Tk C code to see just what it did where to create the exception. I am just happy that Serhiy was able to fixed tkinter without causing another test to fail. -- Terry Jan Reedy From rosuav at gmail.com Sat Feb 1 04:06:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Feb 2014 20:06:57 +1100 Subject: Python shell wont open idle or an exisiting py file In-Reply-To: References: <24EAA33389A147D8BC08B029E2209E16@UserPC> <52EC61FF.4060204@mrabarnett.plus.com> Message-ID: On Sat, Feb 1, 2014 at 7:51 PM, Terry Reedy wrote: > I should have added 'to C itself', as the string terminator. Oh, right. Yes, in that sense \0 is special. It's still wrong that an incoming text string gets interpreted as code, but that's probably just a consequence of the jump from Python to Tcl. ChrisA From davea at davea.name Sat Feb 1 04:38:10 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Feb 2014 04:38:10 -0500 (EST) Subject: fseek In Compressed Files References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> <897c196f-0812-43cf-9829-07993263207e@googlegroups.com> Message-ID: Ayushi Dalmia Wrote in message: > > > The size of this file will be 10 GB. The version of Python I am using is 2.7.2. Yes, performance is an important issue. > Then the only viable option is to extract the entire file and write it to a temp location. Perhaps as you extract it, you could also build a list of offsets, so the seeking by line number can be efficient. -- DaveA From limko9012 at googlemail.com Sat Feb 1 05:13:03 2014 From: limko9012 at googlemail.com (Liam Knott) Date: Sat, 1 Feb 2014 02:13:03 -0800 (PST) Subject: C++ to python for LED Matrix Message-ID: <52c58d64-be7e-4241-aef1-2215acde6ec6@googlegroups.com> Hey folks, So the last week or so I've been searching this site for information on how to control and program a LED Matrix (or a number of them) for a project. A few Topics have caught my eye, with me originally having in mind using a Maxim MAX7221 to control the matrix, but none more than Klaas's: http://www.raspberrypi.org/phpBB3/viewtopic.php?t=41713. This was almost perfect for me, until I saw the code was in C++ and from the title all I know is Python. So after checking the code out and trying to figure how this language works I just couldn't break it down and Unfortunately I don't have a lot of time to learn C++ ( would be great if I could but I don't have that luxury right now). So if anyone is willing to check Klaas's topic and code and convert it into python that would be awesome, even if someone would explain how the code is working that would be great, oh and don't be scared to comment on ways of going about this project. Note: Hoping I could achieve something like this but with the Pi: http://www.youtube.com/watch?v=FzHT-L-7jIA Cheers! Lknott :-D From rpdooling at gmail.com Sat Feb 1 07:19:45 2014 From: rpdooling at gmail.com (Rick Dooling) Date: Sat, 1 Feb 2014 04:19:45 -0800 (PST) Subject: piping with subprocess Message-ID: I spent half a day trying to convert this bash script (on Mac) textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 into Python using subprocess pipes. It works if I save the above into a shell script called convert.sh and then do subprocess.check_call(["convert.sh", file, markdown_file]) where file and markdown_file are variables. But otherwise my piping attempts fail. Could someone show me how to pipe in subprocess. Yes, I've read the doc, especially http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline But I'm a feeble hobbyist, not a computer scientist. Thanks RD From ned at nedbatchelder.com Sat Feb 1 07:28:01 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 01 Feb 2014 07:28:01 -0500 Subject: __init__ is the initialiser In-Reply-To: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 1/31/14 10:42 PM, Steven D'Aprano wrote: > On Fri, 31 Jan 2014 14:52:15 -0500, Ned Batchelder wrote: > >> Why can't we call __init__ the constructor and __new__ the allocator? > > __new__ constructs the object, and __init__ initialises it. What's wrong > with calling them the constructor and initialiser? Is this such a > difficult concept that the average programmer can't learn it? > > I've met people who have difficulty with OOP principles, at least at > first. But once you understand the idea of objects, it isn't that hard to > understand the idea that: > > - first, the object has to be created, or constructed, or allocated > if you will; > > - only then can it be initialised. > > Thus, two methods. __new__ constructs (creates, allocates) a new object; > __init__ initialises it after the event. > > (In hindsight, it was probably a mistake for Python to define two create- > an-object methods, although I expect it was deemed necessary for > historical reasons. Most other languages make do with a single method, > Objective-C being an exception with "alloc" and "init" methods.) > > > > Earlier in this post, you wrote: > >> But that distinction [between __new__ and __init__] isn't useful in >> most programs. > > Well, I don't know about that. I guess it depends on what sort of objects > you're creating. If you're creating immutable objects, then the > distinction is vital. If you're subclassing from immutable built-ins, of > which there are a few, the distinction may be important. If you're using > the object-pool design pattern, the distinction is also vital. It's not > *rare* to care about these things. > > >> The thing most people mean by "constructor" is "the method that gets >> invoked right at the beginning of the object's lifetime, where you can >> add code to initialize it properly." That describes __init__. > > "Most people". I presume you've done a statistically valid survey then > *wink* > > It *better* describes __new__, because it is *not true* that __init__ > gets invoked "right at the beginning of the object's lifetime". Before > __init__ is invoked, the object's lifetime has already begun, inside the > call to __new__. Excluding metaclass shenanigans, the object lifetime > goes: > > > Prior to the object existing: > - static method __new__ called on the class[1] > - __new__ creates the object[2] <=== start of object lifetime > > Within the object's lifetime: > - the rest of the __new__ method runs, which may perform arbitrarily > complex manipulations of the object; > - __new__ exits, returning the object > - __init__ runs > > > So __init__ does not occur *right at the beginning*, and it is completely > legitimate to write your classes using only __new__. You must use __new__ > for immutable objects, and you may use __new__ for mutable ones. __init__ > may be used by convention, but it is entirely redundant. > > I do not buy the argument made by some people that Python ought to follow > whatever (possibly inaccurate or misleading) terminology other languages > use. Java and Ruby have the exact same argument passing conventions as > Python, but one calls it "call by value" and the other "call by > reference", and neither is the same meaning of "call by value/reference" > as used by Pascal, C, Visual Basic, or other languages. So which > terminology should Python use? Both C++ and Haskell have "functors", but > they are completely different things. What Python calls a class method, > Java calls a static method. We could go on for days, just listing > differences in terminology. > > In Python circles, using "constructor" for __new__ and "initialiser" for > __init__ are well-established. In the context of Python, they make good > sense: __new__ creates ("constructs") the object, and __init__ > _init_ialises it. Missing the opportunity to link the method name > __init__ to *initialise* would be a mistake. > > We can decry the fact that computer science has not standardised on a > sensible set of names for concepts, but on the other hand since the > semantics of languages differ slightly, it would be more confusing to try > to force all languages to use the same words for slightly different > concepts. > > The reality is, if you're coming to Python from another language, you're > going to have to learn a whole lot of new stuff anyway, so having to > learn a few language-specific terms is just a small incremental cost. And > if you have no idea about other languages, then it is no harder to learn > that __new__ / __init__ are the constructor/initialiser than it would be > to learn that they are the allocator/constructor or preformulator/ > postformulator. > > I care about using the right terminology that will cause the least amount > of cognitive dissonance to users' understanding of Python, not whether > they have to learn new terminology, and in the context of Python's object > module, "constructor" and "initialiser" best describe what __new__ and > __init__ do. > My summary of our two views is this: I am trying to look at things from a typical programmer's point of view. The existence of __new__ is an advanced topic that many programmers never encounter. Taking a quick scan through some large projects (Django, edX, SQLAlchemy, mako), the ratio of __new__ implementations to __init__ implementations ranges from 0% to 1.5%, which falls into "rare" territory for me. Among programs less than 5000 lines long, I'm sure the number is indistinguishable from 0, though I'm sure someone will question my methodology here as well! :) You are looking at things from an accurate-down-to-the-last-footnote detailed point of view (and have provided some footnotes!). That's a very valuable and important point of view. It's just not how most programmers approach the language. We are also both trying to reduce cognitive dissonance, but again, you are addressing language mavens who understand the footnotes, and I am trying to help the in-the-trenches people who have never encountered __new__ and are wondering why people are using funny words for the code they are writing. Another difference in our approach: do you name things based on how they work under the hood, or how they are used? I hope we can all agree that when writing a user-defined class, the code that in C++ or Java would go into the constructor, in Python typically goes in __init__. When I say that __init__ plays the role of constructor, again, I mean from the typical programmer's point of view when writing typical user-defined classes. Finding names for things is hard, and it's impossible to please both ends of this spectrum. -- Ned Batchelder, http://nedbatchelder.com From __peter__ at web.de Sat Feb 1 07:54:09 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Feb 2014 13:54:09 +0100 Subject: piping with subprocess References: Message-ID: Rick Dooling wrote: > I spent half a day trying to convert this bash script (on Mac) > > textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 > > into Python using subprocess pipes. > > It works if I save the above into a shell script called convert.sh and > then do > > subprocess.check_call(["convert.sh", file, markdown_file]) > > where file and markdown_file are variables. > > But otherwise my piping attempts fail. It is always a good idea to post your "best effort" failed attempt, if only to give us an idea of your level of expertise. > Could someone show me how to pipe in subprocess. Yes, I've read the doc, > especially > > http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > But I'm a feeble hobbyist, not a computer scientist. Try to convert the example from the above page """ output=`dmesg | grep hda` # becomes p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] """ to your usecase. Namely, replace ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o", outfile] Don't forget to set infile = ... outfile = ... to filenames (with absolute paths, to avoid one source of error). If that doesn't work post the code you wrote along with the error messages. From var.mail.daniel at gmail.com Sat Feb 1 07:40:58 2014 From: var.mail.daniel at gmail.com (Daniel da Silva) Date: Sat, 1 Feb 2014 07:40:58 -0500 Subject: piping with subprocess In-Reply-To: References: Message-ID: Try this: from subprocess import check_output import sys check_output("textutil -convert html %s -stdout | pandoc -f html -t markdown -o %s" % sys.argv[1:3], shell=True) On Sat, Feb 1, 2014 at 7:19 AM, Rick Dooling wrote: > I spent half a day trying to convert this bash script (on Mac) > > textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 > > into Python using subprocess pipes. > > It works if I save the above into a shell script called convert.sh and > then do > > subprocess.check_call(["convert.sh", file, markdown_file]) > > where file and markdown_file are variables. > > But otherwise my piping attempts fail. > > Could someone show me how to pipe in subprocess. Yes, I've read the doc, > especially > > http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > But I'm a feeble hobbyist, not a computer scientist. > > Thanks > > RD > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpdooling at gmail.com Sat Feb 1 08:54:34 2014 From: rpdooling at gmail.com (Rick Dooling) Date: Sat, 1 Feb 2014 05:54:34 -0800 (PST) Subject: piping with subprocess In-Reply-To: References: Message-ID: On Saturday, February 1, 2014 6:54:09 AM UTC-6, Peter Otten wrote: > Rick Dooling wrote: > > > > > I spent half a day trying to convert this bash script (on Mac) > > > > > > textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 > > > > > > into Python using subprocess pipes. > > > > > > It works if I save the above into a shell script called convert.sh and > > > then do > > > > > > subprocess.check_call(["convert.sh", file, markdown_file]) > > > > > > where file and markdown_file are variables. > > > > > > But otherwise my piping attempts fail. > > > > It is always a good idea to post your "best effort" failed attempt, if only > > to give us an idea of your level of expertise. > > > > > Could someone show me how to pipe in subprocess. Yes, I've read the doc, > > > especially > > > > > > http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > > > > > But I'm a feeble hobbyist, not a computer scientist. > > > > Try to convert the example from the above page > > > > """ > > output=`dmesg | grep hda` > > # becomes > > p1 = Popen(["dmesg"], stdout=PIPE) > > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > output = p2.communicate()[0] > > """ > > > > to your usecase. Namely, replace > > > > ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] > > ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o", > > outfile] > > > > Don't forget to set > > > > infile = ... > > outfile = ... > > > > to filenames (with absolute paths, to avoid one source of error). > > If that doesn't work post the code you wrote along with the error messages. p1 = subprocess.Popen(["textutil", "-convert", "html", file], stdout=subprocess.PIPE) p2 = subprocess.check_call(["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] Errors Traceback (most recent call last): File "/Users/me/Python/any2pandoc.py", line 70, in convert_word_file(file, markdown_file) File "/Users/me/Python/any2pandoc.py", line 59, in convert_word_file output = p2.communicate()[0] AttributeError: 'int' object has no attribute 'communicate' I get a markdown_file created but it's empty. Thanks, RD ps - Daniel's works fine but I still don't learn to pipe :) From rpdooling at gmail.com Sat Feb 1 09:00:59 2014 From: rpdooling at gmail.com (Rick Dooling) Date: Sat, 1 Feb 2014 06:00:59 -0800 (PST) Subject: piping with subprocess In-Reply-To: References: Message-ID: On Saturday, February 1, 2014 7:54:34 AM UTC-6, Rick Dooling wrote: > On Saturday, February 1, 2014 6:54:09 AM UTC-6, Peter Otten wrote: > > > Rick Dooling wrote: > > > > > > > > > > > > > I spent half a day trying to convert this bash script (on Mac) > > > > > > > > > > > > > > textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 > > > > > > > > > > > > > > into Python using subprocess pipes. > > > > > > > > > > > > > > It works if I save the above into a shell script called convert.sh and > > > > > > > then do > > > > > > > > > > > > > > subprocess.check_call(["convert.sh", file, markdown_file]) > > > > > > > > > > > > > > where file and markdown_file are variables. > > > > > > > > > > > > > > But otherwise my piping attempts fail. > > > > > > > > > > > > It is always a good idea to post your "best effort" failed attempt, if only > > > > > > to give us an idea of your level of expertise. > > > > > > > > > > > > > Could someone show me how to pipe in subprocess. Yes, I've read the doc, > > > > > > > especially > > > > > > > > > > > > > > http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > > > > > > > > > > > > > But I'm a feeble hobbyist, not a computer scientist. > > > > > > > > > > > > Try to convert the example from the above page > > > > > > > > > > > > """ > > > > > > output=`dmesg | grep hda` > > > > > > # becomes > > > > > > p1 = Popen(["dmesg"], stdout=PIPE) > > > > > > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > > > > > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > > > > > output = p2.communicate()[0] > > > > > > """ > > > > > > > > > > > > to your usecase. Namely, replace > > > > > > > > > > > > ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] > > > > > > ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o", > > > > > > outfile] > > > > > > > > > > > > Don't forget to set > > > > > > > > > > > > infile = ... > > > > > > outfile = ... > > > > > > > > > > > > to filenames (with absolute paths, to avoid one source of error). > > > > > > If that doesn't work post the code you wrote along with the error messages. > > > > p1 = subprocess.Popen(["textutil", "-convert", "html", file], stdout=subprocess.PIPE) > > p2 = subprocess.check_call(["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, stdout=subprocess.PIPE) > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > output = p2.communicate()[0] > > > > Errors > > > > Traceback (most recent call last): > > File "/Users/me/Python/any2pandoc.py", line 70, in > > convert_word_file(file, markdown_file) > > File "/Users/me/Python/any2pandoc.py", line 59, in convert_word_file > > output = p2.communicate()[0] > > AttributeError: 'int' object has no attribute 'communicate' > > > > I get a markdown_file created but it's empty. > > > > Thanks, > > > > RD > > > > ps - Daniel's works fine but I still don't learn to pipe :) Okay, sorry. I fixed that obvious goof p1 = subprocess.Popen(["textutil", "-convert", "html", file], stdout=subprocess.PIPE) p2 = subprocess.Popen(["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] Now I get no errors, but I still get a blank markdown file. From andrea.crotti.0 at gmail.com Sat Feb 1 09:12:28 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sat, 1 Feb 2014 14:12:28 +0000 Subject: generator slides review Message-ID: I'm giving a talk tomorrow @Fosdem about generators/iterators/iterables.. The slides are here (forgive the strange Chinese characters): https://dl.dropboxusercontent.com/u/3183120/talks/generators/index.html#3 and the code I'm using is: https://github.com/AndreaCrotti/generators/blob/master/code/generators.py and the tests: https://github.com/AndreaCrotti/generators/blob/master/code/test_generators.py If anyone has any feedback or want to point out I'm saying something stupid I'd love to hear it before tomorrow (or also later I might give this talk again). Thanks From breamoreboy at yahoo.co.uk Sat Feb 1 09:28:41 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Feb 2014 14:28:41 +0000 Subject: piping with subprocess In-Reply-To: References: Message-ID: On 01/02/2014 13:54, Rick Dooling wrote: > On Saturday, February 1, 2014 6:54:09 AM UTC-6, Peter Otten wrote: >> Rick Dooling wrote: >> >> >> >>> I spent half a day trying to convert this bash script (on Mac) >> >>> >> >>> textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 >> >>> >> >>> into Python using subprocess pipes. >> >>> >> >>> It works if I save the above into a shell script called convert.sh and >> >>> then do >> >>> >> >>> subprocess.check_call(["convert.sh", file, markdown_file]) >> >>> >> >>> where file and markdown_file are variables. >> >>> >> >>> But otherwise my piping attempts fail. >> >> >> >> It is always a good idea to post your "best effort" failed attempt, if only >> >> to give us an idea of your level of expertise. >> >> >> >>> Could someone show me how to pipe in subprocess. Yes, I've read the doc, >> >>> especially >> >>> >> >>> http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline >> >>> >> >>> But I'm a feeble hobbyist, not a computer scientist. >> >> >> >> Try to convert the example from the above page >> >> >> >> """ >> >> output=`dmesg | grep hda` >> >> # becomes >> >> p1 = Popen(["dmesg"], stdout=PIPE) >> >> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) >> >> p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. >> >> output = p2.communicate()[0] >> >> """ >> >> >> >> to your usecase. Namely, replace >> >> >> >> ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] >> >> ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o", >> >> outfile] >> >> >> >> Don't forget to set >> >> >> >> infile = ... >> >> outfile = ... >> >> >> >> to filenames (with absolute paths, to avoid one source of error). >> >> If that doesn't work post the code you wrote along with the error messages. Would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing above, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From roy at panix.com Sat Feb 1 09:40:43 2014 From: roy at panix.com (Roy Smith) Date: Sat, 01 Feb 2014 09:40:43 -0500 Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Ned Batchelder wrote: > The existence of __new__ is an > advanced topic that many programmers never encounter. Taking a quick > scan through some large projects (Django, edX, SQLAlchemy, mako), the > ratio of __new__ implementations to __init__ implementations ranges from > 0% to 1.5%, which falls into "rare" territory for me. >From our own codebase: $ find . -name '*.py' | xargs grep 'def.*__new__' | wc -l 1 $ find . -name '*.py' | xargs grep 'def.*__init__' | wc -l 228 Doing the same searches over all the .py files in our virtualenv, I get 2830 (__init__) vs. 50 (__new__). From breamoreboy at yahoo.co.uk Sat Feb 1 10:07:18 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Feb 2014 15:07:18 +0000 Subject: __init__ is the initialiser In-Reply-To: References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 01/02/2014 14:40, Roy Smith wrote: > In article , > Ned Batchelder wrote: > >> The existence of __new__ is an >> advanced topic that many programmers never encounter. Taking a quick >> scan through some large projects (Django, edX, SQLAlchemy, mako), the >> ratio of __new__ implementations to __init__ implementations ranges from >> 0% to 1.5%, which falls into "rare" territory for me. > > From our own codebase: > > $ find . -name '*.py' | xargs grep 'def.*__new__' | wc -l > 1 > $ find . -name '*.py' | xargs grep 'def.*__init__' | wc -l > 228 > > Doing the same searches over all the .py files in our virtualenv, I get > 2830 (__init__) vs. 50 (__new__). > You could remove all 228 __init__ and still get your code to work by scattering object attributes anywhere you like, something I believe you can't do in C++/Java. I doubt that you could remove the single __new__ and get your code to work. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From panast24 at gmail.com Sat Feb 1 10:33:47 2014 From: panast24 at gmail.com (Panagiotis Anastasiou) Date: Sat, 1 Feb 2014 07:33:47 -0800 (PST) Subject: Python prime numbers Message-ID: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far : numprimes = raw_input('Prime Numbers ') count = 0 potentialprime = 2 def primetest(potentialprime): divisor = 2 while divisor <= potentialprime: if potentialprime == 2: return True elif potentialprime % divisor == 0: return False break while potentialprime % divisor != 0: if potentialprime - divisor > 1: divisor += 1 else: return True while count < int(numprimes): if primetest(potentialprime) == True: print potentialprime count += 1 potentialprime += 1 else: potentialprime += 1 but i get the result in a single column . How can i get it in 5 rows? Can someone help please From rpdooling at gmail.com Sat Feb 1 10:35:01 2014 From: rpdooling at gmail.com (Rick Dooling) Date: Sat, 1 Feb 2014 07:35:01 -0800 (PST) Subject: piping with subprocess In-Reply-To: References: Message-ID: On Saturday, February 1, 2014 8:00:59 AM UTC-6, Rick Dooling wrote: > On Saturday, February 1, 2014 7:54:34 AM UTC-6, Rick Dooling wrote: > > > On Saturday, February 1, 2014 6:54:09 AM UTC-6, Peter Otten wrote: > > > > Rick Dooling wrote: > > > > > I spent half a day trying to convert this bash script (on Mac) > > > > textutil -convert html $1 -stdout | pandoc -f html -t markdown -o $2 > > > > into Python using subprocess pipes. > > > > > It works if I save the above into a shell script called convert.sh and > > > > then do > > > > > > subprocess.check_call(["convert.sh", file, markdown_file]) > > > > > where file and markdown_file are variables. > > > > > But otherwise my piping attempts fail. > > > > It is always a good idea to post your "best effort" failed attempt, if only to give us an idea of your level of expertise. > > > > Could someone show me how to pipe in subprocess. Yes, I've read the doc, > > > > especially http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > > > > But I'm a feeble hobbyist, not a computer scientist. > > > > Try to convert the example from the above page > > > > """ > > > > output=`dmesg | grep hda` > > > > # becomes > > > > p1 = Popen(["dmesg"], stdout=PIPE) > > > > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > > > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > > > output = p2.communicate()[0] > > > > """ > > > > to your usecase. Namely, replace > > > > ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] > > > > ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o" outfile] > > > > Don't forget to set > > > > infile = ... > > > > outfile = ... > > > > to filenames (with absolute paths, to avoid one source of error). > > > > If that doesn't work post the code you wrote along with the error messages. > > > p1 = subprocess.Popen(["textutil", "-convert", "html", file], stdout=subprocess.PIPE) > > > p2 = subprocess.check_call(["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, stdout=subprocess.PIPE) > > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > output = p2.communicate()[0] > > Errors > > Traceback (most recent call last): > > File "/Users/me/Python/any2pandoc.py", line 70, in > > convert_word_file(file, markdown_file) > > File "/Users/me/Python/any2pandoc.py", line 59, in convert_word_file > > output = p2.communicate()[0] > > AttributeError: 'int' object has no attribute 'communicate' > > I get a markdown_file created but it's empty. > > Thanks, > > RD > > ps - Daniel's works fine but I still don't learn to pipe :) > Okay, sorry. I fixed that obvious goof > p1 = subprocess.Popen(["textutil", "-convert", "html", file], stdout=subprocess.PIPE) > > p2 = subprocess.Popen(["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, stdout=subprocess.PIPE) > > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > > output = p2.communicate()[0] > > Now I get no errors, but I still get a blank markdown file. Okay, blank lines removed. Apologies. I didn't know Google inserted them. RD From larry.martell at gmail.com Sat Feb 1 10:50:53 2014 From: larry.martell at gmail.com (Larry Martell) Date: Sat, 1 Feb 2014 10:50:53 -0500 Subject: Python prime numbers In-Reply-To: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> References: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> Message-ID: On Saturday, February 1, 2014, Panagiotis Anastasiou wrote: > Hi i'm new in programming and in python and i have an assignment that i > cant complete. I have to Write a Python program to compute and print the > first 200 prime numbers. The output must be formatted with a title and the > prime numbers must be printed in 5 properly aligned columns . I have used > this code so far : > > numprimes = raw_input('Prime Numbers ') > count = 0 > potentialprime = 2 > > def primetest(potentialprime): > divisor = 2 > while divisor <= potentialprime: > if potentialprime == 2: > return True > elif potentialprime % divisor == 0: > return False > break > while potentialprime % divisor != 0: > if potentialprime - divisor > 1: > divisor += 1 > else: > return True > > while count < int(numprimes): > if primetest(potentialprime) == True: > print potentialprime > count += 1 > potentialprime += 1 > else: > potentialprime += 1 > > but i get the result in a single column . How can i get it in 5 rows? Can > someone help please > If you put a comma at the end of the print statement it will suppress the newline. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Feb 1 10:59:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Feb 2014 15:59:49 +0000 Subject: piping with subprocess In-Reply-To: References: Message-ID: On 01/02/2014 15:35, Rick Dooling wrote: > > Okay, blank lines removed. Apologies. I didn't know Google inserted them. > > RD > No problem, the whole snag is people don't know about this flaw in this tool until they're told about it. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From roy at panix.com Sat Feb 1 11:17:40 2014 From: roy at panix.com (Roy Smith) Date: Sat, 01 Feb 2014 11:17:40 -0500 Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: > On 01/02/2014 14:40, Roy Smith wrote: > > In article , > > Ned Batchelder wrote: > > > >> The existence of __new__ is an > >> advanced topic that many programmers never encounter. Taking a quick > >> scan through some large projects (Django, edX, SQLAlchemy, mako), the > >> ratio of __new__ implementations to __init__ implementations ranges from > >> 0% to 1.5%, which falls into "rare" territory for me. > > > > From our own codebase: > > > > $ find . -name '*.py' | xargs grep 'def.*__new__' | wc -l > > 1 > > $ find . -name '*.py' | xargs grep 'def.*__init__' | wc -l > > 228 > > > > Doing the same searches over all the .py files in our virtualenv, I get > > 2830 (__init__) vs. 50 (__new__). In article , Mark Lawrence wrote: > You could remove all 228 __init__ and still get your code to work by > scattering object attributes anywhere you like, something I believe you > can't do in C++/Java. Why not? Here's a simple C++ program which uses a constructor: #include class Foo { public: int i; Foo() : i(42) {} }; int main(int, char**) { Foo foo; printf("foo.i = %d\n", foo.i); } If I wanted to, I could remove the constructor and still "get my code to work by scattering object attributes anywhere I like": #include class Foo { public: int i; }; int main(int, char**) { Foo foo; foo.i = 42; printf("foo.i = %d\n", foo.i); } > I doubt that you could remove the single __new__ and get your code to work. Perhaps. Looking at our own code, the one place we use __new__ is in a metaclass, which I think pretty well reinforces Ned's assertion that __new__ is an advanced topic. From miki.tebeka at gmail.com Sat Feb 1 11:50:48 2014 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 1 Feb 2014 08:50:48 -0800 (PST) Subject: generator slides review In-Reply-To: References: Message-ID: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> On Saturday, February 1, 2014 6:12:28 AM UTC-8, andrea crotti wrote: > I'm giving a talk tomorrow @Fosdem about generators/iterators/iterables.. > > > > The slides are here (forgive the strange Chinese characters): > > https://dl.dropboxusercontent.com/u/3183120/talks/generators/index.html#3 > > > > and the code I'm using is: > > https://github.com/AndreaCrotti/generators/blob/master/code/generators.py > > and the tests: > > https://github.com/AndreaCrotti/generators/blob/master/code/test_generators.py > > > > If anyone has any feedback or want to point out I'm saying something > > stupid I'd love to hear it before tomorrow (or also later I might give > > this talk again). > > Thanks My 2 cents: slide 4: [i*2 for i in range(10)] slide 9: while True: try: it = next(g) body(it) except StopIteration: break slide 21: from itertools import count, ifilterfalse def divided_by(p): return lambda n: n % p == 0 def primes(): nums = count(2) while True: p = next(nums) yield p nums = ifilterfalse(divided_by(p), nums) Another resource you can point to is http://www.dabeaz.com/generators/ Good luck. From __peter__ at web.de Sat Feb 1 12:32:14 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Feb 2014 18:32:14 +0100 Subject: piping with subprocess References: Message-ID: Rick Dooling wrote: > On Saturday, February 1, 2014 6:54:09 AM UTC-6, Peter Otten wrote: >> Try to convert the example from the above page >> >> """ >> output=`dmesg | grep hda` >> # becomes >> p1 = Popen(["dmesg"], stdout=PIPE) >> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) >> p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. >> output = p2.communicate()[0] >> """ >> >> to your usecase. Namely, replace >> >> ["dmesg"] --> ["textutil", "-convert", "html", infile, "-stdout"] >> ["grep", "hda"] --> ["pandoc", "-f", "html", "-t", "marktown", "-o", >> outfile] >> >> Don't forget to set >> >> infile = ... >> outfile = ... >> >> to filenames (with absolute paths, to avoid one source of error). >> If that doesn't work post the code you wrote along with the error >> messages. > > p1 = subprocess.Popen(["textutil", "-convert", "html", file], > stdout=subprocess.PIPE) > p2 = subprocess.check_call(["pandoc", "-f", > "html", "-t", "markdown", "-o", markdown_file], stdin=p1.stdout, > stdout=subprocess.PIPE) > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > output = p2.communicate()[0] > > Errors > > Traceback (most recent call last): > File "/Users/me/Python/any2pandoc.py", line 70, in > convert_word_file(file, markdown_file) > File "/Users/me/Python/any2pandoc.py", line 59, in convert_word_file > output = p2.communicate()[0] > AttributeError: 'int' object has no attribute 'communicate' > > I get a markdown_file created but it's empty. Well, you replaced the Popen() from the example with a check_call() which uses a Popen instance internally, but does not expose it. I recommend that you stick as closely to the example as possible until you have a working baseline version. I'd try textutil = subprocess.Popen( ["textutil", "-convert", "html", file], stdout=subprocess.PIPE) pandoc = subprocess.Popen( ["pandoc", "-f", "html", "-t", "markdown", "-o", markdown_file], stdin=textutil.stdout) textutil.stdout.close() pandoc.communicate() From LConrad at Go2France.com Sat Feb 1 14:08:22 2014 From: LConrad at Go2France.com (Len Conrad) Date: Sat, 01 Feb 2014 13:08:22 -0600 Subject: Chris Miles? TGBooleanFormWidget? Message-ID: <201402012010537.SM02676@W500.Go2France.com> trying to install zoner. Needs http://www.psychofx.com/TGBooleanFormWidget/ but that's giving "502 Bad Gateway" can't find TGBooleanFormWidget anywhere else. Suggestions? Thanks Len -------------- next part -------------- An HTML attachment was scrubbed... URL: From denismfmcmahon at gmail.com Sat Feb 1 14:32:22 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sat, 1 Feb 2014 19:32:22 +0000 (UTC) Subject: Help with some python homework... References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> <8da5d692-1446-4107-9a5a-5efd91f7c051@googlegroups.com> Message-ID: On Fri, 31 Jan 2014 18:14:31 -0700, Scott W Dunning wrote: > little different from a few things you guys had mentioned. For one, I > got the correct time by calculating the number of time run and > converting that into seconds then back out to hr:mn:sc. I didn?t > calculate from midnight. > SECONDS = 1 MINUTES = 60 * SECONDS HOURS = 60 * MINUTES > > time_left_house = 6 * HOURS + 52 * MINUTES This does actually calculate the time in seconds since midnight that you left the house > miles_run_easy_pace = 2 * (8 * MINUTES + 15 * SECONDS) > > miles_run_fast_pace = 3 * (7 * MINUTES + 12 * SECONDS) > > time_returned_home = miles_run_easy_pace + miles_run_fast_pace + > time_left_house And this calculates the time in seconds since midnight that you returned home So although you don't realise it, you are actually working in seconds since midnight, and then converting seconds back into hours, minutes and seconds. -- Denis McMahon, denismfmcmahon at gmail.com From fluttershy363 at gmail.com Sat Feb 1 14:43:18 2014 From: fluttershy363 at gmail.com (Lewis Wood) Date: Sat, 1 Feb 2014 11:43:18 -0800 (PST) Subject: Tkinter widgets into classes. Message-ID: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> I was wandering if I could dynamically change my GUI and after a few searches on Google found the grid_remove() function. What I'm wandering now is if there is a way to group a lot of widgets up into one, and then use the one grid_remove function which will remove them all. Is it possible to do this in a class like this? class group1: label1=Label(text="Upon clicking the button").grid(row=0,column=0) label2=Label(text="The menu will dynamically change").grid(row=1,column=0) group1.grid_remove() From denismfmcmahon at gmail.com Sat Feb 1 14:45:32 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sat, 1 Feb 2014 19:45:32 +0000 (UTC) Subject: Help with some python homework... References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Fri, 31 Jan 2014 22:18:34 -0700, Scott W Dunning wrote: > Any chance you guys could help with another question I have? Below is a > code to a different problem. The only thing I don?t understand is why > when calculating the 'discounted price? you have to subtract 1? Thanks > again guys! price_per_book = 24.95 discount = .40 quantity = 60 discounted_price = (1-discount) * price_per_book shipping = 3.0 + (60 - 1) * .75 total_price = 60 * discounted_price + shipping print total_price, 'Total price' You subtract 1 from the shipping price (which should be quantity - 1) to allow for the fact that the first book costs 3.0 snargles to ship, and extra books in the same shipment cost 0.75 snargles each. So if the quantity is greater than one, the shipping cost is 3 snargles for the first book plus 0.75 snargles times (quantity minus one) The discounted price needs to be the cost, not the discount. If the discount is 0.4 (or 40%), then the cost is 0.6 (or 60%) of the list price. You are trying to calculate the cost, not the discount. list_price = discounted_price + discount_amount 1.0 * list_price = 0.6 * list_price + 0.4 * list_price Hence: discounted_price = list_price - discount_amount 0.6 * list_price = 1.0 * list_price - 0.4 * list_price so discounted_price = ( 1.0 - 0.4 ) * list_price where 0.4 is the decimal fraction of the discount -- Denis McMahon, denismfmcmahon at gmail.com From archie65 at live.co.uk Sat Feb 1 15:03:25 2014 From: archie65 at live.co.uk (archie65 at live.co.uk) Date: Sat, 1 Feb 2014 12:03:25 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> Message-ID: <164222db-b1d9-429d-a60f-4ba421ae3006@googlegroups.com> You become less of a a faget and stop sucking granni tranni pussi dis shud help u lewl From archie65 at live.co.uk Sat Feb 1 15:04:22 2014 From: archie65 at live.co.uk (archie65 at live.co.uk) Date: Sat, 1 Feb 2014 12:04:22 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> Message-ID: <2ef4b774-2b63-4eae-8dfa-0b91ffbab5e6@googlegroups.com> On Saturday, 1 February 2014 19:43:18 UTC, Lewis Wood wrote: > I was wandering if I could dynamically change my GUI and after a few searches on Google found the grid_remove() function. What I'm wandering now is if there is a way to group a lot of widgets up into one, and then use the one grid_remove function which will remove them all. > > > > Is it possible to do this in a class like this? > > > > class group1: > > label1=Label(text="Upon clicking the button").grid(row=0,column=0) > > label2=Label(text="The menu will dynamically change").grid(row=1,column=0) > > > > group1.grid_remove() From timothy.c.delaney at gmail.com Sat Feb 1 15:09:14 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Sun, 2 Feb 2014 07:09:14 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 1 February 2014 23:28, Ned Batchelder wrote: > > You are looking at things from an accurate-down-to-the-last-footnote > detailed point of view (and have provided some footnotes!). That's a very > valuable and important point of view. It's just not how most programmers > approach the language. > This is the *language reference* that is being discussed. It documents the intended semantics of the language. We most certainly should strive to ensure that it is accurate-down-to-the-last-footnote - any difference between the reference documentation and the implementation is a bug in either the documentation or the implementation. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From fluttershy363 at gmail.com Sat Feb 1 15:12:10 2014 From: fluttershy363 at gmail.com (Lewis Wood) Date: Sat, 1 Feb 2014 12:12:10 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> Message-ID: <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> Oh and another question, say I make another window in the program itself using this: def secondwindow(): root2=Tk() root2.mainloop() Would it be possible for me to use some code which would return True if one of these windows is currently up, or return False if the window is not up? From davea at davea.name Sat Feb 1 16:52:51 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Feb 2014 16:52:51 -0500 (EST) Subject: Tkinter widgets into classes. References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> Message-ID: Lewis Wood Wrote in message: > Oh and another question, say I make another window in the program itself using this: > > def secondwindow(): > root2=Tk() > root2.mainloop() > > Would it be possible for me to use some code which would return True if one of these windows is currently up, or return False if the window is not up? > No need. Only one at a time can be running, and you won't return from this function till it's done. To put it another way, you only want one mainloop in your code. -- DaveA From davea at davea.name Sat Feb 1 16:59:43 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Feb 2014 16:59:43 -0500 (EST) Subject: Python prime numbers References: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> Message-ID: Panagiotis Anastasiou Wrote in message: > Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far : > > numprimes = raw_input('Prime Numbers ') > count = 0 > potentialprime = 2 > > def primetest(potentialprime): > divisor = 2 > while divisor <= potentialprime: > if potentialprime == 2: > return True > elif potentialprime % divisor == 0: > return False > break > while potentialprime % divisor != 0: > if potentialprime - divisor > 1: > divisor += 1 > else: > return True > > while count < int(numprimes): > if primetest(potentialprime) == True: > print potentialprime > count += 1 > potentialprime += 1 > else: > potentialprime += 1 > > but i get the result in a single column . How can i get it in 5 rows? Can someone help please > -- DaveA From davea at davea.name Sat Feb 1 17:07:56 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Feb 2014 17:07:56 -0500 (EST) Subject: Python prime numbers References: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> Message-ID: Panagiotis Anastasiou Wrote in message: > Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far : > > numprimes = raw_input('Prime Numbers ') > count = 0 > potentialprime = 2 > > def primetest(potentialprime): > divisor = 2 > while divisor <= potentialprime: > if potentialprime == 2: > return True > elif potentialprime % divisor == 0: > return False > break > while potentialprime % divisor != 0: > if potentialprime - divisor > 1: > divisor += 1 > else: > return True > There are several things wrong with this function, and it's redundant enough that maybe none of them matter. I'd test it carefully. > while count < int(numprimes): > if primetest(potentialprime) == True: > print potentialprime > count += 1 > potentialprime += 1 > else: > potentialprime += 1 > > but i get the result in a single column . How can i get it in 5 rows? Can someone help please > As has been pointed out, you can use a trailing comma to suppress the implied newline for each print. Then you can add it back in every five items by checking count. But you have a bigger problem, lining up the columns. Try using the string modulus operator, or 'format'. -- DaveA From fluttershy363 at gmail.com Sat Feb 1 17:12:09 2014 From: fluttershy363 at gmail.com (Lewis Wood) Date: Sat, 1 Feb 2014 14:12:09 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> Message-ID: <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> On Saturday, 1 February 2014 21:52:51 UTC, Dave Angel wrote: > Lewis Wood Wrote in message: > > > Oh and another question, say I make another window in the program itself using this: > > > > > > def secondwindow(): > > > root2=Tk() > > > root2.mainloop() > > > > > > Would it be possible for me to use some code which would return True if one of these windows is currently up, or return False if the window is not up? > > > > > > > No need. Only one at a time can be running, and you won't return > > from this function till it's done. > > > > To put it another way, you only want one mainloop in your code. > > -- > > DaveA But I can click the button Multiple times and it will create multiple windows? From davea at davea.name Sat Feb 1 17:26:17 2014 From: davea at davea.name (Dave Angel) Date: Sat, 1 Feb 2014 17:26:17 -0500 (EST) Subject: Tkinter widgets into classes. References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: Lewis Wood Wrote in message: > >> (deleting doublespaced googlegroups trash) >> >> >> To put it another way, you only want one mainloop in your code. >> >> -- >> >> DaveA > > But I can click the button Multiple times and it will create multiple windows? > Not using the function you showed. -- DaveA From fluttershy363 at gmail.com Sat Feb 1 18:07:00 2014 From: fluttershy363 at gmail.com (Lewis Wood) Date: Sat, 1 Feb 2014 15:07:00 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: On Saturday, 1 February 2014 22:26:17 UTC, Dave Angel wrote: > Lewis Wood Wrote in message: > > > > > >> > > (deleting doublespaced googlegroups trash) > > >> > > >> > > >> To put it another way, you only want one mainloop in your code. > > >> > > >> -- > > >> > > >> DaveA > > > > > > But I can click the button Multiple times and it will create multiple windows? > > > > > > > Not using the function you showed. > > > > -- > > DaveA It does, this is the whole code: from tkinter import * root=Tk() root.title("Second Root Testing") def secondwindow(): root2=Tk() root2.mainloop() button1=Button(root,text="Root2",command=secondwindow).grid(row=0,column=0) root.mainloop() From look at signature.invalid Sat Feb 1 18:34:02 2014 From: look at signature.invalid (Wiktor) Date: Sun, 2 Feb 2014 00:34:02 +0100 Subject: Python prime numbers References: <158634a8-3c20-4e04-bc2a-a562c7270a3b@googlegroups.com> Message-ID: <10n152z4ab5ee$.uxddm41hh11e$.dlg@40tude.net> On Sat, 1 Feb 2014 07:33:47 -0800 (PST), Panagiotis Anastasiou wrote: > Hi i'm new in programming and in python and i have an assignment that > i cant complete. I have to Write a Python program to compute and print the > first 200 prime numbers. The output must be formatted with a title and the > prime numbers must be printed in 5 properly aligned columns . I have used this > code so far : Hi, try out this code: for i in range(200): print '{0:>5}'.format(i), if (i-4) % 5 == 0: print Or maybe, if it's still unclear, try execute these lines: print 'Hello {0}'.format('world') print '|{0:>30}|'.format('right') print '|{0:<30}|'.format('left') print '|{0:^30}|'.format('center') print '|{0:>16}|'.format('right'), print '|{0:<16}|'.format('left'), print '|{0:^16}|'.format('center') But still, it might be hard to implement this printing for..in loop while you're verifying primes (in another loop), so maybe think about getting first 200 primes in while loop like you do (and only storing them in a list), and then printing them out from this list in external for..in loop. Now, to your primetest() function. It may be good for small primes, but try to verify with it, if 832475734579 is a prime. :) > def primetest(potentialprime): > divisor = 2 > while divisor <= potentialprime: First of all, see that you rarely use this loop - you check this condition at most two times. You end up for good in the second while loop. > if potentialprime == 2: > return True > elif potentialprime % divisor == 0: > return False > break 'break' after return is redundant - never executes > while potentialprime % divisor != 0: > if potentialprime - divisor > 1: > divisor += 1 > else: > return True So, this is your main loop. Very inefficient. Think about that: a) do you really have to check divisors up to the potentialprime? Maybe there is a point, where you may say, that you've checked all possibilities? Remember that a * b = b * a b) do you really have to check every divisor? I mean, increasing it by 1 in every step? -- Best regards, Wiktor Matuszewski 'py{}@wu{}em.pl'.format('wkm', 'ka') From albert.visser at gmail.com Sat Feb 1 19:46:07 2014 From: albert.visser at gmail.com (albert visser) Date: Sun, 02 Feb 2014 01:46:07 +0100 Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: On Sun, 02 Feb 2014 00:07:00 +0100, Lewis Wood wrote: > On Saturday, 1 February 2014 22:26:17 UTC, Dave Angel wrote: >> Lewis Wood Wrote in message: (snip) >> >> DaveA > > It does, this is the whole code: > > from tkinter import * > > root=Tk() > root.title("Second Root Testing") > > > > def secondwindow(): > root2=Tk() > root2.mainloop() > this may seem to work, but you're starting a new event loop here instead of using the current one. I think you want to create another TopLevel() window here, not a new Tk instance. > > button1=Button(root,text="Root2",command=secondwindow).grid(row=0,column=0) > Note that if you want to be able to actually use the button1 symbol, you have to break this statement up: button1=Button(root,text="Root2",command=secondwindow) button1.grid(row=0,column=0) You can't shortcut this because grid() returns None. > > root.mainloop() > -- Vriendelijke groeten / Kind regards, Albert Visser Using Opera's mail client: http://www.opera.com/mail/ From tjreedy at udel.edu Sat Feb 1 20:08:16 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Feb 2014 20:08:16 -0500 Subject: generator slides review In-Reply-To: References: Message-ID: On 2/1/2014 9:12 AM, andrea crotti wrote: > I'm giving a talk tomorrow @Fosdem about generators/iterators/iterables.. > > The slides are here (forgive the strange Chinese characters): > https://dl.dropboxusercontent.com/u/3183120/talks/generators/index.html#3 > > and the code I'm using is: > https://github.com/AndreaCrotti/generators/blob/master/code/generators.py > and the tests: > https://github.com/AndreaCrotti/generators/blob/master/code/test_generators.py > > If anyone has any feedback or want to point out I'm saying something > stupid I'd love to hear it before tomorrow (or also later I might give > this talk again). Comments: The use is assert in the first slide seem bad in a couple of different respects. The use of 'gen_even' before it is defined. A generator expression evaluates (better than 'yields') to a generator, not just an iterator. The definition of 'generator' copies the wrong and confused glossary entry. Generator functions return generators, which are iterators with extra behavior. I would leave out For loop(2). The old pseudo-getitem iterator protocol is seldom explicitly used any more, in the say you showed. In 'Even numbers', I have no idea what the complication of next_even() is about. 'Lazyness drawbacks' overflow_list is bizarre and useless. overflow_gen is bizarre and buggy. If you are intentionally writing buggy code to make a point, label it as such on the slide. Iterators just produce values. Generators can consume as well as produce values, which is why they can act as both iterators and coroutines. @monocle -- Terry Jan Reedy From tjreedy at udel.edu Sat Feb 1 20:26:09 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 01 Feb 2014 20:26:09 -0500 Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: Idle, which used tkinter, runs multiple windows in one process with one event loop. There is no reason I know of to run multiple event loops in one process, and if you do, the results will not be documented and might vary between runs or between different systems. Idle can also be run multiple times in multiple processes, each with its own event loop. But there is seldom a reason to do that with the same version. On the other hand, I routinely have more than one version running in order to test code with multiple versions. I can even have the same file open in multiple versions. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Sat Feb 1 20:28:38 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Feb 2014 01:28:38 GMT Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ed9f46$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sun, 02 Feb 2014 07:09:14 +1100, Tim Delaney wrote: > On 1 February 2014 23:28, Ned Batchelder wrote: >> >> You are looking at things from an accurate-down-to-the-last-footnote >> detailed point of view (and have provided some footnotes!). That's a >> very valuable and important point of view. It's just not how most >> programmers approach the language. >> >> > This is the *language reference* that is being discussed. It documents > the intended semantics of the language. We most certainly should strive > to ensure that it is accurate-down-to-the-last-footnote - any difference > between the reference documentation and the implementation is a bug in > either the documentation or the implementation. +1 -- Steven From rmorgan466 at gmail.com Sat Feb 1 20:46:10 2014 From: rmorgan466 at gmail.com (Rita) Date: Sat, 1 Feb 2014 20:46:10 -0500 Subject: mapping objects Message-ID: Hello, I want to learn more about ORMs so I stumbled upon, SqlAlchemy. If i had a JSON document (or XML, CSV, etc.._) is it possible to convert it to a SQLAlchemy objects? I like the ability to query/filter ( http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#common-filter-operators) the data assuming I set up the proper schema. Also, is this a valid way to use an ORM suite? -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Sat Feb 1 22:29:13 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 01 Feb 2014 20:29:13 -0700 Subject: C++ to python for LED Matrix In-Reply-To: <52c58d64-be7e-4241-aef1-2215acde6ec6@googlegroups.com> References: <52c58d64-be7e-4241-aef1-2215acde6ec6@googlegroups.com> Message-ID: <52EDBB89.9030202@gmail.com> Yes you could use Python for this sort of thing. The link you posted is just using a kernel spi driver that Python can write to just as well as C++ can (via it's /dev/spidev0.0 file). There is a python library that can talk to SPI in Python on the pi: http://www.100randomtasks.com/simple-spi-on-raspberry-pi You still need to know some low-level stuff though. Like hexadecimal, binary bit-wise operations, etc. Definitely talk to people on the Raspberry Pi forum. They are doing this stuff frequently. Also don't be afraid of C. Learn it. You'll be glad. The code you linked to looks more complicated than it really is. The ioctl stuff looks complicated. But everything else is easy. If it weren't for the ioctl stuff, which I know can be translated to Python directly but I'm not quite sure how at the moment, the rest of that code could be transliterated into Python in very short order. The trick is to make the code more pythonic, and use classes when appropriate to encapsulate things. I'd make a class that talks to SPI, for example. It would open the file, set the ioctls, and then provide a basic interface for writing to the bus. Then from that I'd build another class that implements the matrix abstraction, using SPI class for the low-level stuff. From ben+python at benfinney.id.au Sat Feb 1 23:27:36 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 02 Feb 2014 15:27:36 +1100 Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <851tzmgmvb.fsf@benfinney.id.au> Ned Batchelder writes: > My summary of our two views is this: I am trying to look at things > from a typical programmer's point of view. Do you think the typical programmer will be looking in the language reference? I don't. > The existence of __new__ is an advanced topic that many programmers > never encounter. But when they do, the language reference had better be very clear on the purpose of ?__init__? and ?__new__?. > You are looking at things from an accurate-down-to-the-last-footnote > detailed point of view (and have provided some footnotes!). That's a > very valuable and important point of view. It's just not how most > programmers approach the language. Won't most programmers approach the language through (a) some example code, (b) the tutorial, (c) the library reference? Those are appropriate places for helpful simplifications and elisions. > We are also both trying to reduce cognitive dissonance, but again, you > are addressing language mavens who understand the footnotes, and I am > trying to help the in-the-trenches people who have never encountered > __new__ and are wondering why people are using funny words for the > code they are writing. Then I think your attempt to sacrifice precise terminology in the langauge reference is misplaced. The in-the-trenches people won't see it; and, when they go looking for it, they're likely to be wanting exact language-maven-directed specifications. > Finding names for things is hard, and it's impossible to please both > ends of this spectrum. Very true. That's why we have different documents for different audiences. But yes, the terminology needs to hold up for both ends of the spectrum, and naming is difficult. -- \ ?If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea? ?Thomas Jefferson | Ben Finney From swdunning at cox.net Sun Feb 2 01:06:18 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 1 Feb 2014 23:06:18 -0700 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: Yeah you?re right I didn?t even notice that. For some reason I just added the 60 instead of using quantity which had been defined. On Feb 1, 2014, at 8:50 AM, Dennis Lee Bieber wrote: > On Fri, 31 Jan 2014 22:18:34 -0700, Scott W Dunning > declaimed the following: > >> Any chance you guys could help with another question I have? Below is a code to a different problem. The only thing I don?t understand is why when calculating the 'discounted price? you have to subtract 1? Thanks again guys! >> > > Because the discount rate you have is the amount taken OFF the price. > But you need the price AFTER removing the discount amount 100% (1.0) - 40% > (0.4) discount => 60% (0.6) final price > >> price_per_book = 24.95 >> discount = .40 >> quantity = 60 >> discounted_price = (1-discount) * price_per_book >> shipping = 3.0 + (60 - 1) * .75 >> total_price = 60 * discounted_price + shipping >> print total_price, 'Total price' >> > You defined "quantity" but then never used it in the shipping and > total_price lines. > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > https://mail.python.org/mailman/listinfo/python-list From cs at zip.com.au Sun Feb 2 01:58:09 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 2 Feb 2014 17:58:09 +1100 Subject: mapping objects In-Reply-To: References: Message-ID: <20140202065809.GA4704@cskk.homeip.net> On 01Feb2014 20:46, Rita wrote: > I want to learn more about ORMs so I stumbled upon, SqlAlchemy. > > If i had a JSON document (or XML, CSV, etc.._) is it possible to convert it > to a SQLAlchemy objects? I like the ability to query/filter ( > http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#common-filter-operators) > the > data assuming I set up the proper schema. Well, not as directly as you might hope. As I recall, SQLAlchemy ORMs provide an easy way to make objects representing database entities and whose methods automatically drive the necessary SQL actions to manipulate them. On that basis, you won't get anywhere without loading up the JSON/XML/etc, parsing it for relevant information (trivial with CSV, less so for structured data like JSON or XML), and storing it in a database. To which you then point SQLAlchemy. So you're already doing the fiddly bit just to get stuff into the database. The neat filter operations you cite are actually done by special methods on the objects representing tables and columns. For example, User.name == None is done via the __eq__ method of "User.name". And they return strings: bare SQL. The beauty of this is that one can write almost idiomatic python, and SQLA will generate correct SQL in the right dialect for the database backend, and with all the values correctly escaped. However, it does presume you _already_ have a backend that can be queried with SQL. > Also, is this a valid way to use an ORM suite? Well, in principle sure. But SQLA won't do it for you directly. It really is for data already stored in an SQL queriable database. Your point about using SQLA's filter operations is right, _provided_ you have already loaded the original data into a database with the right schema. If you've done that work, then SQLA may well serve you well from that point on. Cheers, -- Cameron Simpson We knew Army cadets were involved because they cut through two fences to get to the goats, and 15 feet away there was an unlocked gate. - a director of sports information in the Navy, regarding the theft of some mascots from the Naval Academy by Army rivals From auriocus at gmx.de Sun Feb 2 05:15:21 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sun, 02 Feb 2014 11:15:21 +0100 Subject: Tkinter widgets into classes. In-Reply-To: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> Message-ID: Am 01.02.14 20:43, schrieb Lewis Wood: > I was wandering if I could dynamically change my GUI and after a few searches on Google found the grid_remove() function. What I'm wandering now is if there is a way to group a lot of widgets up into one, and then use the one grid_remove function which will remove them all. > > Is it possible to do this in a class like this? > > class group1: > label1=Label(text="Upon clicking the button").grid(row=0,column=0) > label2=Label(text="The menu will dynamically change").grid(row=1,column=0) > > group1.grid_remove() Well, you are on the right track, it is a good idea to structure a complex GUI by breaking it up into smaller functional pieces. The right way to do it is called "megawidget", and it's done by making a Frame which contains the subwidgets; e.g. ========================= import Tkinter as Tk import ttk # python3: # import tkinter as Tk # from tkinter import ttk class dbllabel(ttk.Frame): def __init__(self, parent, text1, text2): ttk.Frame.__init__(self, parent) # python3: # super(dbllabel, self).__init__(self, parent) self.l1=ttk.Label(self, text=text1) self.l2=ttk.Label(self, text=text2) self.l1.grid(row=0, column=0) self.l2.grid(row=1, column=0) # now use the dbllabel in our program # like a regular widget root=Tk.Tk() mainframe = ttk.Frame(root) mainframe.pack(expand=True, fill=Tk.BOTH) # here is no difference between making a button # and our fresh new megawidget foo=ttk.Button(mainframe, text="Some other widet") bar=dbllabel(mainframe, text1="First line", text2="Second line") foo.grid(row=0, column=0) bar.grid(row=0, column=1) root.mainloop() ======================== Note that 1) I only have python2 to test it here now, so there might be an error on the python3 parts 2) I've used ttk widgets all over where possible. This should give the most expected look and feel on all platforms 3) More complex megawidgets will of course also group functionality (i.e. reactions to button clicks etc.) in the same megawidget class Christian From auriocus at gmx.de Sun Feb 2 05:22:01 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sun, 02 Feb 2014 11:22:01 +0100 Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: Am 02.02.14 00:07, schrieb Lewis Wood: > It does, this is the whole code: > > from tkinter import * > > root=Tk() > root.title("Second Root Testing") > > def secondwindow(): > root2=Tk() > root2.mainloop() > > > button1=Button(root,text="Root2",command=secondwindow).grid(row=0,column=0) > > root.mainloop() I don't know how this works, but it is definitely wrong. If you need more than one window, use Toplevel() to create it. Christian From andrea.crotti.0 at gmail.com Sun Feb 2 05:40:11 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sun, 2 Feb 2014 10:40:11 +0000 Subject: generator slides review In-Reply-To: References: Message-ID: 2014-02-02 Terry Reedy : > On 2/1/2014 9:12 AM, andrea crotti wrote: > > Comments: > > The use is assert in the first slide seem bad in a couple of different > respects. > Why is it bad? It's probably not necessary but since we ask for a range it might be good to check if the range is valid. Maybe I should raise ValueError instead for a better exception? > The use of 'gen_even' before it is defined. > Well this is because l'm saying that I wish I had something like this, which I define just after. It might be confusing if it's not defined but I thought it's nice to say what I would like to do and then actually define it, what do you think? > A generator expression evaluates (better than 'yields') to a generator, not > just an iterator. > Ok thanks fixed > The definition of 'generator' copies the wrong and confused glossary entry. > Generator functions return generators, which are iterators with extra > behavior. > I understood instead that it was the opposite, a generator is a specialized iterator, so it would be still correct that it returns an iterator, is that wrong? > I would leave out For loop(2). The old pseudo-getitem iterator protocol is > seldom explicitly used any more, in the say you showed. > This was mainly to explain how something like for el in [1, 2, 3]: print(el) can work, assuming defining an object list-like that just implements __getitem__. It's not probably how it's implemented for lists but I thought it could clarify things.. > In 'Even numbers', I have no idea what the complication of next_even() is > about. > Just because I wanted to find a simple way to get the next even (in case I pass an odd start number). I could also do inline but I thought it was more clear.. > 'Lazyness drawbacks' overflow_list is bizarre and useless. overflow_gen is > bizarre and buggy. If you are intentionally writing buggy code to make a > point, label it as such on the slide. > Yes this is intentionally buggy. The thing is that I wanted to show that sometimes generating things makes it harder to debug, and delays some errors, which are anyway there but would come up immediately in case of a list creation. I could not find a better non artificial example for this, any suggestion is welcome.. > Iterators just produce values. Generators can consume as well as produce > values, which is why they can act as both iterators and coroutines. > Well is not more clear to call them in a different way since they do quite a different job as coroutines or generators? (I see this done quite often) Thanks a lot for the great feedback From andrea.crotti.0 at gmail.com Sun Feb 2 05:48:40 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sun, 2 Feb 2014 10:48:40 +0000 Subject: generator slides review In-Reply-To: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: 2014-02-01 Miki Tebeka : > > My 2 cents: > > slide 4: > [i*2 for i in range(10)] > Well this is not correct in theory because the end should be the max number, not the number of elements. So it should be [i*2 for i in range(10/2)] which might be fine but it's not really more clear imho.. > slide 9: > while True: > try: > it = next(g) > body(it) > except StopIteration: > break > Changed it thanks > slide 21: > from itertools import count, ifilterfalse > > def divided_by(p): > return lambda n: n % p == 0 > > def primes(): > nums = count(2) > while True: > p = next(nums) > yield p > nums = ifilterfalse(divided_by(p), nums) > Thank you that's nicer, but ifiilterfalse is not in Python 3 (could use filter of course). From andrea.crotti.0 at gmail.com Sun Feb 2 05:50:44 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sun, 2 Feb 2014 10:50:44 +0000 Subject: generator slides review In-Reply-To: References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: The slides are updated now 2014-02-02 andrea crotti : > 2014-02-01 Miki Tebeka : >> >> My 2 cents: >> >> slide 4: >> [i*2 for i in range(10)] >> > > Well this is not correct in theory because the end should be the max > number, not the number of elements. > So it should be > [i*2 for i in range(10/2)] which might be fine but it's not really > more clear imho.. > >> slide 9: >> while True: >> try: >> it = next(g) >> body(it) >> except StopIteration: >> break >> > > Changed it thanks > >> slide 21: >> from itertools import count, ifilterfalse >> >> def divided_by(p): >> return lambda n: n % p == 0 >> >> def primes(): >> nums = count(2) >> while True: >> p = next(nums) >> yield p >> nums = ifilterfalse(divided_by(p), nums) >> > > Thank you that's nicer, but ifiilterfalse is not in Python 3 (could > use filter of course). From andrea.crotti.0 at gmail.com Sun Feb 2 05:52:26 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sun, 2 Feb 2014 10:52:26 +0000 Subject: generator slides review In-Reply-To: References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: Sorry left too early, the slides are updated with the fixes suggested, thanks everyone. https://dl.dropboxusercontent.com/u/3183120/talks/generators/index.html#1 For me the biggest problem is still: - to find some more interesting example that is easy enough to explain - to find a better order in which explain things, to tell a clear story in a way 2014-02-02 andrea crotti : > The slides are updated now > > 2014-02-02 andrea crotti : >> 2014-02-01 Miki Tebeka : >>> >>> My 2 cents: >>> >>> slide 4: >>> [i*2 for i in range(10)] >>> >> >> Well this is not correct in theory because the end should be the max >> number, not the number of elements. >> So it should be >> [i*2 for i in range(10/2)] which might be fine but it's not really >> more clear imho.. >> >>> slide 9: >>> while True: >>> try: >>> it = next(g) >>> body(it) >>> except StopIteration: >>> break >>> >> >> Changed it thanks >> >>> slide 21: >>> from itertools import count, ifilterfalse >>> >>> def divided_by(p): >>> return lambda n: n % p == 0 >>> >>> def primes(): >>> nums = count(2) >>> while True: >>> p = next(nums) >>> yield p >>> nums = ifilterfalse(divided_by(p), nums) >>> >> >> Thank you that's nicer, but ifiilterfalse is not in Python 3 (could >> use filter of course). From __peter__ at web.de Sun Feb 2 07:47:06 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Feb 2014 13:47:06 +0100 Subject: generator slides review References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: andrea crotti wrote: > 2014-02-01 Miki Tebeka : >> >> My 2 cents: >> slide 21: >> from itertools import count, ifilterfalse >> >> def divided_by(p): >> return lambda n: n % p == 0 >> >> def primes(): >> nums = count(2) >> while True: >> p = next(nums) >> yield p >> nums = ifilterfalse(divided_by(p), nums) >> > > Thank you that's nicer, It may be nice, but is probably less efficient because of the lambda function calls that replace the if expression in your > def exclude_multiples(n, ints): > for i in ints: > if (i % n) != 0: > yield i > but ifiilterfalse is not in Python 3 (could > use filter of course). ifilterfalse() isn't gone in Python3, it just was renamed to filterfalse(). From rmorgan466 at gmail.com Sun Feb 2 07:41:59 2014 From: rmorgan466 at gmail.com (Rita) Date: Sun, 2 Feb 2014 07:41:59 -0500 Subject: mapping objects In-Reply-To: <20140202065809.GA4704@cskk.homeip.net> References: <20140202065809.GA4704@cskk.homeip.net> Message-ID: Thanks for the response Cameron. No amount of 'googling' could provide me with that caliber response :-) So, it seems regardless I would need a database. On Sun, Feb 2, 2014 at 1:58 AM, Cameron Simpson wrote: > On 01Feb2014 20:46, Rita wrote: > > I want to learn more about ORMs so I stumbled upon, SqlAlchemy. > > > > If i had a JSON document (or XML, CSV, etc.._) is it possible to convert > it > > to a SQLAlchemy objects? I like the ability to query/filter ( > > > http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#common-filter-operators > ) > > the > > data assuming I set up the proper schema. > > Well, not as directly as you might hope. As I recall, SQLAlchemy > ORMs provide an easy way to make objects representing database > entities and whose methods automatically drive the necessary SQL > actions to manipulate them. > > On that basis, you won't get anywhere without loading up the > JSON/XML/etc, parsing it for relevant information (trivial with > CSV, less so for structured data like JSON or XML), and storing it > in a database. To which you then point SQLAlchemy. > > So you're already doing the fiddly bit just to get stuff into the database. > > The neat filter operations you cite are actually done by special > methods on the objects representing tables and columns. For example, > > User.name == None > > is done via the __eq__ method of "User.name". And they return > strings: bare SQL. The beauty of this is that one can write almost > idiomatic python, and SQLA will generate correct SQL in the right > dialect for the database backend, and with all the values correctly > escaped. > > However, it does presume you _already_ have a backend that can be > queried with SQL. > > > Also, is this a valid way to use an ORM suite? > > Well, in principle sure. But SQLA won't do it for you directly. It really > is for data already stored in an SQL queriable database. > > Your point about using SQLA's filter operations is right, _provided_ > you have already loaded the original data into a database with the > right schema. If you've done that work, then SQLA may well serve > you well from that point on. > > Cheers, > -- > Cameron Simpson > > We knew Army cadets were involved because they cut through two fences > to get to the goats, and 15 feet away there was an unlocked gate. > - a director of sports information in the Navy, regarding the theft > of some mascots from the Naval Academy by Army rivals > -- > https://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 petef4+usenet at gmail.com Sun Feb 2 07:45:54 2014 From: petef4+usenet at gmail.com (Pete Forman) Date: Sun, 02 Feb 2014 12:45:54 +0000 Subject: pytz question: GMT vs. UTC References: <3g6je9h7fp29pebi7aa04tigc50hm3vepj@4ax.com> <52E9BB8C.80000@mrabarnett.plus.com> Message-ID: <86ha8hsmwt.fsf@gmail.com> Grant Edwards writes: > On 2014-01-30, wxjmfauth at gmail.com wrote: > >> The temperature unit is the "Kelvin", not the "Degree Kelvin". >> One writes: 0 K, 275.15 K > > And remember to say "Kelvins" not "Kelvin" when speaking about > temperatures other than 1 K. And remember to write kelvins. SI units named after people such as kelvin, watt and pascal are lower case while their symbols have a leading capital: K, W, Pa. -- Pete Forman From wxjmfauth at gmail.com Sun Feb 2 09:38:07 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 2 Feb 2014 06:38:07 -0800 (PST) Subject: pytz question: GMT vs. UTC In-Reply-To: <86ha8hsmwt.fsf@gmail.com> References: <3g6je9h7fp29pebi7aa04tigc50hm3vepj@4ax.com> <52E9BB8C.80000@mrabarnett.plus.com> <86ha8hsmwt.fsf@gmail.com> Message-ID: <57a590a5-8f00-4879-8307-4b450f08a5af@googlegroups.com> Le dimanche 2 f?vrier 2014 13:45:54 UTC+1, Pete Forman a ?crit?: > Grant Edwards writes: > > > > > On 2014-01-30, wxjmfauth at gmail.com wrote: > > > > > >> The temperature unit is the "Kelvin", not the "Degree Kelvin". > > >> One writes: 0 K, 275.15 K > > > > > > And remember to say "Kelvins" not "Kelvin" when speaking about > > > temperatures other than 1 K. > > > > And remember to write kelvins. SI units named after people such as > > kelvin, watt and pascal are lower case while their symbols have a > > leading capital: K, W, Pa. > > -- > > Pete Forman Yes, correct. (I focussed on the word *degree* in the expression "degree kelvin". jmf From miki.tebeka at gmail.com Sun Feb 2 09:59:30 2014 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sun, 2 Feb 2014 06:59:30 -0800 (PST) Subject: generator slides review In-Reply-To: References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: > Thank you that's nicer, but ifiilterfalse is not in Python 3 (could > > use filter of course). It was renamed to filterfalse - http://docs.python.org/3.3/library/itertools.html#itertools.filterfalse From allison.k.gray at gmail.com Sun Feb 2 10:39:56 2014 From: allison.k.gray at gmail.com (Allison Gray) Date: Sun, 2 Feb 2014 07:39:56 -0800 (PST) Subject: Unable to Launch Python 2.7 after Windows 8.1 Update Message-ID: I recently obtained a new laptop with Windows 8.1 and installed Python 2.7. Everything was working fine. Then after my first update, I was unable to launch Python. After clicking the Python icon, the thinking cursor activated, but Python never opened. I restored my laptop to a time before the update, and am now able to run Python. I have changed my automatic update setting to prevent this from happening again but this is less than ideal. Has anyone had this problem? Does anyone know what Windows setting would prevent Python IDLE from opening? Any help would be appreciated!! From invalid at invalid.invalid Sun Feb 2 11:03:39 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 2 Feb 2014 16:03:39 +0000 (UTC) Subject: pytz question: GMT vs. UTC References: <3g6je9h7fp29pebi7aa04tigc50hm3vepj@4ax.com> <52E9BB8C.80000@mrabarnett.plus.com> <86ha8hsmwt.fsf@gmail.com> Message-ID: On 2014-02-02, Pete Forman wrote: > Grant Edwards writes: > >> On 2014-01-30, wxjmfauth at gmail.com wrote: >> >>> The temperature unit is the "Kelvin", not the "Degree Kelvin". >>> One writes: 0 K, 275.15 K >> >> And remember to say "Kelvins" not "Kelvin" when speaking about >> temperatures other than 1 K. > > And remember to write kelvins. SI units named after people such as > kelvin, watt and pascal are lower case while their symbols have a > leading capital: K, W, Pa. Indeed. Many years ago, I was taught to capitalize units that were originally proper nouns. I'm pretty sure this isn't the first time I've learned that is incorrect, but my fingers keep insisting on doing it. Interestingly, one does capitalizes Celsius when writing "degrees Celsius" [at least according to the NIST]. http://physics.nist.gov/Pubs/SP811/sec09.html -- Grant From dwightdhutto at gmail.com Sun Feb 2 11:11:07 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 08:11:07 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: price_per_book = 24.95 discount = .40 quantity = 60 Here: discounted_price = (1-discount) * price_per_book The discounted price should be price_per_book - discount shipping = 3.0 + (60 - 1) * .75 shipping should be, I think, should be 3.0 + (quantity * .75) total_price = 60 * discounted_price + shipping replace 60 with quantity (quantity * discounted_price) + shipping print total_price, 'Total price' total_price gives: 945.45 Total price and just 24.55(price per book - discount is ) * quantity is $1473 without the shipping, so the total is way off already: I think the following is what you're looking for: price_per_book = 24.95 discount = .40 quantity = 60 discounted_price = price_per_book-discount shipping = 3.0 + (quantity*.75) total_price = (quantity * discounted_price) + shipping print 'Total price: $%d' % (total_price) Total price: $1521 From python at mrabarnett.plus.com Sun Feb 2 11:16:20 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Feb 2014 16:16:20 +0000 Subject: Unable to Launch Python 2.7 after Windows 8.1 Update In-Reply-To: References: Message-ID: <52EE6F54.2020303@mrabarnett.plus.com> On 2014-02-02 15:39, Allison Gray wrote: > I recently obtained a new laptop with Windows 8.1 and installed > Python 2.7. Everything was working fine. Then after my first update, > I was unable to launch Python. After clicking the Python icon, the > thinking cursor activated, but Python never opened. I restored my > laptop to a time before the update, and am now able to run Python. I > have changed my automatic update setting to prevent this from > happening again but this is less than ideal. Has anyone had this > problem? Does anyone know what Windows setting would prevent Python > IDLE from opening? > > Any help would be appreciated!! > I would've suggested re-installing Python. That would've been worth trying. From python at mrabarnett.plus.com Sun Feb 2 11:38:57 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Feb 2014 16:38:57 +0000 Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: <52EE74A1.2090606@mrabarnett.plus.com> On 2014-02-02 16:11, David Hutto wrote: > price_per_book = 24.95 > discount = .40 > quantity = 60 > The original problem says: Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? > Here: > discounted_price = (1-discount) * price_per_book > > The discounted price should be price_per_book - discount > No, the discount of 0.40 is 40%, not 40 cents. > shipping = 3.0 + (60 - 1) * .75 > shipping should be, I think, should be 3.0 + (quantity * .75) > No, the shipping is 75 cents starting from the second copy. > total_price = 60 * discounted_price + shipping > replace 60 with quantity (quantity * discounted_price) + shipping > > print total_price, 'Total price' > > total_price gives: > 945.45 Total price > and just 24.55(price per book - discount is ) * quantity is $1473 without the shipping, so the total is way off already: > > > I think the following is what you're looking for: > > price_per_book = 24.95 > discount = .40 > quantity = 60 > discounted_price = price_per_book-discount > shipping = 3.0 + (quantity*.75) > total_price = (quantity * discounted_price) + shipping > print 'Total price: $%d' % (total_price) > Total price: $1521 > From dwightdhutto at gmail.com Sun Feb 2 11:36:11 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 08:36:11 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Sunday, February 2, 2014 11:11:07 AM UTC-5, David Hutto wrote: > price_per_book = 24.95 > > discount = .40 > > quantity = 60 > > > > Here: > > discounted_price = (1-discount) * price_per_book > > > > The discounted price should be price_per_book - discount > > > > shipping = 3.0 + (60 - 1) * .75 > > shipping should be, I think, should be 3.0 + (quantity * .75) > > > > total_price = 60 * discounted_price + shipping > > replace 60 with quantity (quantity * discounted_price) + shipping > > > > print total_price, 'Total price' > > > > total_price gives: > > 945.45 Total price > > and just 24.55(price per book - discount is ) * quantity is $1473 without the shipping, so the total is way off already: > > > > > > I think the following is what you're looking for: > > > > price_per_book = 24.95 > > discount = .40 > > quantity = 60 > > discounted_price = price_per_book-discount > > shipping = 3.0 + (quantity*.75) > > total_price = (quantity * discounted_price) + shipping > > print 'Total price: $%d' % (total_price) > > Total price: $1521 My bad, I thought you were using $0.40 as a discount From dwightdhutto at gmail.com Sun Feb 2 11:57:03 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 08:57:03 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Sunday, February 2, 2014 11:38:57 AM UTC-5, MRAB wrote: > On 2014-02-02 16:11, David Hutto wrote: > > > price_per_book = 24.95 > > > discount = .40 > > > quantity = 60 > > > > > The original problem says: > > > > Suppose the cover price of a book is $24.95, but bookstores get a 40% > > discount. Shipping costs $3 for the first copy and 75 cents for each > > additional copy. What is the total wholesale cost for 60 copies? > > > > > Here: > > > discounted_price = (1-discount) * price_per_book > > > > > > The discounted price should be price_per_book - discount > > > > > No, the discount of 0.40 is 40%, not 40 cents. > > > > > shipping = 3.0 + (60 - 1) * .75 > > > shipping should be, I think, should be 3.0 + (quantity * .75) > > > > > No, the shipping is 75 cents starting from the second copy. > > > > > total_price = 60 * discounted_price + shipping > > > replace 60 with quantity (quantity * discounted_price) + shipping > > > > > > print total_price, 'Total price' > > > > > > total_price gives: > > > 945.45 Total price > > > and just 24.55(price per book - discount is ) * quantity is $1473 without the shipping, so the total is way off already: > > > > > > > > > I think the following is what you're looking for: > > > > > > price_per_book = 24.95 > > > discount = .40 > > > quantity = 60 > > > discounted_price = price_per_book-discount > > > shipping = 3.0 + (quantity*.75) > > > total_price = (quantity * discounted_price) + shipping > > > print 'Total price: $%d' % (total_price) > > > Total price: $1521 > > > Revised: price_per_book = 24.95 percent_discount = .40 discounted_price = price_per_book - (price_per_book * percent_discount) quantity = 60 shipping = 3.0 + ((quantity - 1)*.75) total_price = (quantity * discounted_price) + shipping print 'Total price: $%d' % (total_price) From rhodri at wildebst.org.uk Sun Feb 2 12:15:05 2014 From: rhodri at wildebst.org.uk (Rhodri James) Date: Sun, 02 Feb 2014 17:15:05 -0000 Subject: Help with some python homework... References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Sat, 01 Feb 2014 05:18:34 -0000, Scott W Dunning wrote: > Any chance you guys could help with another question I have? Below is a > code to a different problem. The only thing I don?t understand is why > when calculating the 'discounted price? you have to subtract 1? Thanks > again guys! > > price_per_book = 24.95 > discount = .40 > quantity = 60 > discounted_price = (1-discount) * price_per_book > shipping = 3.0 + (60 - 1) * .75 > total_price = 60 * discounted_price + shipping > print total_price, 'Total price' The thing that is confusing you is that "discounted_price" is conflating several steps into one. Think of it like this: * "discount" is the discount rate; in this case meaning that a book costs 40% less than its list price ("price_per_book"). * In other words, the book costs "discount * price_per_book" less than its list price. * So the book costs "price_per_book - (discount * price_per_book)" after applying the discount. * refactoring, that's "(1 - discount) * price_per_book." Ta da! -- Rhodri James *-* Wildebeest Herder to the Masses From denismfmcmahon at gmail.com Sun Feb 2 12:43:01 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 2 Feb 2014 17:43:01 +0000 (UTC) Subject: Help with some python homework... References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Sun, 02 Feb 2014 08:57:03 -0800, David Hutto wrote: > Revised: > discounted_price = price_per_book - (price_per_book * percent_discount) by applying some simple algebra to the right hand side price_per_book - (price_per_book * percent_discount) "x = (x * 1)" so "price_per_book == (price_per_book * 1)" so rhs becomes (price_per_book * 1) - (price_per_book * percent_discount) and "(a * x) - (a * y)" == "a * (x - y)" so rhs becomes price_per_book * (1 - percent_discount) hence: discounted_price = price_per_book * (1 - percent_discount) -- Denis McMahon, denismfmcmahon at gmail.com From jeandupont314 at gmail.com Sun Feb 2 12:44:05 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Sun, 2 Feb 2014 09:44:05 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems Message-ID: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> I'm looking for an efficient method to produce rows of tables like this: for base 2 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 . . . 1 1 1 1 for base 3 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 1 2 . . 2 2 2 2 2 2 As you can see the rows are always twice the size of the base I _don't_ need to have all rows available together in one array which would become too large for higher value number bases. It's sufficient to produce one row after the other, as I will do further data manipulation on such a row immediately. If someone here could suggest best practices to perform this kind of operations,I'd really appreciate it very much kind regards and thanks in advance jean From ashikbekal at gmail.com Sun Feb 2 12:52:16 2014 From: ashikbekal at gmail.com (Ashik Bekal) Date: Sun, 2 Feb 2014 09:52:16 -0800 (PST) Subject: Project survey Message-ID: <53d3847b-8993-48fe-8935-d18fddb26b47@googlegroups.com> Help us improve our app by completing this simple survey... https://docs.google.com/forms/d/164j4anIdefOF7yhuRWIi3IF2EW_Vmippy4lLtxUhj68/viewform From roy at panix.com Sun Feb 2 13:07:38 2014 From: roy at panix.com (Roy Smith) Date: Sun, 02 Feb 2014 13:07:38 -0500 Subject: [newbie] making rows of table with discrete values for different number systems References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> Message-ID: In article <515e582f-ed17-4d4e-9872-f07f1fda6ed2 at googlegroups.com>, Jean Dupont wrote: > I'm looking for an efficient method to produce rows of tables like this: > > for base 2 > 0 0 0 0 > 0 0 0 1 > 0 0 1 0 > 0 0 1 1 > 0 1 0 0 > . > . > . > 1 1 1 1 > > for base 3 > 0 0 0 0 0 0 > 0 0 0 0 0 1 > 0 0 0 0 0 2 > 0 0 0 0 1 0 > 0 0 0 0 1 1 > 0 0 0 0 1 2 > . > . > 2 2 2 2 2 2 This sounds like a homework problem :-) > As you can see the rows are always twice the size of the base Why? > I _don't_ need to have all rows available together in one array which would > become too large for higher value number bases. It's sufficient to produce > one row after the other, as I will do further data manipulation on such a row > immediately. What I get out of that is that you don't want to just print them, you want to have some function which returns all the generated rows in order. The way to do that is with the yield statement. Take a look at https://wiki.python.org/moin/Generators for some discussion on how that works. Actually, http://stackoverflow.com/questions/231767/ looks like an even better discussion. Does that help you any? From dwightdhutto at gmail.com Sun Feb 2 13:09:08 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 10:09:08 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: On Sunday, February 2, 2014 12:43:01 PM UTC-5, Denis McMahon wrote: > On Sun, 02 Feb 2014 08:57:03 -0800, David Hutto wrote: > > > > > Revised: > > > > > discounted_price = price_per_book - (price_per_book * percent_discount) > > > > by applying some simple algebra to the right hand side > > > > price_per_book - (price_per_book * percent_discount) > > > > "x = (x * 1)" so "price_per_book == (price_per_book * 1)" so rhs becomes > > > > (price_per_book * 1) - (price_per_book * percent_discount) > > > > and "(a * x) - (a * y)" == "a * (x - y)" so rhs becomes > > > > price_per_book * (1 - percent_discount) > > > > hence: > > > > discounted_price = price_per_book * (1 - percent_discount) > > > > -- > > Denis McMahon The one just looks out of place compare to using properly defined names,(algebra aside) like this: def order_total(): price_per_book = float(raw_input("Enter price per book: $")) percent_discount_amount = float(raw_input("Enter percent discount amount(in format example .40): ")) quantity = float(raw_input("Enter quantity of books: ")) first_book_shipping = float(raw_input("Enter first book's shipping: $")) extra_book_shipping = float(raw_input("Enter extra book's shipping costs: $")) percent_discount = price_per_book * percent_discount_amount amount_of_first_books = 1 # of course it would equal 1 discounted_price = price_per_book - percent_discount shipping = first_book_shipping + ((quantity - amount_of_first_books) * extra_book_shipping) total_price = (quantity * discounted_price) + shipping print 'Total price: $%d' % (total_price) order_total() ************Or Use with params for iterating through larger amounts of books to be calculated***************** def order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping): percent_discount = price_per_book * percent_discount_amount amount_of_first_book = 1 # of course it would equal 1 discounted_price = price_per_book - percent_discount shipping = first_book_shipping + ((quantity - amount_of_first_book) * extra_book_shipping) total_price = (quantity * discounted_price) + shipping print 'Total price: $%d' % (total_price) price_per_book = float(raw_input("Enter price per book: $")) percent_discount_amount = float(raw_input("Enter percent discount amount(in format example .40): ")) quantity = float(raw_input("Enter quantity of books: ")) first_book_shipping = float(raw_input("Enter first book's shipping: $")) extra_book_shipping = float(raw_input("Enter extra book's shipping costs: $")) order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping) The numbers just seem out of place when a var can be used that properly defines it, or another way to arrive at the same solution. From __peter__ at web.de Sun Feb 2 13:10:32 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Feb 2014 19:10:32 +0100 Subject: [newbie] making rows of table with discrete values for different number systems References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> Message-ID: Jean Dupont wrote: > I'm looking for an efficient method to produce rows of tables like this: > > for base 2 > 0 0 0 0 > 0 0 0 1 > 0 0 1 0 > 0 0 1 1 > 0 1 0 0 > . > . > . > 1 1 1 1 > > for base 3 > 0 0 0 0 0 0 > 0 0 0 0 0 1 > 0 0 0 0 0 2 > 0 0 0 0 1 0 > 0 0 0 0 1 1 > 0 0 0 0 1 2 > . > . > 2 2 2 2 2 2 > > As you can see the rows are always twice the size of the base > I _don't_ need to have all rows available together in one array which > would become too large for higher value number bases. It's sufficient to > produce one row after the other, as I will do further data manipulation on > such a row immediately. > > If someone here could suggest best practices to perform this kind of > operations,I'd really appreciate it very much Have a look at itertools.product(): >>> import itertools >>> for row in itertools.product(range(2), repeat=4): ... print(*row) ... 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 From roegltd at gmail.com Sun Feb 2 13:26:05 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 2 Feb 2014 10:26:05 -0800 (PST) Subject: Python (windows)packet sniffer ARP In-Reply-To: References: Message-ID: <697d33c0-c118-4ce0-a631-f91d36cb456a@googlegroups.com> On Friday, January 31, 2014 9:10:28 AM UTC+2, Ralle wrote: > Hello > > I am wondering if it possible to create a packet sniffer in windows using python that only sniffs for ARP packets. In addition to Mark Betz suggestion - http://www.wireshark.org/ it works above winpcap and it is full functional protocol analyzer. though for high loads it just hangs. From dwightdhutto at gmail.com Sun Feb 2 14:08:40 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 11:08:40 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: Or a better iterating example for a database of shipping, or ordering books would be: import random as r def order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping): percent_discount = price_per_book * percent_discount_amount amount_of_first_book = 1 # of course it would equal 1 discounted_price = price_per_book - percent_discount shipping = first_book_shipping + ((quantity - amount_of_first_book) * extra_book_shipping) total_price = (quantity * discounted_price) + shipping print "Book XYZ-%d-ABC \nPrice per book: $%d\nPercent discount amount: %f\nQuantity of books: %f\nFirst book's shipping: $%f\nextra_book_shipping: $%f\nTotal price: $%f\n" % (books,price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping,total_price) if __name__ == '__main__': for books in range(0,10): price_per_book = float(r.randint(1,100)) percent_discount_amount = float(".%d" % r.randint(0,100)) quantity = float(r.randint(0,100)) first_book_shipping = float(r.randint(0,100)) extra_book_shipping = float(r.randint(0,100)) order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping) From dwightdhutto at gmail.com Sun Feb 2 14:21:44 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 11:21:44 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> Message-ID: Should have been the following, which just shows the books price as a float as well, but you get the point by now, I'm sure: import random as r def order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping): percent_discount = price_per_book * percent_discount_amount amount_of_first_book = 1 # of course it would equal 1 discounted_price = price_per_book - percent_discount shipping = first_book_shipping + ((quantity - amount_of_first_book) * extra_book_shipping) total_price = (quantity * discounted_price) + shipping print "Book XYZ-%d-ABC \nPrice per book: $%f\nPercent discount amount: %f\nQuantity of books: %f\nFirst book's shipping: $%f\nextra_book_shipping: $%f\nTotal price: $%f\n" % (books,price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping,total_price) if __name__ == '__main__': for books in range(0,10): price_per_book = float(r.randint(1,100)) percent_discount_amount = float(".%d" % r.randint(0,100)) quantity = float(r.randint(0,100)) first_book_shipping = float(r.randint(0,100)) extra_book_shipping = float(r.randint(0,100)) order_total(price_per_book,percent_discount_amount,quantity,first_book_shipping,extra_book_shipping) From fluttershy363 at gmail.com Sun Feb 2 15:38:16 2014 From: fluttershy363 at gmail.com (Lewis Wood) Date: Sun, 2 Feb 2014 12:38:16 -0800 (PST) Subject: Tkinter widgets into classes. In-Reply-To: References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> Message-ID: <0bfb9c90-ee4d-42aa-b181-17b2b6dd1ea7@googlegroups.com> Thanks all who replied, will look further into megawidgets and the Toplevel() function. Is there a way to get a separate window to return something when closed? From jeandupont314 at gmail.com Sun Feb 2 15:51:15 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Sun, 2 Feb 2014 12:51:15 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> Message-ID: <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: > Jean Dupont wrote: > > > I'm looking for an efficient method to produce rows of tables like this: > > > > for base 2 > > 0 0 0 0 > > 0 0 0 1 > > 0 0 1 0 > > 0 0 1 1 > > 0 1 0 0 > > . > > . > > . > > 1 1 1 1 > > > > for base 3 > > 0 0 0 0 0 0 > > 0 0 0 0 0 1 > > 0 0 0 0 0 2 > > 0 0 0 0 1 0 > > 0 0 0 0 1 1 > > 0 0 0 0 1 2 > > . > > . > > 2 2 2 2 2 2 > > > > As you can see the rows are always twice the size of the base > > I _don't_ need to have all rows available together in one array which > > would become too large for higher value number bases. It's sufficient to > > produce one row after the other, as I will do further data manipulation on > > such a row immediately. > > > > If someone here could suggest best practices to perform this kind of > > operations,I'd really appreciate it very much > > Have a look at itertools.product(): > > >>> import itertools > >>> for row in itertools.product(range(2), repeat=4): > ... print(*row) > ... > 0 0 0 0 > 0 0 0 1 > 0 0 1 0 > 0 0 1 1 > 0 1 0 0 > 0 1 0 1 > 0 1 1 0 > 0 1 1 1 > 1 0 0 0 > 1 0 0 1 > 1 0 1 0 > 1 0 1 1 > 1 1 0 0 > 1 1 0 1 > 1 1 1 0 > 1 1 1 1 Thanks for the suggestion I'm going to look into it further kind regards, jean From gordon at panix.com Sun Feb 2 16:16:14 2014 From: gordon at panix.com (John Gordon) Date: Sun, 2 Feb 2014 21:16:14 +0000 (UTC) Subject: Unable to Launch Python 2.7 after Windows 8.1 Update References: Message-ID: In Allison Gray writes: > I recently obtained a new laptop with Windows 8.1 and installed Python 2.7.= > Everything was working fine. Then after my first update, I was unable to l= > aunch Python. After clicking the Python icon, the thinking cursor activated= > , but Python never opened. I restored my laptop to a time before the update= > , and am now able to run Python. I have changed my automatic update setting= > to prevent this from happening again but this is less than ideal. Has anyo= > ne had this problem? Does anyone know what Windows setting would prevent Py= > thon IDLE from opening?=20 Try opening a command window and run Python from there; that way you'll be able to see any error mesages that crop up. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From charliewinn97 at gmail.com Sun Feb 2 16:16:44 2014 From: charliewinn97 at gmail.com (Charlie Winn) Date: Sun, 2 Feb 2014 13:16:44 -0800 (PST) Subject: Calculator Problem Message-ID: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this def Addition(): print('Addition: What are two your numbers?') 1 = float(input('First Number:')) 2 = float(input('Second Number:')) print('Your Final Result is:', 1 + 2) def Subtraction(): print('Subtraction: What are two your numbers?') 3 = float(input('First Number:')) 4 = float(input('Second Number:')) print('Your Final Result is:', 3 - 4) def Multiplication(): print('Multiplication: What are two your numbers?') 5 = float(input('First Number:')) 6 = float(input('Second Number:')) print('Your Final Result is:', 5 * 6) def Division(): print('Division: What are your two numbers?') 7 = float(input('First Number:')) 8 = float(input('Second Number:')) print('Your Final Result is:', 7 / 8) print('What type of calculation would you like to do?') Question = input('(Add, Subtract, Divide or Multiply)') if Question.lower().startswith('a'): print(Addition()) elif Question.lower().startswith('s'): print(Subtraction()) elif Question.lower().startswith('d'): print(Division()) elif Question.lower().startswith('m'): print(Multiplication()) else: print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') while Question == 'test': Question() From allison.k.gray at gmail.com Sun Feb 2 16:22:31 2014 From: allison.k.gray at gmail.com (Allison Gray) Date: Sun, 2 Feb 2014 13:22:31 -0800 (PST) Subject: Unable to Launch Python 2.7 after Windows 8.1 Update In-Reply-To: References: Message-ID: <6a515321-3a06-469e-85d1-e9553a8ecaf8@googlegroups.com> > > > > > I would've suggested re-installing Python. That would've been worth > > trying. Unfortunately, I did uninstall and re-install Python. It didn't help. From alister.ware at ntlworld.com Sun Feb 2 16:39:30 2014 From: alister.ware at ntlworld.com (Alister) Date: Sun, 02 Feb 2014 21:39:30 GMT Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On Sun, 02 Feb 2014 13:16:44 -0800, Charlie Winn wrote: > Hey Guys i Need Help , When i run this program i get the 'None' Under > the program, see what i mean by just running it , can someone help me > fix this > > def Addition(): > print('Addition: What are two your numbers?') > 1 = float(input('First Number:')) > 2 = float(input('Second Number:')) > print('Your Final Result is:', 1 + 2) > > > def Subtraction(): > print('Subtraction: What are two your numbers?') > 3 = float(input('First Number:')) > 4 = float(input('Second Number:')) > print('Your Final Result is:', 3 - 4) > > > def Multiplication(): > print('Multiplication: What are two your numbers?') > 5 = float(input('First Number:')) > 6 = float(input('Second Number:')) > print('Your Final Result is:', 5 * 6) > > > def Division(): > print('Division: What are your two numbers?') > 7 = float(input('First Number:')) > 8 = float(input('Second Number:')) > print('Your Final Result is:', 7 / 8) > > > > print('What type of calculation would you like to do?') > Question = input('(Add, Subtract, Divide or Multiply)') > if Question.lower().startswith('a'): > print(Addition()) > elif Question.lower().startswith('s'): > print(Subtraction()) > elif Question.lower().startswith('d'): > print(Division()) > elif Question.lower().startswith('m'): > print(Multiplication()) > else: > print('Please Enter The First Letter Of The Type Of Calculation > You Would Like To Use') > > while Question == 'test': > Question() your functions need to return values not print them. I would also ask for the inputs before calling the functions I suggest you ask your tutor to go into more details if how to do this has not already been explained in your lessons. -- > Tut mir Leid, Jost, aber Du bist ein unertraeglicher Troll. Was soll das? Du *beleidigst* die Trolle! -- de.comp.os.unix.linux.misc From gary.herron at islandtraining.com Sun Feb 2 16:46:24 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Sun, 02 Feb 2014 13:46:24 -0800 Subject: Calculator Problem In-Reply-To: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: <52EEBCB0.8010500@islandtraining.com> On 02/02/2014 01:16 PM, Charlie Winn wrote: > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > def Addition(): > print('Addition: What are two your numbers?') > 1 = float(input('First Number:')) > 2 = float(input('Second Number:')) > print('Your Final Result is:', 1 + 2) > > > def Subtraction(): > print('Subtraction: What are two your numbers?') > 3 = float(input('First Number:')) > 4 = float(input('Second Number:')) > print('Your Final Result is:', 3 - 4) > > > def Multiplication(): > print('Multiplication: What are two your numbers?') > 5 = float(input('First Number:')) > 6 = float(input('Second Number:')) > print('Your Final Result is:', 5 * 6) > > > def Division(): > print('Division: What are your two numbers?') > 7 = float(input('First Number:')) > 8 = float(input('Second Number:')) > print('Your Final Result is:', 7 / 8) > > > > print('What type of calculation would you like to do?') > Question = input('(Add, Subtract, Divide or Multiply)') > if Question.lower().startswith('a'): > print(Addition()) > elif Question.lower().startswith('s'): > print(Subtraction()) > elif Question.lower().startswith('d'): > print(Division()) > elif Question.lower().startswith('m'): > print(Multiplication()) > else: > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > while Question == 'test': > Question() Sorry, but in fact you did *not* run this program as you claim. It's full of syntax errors. Any attempt to run it will display syntax errors immediately, and never actually run. So please tell us what really happened. But even without an accurate description of what you did, I can say this: Lines like 1 = float(...) don't make sense. It's as if you are trying to change the value of the number one, but that's nonsense. And lines like print('Your Final Result is:', 5 * 6) had better print out 30 (since that is what 5 times 6 is) but that's clearly not what you intended. Gary Herron From denismfmcmahon at gmail.com Sun Feb 2 17:11:08 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 2 Feb 2014 22:11:08 +0000 (UTC) Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On Sun, 02 Feb 2014 13:46:24 -0800, Gary Herron wrote: > Sorry, but in fact you did *not* run this program as you claim. +1 I can also see a call to a function named Question, but I can't see where that function is defined. That might not be a major issue, because I don't think the while condition that leads to the function call is ever fulfilled anyway. -- Denis McMahon, denismfmcmahon at gmail.com From andrea.crotti.0 at gmail.com Sun Feb 2 17:55:59 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Sun, 2 Feb 2014 22:55:59 +0000 Subject: generator slides review In-Reply-To: References: <8118b17c-3352-4832-8567-089bd14c21ce@googlegroups.com> Message-ID: Thanks everyone for your feedback. The talk I think went well, maybe I was too fast because I only used 21 minutes. >From the audience feedback, there were some questions about my "Buggy code" example, so yes probably it's not a good example since it's too artificial. I'll have to find something more useful about that or just skip this maybe. For possible generators drawbacks though I could add maintanability, if you start passing generators around in 3-4 nested levels finding out what is the original source of can be difficult. I'm also still not convinced by the definitions, which I tried now to make clear and ay something like: - and iterator defines *how you iterate* over an object (with the __next__ method) - an iterable defines *if you can iterate* over an object (with the __iter__ method) And when I do something like this: class GenIterable: def __init__(self, start=0): self.even = start if is_even(start) else start + 1 def __iter__(self): return self def __next__(self): tmp = self.even self.even += 2 return tmp it basically means that the a GenIterable object is iterable (because of __iter__) and the way you iterate over it is to call the next method on the object itself (since we return self and we define __next__). That seems clear enough, what do you think? I might give this talk again so feedback is still appreciated! From cs at zip.com.au Sun Feb 2 17:40:35 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 3 Feb 2014 09:40:35 +1100 Subject: mapping objects In-Reply-To: References: Message-ID: <20140202224035.GA41834@cskk.homeip.net> On 02Feb2014 07:41, Rita wrote: > Thanks for the response Cameron. No amount of 'googling' could provide me > with that caliber response :-) > > So, it seems regardless I would need a database. To use SQLA, yes. The SQLite backend is a very cheap/easy way to start; local files, no server needed etc. In unit tests I use this DB URL: 'sqlite:///:memory:'. It makes an in-memory database. Of course, it vanishes as soon the the program exits, but for this purpose that's fine. BTW, if you're parsing XML data specificly, look at BeautifulSoup 4 and XPath (search syntax; IIRC the XML objects you get from BS4 can use it to locate things). Cheers, -- Cameron Simpson The nice thing about standards is that you have so many to choose from; furthermore, if you do not like any of them, you can just wait for next year's model. - Andrew S. Tanenbaum From greg.ewing at canterbury.ac.nz Sun Feb 2 18:15:30 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Feb 2014 12:15:30 +1300 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Roy Smith wrote: > In article <52ec84bc$0$29972$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >>A dubious analogy, since there are artists who would say that attacking >>the canvas with a knife and setting the remains on fire count as a form >>of artistic creation :-) > > That's __del__() But it only works if the canvas is not referenced anywhere in any art catalogues. Otherwise the canvas fails to catch fire, and gets put on a list of list of artworks to be considered for manual incineration. -- Greg From greg.ewing at canterbury.ac.nz Sun Feb 2 18:23:03 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Feb 2014 12:23:03 +1300 Subject: __init__ is the initialiser In-Reply-To: References: Message-ID: Mark Lawrence wrote: > Called when the instance is created. The arguments are those passed to > the class constructor expression. If a base class has an __init__() > method, the derived class?s __init__() method, if any, must explicitly > call it to ensure proper initialization of the base class part of the > instance; for example: BaseClass.__init__(self, [args...]). As a special > constraint on constructors, no value may be returned; doing so will > cause a TypeError to be raised at runtime. > " > > Should the wording of the above be changed to clearly reflect that we > have an initialiser here and that __new__ is the constructor? The first instance of "constructor" in that paragraph refers to the expression used to instantiate an object, e.g. 'MyClass(foo, blarg)', which is fine. The second instance might be clearer if it said "as a special constraint on the __init__ method" and avoided the word "constructor" altogether. Generally I think it would be better to talk about "the __new__ method" and "the __init__ method", and not call either of them a constructor. -- Greg From rosuav at gmail.com Sun Feb 2 18:27:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Feb 2014 10:27:51 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 10:15 AM, Gregory Ewing wrote: > Roy Smith wrote: >> >> In article <52ec84bc$0$29972$c3e8da3$5496439d at news.astraweb.com>, >> Steven D'Aprano wrote: >> >>> A dubious analogy, since there are artists who would say that attacking >>> the canvas with a knife and setting the remains on fire count as a form of >>> artistic creation :-) >> >> >> That's __del__() > > > But it only works if the canvas is not referenced > anywhere in any art catalogues. Otherwise the > canvas fails to catch fire, and gets put on a > list of list of artworks to be considered for > manual incineration. What you see here is proof that Python really does need an explicit destroy() function. It would need to recycle the object [1], forcing all references to it to dangle: >>> a = object() >>> b = a >>> destroy(a) >>> c = b Traceback (most recent call last): File "", line 1, in c = b SegmentationError: dereferencing a dangling pointer It's a serious lack in Python. Currently it's not possible to do this without fiddling around in ctypes. ChrisA [1] Scrub the RAM clean and return it to the computer, put the 1 bits onto the stack for subsequent reuse, and throw all the useless 0 bits out onto the heap. From roy at panix.com Sun Feb 2 18:34:25 2014 From: roy at panix.com (Roy Smith) Date: Sun, 02 Feb 2014 18:34:25 -0500 Subject: __init__ is the initialiser References: Message-ID: In article , Gregory Ewing wrote: > Generally I think it would be better to talk about "the > __new__ method" and "the __init__ method", and not call > either of them a constructor. +1 From greg.ewing at canterbury.ac.nz Sun Feb 2 18:38:00 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Feb 2014 12:38:00 +1300 Subject: __init__ is the initialiser In-Reply-To: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > (In hindsight, it was probably a mistake for Python to define two create- > an-object methods, although I expect it was deemed necessary for > historical reasons. I'm not sure that all of the reasons are historical. Languages that have a single creation/initialisation method also usually have a mechanism for automatically calling a base version of the method if you don't do that explicitly, and they typically do it by statically analysing the source. That's not so easy in a dynamic language. If Python only had __new__, everyone who overrode it would have to start with an explicit call to the base class's __new__, adding a lot of boilerplate and forcing people to learn how to make base method calls much sooner than they would otherwise need to. -- Greg From roy at panix.com Sun Feb 2 18:40:59 2014 From: roy at panix.com (Roy Smith) Date: Sun, 02 Feb 2014 18:40:59 -0500 Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > What you see here is proof that Python really does need an explicit > destroy() function. It would need to recycle the object [1], forcing > all references to it to dangle: > > >>> a = object() > >>> b = a > >>> destroy(a) > >>> c = b > > Traceback (most recent call last): > File "", line 1, in > c = b > SegmentationError: dereferencing a dangling pointer > > It's a serious lack in Python. Currently it's not possible to do this > without fiddling around in ctypes. > > ChrisA > > [1] Scrub the RAM clean and return it to the computer, put the 1 bits > onto the stack for subsequent reuse, and throw all the useless 0 bits > out onto the heap. I'm reasonably sure you posted this as humor, but there is some truth in what you said. In the crypto/security domain, you often want to keep a key or cleartext around only for the time it's needed, and scrub the memory it was occupying as soon as it is no longer in use. I don't know how you would do that in Python. From kalvinmanual3 at gmail.com Sun Feb 2 18:59:29 2014 From: kalvinmanual3 at gmail.com (kalvinmanual3) Date: Sun, 02 Feb 2014 17:59:29 -0600 Subject: Concepts and Applications of Finite Element Analysis (4th Ed., Cook, Malkus, Plesha & Witt) Message-ID: I have solutions manuals to all problems and exercises in these textbooks. To get one in an electronic format contact me at: kalvinmanual(at)gmail(dot)com and let me know its title, author and edition. Please this service is NOT free. SOLUTIONS MANUAL TO Chemical and Engineering Thermodynamics 3Ed by Stanley I. Sandler SOLUTIONS MANUAL TO Chemical Engineering Design (Coulson & Richardson's Chemical Engineering - Volume 6) - (4th Ed., Sinnott) SOLUTIONS MANUAL TO Chemical Engineering Volume 1, 6th Edition, by Richardson, Coulson,Backhurst, Harker SOLUTIONS MANUAL TO CHEMICAL, BIOCHEMICAL, AND ENGINEERING THERMODYNAMICS, 4TH ED BY SANDLER SOLUTIONS MANUAL TO Chemistry 2nd Edition Vol.1 by Julia Burdge SOLUTIONS MANUAL TO Chemistry, 10th Ed by Chang SOLUTIONS MANUAL TO Chip Design for Submicron VLSI CMOS Layout and Simulation, John P. Uyemura SOLUTIONS MANUAL TO Cisco Technical Solution Series IP Telephony Solution Guide Version 2.0 SOLUTIONS MANUAL TO Classical Dynamics of Particles and Systems, 5th Ed, by Marion, Thornton SOLUTIONS MANUAL TO Classical Dynamics, A Contemporary Approach (Jorge V. Jose) SOLUTIONS MANUAL TO Classical Electrodynamics 2nd edition by John David Jackson SOLUTIONS MANUAL TO Classical Electrodynamics by John David Jackson SOLUTIONS MANUAL TO Classical Electrodynamics by Kasper Van Wijk SOLUTIONS MANUAL TO Classical Mechanics (Douglas Gregory) SOLUTIONS MANUAL TO Classical Mechanics 2nd Ed by Goldstein SOLUTIONS MANUAL TO CMOS Analog Circuit Design, 2ed by Phillip E. Allen, Douglas R. Holberg SOLUTIONS MANUAL TO CMOS- Circuit Design, Layout, and Simulation, Revised 2nd Ed by R. Jacob Baker SOLUTIONS MANUAL TO Cmos Digital Integrated Circuits , Sung-Mo Kang,Yusuf Leblebici SOLUTIONS MANUAL TO CMOS Mixed-Signal Circuit Design, 2nd Ed by R. Jacob Baker SOLUTIONS MANUAL TO CMOS VLSI Design Circuit & Design Perspective 3rd Ed by Haris & West SOLUTIONS MANUAL TO College Algebra 8th Ed by Michael Sullivan SOLUTIONS MANUAL TO COLLEGE ALGEBRA AND TRIGONOMETRY 6th E by Aufmann, Barker, Verity SOLUTIONS MANUAL TO College Geometry A Discovery Approach 2nd E by David Kay SOLUTIONS MANUAL TO College Physics 8 ED by Serway, Faughn, Vuille SOLUTIONS MANUAL TO College Physics 9 ED by Serway, Faughn, Vuille SOLUTIONS MANUAL TO Communication Networks, 2e, Alberto Leon-Garcia, Indra Widjaja SOLUTIONS MANUAL TO Communication Systems (4th Ed., Simon Haykin) SOLUTIONS MANUAL TO Communication Systems An Introduction to Signals and Noise in Electrical Communication, 4E, A. Bruce Carlson SOLUTIONS MANUAL TO Communication Systems Engineering (2nd Ed., John G. Proakis & Masoud Salehi) SOLUTIONS MANUAL TO Complex Variables and Applications 7 ed by JW Brown RV Churchill SOLUTIONS MANUAL TO Complex Variables with Applications, 3rd ED by David A. Wunsch SOLUTIONS MANUAL TO COMPUTATIONAL FINANCE A SCIENTIFIC PERSPECTIVE MILEN KASSABOV,CORNELIS A. LOS SOLUTIONS MANUAL TO Computational Techniques for Fluid Dynamics Srinivas, K., Fletcher, C.A.J. SOLUTIONS MANUAL TO Computer Architecture - A Quantitative Approach, 4th Ed by Hennessy, Patterson SOLUTIONS MANUAL TO Computer Architecture Pipelined & Parallel Processor Design by Michael J Flynn SOLUTIONS MANUAL TO Computer Graphics Using OpenGL 3rd E by Francis S Hill, Jr. & Stephen M Kelley SOLUTIONS MANUAL TO Computer Networking A Top-Down Approach Featuring the Internet, 3E Kurose,Ross SOLUTIONS MANUAL TO Computer Networking: A Top-Down Approach (4th Ed., James F. Kurose & Keith W. Ross) SOLUTIONS MANUAL TO Computer Networks - A Systems Approach 3 ed by Peterson Davie SOLUTIONS MANUAL TO Computer Networks - A Systems Approach 4 ed by Peterson Davie SOLUTIONS MANUAL TO Computer Networks A Systems Approach, 2nd Edition, Larry Peterson, Bruce Davie SOLUTIONS MANUAL TO Computer Networks, 4th Ed., by Andrew S. Tanenbaum SOLUTIONS MANUAL TO Computer Organization 3rd Edition by Carl Hamacher , Zvonoko Vranesic ,Safwat Zaky SOLUTIONS MANUAL TO Computer Organization and Architecture: Designing for Performance (7th Ed., William Stallings) SOLUTIONS MANUAL TO Computer Organization and Design The Hardware Software Interface 4 ed by David A Patterson SOLUTIONS MANUAL TO Computer Organization and Design The Hardware Software Interface, 3rd edition by David A Patterson and John L Hennessy SOLUTIONS MANUAL TO Computer Science Illuminated 4th ed by Nell Dale, John Lewis SOLUTIONS MANUAL TO Computer system architecture 3rd Ed Morris Mano SOLUTIONS MANUAL TO Computer Systems Organization and Architecture by John D. Carpinelli SOLUTIONS MANUAL TO Computer Vision A Modern Approach by Forsyth, Ponce SOLUTIONS MANUAL TO Computer-Controlled Systems 3rd ED by Astrom, Wittenmark SOLUTIONS MANUAL TO Concepts and Applications of Finite Element Analysis (4th Ed., Cook, Malkus, Plesha & Witt) SOLUTIONS MANUAL TO Concepts in Thermal Physics 2nd Ed by Blundell SOLUTIONS MANUAL TO Concepts of Physics (Volume 1 & 2) by H.C. Verma SOLUTIONS MANUAL TO Concepts of Programming Languages 7th ED by Sebesta SOLUTIONS MANUAL TO Construction Surveying and Layout 2ed by Crawford SOLUTIONS MANUAL TO Contemporary Engineering Economics (4th Ed., Chan Park) SOLUTIONS MANUAL TO Contemporary Engineering Economics 5th Ed by Chan S. Park SOLUTIONS MANUAL TO Continuum Electromechanics by James R. Melcher SOLUTIONS MANUAL TO Control Systems Engineering, 4E, by Norman Nise SOLUTIONS MANUAL TO Control Systems Principles and Design 2e by M. Gopal SOLUTIONS MANUAL TO Corporate Finance & MyFinanceLab Student Access Code Card, Global 2 Ed by Berk, DeMarzo SOLUTIONS MANUAL TO Corporate Finance 8th edition by Ross SOLUTIONS MANUAL TO Corporate Finance 9th edition by Ross SOLUTIONS MANUAL TO Corporate Finance The Core plus MyFinanceLab Student Access Kit (Jonathan Berk & Peter DeMarzo) SOLUTIONS MANUAL TO Corporate Finance, 7E, by Ross SOLUTIONS MANUAL TO Corporations, Partnerships, Estates and Trusts ( 2011 ) by Hoffman, Maloney SOLUTIONS MANUAL TO COST ACCOUNTING - Creating Value for Management 5th E by MICHAEL MAHER SOLUTIONS MANUAL TO Cost Accounting-A Managerial Emphasis 13th Ed by Charles Horngren SOLUTIONS MANUAL TO Cryptography and Network Security (4th Ed., William Stallings) SOLUTIONS MANUAL TO Data & Computer Communication, 7th Ed, by William Stallings SOLUTIONS MANUAL TO Data Communications and Networking by Behroz Forouzan SOLUTIONS MANUAL TO Data Communications Networking 4th Ed by Behrouz Forouzan SOLUTIONS MANUAL TO Data Structures with Java by John R. Hubbard, Anita Huray SOLUTIONS MANUAL TO Database Management Systems, 3rd Ed., by Ramakrishnan, Gehrke SOLUTIONS MANUAL TO Database System Concepts 4th ED by Silberschatz , Korth , Sudarshan SOLUTIONS MANUAL TO Database System Concepts 5th ED by Silberschatz, Korth, Sudarshan SOLUTIONS MANUAL TO Database Systems An Application-Oriented Approach (introductory Version ) by Michael Kifer, Arthur Bernstein, Philip M.Lewis, Prabin K. Panigrahi SOLUTIONS MANUAL TO Design Analysis in Rock Mechanics by William G. Pariseau SOLUTIONS MANUAL TO Design and Analysis of Experiments, 6E, by Montgomery SOLUTIONS MANUAL TO Design of Analog CMOS Integrated Circuits by Razavi SOLUTIONS MANUAL TO Design of Analog CMOS Integrated Circuits, 2 Edition, by Razavi Douglas C. Montgomery SOLUTIONS MANUAL TO Design of Fluid Thermal Systems, 2nd Edition janna SOLUTIONS MANUAL TO Design of Machinery (3rd Ed., Norton) SOLUTIONS MANUAL TO Design of machinery 4th ed by Norton SOLUTIONS MANUAL TO Design of Reinforced Concrete, 8th Ed by McCormac, Brown SOLUTIONS MANUAL TO Design with Operational Amplifiers and Analog Integrated Circuits (3rd Ed., Sergio Franco) From timothy.c.delaney at gmail.com Sun Feb 2 19:02:17 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Mon, 3 Feb 2014 11:02:17 +1100 Subject: __init__ is the initialiser In-Reply-To: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 1 February 2014 14:42, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > On Fri, 31 Jan 2014 14:52:15 -0500, Ned Batchelder wrote: > > (In hindsight, it was probably a mistake for Python to define two create- > an-object methods, although I expect it was deemed necessary for > historical reasons. Most other languages make do with a single method, > Objective-C being an exception with "alloc" and "init" methods.) > I disagree. In nearly every language I've used which only has single-phase construction, I've wished for two-phase construction. By the time you get to __init__ you know the following things about the instance: 1. It is a complete instance of the subclass - there's no part of the structure that is invalid to access (of course, many attributes might not yet exist). 2. Calling a method from __init__ will call the subclass' method. This allows subclasses to hook into the initisation process by overriding methods (of course, the subclass will need to ensure it has initialised all the state it needs). This is generally not allowed in languages with single-phase construction because the object is in an intermediate state. For example, in C++ the vtable is for the class currently being constructed, not the subclass, so it will always call the current class' implementation of the method. In Java you can actually call the subclass' implementation, but in that case it will call the subclass method before the subclass constructor is actually run, meaning that instance variables will have their default values (null for objects). When the base class constructor is eventually run the instance variables will be assigned the values in the class definition (replacing anything set by the subclass method call). Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Feb 2 19:07:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Feb 2014 11:07:30 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 10:40 AM, Roy Smith wrote: > I'm reasonably sure you posted this as humor, but there is some truth in > what you said. In the crypto/security domain, you often want to keep a > key or cleartext around only for the time it's needed, and scrub the > memory it was occupying as soon as it is no longer in use. > > I don't know how you would do that in Python. I did, but you're right. It's fundamentally not possible in pure Python, because there's no way to flag a block of memory as "do not page this to disk". For what you're talking about to be at all possible, you would need support from the language, from the OS, and possibly from the CPU as well. I'm sure this sort of thing exists, but if it does, it'll probably be something that Python itself wouldn't concern itself with - you'd get it via openssl or something. There have been occasional times I've wanted an "explicit destruction" feature. Rather than the facetious exception I listed above, it'd be better to have all those references (including the original one in a, since there's nothing special about that) turn into some kind of "null state" - either None, or a special object that marks itself as a destructed/destroyed (terminology debates aside) object. With custom types, I can mark them off with a special flag, and check that all the time; but I can't, for instance, have a dict that maps some lookup keyword to its output file, and then destroy output files to remove all their references from everywhere in the dict. (I have had something along these lines, a bit more complicated than this, but not in Python.) But I do like the idea of an arsonist being unable to destroy a painting because of the reference loop between its catalog number on the back and the catalog itself. ChrisA From davea at davea.name Sun Feb 2 19:35:21 2014 From: davea at davea.name (Dave Angel) Date: Sun, 2 Feb 2014 19:35:21 -0500 (EST) Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico Wrote in message: > > > [1] Scrub the RAM clean and return it to the computer, put the 1 bits > onto the stack for subsequent reuse, and throw all the useless 0 bits > out onto the heap. > But don't you realize, we have to keep the zero bits around, so the one bits have someone to feel superior to. -- DaveA From steve+comp.lang.python at pearwood.info Sun Feb 2 19:33:10 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Feb 2014 00:33:10 GMT Subject: __init__ is the initialiser References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52eee3c5$0$29972$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Feb 2014 12:38:00 +1300, Gregory Ewing wrote: > Steven D'Aprano wrote: >> (In hindsight, it was probably a mistake for Python to define two >> create- an-object methods, although I expect it was deemed necessary >> for historical reasons. > > I'm not sure that all of the reasons are historical. Languages that have > a single creation/initialisation method also usually have a mechanism > for automatically calling a base version of the method if you don't do > that explicitly, and they typically do it by statically analysing the > source. That's not so easy in a dynamic language. Just because statically-typed languages do it at compile-time doesn't mean Python couldn't do it at run-time. All the information is readily available, so Python could do something like this: # --- Untested --- # Automatically call each __new__ constructor method, starting from # the most fundamental (object) and ending with the current class. stack = [] for c in cls.__mro__: if hasattr(c, '__new__'): stack.append(c.__new__) while stack: stack.pop()(*args) Note that this design is sub-optimal: the constructor methods don't receive the newly-created instance as an argument, which makes it hard to do initialisation, and makes the whole exercise rather pointless. But with a slight change of semantics, we can make this work rather sensibly. Change the signature of __new__ to: def __new__(cls, self=None, *args, **kwargs) and the last two lines to: instance = None while stack: instance = stack.pop()(instance, *args) Is this a good design? Possibly not. But it's possible, and not terribly hard. Dynamism is no barrier to automatically calling constructors. What I meant by backwards compatibility is that prior to the introduction of new-style classes, you couldn't override __new__, only __init__. So if you had a classic class, you'd have to receive the instance: class Classic: def __init__(self, *args): ... but for new-style classes, you'd receive the class: class Newstyle(object): def __init__(cls, *args): ... which is confusing and awkward, and would make it annoying to migrate from classic classes to new-style classes. So from the backwards- compatibility perspective, __init__ has to receive the instance (self) as first argument. So the simplest way to satisfy that requirement, and still allow the class to define a constructor method that receives the class and constructs the instance, is to define a second special method. Which is what was done. > If Python only had __new__, everyone who overrode it would have to start > with an explicit call to the base class's __new__, adding a lot of > boilerplate and forcing people to learn how to make base method calls > much sooner than they would otherwise need to. There is that as well. -- Steven From roy at panix.com Sun Feb 2 19:45:48 2014 From: roy at panix.com (Roy Smith) Date: Sun, 02 Feb 2014 19:45:48 -0500 Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Dave Angel wrote: > Chris Angelico Wrote in message: > > > > > > [1] Scrub the RAM clean and return it to the computer, put the 1 bits > > onto the stack for subsequent reuse, and throw all the useless 0 bits > > out onto the heap. > > > > But don't you realize, we have to keep the zero bits around, so > the one bits have someone to feel superior to. Just wait until the two bits start showing up. Then let's how the one bits feel, huh? From roegltd at gmail.com Sun Feb 2 20:02:35 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 2 Feb 2014 17:02:35 -0800 (PST) Subject: Python (windows)packet sniffer ARP In-Reply-To: <697d33c0-c118-4ce0-a631-f91d36cb456a@googlegroups.com> References: <697d33c0-c118-4ce0-a631-f91d36cb456a@googlegroups.com> Message-ID: On Sunday, February 2, 2014 8:26:05 PM UTC+2, Asaf Las wrote: > On Friday, January 31, 2014 9:10:28 AM UTC+2, Ralle wrote: > > > Hello > > I am wondering if it possible to create a packet sniffer in > > windows using python that only sniffs for ARP packets. There is also example on bottom of socket module for raw sockets you can try it run (trigger arp packet by deleting one of dynamic entries in your arp table by arp -d xxx.xxx.xxx.xxx) http://docs.python.org/3.3/library/socket.html?highlight=socket#example From inpost at gmail.com Sun Feb 2 14:20:32 2014 From: inpost at gmail.com (e-letter) Date: Sun, 2 Feb 2014 19:20:32 +0000 Subject: bw2ui installation failure Message-ID: Readers, Firstly, sorry for the cross-post: https://groups.google.com/d/topic/brightway2/-akB-OQBZi4 Any advice about forcing installation of a later version of a software please? From dwightdhutto at gmail.com Sun Feb 2 20:12:32 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 17:12:32 -0800 (PST) Subject: Help with some python homework... In-Reply-To: References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> <8da5d692-1446-4107-9a5a-5efd91f7c051@googlegroups.com> Message-ID: <4130ca2c-1608-4547-a083-95742e44176f@googlegroups.com> On Saturday, February 1, 2014 2:32:22 PM UTC-5, Denis McMahon wrote: > On Fri, 31 Jan 2014 18:14:31 -0700, Scott W Dunning wrote: > > > > > little different from a few things you guys had mentioned. For one, I > > > got the correct time by calculating the number of time run and > > > converting that into seconds then back out to hr:mn:sc. I didn't > > > calculate from midnight. > > > > > SECONDS = 1 MINUTES = 60 * SECONDS HOURS = 60 * MINUTES > > > > > > time_left_house = 6 * HOURS + 52 * MINUTES > > > > This does actually calculate the time in seconds since midnight that you > > left the house > > > > > miles_run_easy_pace = 2 * (8 * MINUTES + 15 * SECONDS) > > > > > > miles_run_fast_pace = 3 * (7 * MINUTES + 12 * SECONDS) > > > > > > time_returned_home = miles_run_easy_pace + miles_run_fast_pace + > > > time_left_house > > > > And this calculates the time in seconds since midnight that you returned > > home > > > > So although you don't realise it, you are actually working in seconds > > since midnight, and then converting seconds back into hours, minutes and > > seconds. > > > > -- > > Denis McMahon A little OT, but these might peak your interest for this: http://en.wikipedia.org/wiki/Epoch_%28reference_date%29 http://en.wikipedia.org/wiki/Leap_second From roegltd at gmail.com Sun Feb 2 20:15:51 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 2 Feb 2014 17:15:51 -0800 (PST) Subject: bw2ui installation failure In-Reply-To: References: Message-ID: On Sunday, February 2, 2014 9:20:32 PM UTC+2, e-letter wrote: > Readers, > Firstly, sorry for the cross-post: > https://groups.google.com/d/topic/brightway2/-akB-OQBZi4 > Any advice about forcing installation of a later version of a software please? for pip it is: pip install --upgrade module_name if pypm mimics pip then this should help. if pypm is python based - check if it has such option in argument handling part. From jeanpierreda at gmail.com Sun Feb 2 20:24:21 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 2 Feb 2014 17:24:21 -0800 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 2, 2014 at 4:07 PM, Chris Angelico wrote: > On Mon, Feb 3, 2014 at 10:40 AM, Roy Smith wrote: >> I'm reasonably sure you posted this as humor, but there is some truth in >> what you said. In the crypto/security domain, you often want to keep a >> key or cleartext around only for the time it's needed, and scrub the >> memory it was occupying as soon as it is no longer in use. >> >> I don't know how you would do that in Python. > > I did, but you're right. > > It's fundamentally not possible in pure Python, because there's no way > to flag a block of memory as "do not page this to disk". For what > you're talking about to be at all possible, you would need support > from the language, from the OS, mlock on linux, VirtualAlloc (?) on windows. This can be done in CPython after the fact, but you'd want the memory to be unpageable before it has contents put in it, not after. Destroying memory is comparatively easy, as you say -- just make the object's internal state "invalid", rather than adding anything to the language. -- Devin From rosuav at gmail.com Sun Feb 2 20:37:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Feb 2014 12:37:17 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 12:24 PM, Devin Jeanpierre wrote: > On Sun, Feb 2, 2014 at 4:07 PM, Chris Angelico wrote: >> On Mon, Feb 3, 2014 at 10:40 AM, Roy Smith wrote: >>> I'm reasonably sure you posted this as humor, but there is some truth in >>> what you said. In the crypto/security domain, you often want to keep a >>> key or cleartext around only for the time it's needed, and scrub the >>> memory it was occupying as soon as it is no longer in use. >>> >>> I don't know how you would do that in Python. >> >> I did, but you're right. >> >> It's fundamentally not possible in pure Python, because there's no way >> to flag a block of memory as "do not page this to disk". For what >> you're talking about to be at all possible, you would need support >> from the language, from the OS, > > mlock on linux, VirtualAlloc (?) on windows. This can be done in > CPython after the fact, but you'd want the memory to be unpageable > before it has contents put in it, not after. Yeah, like I said it needs language and OS support. There's no way to call those APIs from pure Python code. (And I'm not sure whether those functions work without appropriate CPU-level support; for instance, what happens if your OS is running inside a VM?) > Destroying memory is comparatively easy, as you say -- just make the > object's internal state "invalid", rather than adding anything to the > language. Yeah. Works fine if you have a cooperative system that checks that state every time; otherwise, it'd need at least some language support (the goal is to have its destructor called and all its references wiped, so resources get released). ChrisA From jeanpierreda at gmail.com Sun Feb 2 20:54:31 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 2 Feb 2014 17:54:31 -0800 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 2, 2014 at 5:37 PM, Chris Angelico wrote: > On Mon, Feb 3, 2014 at 12:24 PM, Devin Jeanpierre >> Destroying memory is comparatively easy, as you say -- just make the >> object's internal state "invalid", rather than adding anything to the >> language. > > Yeah. Works fine if you have a cooperative system that checks that > state every time; otherwise, it'd need at least some language support > (the goal is to have its destructor called and all its references > wiped, so resources get released). I guess my point is that I don't see what you need on top of extension modules. Same for previous paragraph. -- Devin From roegltd at gmail.com Sun Feb 2 20:56:43 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 2 Feb 2014 17:56:43 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> Message-ID: <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> On Sunday, February 2, 2014 10:51:15 PM UTC+2, Jean Dupont wrote: > Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: > > I'm looking for an efficient method to produce rows of tables like this: > jean you can also try to make below universal for all needed bases: m = lambda m, n: 1 if m & n else 0 k = [[ m(x,8) , m(x, 4), m(x, 2), m(x, 1)] for x in range(10)] print (k) From edvogel56 at gmail.com Sun Feb 2 21:06:11 2014 From: edvogel56 at gmail.com (edvogel56 at gmail.com) Date: Sun, 2 Feb 2014 18:06:11 -0800 (PST) Subject: Python 3.3 and Pygame 19.2a install problems Message-ID: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> Hi, I am putting together tutorials to accompany "Invent Your Own Computer Games with Python" for a volunteer gig. I installed Python 3.3 and Pygame 19.2a on an XP machine and it works fine. However the install on my Win7 (Home Edition)HP notebook is not working. While running python code from Idle that uses Pygames I get this message: Traceback (most recent call last): File "C:\Users\Ed\Documents\SOMA\Minecraft and Python\inventwithpython_src\dodger.py", line 1, in import pygame, random, sys File "C:\Python33\lib\site-packages\pygame\__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: The specified module could not be found. I am looking at the computers and installed directories side by side and I don't see anything "missing." That being said there is a base.pyd file but not a base.dll. I understand .pyd files are a type of dll. Could there be something about Win7 doesn't like about that naming convention? Please advise. Thanks! EdV From roegltd at gmail.com Sun Feb 2 21:17:55 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 2 Feb 2014 18:17:55 -0800 (PST) Subject: Python declarative In-Reply-To: References: <8fde6d34-47c5-49a1-a6d0-9ffe3df2d401@googlegroups.com> <52e473fc$0$29999$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52772411-bd51-430e-89b3-3d7287137a1c@googlegroups.com> On Sunday, January 26, 2014 4:45:59 AM UTC+2, Mark Lawrence wrote: > On 26/01/2014 02:33, Steven D'Aprano wrote: > > If I worked as a consultant I'd much prefer the XML version as I'd be > able to charge much more on the grounds that I'd done much more, hoping > that the people paying didn't bother with design reviews or the like :) > > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > Mark Lawrence Google's android uses XML for GUI widget definitions. /Asaf From edvogel56 at gmail.com Sun Feb 2 22:04:48 2014 From: edvogel56 at gmail.com (edvogel56 at gmail.com) Date: Sun, 2 Feb 2014 19:04:48 -0800 (PST) Subject: Python 3.3 and Pygame 19.2a install problems In-Reply-To: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> Message-ID: <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> On Sunday, February 2, 2014 8:06:11 PM UTC-6, edvo... at gmail.com wrote: > Hi, > > I am putting together tutorials to accompany "Invent Your Own Computer Games with Python" for a volunteer gig. I installed Python 3.3 and Pygame 19.2a on an XP machine and it works fine. However the install on my Win7 (Home Edition)HP notebook is not working. > > > > While running python code from Idle that uses Pygames I get this message: > > > > Traceback (most recent call last): > > File "C:\Users\Ed\Documents\SOMA\Minecraft and Python\inventwithpython_src\dodger.py", line 1, in > > import pygame, random, sys > > File "C:\Python33\lib\site-packages\pygame\__init__.py", line 95, in > > from pygame.base import * > > ImportError: DLL load failed: The specified module could not be found. > > > > > > I am looking at the computers and installed directories side by side and I don't see anything "missing." That being said there is a base.pyd file but not a base.dll. I understand .pyd files are a type of dll. Could there be something about Win7 doesn't like about that naming convention? > > > > Please advise. > > > > Thanks! > > > > EdV Found the answer here: http://www.reddit.com/r/inventwithpython/comments/1dzl8m/when_importing_pygame_i_get_importerror_dll_load/ Questions but no big deal - 1. Why doesn't pygame.org have the most recent install files compatible with the most recent python? I ended up finding them here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ 2. Interesting that "3.2" pygames works with "3.3" python on my XP but the Win 7 required the "3.3" pygames. Thoughts? Thanks again. EdV From davea at davea.name Sun Feb 2 22:08:34 2014 From: davea at davea.name (Dave Angel) Date: Sun, 2 Feb 2014 22:08:34 -0500 (EST) Subject: Python 3.3 and Pygame 19.2a install problems References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> Message-ID: edvogel56 at gmail.com Wrote in message: > That being said there is a base.pyd file but not a base.dll. I understand .pyd files are a type of dll. Could there be something about Win7 doesn't like about that naming convention? > > Please advise. > > I highly doubt that. Most Windows dlls have some other extension, and I can't believe Win7 breaking such a long tradition. I would instead guess that you have a path problem, either with sys.path or with Windows PATH variable. -- DaveA From davea at davea.name Sun Feb 2 22:14:27 2014 From: davea at davea.name (Dave Angel) Date: Sun, 2 Feb 2014 22:14:27 -0500 (EST) Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Roy Smith Wrote in message: > In article , > Dave Angel wrote: > >> Chris Angelico Wrote in message: >> > >> > >> > [1] Scrub the RAM clean and return it to the computer, put the 1 bits >> > onto the stack for subsequent reuse, and throw all the useless 0 bits >> > out onto the heap. >> > >> >> But don't you realize, we have to keep the zero bits around, so >> the one bits have someone to feel superior to. > > Just wait until the two bits start showing up. Then let's how the one > bits feel, huh? > And when the q-bits get entangled up, we won't know the question till after the answer has collapsed. -- DaveA From skip at pobox.com Sun Feb 2 22:15:12 2014 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Feb 2014 21:15:12 -0600 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 2, 2014 at 9:14 PM, Dave Angel wrote: > And when the q-bits get entangled up, we won't know the question > till after the answer has collapsed. Won't looking at the answer change it? Skip From dwightdhutto at gmail.com Sun Feb 2 22:21:50 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 22:21:50 -0500 Subject: Tkinter widgets into classes. In-Reply-To: <0bfb9c90-ee4d-42aa-b181-17b2b6dd1ea7@googlegroups.com> References: <5e297400-3322-45aa-ab7e-016af083b259@googlegroups.com> <04a9d0b0-c968-42c2-94d2-93438558e227@googlegroups.com> <2377621f-a208-4a12-b66c-bb678df6efcf@googlegroups.com> <0bfb9c90-ee4d-42aa-b181-17b2b6dd1ea7@googlegroups.com> Message-ID: I just happened to find this link: http://effbot.org/tkinterbook/ through this link: https://wiki.python.org/moin/TkInter which ALL happened to stem from this link: https://www.google.com/search?client=ubuntu&channel=fs&q=python+tkinter+tutorials&ie=utf-8&oe=utf-8 On Sun, Feb 2, 2014 at 3:38 PM, Lewis Wood wrote: > Thanks all who replied, will look further into megawidgets and the > Toplevel() function. Is there a way to get a separate window to return > something when closed? > -- > https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Feb 3 00:06:22 2014 From: davea at davea.name (Dave Angel) Date: Mon, 3 Feb 2014 00:06:22 -0500 (EST) Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Skip Montanaro Wrote in message: > On Sun, Feb 2, 2014 at 9:14 PM, Dave Angel wrote: >> And when the q-bits get entangled up, we won't know the question >> till after the answer has collapsed. > > Won't looking at the answer change it? > No, looking at it is what collapses it. Before that it was just another Schroedinger's cat -- DaveA From roy at panix.com Mon Feb 3 00:12:45 2014 From: roy at panix.com (Roy Smith) Date: Mon, 03 Feb 2014 00:12:45 -0500 Subject: __init__ is the initialiser References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Dave Angel wrote: > Skip Montanaro Wrote in message: > > On Sun, Feb 2, 2014 at 9:14 PM, Dave Angel wrote: > >> And when the q-bits get entangled up, we won't know the question > >> till after the answer has collapsed. > > > > Won't looking at the answer change it? > > > > No, looking at it is what collapses it. Before that it was just > another Schroedinger's cat So, what you're saying is when I delete an object, __del__() has both been called and not been called? From rosuav at gmail.com Mon Feb 3 00:49:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 3 Feb 2014 16:49:52 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 4:12 PM, Roy Smith wrote: > So, what you're saying is when I delete an object, __del__() has both > been called and not been called? >>> class Schrodinger: def __init__(self): print("Init!") >>> print(Schrodinger()) Init! <__main__.Schrodinger object at 0x02B52570> At this point, __del__ has indeed both been called and not been called. However, observing its state will force it to collapse: >>> class Schrodinger: def __init__(self): print("Init!") def __del__(self): print("Del!") >>> print(Schrodinger()) Init! <__main__.Schrodinger object at 0x02B52830> Del! If an object falls off the heap and there's no __del__ method to hear it, does it call __del__? ChrisA From ethan at stoneleaf.us Mon Feb 3 00:34:41 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 02 Feb 2014 21:34:41 -0800 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52EF2A71.9060404@stoneleaf.us> On 02/02/2014 09:12 PM, Roy Smith wrote: > In article , > Dave Angel wrote: > >> Skip Montanaro Wrote in message: >>> On Sun, Feb 2, 2014 at 9:14 PM, Dave Angel wrote: >>>> And when the q-bits get entangled up, we won't know the question >>>> till after the answer has collapsed. >>> >>> Won't looking at the answer change it? >>> >> >> No, looking at it is what collapses it. Before that it was just >> another Schroedinger's cat > > So, what you're saying is when I delete an object, __del__() has both > been called and not been called? That would certainly explain the problems with __del__! -- ~Ethan~ From tjreedy at udel.edu Mon Feb 3 01:43:06 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 01:43:06 -0500 Subject: Python 3.3 and Pygame 19.2a install problems In-Reply-To: <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> Message-ID: On 2/2/2014 10:04 PM, edvogel56 at gmail.com wrote: >> Traceback (most recent call last): File >> "C:\Users\Ed\Documents\SOMA\Minecraft and >> Python\inventwithpython_src\dodger.py", line 1, in >> import pygame, random, sys File >> "C:\Python33\lib\site-packages\pygame\__init__.py", line 95, in >> >> from pygame.base import * >> ImportError: DLL load failed: The specified module could not be >> found. > Found the answer here: > http://www.reddit.com/r/inventwithpython/comments/1dzl8m/when_importing_pygame_i_get_importerror_dll_load/ > > Questions but no big deal - 1. Why doesn't pygame.org have the most > recent install files compatible with the most recent python I ended > up finding them here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ The base problem is that Microsoft changes the Visual C runtime with each version of the VC compiler. Python 3.3 was compiled with a newer version. It is a nuisance for packages to keep recompiling with a new VC version. Py 3.4 is using the same version as 3.4, so PyGames *might* work with 3.4, or there might be other compatibilities. > 2. Interesting that "3.2" pygames works with "3.3" python on my XP > but the Win 7 required the "3.3" pygames. Thoughts? It is possible that the VC++2010 runtime does not work with XP, but requires Vista+ and that the Microsoft installer installs the older VC++2008 runtime on XP even when installing 3.3. If you install for a single user, the vcxxxxx.dll is in the python directory or subdirectory. For all-user installs, it is in one of the windows/systemxx directories. But this is just a guess. -- Terry Jan Reedy From tjreedy at udel.edu Mon Feb 3 02:17:51 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 02:17:51 -0500 Subject: generator slides review In-Reply-To: References: Message-ID: On 2/2/2014 5:40 AM, andrea crotti wrote: > 2014-02-02 Terry Reedy : >> On 2/1/2014 9:12 AM, andrea crotti wrote: >> >> Comments: >> >> The use is assert in the first slide seem bad in a couple of different >> respects. >> > > Why is it bad? It's probably not necessary but since we ask for a > range it might be good to check if the range is valid. > Maybe I should raise ValueError instead for a better exception? In general, use assert (== AssertionError) to check program logic (should never raise). Remember that assert can be optimized away. Use other exceptions to check user behavior. So I believe that ValueError is appropriate here. I think I also questioned the particular check. >> The use of 'gen_even' before it is defined. >> > > Well this is because l'm saying that I wish I had something like this, > which I define just after. It might be confusing if it's not defined > but I thought it's nice to say what I would like to do and then > actually define it, what do you think? In commenting on the slides, I did not know what you would say to supplement them. >> A generator expression evaluates (better than 'yields') to a generator, not >> just an iterator. >> > > Ok thanks fixed > >> The definition of 'generator' copies the wrong and confused glossary entry. >> Generator functions return generators, which are iterators with extra >> behavior. >> > > I understood instead that it was the opposite, a generator is a > specialized iterator, 'Generator functions', which you labeled 'generators', are functions, not iterators. The generators they return (and the generators that generator expressions evaluate to) are iterators, and more. >>> type(a for a in 'abc') I am not sure whether 'specialized' or 'generalized' is the better term. >> I would leave out For loop(2). The old pseudo-getitem iterator protocol is >> seldom explicitly used any more, in the say you showed. /say/way/ > This was mainly to explain how something like > for el in [1, 2, 3]: > print(el) > > can work, But it is no longer has that *does* work. All the builtin xyz collection classes have a corresponding xyz_iterator class with a __next__ method that knows how to sequentially access collection items. We do not normally see or think about them, but they are there working for us every time we do 'for item in xyz_instance:' >>> [].__iter__() In Python one could write the following: class list_iterator: def __init__(self, baselist): self.baselist = baselist self.index = -1 # see __next__ for why def __iter__(self): return self def __next__(self): self.index += 1 return self.baselist[self.index] but the C version should use a static pointer into the object address array, >> 'Lazyness drawbacks' overflow_list is bizarre and useless. overflow_gen is >> bizarre and buggy. If you are intentionally writing buggy code to make a >> point, label it as such on the slide. >> > > Yes this is intentionally buggy. The thing is that I wanted to show > that sometimes generating things makes it harder to debug, and delays > some errors, which are anyway there but would come up immediately in > case of a list creation. > I could not find a better non artificial example for this, any > suggestion is welcome.. slide 1 --------- def recip_list(start, stop): lis [] for i range(start, stop): list.append(1/i) return lis for x in recip_list(-100, 3): # fail here print x slide 2 ------- def recip_gen(start, stop): for i in range(start, stop): yield 1/i for x in recip_gen(-100, 3): print x # fail here after printing 100 lines ... -- Terry Jan Reedy From orgnut at yahoo.com Mon Feb 3 02:48:01 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sun, 02 Feb 2014 23:48:01 -0800 Subject: Help with some python homework... In-Reply-To: <4130ca2c-1608-4547-a083-95742e44176f@googlegroups.com> References: <02c4c69d-71f1-4a01-86df-d4d5a7ffb3f5@googlegroups.com> <8da5d692-1446-4107-9a5a-5efd91f7c051@googlegroups.com> <4130ca2c-1608-4547-a083-95742e44176f@googlegroups.com> Message-ID: On 02/02/2014 05:12 PM, David Hutto wrote: > A little OT, but these might peak your interest for this: Also a little OT, but the word you're looking for is spelled pique. ;-) (Although, it IS pronounced 'peak'.) -=- Larry -=- From fmasanori at gmail.com Mon Feb 3 04:15:49 2014 From: fmasanori at gmail.com (Fernando Masanori Ashikaga) Date: Mon, 3 Feb 2014 01:15:49 -0800 (PST) Subject: Python for Myo Control Armband Message-ID: Does anyone know if there is already a Python library for Myo [1] Gesture Control Armband? There are other gesture controls with Python libraries? Thanks in advance [1] https://www.thalmic.com/en/myo/ From vincent.vandevyvre at swing.be Mon Feb 3 05:27:54 2014 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Mon, 03 Feb 2014 11:27:54 +0100 Subject: Python for Myo Control Armband In-Reply-To: References: Message-ID: <52EF6F2A.4080204@swing.be> An HTML attachment was scrubbed... URL: From ram.rachum at gmail.com Mon Feb 3 05:50:15 2014 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Feb 2014 02:50:15 -0800 (PST) Subject: Problems compiling Python 3.4 on Ubuntu Message-ID: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> Hi, I'm trying to install Python 3.4b3 on Ubuntu. Since compilation seems to be the only way, I'm trying that. I downloaded the source, I changed Setup.dist to have this: SSL=/usr _ssl _ssl.c \ -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ -L$(SSL)/lib -lssl -lcrypto I installed openssl and various sqlite packages beforehand. But when I do this: ./configure --prefix=/opt/python3.4 && make && make install I get, after a huge wall of text, this: ./Modules/_ssl.c:57:25: fatal error: openssl/rsa.h: No such file or directory #include "openssl/rsa.h" ^ compilation terminated. What do I do to solve this? Thanks, Ram. From airween at gmail.com Mon Feb 3 06:08:17 2014 From: airween at gmail.com (Ervin =?utf-8?Q?Heged=C3=BCs?=) Date: Mon, 3 Feb 2014 12:08:17 +0100 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> Message-ID: <20140203110816.GA7423@arxnet.hu> Hello, On Mon, Feb 03, 2014 at 02:50:15AM -0800, cool-RR wrote: > Hi, > > I'm trying to install Python 3.4b3 on Ubuntu. Since compilation seems to be the only way, I'm trying that. > > I downloaded the source, I changed Setup.dist to have this: > > SSL=/usr > _ssl _ssl.c \ > -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ > -L$(SSL)/lib -lssl -lcrypto > [...] > ./Modules/_ssl.c:57:25: fatal error: openssl/rsa.h: No such file or directory > #include "openssl/rsa.h" > ^ > compilation terminated. > > What do I do to solve this? try this: sudo apt-get install libssl-dev cheers, a. From mmanns at gmx.net Sun Feb 2 13:52:08 2014 From: mmanns at gmx.net (Martin Manns) Date: Sun, 2 Feb 2014 19:52:08 +0100 Subject: [ANN] pyspread 0.2.6 Message-ID: ============== pyspread 0.2.6 ============== Pyspread 0.2.6 is released. This update brings Excel xls file reading and prevents many pyspread lock ups that were caused by misbehaving user code. About pyspread ============== Pyspread is a non-traditional spreadsheet application that is based on and written in the programming language Python. The goal of pyspread is to be the most pythonic spreadsheet application. Pyspread is free software. It is released under the GPL v3. Project website: http://manns.github.com/pyspread/ Download page: https://pypi.python.org/pypi/pyspread What is new in 0.2.6 ==================== + Reading support for Excel xls files (requires dependency xlrd) + Code execution timeout, i. e. buggy code such as infinite loops does not lock up pyspread any more. Note: The timeout does not work for C operations such as a ** + Macro dialog now provides an error message field + Multiple rows/columns can now be resized together when selected + Show frozen option added that changes background of frozen cells + The cell editor now is resized when the text grows too large + Cells are now always clipped + Example macro for in cell LaTeX equations added + Contour plots and Sankey charts added to chart dialog + Pie chart can now be rotated in the chart dialog + Chart fonts and ticks can now be changed in chart dialog + Some bug fixes Known issues ============ + Selection mode is disabled in Windows. + Sometimes, pressing redo when there is nothing left to redo has undesired effects such as redoing an operation again. + Pyspread with wxPython 3.x instead of 2.8.x may be slow and buggy + On some (not all) Windows system lockup prevention does not work Enjoy Martin From edvogel56 at gmail.com Mon Feb 3 08:48:10 2014 From: edvogel56 at gmail.com (edvogel56 at gmail.com) Date: Mon, 3 Feb 2014 05:48:10 -0800 (PST) Subject: Python 3.3 and Pygame 19.2a install problems In-Reply-To: References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> Message-ID: <472f9634-6f15-41b4-8405-6979aec98d5d@googlegroups.com> On Monday, February 3, 2014 12:43:06 AM UTC-6, Terry Reedy wrote: > On 2/2/2014 10:04 PM, EdV wrote: > > > > >> Traceback (most recent call last): File > > >> "C:\Users\Ed\Documents\SOMA\Minecraft and > > >> Python\inventwithpython_src\dodger.py", line 1, in > > >> import pygame, random, sys File > > >> "C:\Python33\lib\site-packages\pygame\__init__.py", line 95, in > > >> > > >> from pygame.base import * > > >> ImportError: DLL load failed: The specified module could not be > > >> found. > > > > > Found the answer here: > > > http://www.reddit.com/r/inventwithpython/comments/1dzl8m/when_importing_pygame_i_get_importerror_dll_load/ > > > > > > Questions but no big deal - 1. Why doesn't pygame.org have the most > > > recent install files compatible with the most recent python I ended > > > up finding them here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > > > The base problem is that Microsoft changes the Visual C runtime with > > each version of the VC compiler. Python 3.3 was compiled with a newer > > version. It is a nuisance for packages to keep recompiling with a new VC > > version. Py 3.4 is using the same version as 3.4, so PyGames *might* > > work with 3.4, or there might be other compatibilities. > > > > > 2. Interesting that "3.2" pygames works with "3.3" python on my XP > > > but the Win 7 required the "3.3" pygames. Thoughts? > > > > It is possible that the VC++2010 runtime does not work with XP, but > > requires Vista+ and that the Microsoft installer installs the older > > VC++2008 runtime on XP even when installing 3.3. If you install for a > > single user, the vcxxxxx.dll is in the python directory or subdirectory. > > For all-user installs, it is in one of the windows/systemxx directories. > > But this is just a guess. > > > > > > -- > > Terry Jan Reedy Thanks much. Glad to be getting these ideas in mind before I start having kids do installations and not have something intelligent to talk about when things don't work. I am more interested in having them explore programming but an important part of our work is how to deal with frustration and unexpected problems. From nicholas.cole at gmail.com Mon Feb 3 08:50:04 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Mon, 3 Feb 2014 13:50:04 +0000 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 12:07 AM, Chris Angelico wrote: > On Mon, Feb 3, 2014 at 10:40 AM, Roy Smith wrote: >> I'm reasonably sure you posted this as humor, but there is some truth in >> what you said. In the crypto/security domain, you often want to keep a >> key or cleartext around only for the time it's needed, and scrub the >> memory it was occupying as soon as it is no longer in use. >> >> I don't know how you would do that in Python. > > I did, but you're right. > > It's fundamentally not possible in pure Python, because there's no way > to flag a block of memory as "do not page this to disk". For what > you're talking about to be at all possible, you would need support > from the language, from the OS, and possibly from the CPU as well. I'm > sure this sort of thing exists, but if it does, it'll probably be > something that Python itself wouldn't concern itself with - you'd get > it via openssl or something. > > There have been occasional times I've wanted an "explicit destruction" > feature. Rather than the facetious exception I listed above, it'd be > better to have all those references (including the original one in a, > since there's nothing special about that) turn into some kind of "null > state" - either None, or a special object that marks itself as a > destructed/destroyed (terminology debates aside) object. With custom > types, I can mark them off with a special flag, and check that all the > time; but I can't, for instance, have a dict that maps some lookup > keyword to its output file, and then destroy output files to remove > all their references from everywhere in the dict. (I have had > something along these lines, a bit more complicated than this, but not > in Python.) Can't you get close to that using weakrefs? I'll admit that care is required. N. From wxjmfauth at gmail.com Mon Feb 3 08:59:26 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 3 Feb 2014 05:59:26 -0800 (PST) Subject: generator slides review and Python doc (+/- text bug) Message-ID: generator slides review and Python doc I do not know what tool is used to produce such slides. When the mouse is over a a text like a title ( ... <\H*> ???) the text get transformed and a colored eol is appearing. Example with the slide #3: Even numbers becomes Even numbers? with a visible colored "?", 'SECTION SIGN' I noticed the same effect with the Python doc since ? (long time). Eg. The Python Tutorial appears as The Python Tutorial? with a visible colored "?", 'PILCROW SIGN', blueish in Python 3, red in Python 2.7.6. And in plenty third party Python docs using probaly the same tool as the official Python doc. The eol glyph may vary and may not be a "?" or a "?". Windows, Firefox and others. The .chm files do not seem to be affected. jmf From jeanmichel at sequans.com Mon Feb 3 09:10:08 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 3 Feb 2014 15:10:08 +0100 (CET) Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: Message-ID: <1238182389.2921577.1391436608903.JavaMail.root@sequans.com> ----- Original Message ----- > generator slides review and Python doc > > > I do not know what tool is used to produce such > slides. > > When the mouse is over a a text like a title ( ... <\H*> ???) > the text get transformed and a colored eol is appearing. Used to get a link to the given chapter/section... Works as intended. Sphinx features the same thing, it can be disabled. JM Note : the links provided in the OP example are broken though -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From jeandupont314 at gmail.com Mon Feb 3 10:05:40 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 07:05:40 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> Message-ID: <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Op maandag 3 februari 2014 02:56:43 UTC+1 schreef Asaf Las: > On Sunday, February 2, 2014 10:51:15 PM UTC+2, Jean Dupont wrote: > > Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: > > > > I'm looking for an efficient method to produce rows of tables like this: > > jean > you can also try to make below universal for all needed bases: > m = lambda m, n: 1 if m & n else 0 > k = [[ m(x,8) , m(x, 4), m(x, 2), m(x, 1)] for x in range(10)] > print (k) Dear Asaf, I'm not at ease with lamba-notation, could you show me how to modify your example for the base 3 case? I guess then it will be much clearer to me thanks in advance jean From jeandupont314 at gmail.com Mon Feb 3 10:06:13 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 07:06:13 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> Message-ID: <1a76f8ae-b194-4800-a77c-bd1e95a35a1b@googlegroups.com> Op zondag 2 februari 2014 19:07:38 UTC+1 schreef Roy Smith: > In article <515e582f-ed17-4d4e-9872-f07f1fda6ed2 at googlegroups.com>, > Jean Dupont wrote: > > > I'm looking for an efficient method to produce rows of tables like this: > > > > for base 2 > > 0 0 0 0 > > 0 0 0 1 > > 0 0 1 0 > > 0 0 1 1 > > 0 1 0 0 > > . > > . > > . > > 1 1 1 1 > > > > for base 3 > > 0 0 0 0 0 0 > > 0 0 0 0 0 1 > > 0 0 0 0 0 2 > > 0 0 0 0 1 0 > > 0 0 0 0 1 1 > > 0 0 0 0 1 2 > > . > > . > > 2 2 2 2 2 2 > > This sounds like a homework problem :-) > > > As you can see the rows are always twice the size of the base > > Why? > > > I _don't_ need to have all rows available together in one array which would > > become too large for higher value number bases. It's sufficient to produce > > one row after the other, as I will do further data manipulation on such a row > > immediately. > > What I get out of that is that you don't want to just print them, you > want to have some function which returns all the generated rows in > order. The way to do that is with the yield statement. Take a look at > https://wiki.python.org/moin/Generators for some discussion on how that > works. Actually, http://stackoverflow.com/questions/231767/ > looks like an even better discussion. > > Does that help you any? Thanks, I'll try to figure out what yield does kind regards, jean From ram.rachum at gmail.com Mon Feb 3 10:14:01 2014 From: ram.rachum at gmail.com (Ram Rachum) Date: Mon, 3 Feb 2014 17:14:01 +0200 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: <20140203110816.GA7423@arxnet.hu> References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: Worked! Thanks Ervin! On Mon, Feb 3, 2014 at 1:08 PM, Ervin Heged?s wrote: > Hello, > > On Mon, Feb 03, 2014 at 02:50:15AM -0800, cool-RR wrote: > > Hi, > > > > I'm trying to install Python 3.4b3 on Ubuntu. Since compilation seems to > be the only way, I'm trying that. > > > > I downloaded the source, I changed Setup.dist to have this: > > > > SSL=/usr > > _ssl _ssl.c \ > > -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ > > -L$(SSL)/lib -lssl -lcrypto > > > [...] > > > ./Modules/_ssl.c:57:25: fatal error: openssl/rsa.h: No such file or > directory > > #include "openssl/rsa.h" > > ^ > > compilation terminated. > > > > What do I do to solve this? > > try this: > > sudo apt-get install libssl-dev > > > cheers, > > > a. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roegltd at gmail.com Mon Feb 3 10:34:18 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 3 Feb 2014 07:34:18 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: On Monday, February 3, 2014 5:05:40 PM UTC+2, Jean Dupont wrote: > Op maandag 3 februari 2014 02:56:43 UTC+1 schreef Asaf Las: > > > On Sunday, February 2, 2014 10:51:15 PM UTC+2, Jean Dupont wrote: > > > Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: > > > I'm looking for an efficient method to produce rows of tables like this: > > > jean > > > you can also try to make below universal for all needed bases: > > m = lambda m, n: 1 if m & n else 0 > > k = [[ m(x,8) , m(x, 4), m(x, 2), m(x, 1)] for x in range(10)] > > > print (k) > > Dear Asaf, > I'm not at ease with lamba-notation, could you show me how to modify your > example for the base 3 case? I guess then it will be much clearer to me > thanks in advance > > jean I don't have to - use normal functions instead :-) /Asaf From christian at python.org Mon Feb 3 10:50:22 2014 From: christian at python.org (Christian Heimes) Date: Mon, 03 Feb 2014 16:50:22 +0100 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: On 03.02.2014 16:14, Ram Rachum wrote: > Worked! Thanks Ervin! $ sudo apt-get build-dep python3.3 will install everything you need to compile Python 3.4 on Debian and Ubuntu. Good luck! :) Christian From rustompmody at gmail.com Mon Feb 3 10:51:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 3 Feb 2014 07:51:13 -0800 (PST) Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: <2885379d-34ea-4970-84aa-800bd884f1b4@googlegroups.com> On Monday, February 3, 2014 8:44:01 PM UTC+5:30, cool-RR wrote: > On Mon, Feb 3, 2014 at 1:08 PM, Ervin Heged?s wrote: > > > try this: > > sudo apt-get install libssl-dev > Worked! Thanks Ervin! In general its a good idea to *look at* what you get with apt-get build-dep python3 You need not go ahead with installing what it says it will install -- tends to pull in a lot of useless stuff -- but you may also see names that are clearly needed From torriem at gmail.com Mon Feb 3 11:50:47 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 03 Feb 2014 09:50:47 -0700 Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: <52EFC8E7.4010409@gmail.com> On 02/03/2014 06:59 AM, wxjmfauth at gmail.com wrote: > generator slides review and Python doc > > > I do not know what tool is used to produce such > slides. What slides? What web site are you referring to? A little context wouldn't hurt. From jeandupont314 at gmail.com Mon Feb 3 11:50:31 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 08:50:31 -0800 (PST) Subject: [newbie] troubles with tuples Message-ID: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> I'm looking at the way to address tuples e.g. tup2 = (1, 2, 3, 4, 5, 6, 7 ); As I found out indices start with 0 in Python, so tup2[0] gives me 1, the first element in the tuple as expected tup2[1] gives me 2, the second element in the tuple as expected now here comes what surprises me: tup2[0:1] does not give me the expected (1,2) but (2,) what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? thanks in advance and kind regards, jean From roegltd at gmail.com Mon Feb 3 11:59:50 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 3 Feb 2014 08:59:50 -0800 (PST) Subject: [newbie] troubles with tuples In-Reply-To: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> Message-ID: <97e7f0a4-9e9e-4361-8183-d6f390e26148@googlegroups.com> On Monday, February 3, 2014 6:50:31 PM UTC+2, Jean Dupont wrote: > I'm looking at the way to address tuples > > e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > As I found out indices start with 0 in Python, so > tup2[0] gives me 1, the first element in the tuple as expected > tup2[1] gives me 2, the second element in the tuple as expected > now here comes what surprises me: > tup2[0:1] does not give me the expected (1,2) but (2,) > what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? > > thanks in advance and kind regards, > > jean Hi from http://docs.python.org/3.3/library/stdtypes.html?highlight=tuple#tuple " The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty." so in above k < j but not equal so in your example slice will be of only one member. /Asaf From larry.martell at gmail.com Mon Feb 3 12:00:33 2014 From: larry.martell at gmail.com (Larry Martell) Date: Mon, 3 Feb 2014 12:00:33 -0500 Subject: [newbie] troubles with tuples In-Reply-To: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> Message-ID: On Mon, Feb 3, 2014 at 11:50 AM, Jean Dupont wrote: > I'm looking at the way to address tuples > e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > > As I found out indices start with 0 in Python, so > tup2[0] gives me 1, the first element in the tuple as expected > tup2[1] gives me 2, the second element in the tuple as expected > now here comes what surprises me: > tup2[0:1] does not give me the expected (1,2) but (2,) > > what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? > > thanks in advance and kind regards, Some examples: a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array a[-1] # last item in the array a[-2:] # last two items in the array a[:-2] # everything except the last two items HTH, -larry From rustompmody at gmail.com Mon Feb 3 12:06:46 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 3 Feb 2014 09:06:46 -0800 (PST) Subject: [newbie] troubles with tuples In-Reply-To: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> Message-ID: <6214e086-7616-41bc-8e82-665b01dddd25@googlegroups.com> On Monday, February 3, 2014 10:20:31 PM UTC+5:30, Jean Dupont wrote: > I'm looking at the way to address tuples > e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > As I found out indices start with 0 in Python, so > tup2[0] gives me 1, the first element in the tuple as expected > tup2[1] gives me 2, the second element in the tuple as expected > now here comes what surprises me: > tup2[0:1] does not give me the expected (1,2) but (2,) Python 2.7.6 (default, Jan 11 2014, 17:06:02) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> tup2=(1,2,3,4,5,6,7) >>> tup2[0:1] (1,) >>> So assuming you meant (1,) and wrote (2,) :-) > what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? Generally ranges in python are lower-inclusive upper-exclusive What some math texts write as [lo, hi) So if you want from index 1 to 2-inclusive it is 1 to 3 exclusive tup2[0:2] See for motivations http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831.html And one more surprising thing to note is that negatives count from the end From skip at pobox.com Mon Feb 3 12:41:27 2014 From: skip at pobox.com (Skip Montanaro) Date: Mon, 3 Feb 2014 11:41:27 -0600 Subject: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString Message-ID: For various reasons at work, we get Python from a third party. I just installed VTK for OpenSuSE on one of my desktop machines using zypper. When I import it from /usr/bin/python (2.7.3), the import works just fine. When I try to import it from our vendor-provided Python (2.7.2), I get this traceback: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/site-packages/vtk/__init__.py", line 41, in from vtkCommonPython import * ImportError: /usr/lib64/libvtkPythonCore.so.5.10: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString I think this means that at configure time, OpenSuSE and our vendor chose different values for the --enable-unicode option. Is that correct? If so, I have a few questions: 1. Is there a workaround short of rebuild one version of Python or the other? 2. Does the flexible string representation avoid this problem? 3. Which builder (OpenSuSE or our vendor) decided the default wasn't good enough? Thx, Skip From sg552 at hotmail.co.uk Mon Feb 3 12:42:36 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Mon, 03 Feb 2014 17:42:36 +0000 Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: On 03/02/2014 13:59, wxjmfauth at gmail.com wrote: > [...] > > I noticed the same effect with the Python doc > since ? (long time). > > Eg. > > The Python Tutorial > appears as > The Python Tutorial? > > with a visible colored "?", 'PILCROW SIGN', > blueish in Python 3, red in Python 2.7.6. Hint: try clicking the ?. From ian.g.kelly at gmail.com Mon Feb 3 12:44:21 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Feb 2014 10:44:21 -0700 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 3, 2014 at 6:44 AM, Dennis Lee Bieber wrote: > On Sun, 02 Feb 2014 18:40:59 -0500, Roy Smith declaimed the > following: > >>I'm reasonably sure you posted this as humor, but there is some truth in >>what you said. In the crypto/security domain, you often want to keep a >>key or cleartext around only for the time it's needed, and scrub the >>memory it was occupying as soon as it is no longer in use. >> >>I don't know how you would do that in Python. > > Don't store it as text... Use a numeric array of byte values, which can > then be run through a clearing procedure (overwrite with random values, > overwrite with ones complement of same random values, overwrite with new > random values). > > Python may be caching the individual byte values, but the are unlikely > to be in any sequence indicative of a key. If Python interns the byte objects though, won't overwriting them lead to subtle bugs later on as Python attempts to reuse them? They may even be reused already from earlier byte objects with the same values, that may or may not still have references. From andrea.crotti.0 at gmail.com Mon Feb 3 12:45:55 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 3 Feb 2014 17:45:55 +0000 Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: 2014-02-03 : > generator slides review and Python doc > > > I do not know what tool is used to produce such > slides. > > When the mouse is over a a text like a title ( ... <\H*> ???) > the text get transformed and a colored eol is appearing. > > Example with the slide #3: > > Even numbers > becomes > Even numbers? > > with a visible colored "?", 'SECTION SIGN' > > > I noticed the same effect with the Python doc > since ? (long time). > > Eg. > > The Python Tutorial > appears as > The Python Tutorial? > > with a visible colored "?", 'PILCROW SIGN', > blueish in Python 3, red in Python 2.7.6. > > > And in plenty third party Python docs using > probaly the same tool as the official Python > doc. > The eol glyph may vary and may not be a "?" or a "?". > > Windows, Firefox and others. > > The .chm files do not seem to be affected. > > jmf > -- > https://mail.python.org/mailman/listinfo/python-list I just saw now this mail you didn't reply to my email correctly.. Anyway I use this: https://github.com/nyergler/hieroglyph And I just use sphinx + RST to generate the slides, the raw source is here: https://raw2.github.com/AndreaCrotti/generators/master/index.rst From rosuav at gmail.com Mon Feb 3 12:57:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 04:57:13 +1100 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Feb 4, 2014 at 12:50 AM, Nicholas Cole wrote: >> There have been occasional times I've wanted an "explicit destruction" >> feature. Rather than the facetious exception I listed above, it'd be >> better to have all those references (including the original one in a, >> since there's nothing special about that) turn into some kind of "null >> state" - either None, or a special object that marks itself as a >> destructed/destroyed (terminology debates aside) object. With custom >> types, I can mark them off with a special flag, and check that all the >> time; but I can't, for instance, have a dict that maps some lookup >> keyword to its output file, and then destroy output files to remove >> all their references from everywhere in the dict. (I have had >> something along these lines, a bit more complicated than this, but not >> in Python.) > > Can't you get close to that using weakrefs? I'll admit that care is required. Weakrefs are a related tool, but solving a different problem. What I wanted here was an easy way to force all references to a particular file to be wiped out, based on one of the existing references. Here's a concocted setup that's broadly similar to what I was doing, which might illustrate the issue: log_files = {} def add_log_file(fn, *keywords): f = open(fn, "w") for kw in keywords: log_files[kw]=f for line in process_me_line_generator(): kw = line.split()[0] f = log_files.get(kw) if not f: continue f.write(line+"\n") if 'quit' in line: # Okay, let's now close this file. destruct(f) In this particular case, I could use "f.close()" and "if not f or f.closed: continue", but that requires that the object cooperate in this way, and I'm not entirely sure about resource usage. (I was actually working with a database connection object, IIRC, which didn't offer me a way to inquire if it was still open or not.) To do this with weak refs, I'd have to have some other source of strong refs, and closing would be done by digging through that list, disposing of it from there, and then triggering garbage collection. I suppose it could be made to work, but it feels like going about everything backwards. ChrisA From charliewinn97 at gmail.com Mon Feb 3 13:04:35 2014 From: charliewinn97 at gmail.com (Charlie Winn) Date: Mon, 3 Feb 2014 10:04:35 -0800 (PST) Subject: Calculator Problem In-Reply-To: References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> On Sunday, February 2, 2014 9:46:24 PM UTC, Gary Herron wrote: > On 02/02/2014 01:16 PM, Charlie Winn wrote: > > > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > > > def Addition(): > > > print('Addition: What are two your numbers?') > > > 1 = float(input('First Number:')) > > > 2 = float(input('Second Number:')) > > > print('Your Final Result is:', 1 + 2) > > > > > > > > > def Subtraction(): > > > print('Subtraction: What are two your numbers?') > > > 3 = float(input('First Number:')) > > > 4 = float(input('Second Number:')) > > > print('Your Final Result is:', 3 - 4) > > > > > > > > > def Multiplication(): > > > print('Multiplication: What are two your numbers?') > > > 5 = float(input('First Number:')) > > > 6 = float(input('Second Number:')) > > > print('Your Final Result is:', 5 * 6) > > > > > > > > > def Division(): > > > print('Division: What are your two numbers?') > > > 7 = float(input('First Number:')) > > > 8 = float(input('Second Number:')) > > > print('Your Final Result is:', 7 / 8) > > > > > > > > > > > > print('What type of calculation would you like to do?') > > > Question = input('(Add, Subtract, Divide or Multiply)') > > > if Question.lower().startswith('a'): > > > print(Addition()) > > > elif Question.lower().startswith('s'): > > > print(Subtraction()) > > > elif Question.lower().startswith('d'): > > > print(Division()) > > > elif Question.lower().startswith('m'): > > > print(Multiplication()) > > > else: > > > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > > > while Question == 'test': > > > Question() > > > > Sorry, but in fact you did *not* run this program as you claim. It's > > full of syntax errors. Any attempt to run it will display syntax errors > > immediately, and never actually run. So please tell us what really > > happened. > > > > But even without an accurate description of what you did, I can say this: > > > > Lines like > > 1 = float(...) > > don't make sense. It's as if you are trying to change the value of the > > number one, but that's nonsense. > > > > And lines like > > print('Your Final Result is:', 5 * 6) > > had better print out 30 (since that is what 5 times 6 is) but that's > > clearly not what you intended. > > > > Gary Herron excuse me but don't be so ******* rude , i did run this program and it did run correctly and if you want me to prove it with screenshots so be it , so don't make accusations ** Gary ** i only came here for some help not to be accused of not even running my program Charlie :D From joel.goldstick at gmail.com Mon Feb 3 13:17:44 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 3 Feb 2014 13:17:44 -0500 Subject: Calculator Problem In-Reply-To: <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> Message-ID: On Feb 3, 2014 1:05 PM, "Charlie Winn" wrote: > > On Sunday, February 2, 2014 9:46:24 PM UTC, Gary Herron wrote: > > On 02/02/2014 01:16 PM, Charlie Winn wrote: > > > > > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > > > > > > > def Addition(): > > > > > print('Addition: What are two your numbers?') > > > > > 1 = float(input('First Number:')) You can't name a variable a number > > > > > 2 = float(input('Second Number:')) > > > > > print('Your Final Result is:', 1 + 2) You should a result, then print it after the function. > > > > > > > > > > > > > def Subtraction(): > > > > > print('Subtraction: What are two your numbers?') > > > > > 3 = float(input('First Number:')) > > > > > 4 = float(input('Second Number:')) > > > > > print('Your Final Result is:', 3 - 4) > > > > > > > > > > > > > > > def Multiplication(): > > > > > print('Multiplication: What are two your numbers?') > > > > > 5 = float(input('First Number:')) > > > > > 6 = float(input('Second Number:')) > > > > > print('Your Final Result is:', 5 * 6) > > > > > > > > > > > > > > > def Division(): > > > > > print('Division: What are your two numbers?') > > > > > 7 = float(input('First Number:')) > > > > > 8 = float(input('Second Number:')) > > > > > print('Your Final Result is:', 7 / 8) > > > > > > > > > > > > > > > > > > > > print('What type of calculation would you like to do?') > > > > > Question = input('(Add, Subtract, Divide or Multiply)') > > > > > if Question.lower().startswith('a'): > > > > > print(Addition()) > > > > > elif Question.lower().startswith('s'): > > > > > print(Subtraction()) > > > > > elif Question.lower().startswith('d'): > > > > > print(Division()) > > > > > elif Question.lower().startswith('m'): > > > > > print(Multiplication()) > > > > > else: > > > > > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > > > > > > > while Question == 'test': > > > > > Question() > > > > > > > > Sorry, but in fact you did *not* run this program as you claim. It's > > > > full of syntax errors. Any attempt to run it will display syntax errors > > > > immediately, and never actually run. So please tell us what really > > > > happened. > > > > > > > > But even without an accurate description of what you did, I can say this: > > > > > > > > Lines like > > > > 1 = float(...) > > > > don't make sense. It's as if you are trying to change the value of the > > > > number one, but that's nonsense. > > > > > > > > And lines like > > > > print('Your Final Result is:', 5 * 6) > > > > had better print out 30 (since that is what 5 times 6 is) but that's > > > > clearly not what you intended. > > > > > > > > Gary Herron > > excuse me but don't be so ******* rude , i did run this program and it did run correctly and if you want me to prove it with screenshots so be it , so don't make accusations ** Gary ** i only came here for some help not to be accused of not even running my program If you can run this, cut and paste the results > > Charlie :D > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Feb 3 13:27:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 05:27:08 +1100 Subject: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString In-Reply-To: References: Message-ID: On Tue, Feb 4, 2014 at 4:41 AM, Skip Montanaro wrote: > I think this means that at configure time, OpenSuSE and our vendor > chose different values for the --enable-unicode option. Is that > correct? Easy enough to check. Fire up each Python and have a look at what sys.maxunicode is - if it's 65535, you have a buggy-mode Python that uses either UCS-2 or UTF-16 internally. > If so, I have a few questions: > > 1. Is there a workaround short of rebuild one version of Python or the other? I don't think so. What you're seeing may be a relatively simple-looking error, but the internal representation of every single string is different. Bound to cause problems. > 2. Does the flexible string representation avoid this problem? Well yes, by eliminating the option of a UCS-2 build altogether, the FSR prevents the compatibility problem of some choosing it and some not :) > 3. Which builder (OpenSuSE or our vendor) decided the default wasn't > good enough? Not sure, but I would strongly recommend going for a wide build. It may be a pain to use that much RAM everywhere, but at least you get correct behaviour; and that's how most Pythons on Linux have been (most Windows Pythons were built narrow). But there is another concern, which your second point minorly touches on. I'm not certain, but I think the name _PyUnicodeUCS4_AsDefaultEncodedString means that VTK was built against a wide Python ("UCS4") and calls _PyUnicode_AsDefaultEncodedString. According to PEP 393, that function - which had always been internal anyway - is completely removed. Porting VTK to Python 3.3+ will mean changing that. ChrisA From charliewinn97 at gmail.com Mon Feb 3 13:25:37 2014 From: charliewinn97 at gmail.com (Charlie Winn) Date: Mon, 3 Feb 2014 10:25:37 -0800 (PST) Subject: Calculator Problem In-Reply-To: References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> Message-ID: <413998dd-b101-46e4-9012-c79c2cd66cf0@googlegroups.com> On Monday, February 3, 2014 6:17:44 PM UTC, Joel Goldstick wrote: > On Feb 3, 2014 1:05 PM, "Charlie Winn" wrote: > > > > > > On Sunday, February 2, 2014 9:46:24 PM UTC, Gary Herron wrote: > > > > On 02/02/2014 01:16 PM, Charlie Winn wrote: > > > > > > > > > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > > > > > > > > > > > > > > > def Addition(): > > > > > > > > > ? ? ?print('Addition: What are two your numbers?') > > > > > > > > > ? ? ?1 = float(input('First Number:')) > > You can't name a variable a number > > > > > > > > > ? ? ?2 = float(input('Second Number:')) > > > > > > > > > ? ? ?print('Your Final Result is:', 1 + 2) > > You should a result, then print it after the function. > > > > > > > > > > > > > > > > > > > > > > > def Subtraction(): > > > > > > > > > ? ? ?print('Subtraction: What are two your numbers?') > > > > > > > > > ? ? ?3 = float(input('First Number:')) > > > > > > > > > ? ? ?4 = float(input('Second Number:')) > > > > > > > > > ? ? ?print('Your Final Result is:', 3 - 4) > > > > > > > > > > > > > > > > > > > > > > > > > > > def Multiplication(): > > > > > > > > > ? ? ?print('Multiplication: What are two your numbers?') > > > > > > > > > ? ? ?5 = float(input('First Number:')) > > > > > > > > > ? ? ?6 = float(input('Second Number:')) > > > > > > > > > ? ? ?print('Your Final Result is:', 5 * 6) > > > > > > > > > > > > > > > > > > > > > > > > > > > def Division(): > > > > > > > > > ? ? ?print('Division: What are your two numbers?') > > > > > > > > > ? ? ?7 = float(input('First Number:')) > > > > > > > > > ? ? ?8 = float(input('Second Number:')) > > > > > > > > > ? ? ?print('Your Final Result is:', 7 / 8) > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > print('What type of calculation would you like to do?') > > > > > > > > > Question = input('(Add, Subtract, Divide or Multiply)') > > > > > > > > > if Question.lower().startswith('a'): > > > > > > > > > ? ? ? ? ? ? ?print(Addition()) > > > > > > > > > elif Question.lower().startswith('s'): > > > > > > > > > ? ? ? ? ? ? ?print(Subtraction()) > > > > > > > > > elif Question.lower().startswith('d'): > > > > > > > > > ? ? ? ? ? ? ?print(Division()) > > > > > > > > > elif Question.lower().startswith('m'): > > > > > > > > > ? ? ? ? ? ? ?print(Multiplication()) > > > > > > > > > else: > > > > > > > > > ? ? ? ? ?print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > > > > > > > > > > > > > > > while Question == 'test': > > > > > > > > > ? ? ? ? ?Question() > > > > > > > > > > > > > > > > Sorry, but in fact you did *not* run this program as you claim. It's > > > > > > > > full of syntax errors. ?Any attempt to run it will display syntax errors > > > > > > > > immediately, and never actually run. ? So please tell us what really > > > > > > > > happened. > > > > > > > > > > > > > > > > But even without an accurate description of what you did, I can say this: > > > > > > > > > > > > > > > > Lines like > > > > > > > > ? ? ?1 = float(...) > > > > > > > > don't make sense. ?It's as if you are trying to change the value of the > > > > > > > > number one, but that's nonsense. > > > > > > > > > > > > > > > > And lines like > > > > > > > > ? ? ?print('Your Final Result is:', 5 * 6) > > > > > > > > had better print out 30 (since that is what 5 times 6 is) but that's > > > > > > > > clearly not what you intended. > > > > > > > > > > > > > > > > Gary Herron > > > > > > excuse me but don't be so ******* rude , i did run this program and it did run correctly and if you want me to prove it with screenshots so be it , so don't make accusations ** Gary ** i only came here for some help not to be accused of not even running my program > > > If you can run this, cut and paste the results > > > > > > Charlie :D > > > -- > > > https://mail.python.org/mailman/listinfo/python-list Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> What type of calculation would you like to do? (Add, Subtract, Divide or Multiply)a Addition: What are two your numbers? First Number:5 Second Number:96 Your Final Result is: 101.0 None >>> From roy at panix.com Mon Feb 3 13:26:22 2014 From: roy at panix.com (Roy Smith) Date: Mon, 03 Feb 2014 13:26:22 -0500 Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> Message-ID: Charlie Winn wrote: > excuse me but don't be so ******* rude , i did run this program and it did > run correctly and if you want me to prove it with screenshots so be it , so > don't make accusations ** Gary ** i only came here for some help not to be > accused of not even running my program Hi Charlie, I don't think anybody doubts that you ran your program. More likely, the code that you ran simply isn't the code that you posted. When posting code, it's best to copy-paste the exact code you ran. You posted this: > > > def Addition(): > > > print('Addition: What are two your numbers?') > > > 1 = float(input('First Number:')) > > > 2 = float(input('Second Number:')) > > > print('Your Final Result is:', 1 + 2) That code could not have been what you ran, because it's not runnable. It's a syntax error (in both Python 2 and 3). From storchaka at gmail.com Mon Feb 3 13:32:49 2014 From: storchaka at gmail.com (Serhiy Storchaka) Date: Mon, 03 Feb 2014 20:32:49 +0200 Subject: fseek In Compressed Files In-Reply-To: References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> Message-ID: 30.01.14 18:21, Peter Otten ???????(??): > Do you know an efficient way to implement random access for a bzip2 or gzip > file? See dictzip and BGZF. Unfortunately Python stdlib doesn't support them. From wxjmfauth at gmail.com Mon Feb 3 13:37:28 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 3 Feb 2014 10:37:28 -0800 (PST) Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: Le lundi 3 f?vrier 2014 18:42:36 UTC+1, Rotwang a ?crit?: > On 03/02/2014 13:59, wxjmfauth at gmail.com wrote: > > > [...] > > > > > > I noticed the same effect with the Python doc > > > since ? (long time). > > > > > > Eg. > > > > > > The Python Tutorial > > > appears as > > > The Python Tutorial? > > > > > > with a visible colored "?", 'PILCROW SIGN', > > > blueish in Python 3, red in Python 2.7.6 > > > > Hint: try clicking the ?. I never was aware of this "feature". Is it deliverate? It gives to me the feeling of a badly programmed html page, especially if this sign does correspond to an eol! jmf From rosuav at gmail.com Mon Feb 3 13:46:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 05:46:05 +1100 Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: On Tue, Feb 4, 2014 at 5:37 AM, wrote: > Le lundi 3 f?vrier 2014 18:42:36 UTC+1, Rotwang a ?crit : >> On 03/02/2014 13:59, wxjmfauth at gmail.com wrote: >> Hint: try clicking the ?. > > I never was aware of this "feature". Is it deliverate? > > It gives to me the feeling of a badly programmed > html page, especially if this sign does correspond > to an eol! Very deliberate, and very useful. I don't know why that sign should correspond to a line end; I grew up with it representing "paragraph", which is close to what it means here. (Well, that and "Ctrl-T", since it was character 20 on those old systems.) Yes, it does sometimes get a little distracting as the mouse moves over and away, but it would be more confusing to have it always shown, and I don't know of any better way to do it. ChrisA From rosuav at gmail.com Mon Feb 3 13:48:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 05:48:15 +1100 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: On Tue, Feb 4, 2014 at 2:50 AM, Christian Heimes wrote: > On 03.02.2014 16:14, Ram Rachum wrote: >> Worked! Thanks Ervin! > > $ sudo apt-get build-dep python3.3 > > will install everything you need to compile Python 3.4 on Debian and > Ubuntu. Good luck! :) Technically that gets everything you need to compile Python 3.3... wasn't there one more library needed for 3.4? It's still an excellent way to get nearly everything, though. ChrisA From python at mrabarnett.plus.com Mon Feb 3 13:55:48 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Feb 2014 18:55:48 +0000 Subject: Python 3.3 and Pygame 19.2a install problems In-Reply-To: References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> Message-ID: <52EFE634.3010900@mrabarnett.plus.com> On 2014-02-03 06:43, Terry Reedy wrote: > On 2/2/2014 10:04 PM, edvogel56 at gmail.com wrote: > >>> Traceback (most recent call last): File >>> "C:\Users\Ed\Documents\SOMA\Minecraft and >>> Python\inventwithpython_src\dodger.py", line 1, in > >> import pygame, random, sys File >>> "C:\Python33\lib\site-packages\pygame\__init__.py", line 95, in >>> > >> from pygame.base import * >>> ImportError: DLL load failed: The specified module could not be >>> found. > >> Found the answer here: >> http://www.reddit.com/r/inventwithpython/comments/1dzl8m/when_importing_pygame_i_get_importerror_dll_load/ >> >> Questions but no big deal - 1. Why doesn't pygame.org have the most >> recent install files compatible with the most recent python I ended >> up finding them here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > The base problem is that Microsoft changes the Visual C runtime with > each version of the VC compiler. Python 3.3 was compiled with a newer > version. It is a nuisance for packages to keep recompiling with a new VC > version. Py 3.4 is using the same version as 3.4, so PyGames *might* > work with 3.4, or there might be other compatibilities. > >> 2. Interesting that "3.2" pygames works with "3.3" python on my XP >> but the Win 7 required the "3.3" pygames. Thoughts? > > It is possible that the VC++2010 runtime does not work with XP, but > requires Vista+ and that the Microsoft installer installs the older > VC++2008 runtime on XP even when installing 3.3. If you install for a > single user, the vcxxxxx.dll is in the python directory or subdirectory. > For all-user installs, it is in one of the windows/systemxx directories. > But this is just a guess. > I've used Visual C++ Express 2010 on XP Pro without any problem. From skip at pobox.com Mon Feb 3 13:59:42 2014 From: skip at pobox.com (Skip Montanaro) Date: Mon, 3 Feb 2014 12:59:42 -0600 Subject: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString In-Reply-To: References: Message-ID: On Mon, Feb 3, 2014 at 12:27 PM, Chris Angelico wrote: > On Tue, Feb 4, 2014 at 4:41 AM, Skip Montanaro wrote: >> I think this means that at configure time, OpenSuSE and our vendor >> chose different values for the --enable-unicode option. Is that >> correct? > > Easy enough to check. Fire up each Python and have a look at what > sys.maxunicode is - if it's 65535, you have a buggy-mode Python that > uses either UCS-2 or UTF-16 internally. Thanks. I get 65535 for our vendor-built Python, and 1114111 from /usr/bin/python. So (no great surprise), it looks like our vendor is to blame. > But there is another concern, which your second point minorly touches > on. I'm not certain, but I think the name > _PyUnicodeUCS4_AsDefaultEncodedString means that VTK was built against > a wide Python ("UCS4") and calls _PyUnicode_AsDefaultEncodedString. > According to PEP 393, that function - which had always been internal > anyway - is completely removed. Porting VTK to Python 3.3+ will mean > changing that. I'm not concerned about that, certainly not in the immediate term. /usr/bin/python and VTK appear to agree on this stuff. I trust Kitware and the OpenSuSE people to take care of these sorts of problems if VTK ever supports Python 3.x. Skip From sg552 at hotmail.co.uk Mon Feb 3 13:55:26 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Mon, 03 Feb 2014 18:55:26 +0000 Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: On 03/02/2014 18:37, wxjmfauth at gmail.com wrote: >> [...] >> >> Hint: try clicking the ?. > > I never was aware of this "feature". Is it deliverate? Do you mean deliberate? Of course it is. > It gives to me the feeling of a badly programmed > html page, especially if this sign does correspond > to an eol! Why on Earth would the sign correspond to an EOL? The section sign and pilcrow have a history of being used to refer to sections and paragraphs respectively, so using them for permalinks to individual sections of a web page makes perfect sense. From zachary.ware+pylist at gmail.com Mon Feb 3 14:05:40 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Mon, 3 Feb 2014 13:05:40 -0600 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: On Mon, Feb 3, 2014 at 12:48 PM, Chris Angelico wrote: > On Tue, Feb 4, 2014 at 2:50 AM, Christian Heimes wrote: >> On 03.02.2014 16:14, Ram Rachum wrote: >>> Worked! Thanks Ervin! >> >> $ sudo apt-get build-dep python3.3 >> >> will install everything you need to compile Python 3.4 on Debian and >> Ubuntu. Good luck! :) > > Technically that gets everything you need to compile Python 3.3... > wasn't there one more library needed for 3.4? It's still an excellent > way to get nearly everything, though. I think you're thinking of 3.2 -> 3.3. 3.3 added the lzma module, which requires lzma-dev. I think 3.4 has the same requirements as 3.3. -- Zach From rosuav at gmail.com Mon Feb 3 14:09:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 06:09:33 +1100 Subject: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString In-Reply-To: References: Message-ID: On Tue, Feb 4, 2014 at 5:59 AM, Skip Montanaro wrote: > On Mon, Feb 3, 2014 at 12:27 PM, Chris Angelico wrote: >> On Tue, Feb 4, 2014 at 4:41 AM, Skip Montanaro wrote: >>> I think this means that at configure time, OpenSuSE and our vendor >>> chose different values for the --enable-unicode option. Is that >>> correct? >> >> Easy enough to check. Fire up each Python and have a look at what >> sys.maxunicode is - if it's 65535, you have a buggy-mode Python that >> uses either UCS-2 or UTF-16 internally. > > Thanks. I get 65535 for our vendor-built Python, and 1114111 from > /usr/bin/python. So (no great surprise), it looks like our vendor is > to blame. That could be a problem, if you now need to have a complete backward-incompatible Python replacement. Could be a bit of a pain for all your other extensions. But it's worth doing if you have any chance of ever seeing an astral character. >> But there is another concern, which your second point minorly touches >> on. I'm not certain, but I think the name >> _PyUnicodeUCS4_AsDefaultEncodedString means that VTK was built against >> a wide Python ("UCS4") and calls _PyUnicode_AsDefaultEncodedString. >> According to PEP 393, that function - which had always been internal >> anyway - is completely removed. Porting VTK to Python 3.3+ will mean >> changing that. > > I'm not concerned about that, certainly not in the immediate term. > /usr/bin/python and VTK appear to agree on this stuff. I trust Kitware > and the OpenSuSE people to take care of these sorts of problems if VTK > ever supports Python 3.x. Okay. You mentioned the FSR, which is a 3.3 feature, so I thought I may as well point out what the associated PEP says about that particular function. Good luck getting this fixed. Even if you do manage to get your vendor to start shipping wide builds, you're going to have people screaming about how much more RAM their processes use now :( Never mind that other Linux builds of Python have done the same thing for years. ChrisA From rosuav at gmail.com Mon Feb 3 14:11:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 06:11:03 +1100 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: On Tue, Feb 4, 2014 at 6:05 AM, Zachary Ware wrote: > On Mon, Feb 3, 2014 at 12:48 PM, Chris Angelico wrote: >> On Tue, Feb 4, 2014 at 2:50 AM, Christian Heimes wrote: >>> On 03.02.2014 16:14, Ram Rachum wrote: >>>> Worked! Thanks Ervin! >>> >>> $ sudo apt-get build-dep python3.3 >>> >>> will install everything you need to compile Python 3.4 on Debian and >>> Ubuntu. Good luck! :) >> >> Technically that gets everything you need to compile Python 3.3... >> wasn't there one more library needed for 3.4? It's still an excellent >> way to get nearly everything, though. > > I think you're thinking of 3.2 -> 3.3. 3.3 added the lzma module, > which requires lzma-dev. I think 3.4 has the same requirements as > 3.3. Ah, that would be it, thanks. I just remembered I'd recently used build-dep across versions and had to get something involving data compression. Went digging for stuff starting with 'z', but missed this because, well, it doesn't start with 'z' :) Thanks. ChrisA From jeandupont314 at gmail.com Mon Feb 3 14:18:21 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 11:18:21 -0800 (PST) Subject: [newbie] troubles with tuples In-Reply-To: <6214e086-7616-41bc-8e82-665b01dddd25@googlegroups.com> References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> <6214e086-7616-41bc-8e82-665b01dddd25@googlegroups.com> Message-ID: Op maandag 3 februari 2014 18:06:46 UTC+1 schreef Rustom Mody: > On Monday, February 3, 2014 10:20:31 PM UTC+5:30, Jean Dupont wrote: > > I'm looking at the way to address tuples > > e.g. > > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > > As I found out indices start with 0 in Python, so > > tup2[0] gives me 1, the first element in the tuple as expected > > tup2[1] gives me 2, the second element in the tuple as expected > > now here comes what surprises me: > > tup2[0:1] does not give me the expected (1,2) but (2,) > > Python 2.7.6 (default, Jan 11 2014, 17:06:02) > [GCC 4.8.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> tup2=(1,2,3,4,5,6,7) > >>> tup2[0:1] > (1,) > >>> > So assuming you meant (1,) and wrote (2,) :-) > > what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? > Generally ranges in python are lower-inclusive upper-exclusive > What some math texts write as [lo, hi) > So if you want from index 1 to 2-inclusive it is 1 to 3 exclusive > tup2[0:2] > > See for motivations > http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831.html > And one more surprising thing to note is that negatives count from the end Thank you (and the others) for making this "logical" kind regards, jean From wxjmfauth at gmail.com Mon Feb 3 14:31:12 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 3 Feb 2014 11:31:12 -0800 (PST) Subject: generator slides review and Python doc (+/- text bug) In-Reply-To: References: Message-ID: <4fdb224c-be3d-45f1-998e-993f22ecab91@googlegroups.com> Le lundi 3 f?vrier 2014 19:55:26 UTC+1, Rotwang a ?crit?: > On 03/02/2014 18:37, wxjmfauth at gmail.com wrote: > > >> [...] > > >> > > >> Hint: try clicking the ?. > > > > > > I never was aware of this "feature". Is it deliverate? > > > > Do you mean deliberate? Of course it is. > > > > > > > It gives to me the feeling of a badly programmed > > > html page, especially if this sign does correspond > > > to an eol! > > > > Why on Earth would the sign correspond to an EOL? The section sign and > > pilcrow have a history of being used to refer to sections and paragraphs > > respectively, so using them for permalinks to individual sections of a > > web page makes perfect sense. Sorry. I should have written "end of paragraph or section". Having said this, that's because these signs are usually used to signal an "end of ...', that I find these signs as link not really meaningful. jmf From jeandupont314 at gmail.com Mon Feb 3 14:37:36 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 11:37:36 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: Op maandag 3 februari 2014 16:34:18 UTC+1 schreef Asaf Las: > On Monday, February 3, 2014 5:05:40 PM UTC+2, Jean Dupont wrote: > > Op maandag 3 februari 2014 02:56:43 UTC+1 schreef Asaf Las: > > > > > On Sunday, February 2, 2014 10:51:15 PM UTC+2, Jean Dupont wrote: > > > > Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: > > > > I'm looking for an efficient method to produce rows of tables like this: > > > > jean > > > > > you can also try to make below universal for all needed bases: > > > m = lambda m, n: 1 if m & n else 0 > > > k = [[ m(x,8) , m(x, 4), m(x, 2), m(x, 1)] for x in range(10)] > > > > > print (k) > > > > Dear Asaf, > > I'm not at ease with lamba-notation, could you show me how to modify your > > example for the base 3 case? I guess then it will be much clearer to me > > thanks in advance > > > > jean > > I don't have to - use normal functions instead :-) Of course you don't have to, but I'm curious and learn well by examples :-( From skip at pobox.com Mon Feb 3 14:52:17 2014 From: skip at pobox.com (Skip Montanaro) Date: Mon, 3 Feb 2014 13:52:17 -0600 Subject: undefined symbol: _PyUnicodeUCS4_AsDefaultEncodedString In-Reply-To: References: Message-ID: > Good luck getting this fixed. Even if you do manage to get your vendor > to start shipping wide builds, you're going to have people screaming > about how much more RAM their processes use now :( Never mind that > other Linux builds of Python have done the same thing for years. Our vendor hasn't been all that responsive about other things, so I'm not too worried about the screams from users. Besides, essentially everything we do that matters here is plain old ASCII. Many of our C++ libraries don't grok Unicode, so there's not much chance a wide version of Python from our vendor would cause much problem. Thanks, Skip From roegltd at gmail.com Mon Feb 3 14:50:04 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 3 Feb 2014 11:50:04 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: <197d89ae-6a55-4c79-b808-fec3294d0bf6@googlegroups.com> On Monday, February 3, 2014 9:37:36 PM UTC+2, Jean Dupont wrote: > Op maandag 3 februari 2014 16:34:18 UTC+1 schreef Asaf Las: > > Of course you don't have to, but I'm curious and learn well by examples > :-( Hi Jean Don't get me wrong i did not mean to be rude (was joking) - i think if you will do it yourself that will be very good for you - you can learn a lot from that as i did not very long time ago. My apologies for inconvenience. /Asaf From roegltd at gmail.com Mon Feb 3 14:52:21 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 3 Feb 2014 11:52:21 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: <11ba2e57-a7b9-4345-8dd8-96d9dbfedaa8@googlegroups.com> On Monday, February 3, 2014 9:37:36 PM UTC+2, Jean Dupont wrote: > Op maandag 3 februari 2014 16:34:18 UTC+1 schreef Asaf Las: > > Of course you don't have to, but I'm curious and learn well by examples > > :-( And making this design generic is really a good example indeed. From mail at timgolden.me.uk Mon Feb 3 15:03:18 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 Feb 2014 20:03:18 +0000 Subject: Unable to Launch Python 2.7 after Windows 8.1 Update In-Reply-To: References: Message-ID: <52EFF606.6010906@timgolden.me.uk> On 02/02/2014 15:39, Allison Gray wrote: > I recently obtained a new laptop with Windows 8.1 and installed > Python 2.7. Everything was working fine. Then after my first update, > I was unable to launch Python. After clicking the Python icon, the > thinking cursor activated, but Python never opened. I restored my > laptop to a time before the update, and am now able to run Python. I > have changed my automatic update setting to prevent this from > happening again but this is less than ideal. Has anyone had this > problem? Does anyone know what Windows setting would prevent Python > IDLE from opening? I'm not running Win8.1 here but I'll try to run up a VM to reproduce it. In case it matters: do you know what version of Win8.1 it was? Enterprise? Professional? TJG From nicholas.cole at gmail.com Mon Feb 3 14:57:51 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Mon, 3 Feb 2014 19:57:51 +0000 Subject: __init__ is the initialiser In-Reply-To: References: <858utviwgs.fsf@benfinney.id.au> <52EC3C40.7080402@stoneleaf.us> <52ec84bc$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Monday, 3 February 2014, Chris Angelico wrote: > On Tue, Feb 4, 2014 at 12:50 AM, Nicholas Cole > > wrote: > >> There have been occasional times I've wanted an "explicit destruction" > >> feature. Rather than the facetious exception I listed above, it'd be > >> better to have all those references (including the original one in a, > >> since there's nothing special about that) turn into some kind of "null > >> state" - either None, or a special object that marks itself as a > >> destructed/destroyed (terminology debates aside) object. With custom > >> types, I can mark them off with a special flag, and check that all the > >> time; but I can't, for instance, have a dict that maps some lookup > >> keyword to its output file, and then destroy output files to remove > >> all their references from everywhere in the dict. (I have had > >> something along these lines, a bit more complicated than this, but not > >> in Python.) > > > > Can't you get close to that using weakrefs? I'll admit that care is > required. > > Weakrefs are a related tool, but solving a different problem. What I > wanted here was an easy way to force all references to a particular > file to be wiped out, based on one of the existing references. Here's > a concocted setup that's broadly similar to what I was doing, which > might illustrate the issue: > > log_files = {} > > def add_log_file(fn, *keywords): > f = open(fn, "w") > for kw in keywords: log_files[kw]=f > > for line in process_me_line_generator(): > kw = line.split()[0] > f = log_files.get(kw) > if not f: continue > f.write(line+"\n") > if 'quit' in line: > # Okay, let's now close this file. > destruct(f) > > > In this particular case, I could use "f.close()" and "if not f or > f.closed: continue", but that requires that the object cooperate in > this way, and I'm not entirely sure about resource usage. (I was > actually working with a database connection object, IIRC, which didn't > offer me a way to inquire if it was still open or not.) To do this > with weak refs, I'd have to have some other source of strong refs, and > closing would be done by digging through that list, disposing of it > from there, and then triggering garbage collection. I suppose it could > be made to work, but it feels like going about everything backwards. > > ChrisA > When I have had similar problems, I've wrapped the 'strong' reference to the thing I might need to destroy inside an object, and had the 'destroy' method delete it. I'll admit that it isn't quite as convenient as having something that would work for arbitrary objects at arbitrary moments, but it works almost exactly as you describe for the file object above, and it can be quite neat and tidy. Best wishes, N. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Feb 3 15:57:38 2014 From: davea at davea.name (Dave Angel) Date: Mon, 3 Feb 2014 15:57:38 -0500 (EST) Subject: fseek In Compressed Files References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> <78213f6b-3311-4487-a611-ecd3de33a168@googlegroups.com> Message-ID: Ayushi Dalmia Wrote in message: > On Thursday, January 30, 2014 4:20:26 PM UTC+5:30, Ayushi Dalmia wrote: >> Hello, >> >> >> >> I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. > > This is what I have done: > > import bz2 > import sys > from random import randint > > index={} > > data=[] > f=open('temp.txt','r') > for line in f: > data.append(line) > > filename='temp1.txt.bz2' > with bz2.BZ2File(filename, 'wb', compresslevel=9) as f: > f.writelines(data) > > prevsize=0 > list1=[] > offset={} > with bz2.BZ2File(filename, 'rb') as f: > for line in f: > words=line.strip().split(' ') > list1.append(words[0]) > offset[words[0]]= prevsize > prevsize = sys.getsizeof(line)+prevsize sys.getsizeof looks at internal size of a python object, and is totally unrelated to a size on disk of a text line. len () might come closer, unless you're on Windows. You really should be using tell to define the offsets for later seek. In text mode any other calculation is not legal, ie undefined. > > > data=[] > count=0 > > with bz2.BZ2File(filename, 'rb') as f: > while count<20: > y=randint(1,25) > print y > print offset[str(y)] > count+=1 > f.seek(int(offset[str(y)])) > x= f.readline() > data.append(x) > > f=open('b.txt','w') > f.write(''.join(data)) > f.close() > > where temp.txt is the posting list file which is first written in a compressed format and then read later. I thought you were starting with a compressed file. If you're being given an uncompressed file, just deal with it directly. >I am trying to build the index for the entire wikipedia dump which needs to be done in a space and time optimised way. The temp.txt is as follows: > > 1 456 t0b3c0i0e0:784 t0b2c0i0e0:801 t0b2c0i0e0 > 2 221 t0b1c0i0e0:774 t0b1c0i0e0:801 t0b2c0i0e0 > 3 455 t0b7c0i0e0:456 t0b1c0i0e0:459 t0b2c0i0e0:669 t0b10c11i3e0:673 t0b1c0i0e0:678 t0b2c0i1e0:854 t0b1c0i0e0 > 4 410 t0b4c0i0e0:553 t0b1c0i0e0:609 t0b1c0i0e0 > 5 90 t0b1c0i0e0 So every line begins with its line number in ascii form? If true, the dict above called offsets should just be a list. Maybe you should just quote the entire assignment. You're probably adding way too much complication to it. -- DaveA From jeandupont314 at gmail.com Mon Feb 3 16:36:24 2014 From: jeandupont314 at gmail.com (Jean Dupont) Date: Mon, 3 Feb 2014 13:36:24 -0800 (PST) Subject: [newbie] copying identical list for a function argument Message-ID: I have a list like this: [1,2,3] The argument of my function should be a repeated version e.g. [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times repeated also) what is the prefered method to realize this in Python? any help would be really appreciated kind regards, jean From tjreedy at udel.edu Mon Feb 3 16:42:21 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 16:42:21 -0500 Subject: Python 3.3 and Pygame 19.2a install problems In-Reply-To: <52EFE634.3010900@mrabarnett.plus.com> References: <919dac44-2102-416f-a9e5-8857ef11476b@googlegroups.com> <4fb4efe9-8842-4c55-8ee7-ba2cf8b54432@googlegroups.com> <52EFE634.3010900@mrabarnett.plus.com> Message-ID: On 2/3/2014 1:55 PM, MRAB wrote: > On 2014-02-03 06:43, Terry Reedy wrote: >> It is possible that the VC++2010 runtime does not work with XP, but >> requires Vista+ and that the Microsoft installer installs the older >> VC++2008 runtime on XP even when installing 3.3. If you install for a >> single user, the vcxxxxx.dll is in the python directory or subdirectory. >> For all-user installs, it is in one of the windows/systemxx directories. >> But this is just a guess. The names are msvcxxxx.dll and specifically msvcrtxxx.dll > I've used Visual C++ Express 2010 on XP Pro without any problem. The question I was trying to answer is why code compiled with VC2010 would act differently (work with 3.2 or not) on xp and win7. When running of win7, the code can use system calls that did not exist in xp. When running on xp, the code must do something different (probably slower, if not stop). Exactly where the different paths reside is not so important. -- Terry Jan Reedy From tjreedy at udel.edu Mon Feb 3 16:50:06 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 16:50:06 -0500 Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: On 2/3/2014 10:05 AM, Jean Dupont wrote: > Op maandag 3 februari 2014 02:56:43 UTC+1 schreef Asaf Las: >> On Sunday, February 2, 2014 10:51:15 PM UTC+2, Jean Dupont wrote: >>> Op zondag 2 februari 2014 19:10:32 UTC+1 schreef Peter Otten: >>> >>> I'm looking for an efficient method to produce rows of tables like this: >>> jean >> you can also try to make below universal for all needed bases: >> m = lambda m, n: 1 if m & n else 0 name = lambda xxx is poor style because it produces a function object lacking a proper name. Reusing the function name as a local is also confusing. The above is equivalent to def m(k, n): return 1 if k & n else 0 >> k = [[ m(x,8) , m(x, 4), m(x, 2), m(x, 1)] for x in range(10)] >> print (k) > Dear Asaf, > I'm not at ease with lamba-notation, could you show me how to modify your > example for the base 3 case? I guess then it will be much clearer to me > > thanks in advance > jean > -- Terry Jan Reedy From tjreedy at udel.edu Mon Feb 3 16:52:18 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 16:52:18 -0500 Subject: [newbie] troubles with tuples In-Reply-To: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> Message-ID: On 2/3/2014 11:50 AM, Jean Dupont wrote: > I'm looking at the way to address tuples > e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > > As I found out indices start with 0 in Python, so > tup2[0] gives me 1, the first element in the tuple as expected > tup2[1] gives me 2, the second element in the tuple as expected > now here comes what surprises me: > tup2[0:1] does not give me the expected (1,2) but (2,) > > what is the reason for this and how then should one get the first and the second element of a tuple? Or the 3rd until the 5th? > > thanks in advance and kind regards, This should be covered in the tutorial, which you should read if you have not already. -- Terry Jan Reedy From gary.herron at islandtraining.com Mon Feb 3 17:06:16 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Mon, 03 Feb 2014 14:06:16 -0800 Subject: [newbie] copying identical list for a function argument In-Reply-To: References: Message-ID: <52F012D8.6050008@islandtraining.com> On 02/03/2014 01:36 PM, Jean Dupont wrote: > I have a list like this: > [1,2,3] > > The argument of my function should be a repeated version e.g. > [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times repeated also) That's not very clear. You say "The" argument (singular; meaning 1) but then show what seems to be four arguments. Can you show us the function you mention. A number of things come to mind: >>> 4*[[1,2,3]] [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] so fn(n*[[1,2,3]]) might do for a single parameter function def fn(L): ... On the other hand expanding a sequence into individual parameters: fn(*(4*[[1,2,3]])) # note extra * preceding the arg willl be a valid call for def fn(a,b,c,d): ... I'm sure other interpretations of your question are possible. Gary Herron > > what is the prefered method to realize this in Python? > > any help would be really appreciated > > kind regards, > jean > From steve+comp.lang.python at pearwood.info Mon Feb 3 17:19:39 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Feb 2014 22:19:39 GMT Subject: [newbie] copying identical list for a function argument References: Message-ID: <52f015fa$0$29972$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Feb 2014 13:36:24 -0800, Jean Dupont wrote: > I have a list like this: > [1,2,3] > > The argument of my function should be a repeated version e.g. > [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times > repeated also) > > what is the prefered method to realize this in Python? I don't really understand your question. It could mean any of various things, so I'm going to try to guess what you mean. If my guesses are wrong, please ask again, giving more detail, and possibly an example of what you want to do and the result you expect. I think you mean that you have some function that needs to take (say) five arguments, and you want to avoid writing: result = function([1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 23], [1, 2, 3]) because it's too easy to make a mistake (as I did, deliberately, above -- can you see it?). If my guess is correct, try this: mylist = [1, 2, 3] result = function(mylist, mylist, mylist, mylist, mylist) That's perfectly reasonable for two or three arguments, but not so much for five. Instead, here's a trick: first we make five identical references to the same list: [mylist]*5 # same as [mylist, mylist, mylist, mylist, mylist] then expand them as arguments to the function: mylist = [1, 2, 3] list_of_lists = [mylist]*5 result = function(*list_of_lists) (The * operator means multiplication when used between two arguments, and inside a function call a leading * also does argument expansion.) But wait... there's something slightly weird here. Even though there are five distinct references to mylist, they're all the same list! Change one, change all. This may be what you want, or it may be a problem. Hard to tell from your question. Think about references as being a little bit like names. A *single* person could be known as "son", "Dad", "Mr Obama", "Barack", "Mr President", "POTUS", and more. In this case, we have a single list, [1, 2, 3], which is known by six references: the name "mylist", and five additional references list_of_lists index 0, list_of_lists index 1, and so on up to list_of_lists index 4. We can prove that they all refer to the same list by running a bit of code in the interactive interpreter: py> mylist = [1, 2, 3] py> list_of_lists = [mylist]*5 py> list_of_lists [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] py> mylist.append(99) py> list_of_lists [[1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99]] So rather than having five references to the same, identical, list, you might want five *copies*. You can copy a list using slicing: mylist = [1, 2, 3] copy = mylist[:] Instead of using list multiplication to repeat five identical lists, we make five copies using a list comprehension: list_of_lists = [mylist[:] for i in range(5)] then expand it in the function call as before: result = function(*list_of_lists) Hope this helps, -- Steven From andrea.crotti.0 at gmail.com Mon Feb 3 17:22:14 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Mon, 3 Feb 2014 22:22:14 +0000 Subject: generator slides review In-Reply-To: References: Message-ID: 2014-02-03 Terry Reedy : > On 2/2/2014 5:40 AM, andrea crotti wrote: >> > In general, use assert (== AssertionError) to check program logic (should > never raise). Remember that assert can be optimized away. Use other > exceptions to check user behavior. So I believe that ValueError is > appropriate here. I think I also questioned the particular check. > Yes that's right thanks fixed it > > 'Generator functions', which you labeled 'generators', are functions, not > iterators. The generators they return (and the generators that generator > expressions evaluate to) are iterators, and more. > >>>> type(a for a in 'abc') > > > I am not sure whether 'specialized' or 'generalized' is the better term. Well it's true that they are functions, but they also behaved differently than functions. I've read there has been some debate at that time whether to create a different keyword to define generators or not, in the end they didn't but it wouldn't be wrong imho.. > >> This was mainly to explain how something like >> for el in [1, 2, 3]: >> print(el) >> >> can work, > > > But it is no longer has that *does* work. All the builtin xyz collection > classes have a corresponding xyz_iterator class with a __next__ method that > knows how to sequentially access collection items. We do not normally see or > think about them, but they are there working for us every time we do 'for > item in xyz_instance:' > >>>> [].__iter__() > > > In Python one could write the following: > > class list_iterator: > def __init__(self, baselist): > self.baselist = baselist > self.index = -1 # see __next__ for why > > def __iter__(self): > return self > def __next__(self): > self.index += 1 > return self.baselist[self.index] Yes maybe that's a much better example to show thank you. >> >> Yes this is intentionally buggy. The thing is that I wanted to show >> that sometimes generating things makes it harder to debug, and delays >> some errors, which are anyway there but would come up immediately in >> case of a list creation. >> I could not find a better non artificial example for this, any >> suggestion is welcome.. > > > slide 1 > --------- > def recip_list(start, stop): > lis [] > for i range(start, stop): > list.append(1/i) > return lis > > for x in recip_list(-100, 3): # fail here > print x > > > > slide 2 > ------- > def recip_gen(start, stop): > for i in range(start, stop): > yield 1/i > > > for x in recip_gen(-100, 3): > print x # fail here after printing 100 lines > ... > > That's already better, another thing which I just thought about could be this (which actually happened a few times): def original_gen(): count = 0 while count < 10: yield count count += 1 def consumer(): gen = original_gen() # lis = list(gen) for n in gen: print(n * 2) if I uncomment the line with "lis = list(gen)" it won't print anything anymore, because we have to make sure we only loop over ONCE. That maybe is a better example of possible drawback? (well maybe not a drawback but a potential common mistake) From steve+comp.lang.python at pearwood.info Mon Feb 3 17:24:58 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Feb 2014 22:24:58 GMT Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> Message-ID: <52f0173a$0$29972$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Feb 2014 10:04:35 -0800, Charlie Winn wrote: > excuse me but don't be so ******* rude , i did run this program and it > did run correctly Charlie, you may have run *some* program, but it wasn't the program you posted here. And if it ran correctly, why are you asking for help? The code you ran and the code you posted here are not the same, because the code you posted will not run due to multiple syntax errors. If you had tried to run *that* program you would have received multiple syntax errors: py> 1 = float(input('First Number:')) File "", line 1 SyntaxError: can't assign to literal So you must have run a different program. Please show us the program you *actually* used, and then we can help you. -- Steven From ben+python at benfinney.id.au Mon Feb 3 17:56:43 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 04 Feb 2014 09:56:43 +1100 Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) References: Message-ID: <85eh3jg5zo.fsf_-_@benfinney.id.au> Rotwang writes: > Why on Earth would the [???, U+00B6 PILCROW SIGN] correspond to an > EOL? The section sign and pilcrow have a history of being used to > refer to sections and paragraphs respectively, so using them for > permalinks to individual sections of a web page makes perfect sense. Symbols commonly have multiple meanings, derived from usage. -- \ ?Progress might have been all right once, but it's gone on too | `\ long.? ?Ogden Nash | _o__) | Ben Finney From python.list at tim.thechases.com Mon Feb 3 16:51:23 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 3 Feb 2014 15:51:23 -0600 Subject: [newbie] copying identical list for a function argument In-Reply-To: References: Message-ID: <20140203155123.4b0f4998@bigbox.christie.dr> On 2014-02-03 13:36, Jean Dupont wrote: > I have a list like this: > [1,2,3] > > The argument of my function should be a repeated version e.g. > [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of > times repeated also) > > what is the prefered method to realize this in Python? > > any help would be really appreciated It depends on whether you want the contained list to be the *same* list or *copies* of that list. You can do either of the following: lst = [1,2,3] dupes1 = [lst[:] for _ in range(5)] dupes2 = [lst for _ in range(5)] dupes3 = [lst] * 5 The dupes2 and dupes3 should be the same (the latter is a simpler syntax for it): each contains the same list multiple times. To see this, do lst.append(4) and then inspect dupes1 compared to dupes2/dupes3. -tkc From gary.herron at islandtraining.com Mon Feb 3 18:06:05 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Mon, 03 Feb 2014 15:06:05 -0800 Subject: Calculator Problem In-Reply-To: <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> Message-ID: <52F020DD.4010307@islandtraining.com> On 02/03/2014 10:04 AM, Charlie Winn wrote: > On Sunday, February 2, 2014 9:46:24 PM UTC, Gary Herron wrote: >> ... >> >> >> Sorry, but in fact you did *not* run this program as you claim. It's >> >> full of syntax errors. Any attempt to run it will display syntax errors >> >> immediately, and never actually run. So please tell us what really >> >> happened. ... >> >> >> Gary Herron > excuse me but don't be so ******* rude , i did run this program and it did run correctly and if you want me to prove it with screenshots so be it , so don't make accusations ** Gary ** i only came here for some help not to be accused of not even running my program > > Charlie :D Sorry, it wasn't rude, it was a statement of fact pointing out an error on your part. You may *think* you ran the code you posted, but in fact you could not have done so. The code you posted will not run. Not in any version of Python, past, present or future. Assigning to a literal 1 = ... makes no sense and produces a syntax error. That's the only result you could have gotten. If you think that's what you've done, then by all means post a screen-shot showing is how you came to that conclusion, and we'll correct you again. But I'll guarantee with absolute certainty, that your posted Python program did not *run* "correctly" or incorrectly. People on the group are willing to help with nearly anything, but it's all a volunteer effort. You waste our time (either carelessly or maliciously) if you don't accurately post your code and the results of running that code. So please try again. You *will* get help. There are a number of other errors in your program also. We can get to those once we know what code you are really running, and are sure that you know what it means to *run* it, and that you can correctly identify the results -- error or not. Gary Herron From ian.g.kelly at gmail.com Mon Feb 3 18:10:24 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Feb 2014 16:10:24 -0700 Subject: Calculator Problem In-Reply-To: <52f0173a$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> <52f0173a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Feb 3, 2014 3:26 PM, "Steven D'Aprano" < steve+comp.lang.python at pearwood.info> wrote: > > On Mon, 03 Feb 2014 10:04:35 -0800, Charlie Winn wrote: > > > excuse me but don't be so ******* rude , i did run this program and it > > did run correctly > > Charlie, you may have run *some* program, but it wasn't the program you > posted here. And if it ran correctly, why are you asking for help? He said previously that he doesn't want it printing the None after the result. I think that was already answered though: Assuming that the code being run is structurally similar to what was posted, it prints None because the calculator functions print their result instead of returning it, and then the main function also prints the return value from the calculator functions, which is None. The print should be in one place or the other, not both. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thebiggestbangtheory at gmail.com Mon Feb 3 18:33:41 2014 From: thebiggestbangtheory at gmail.com (thebiggestbangtheory at gmail.com) Date: Mon, 3 Feb 2014 15:33:41 -0800 (PST) Subject: Advice needed for Python packaging - can't find required library during installation Message-ID: <14a9fb0b-75a8-4d22-8c5b-75b1bf02493e@googlegroups.com> Hello all, I am trying to package up a very simple python app. In my setup.py file I have a couple of lines that include the following: from setuptools import setup setup( name='ban', version='0.1', packages=['ban',], description='Python Distribution Utilities', author='Ban', author_email='ban at tbbt.com', package_data={'ban': ['data/*.dat']}, long_description=open('README.txt').read(), install_requires=['Google-Safe-Browsing-v2-Lookup'], ) The error I see when running: $> python setup.py install *************************** running install running bdist_egg running egg_info writing requirements to ban.egg-info/requires.txt writing ban.egg-info/PKG-INFO writing top-level names to ban.egg-info/top_level.txt writing dependency_links to ban.egg-info/dependency_links.txt reading manifest file 'ban.egg-info/SOURCES.txt' writing manifest file 'ban.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running install_lib running build_py creating build creating build/lib.linux-x86_64-2.6 creating build/lib.linux-x86_64-2.6/ban copying ban/analyzer.py -> build/lib.linux-x86_64-2.6/ban copying ban/__init__.py -> build/lib.linux-x86_64-2.6/ban creating build/bdist.linux-x86_64 creating build/bdist.linux-x86_64/egg creating build/bdist.linux-x86_64/egg/ban copying build/lib.linux-x86_64-2.6/ban/analyzer.py -> build/bdist.linux-x86_64/egg/ban copying build/lib.linux-x86_64-2.6/ban/__init__.py -> build/bdist.linux-x86_64/egg/ban byte-compiling build/bdist.linux-x86_64/egg/ban/analyzer.py to analyzer.pyc byte-compiling build/bdist.linux-x86_64/egg/ban/__init__.py to __init__.pyc creating build/bdist.linux-x86_64/egg/EGG-INFO copying ban.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO copying ban.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying ban.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying ban.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO copying ban.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO zip_safe flag not set; analyzing archive contents... creating dist creating 'dist/ban-0.1-py2.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it removing 'build/bdist.linux-x86_64/egg' (and everything under it) Processing ban-0.1-py2.6.egg removing '/usr/local/lib/python2.6/dist-packages/ban-0.1-py2.6.egg' (and everything under it) creating /usr/local/lib/python2.6/dist-packages/ban-0.1-py2.6.egg Extracting ban-0.1-py2.6.egg to /usr/local/lib/python2.6/dist-packages ban 0.1 is already the active version in easy-install.pth Installed /usr/local/lib/python2.6/dist-packages/ban-0.1-py2.6.egg Processing dependencies for ban==0.1 Searching for Google-Safe-Browsing-v2-Lookup Reading http://pypi.python.org/simple/Google-Safe-Browsing-v2-Lookup/ No local packages or download links found for Google-Safe-Browsing-v2-Lookup error: Could not find suitable distribution for Requirement.parse('Google-Safe-Browsing-v2-Lookup') ************************** Issue #1 Apparently the setup script cannot find the package - Google-Safe-Browsing-v2-Lookup . However, I can install this package via pip. What should I specify in the setup.py file instead of install_requires=['Google-Safe-Browsing-v2-Lookup'] so that the library is properly installed ? Any advice is appreciated. From bc at freeuk.com Mon Feb 3 18:43:57 2014 From: bc at freeuk.com (BartC) Date: Mon, 3 Feb 2014 23:43:57 -0000 Subject: Postfix conditionals In-Reply-To: References: Message-ID: <8SVHu.12417$MB1.2814@fx09.am4> "G?ktu? Kayaalp" wrote in message news:mailman.4966.1388953508.18130.python-list at python.org... > AFAIK, we do not have "postfix conditionals" in Python, i.e. a condition > appended to a > statement, which determines whether the statement runs or not: > > py> for i in [False]: > ... break if not i > > The above piece of code is equivalent to this in Python: > > py> for i in [False]: > ... if not i > ... break > What are your thoughts on this? I develop my own language (not Python, but also dynamic and interpreted). I have this feature, and it's OK, but not indispensible. I varied it a bit by allowing 'if', 'when' and 'unless' as the conditionals, just to break it up a little. However, it just maps internally to a regular if-statement. In Python though, the normal way of writing 'break if not i' is about the same length (in my language it's somewhat longer), so I can't see it getting much support. What would be far more useful would be a proper 'switch' statement, but if that's not in, then I don't think your proposal will get far! (There are various clunky workarounds for switch - one idea is to use an if-elseif chain, but that's just what it tries to avoid. Switch is attractive for an interpreted language because - provided all cases are constants, a bit of a problem in Python, because as soon as you give a name to something, it's no longer constant - it can be implemented very efficiently.) -- Bartc From greg.ewing at canterbury.ac.nz Mon Feb 3 18:47:12 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 Feb 2014 12:47:12 +1300 Subject: __init__ is the initialiser In-Reply-To: <52eee3c5$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52ec6d1f$0$29972$c3e8da3$5496439d@news.astraweb.com> <52eee3c5$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > # --- Untested --- > # Automatically call each __new__ constructor method, starting from > # the most fundamental (object) and ending with the current class. > stack = [] > for c in cls.__mro__: > if hasattr(c, '__new__'): > stack.append(c.__new__) > while stack: > stack.pop()(*args) That sort of thing doesn't allow for passing different arguments to the base __new__. Also remember that in Python, __new__ isn't actually required to call a matching base version at all -- it's legal to do something quite different, such as returning a cached instance or instantiating a different type of object altogether. > What I meant by backwards compatibility is that prior to the introduction > of new-style classes, you couldn't override __new__, only __init__. So if > you had a classic class, you'd have to receive the instance: > > class Classic: > def __init__(self, *args): > ... > > but for new-style classes, you'd receive the class: > > class Newstyle(object): > def __init__(cls, *args): > ... What I'm saying is that even if all classes had been new-style from the beginning, it's by no means certain that Guido wouldn't have come up with the __new__/__init__ system anyway, because of the flexibility it provides. Python isn't the only language to do something like that. In Objective-C, the basic pattern for instantiating an object goes like [[SomeClass alloc] init: args] where 'alloc' allocates memory for the object and 'init:' or some variation thereof initialises it. -- Greg From denismfmcmahon at gmail.com Mon Feb 3 19:11:26 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Feb 2014 00:11:26 +0000 (UTC) Subject: [newbie] making rows of table with discrete values for different number systems References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> Message-ID: On Sun, 02 Feb 2014 09:44:05 -0800, Jean Dupont wrote: > I'm looking for an efficient method to produce rows of tables like this: > > for base 2 0 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 . > . > . > 1 1 1 1 > > for base 3 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 1 0 0 0 0 0 1 1 0 > 0 0 0 1 2 . > . > 2 2 2 2 2 2 > > As you can see the rows are always twice the size of the base I _don't_ > need to have all rows available together in one array which would become > too large for higher value number bases. It's sufficient to produce one > row after the other, as I will do further data manipulation on such a > row immediately. > > If someone here could suggest best practices to perform this kind of > operations,I'd really appreciate it very much > > kind regards and thanks in advance jean s=3 p=s*2 def b(n,x): s=[] while n: s.append(str(n%x)) n=n/x if s==[]: return "0" return ''.join(s[::-1]) for i in range(s**p): r=("{:0"+str(p)+"d}").format(int(b(i,s))) if len(r)==p: print [int(r[a])for a in range(len(r))] change s to 2 or 4 etc -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Mon Feb 3 19:41:06 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Feb 2014 00:41:06 +0000 (UTC) Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> <61630cc4-a9fe-4936-a86e-65c891224a63@googlegroups.com> <413998dd-b101-46e4-9012-c79c2cd66cf0@googlegroups.com> Message-ID: On Mon, 03 Feb 2014 10:25:37 -0800, Charlie Winn wrote: > Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 > bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for > more information. >>>> ================================ RESTART >>>> ================================ >>>> > What type of calculation would you like to do? > (Add, Subtract, Divide or Multiply)a Addition: What are two your > numbers? > First Number:5 Second Number:96 Your Final Result is: 101.0 None >>>> That wasn't obtained from running the code you posted. Your code *as you posted it* gives: $ python charlie.py File "charlie.py", line 4 1 = float(input('First Number:')) SyntaxError: can't assign to literal $ -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Mon Feb 3 19:50:44 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 4 Feb 2014 00:50:44 +0000 (UTC) Subject: [newbie] troubles with tuples References: <893ced1a-dd55-48d7-8849-b2e45da2740e@googlegroups.com> Message-ID: On Mon, 03 Feb 2014 08:50:31 -0800, Jean Dupont wrote: > I'm looking at the way to address tuples e.g. > tup2 = (1, 2, 3, 4, 5, 6, 7 ); > > As I found out indices start with 0 in Python, so tup2[0] gives me 1, > the first element in the tuple as expected tup2[1] gives me 2, the > second element in the tuple as expected now here comes what surprises > me: > tup2[0:1] does not give me the expected (1,2) but (2,) > > what is the reason for this and how then should one get the first and > the second element of a tuple? Or the 3rd until the 5th? > > thanks in advance and kind regards, > > jean >>> tup = (0,1,2,3,4,5,6,7) >>> tup[0:1] (0,) >>> tup[1:2] (1,) >>> tup[2:3] (2,) >>> tup[0:2] (0, 1) >>> tup[2:5] (2, 3, 4) This is as I'd expect, as the notation [0:1] means: starting from the 0th element, up to and including the element preceding the first element Or [m:n] means starting from the mth element, everything up to and including the element preceding the nth element Are you sure you got (2,) for [0:1] and not for [2:3]? Are you sure your initial tuple is what you thought it was? -- Denis McMahon, denismfmcmahon at gmail.com From tjreedy at udel.edu Mon Feb 3 19:55:03 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 03 Feb 2014 19:55:03 -0500 Subject: generator slides review In-Reply-To: References: Message-ID: On 2/3/2014 5:22 PM, andrea crotti wrote: > That's already better, another thing which I just thought about could > be this (which actually happened a few times): > > def original_gen(): > count = 0 > while count < 10: > yield count > count += 1 > > > def consumer(): > gen = original_gen() > # lis = list(gen) > for n in gen: > print(n * 2) > > if I uncomment the line with "lis = list(gen)" > it won't print anything anymore, because we have to make sure we only > loop over ONCE. > That maybe is a better example of possible drawback? (well maybe not a > drawback but a potential common mistake) A couple of days ago I made a similar error. Stdlib code a = list(f(iterable1)) return g(a) # g just need an iterable The return value is buggy. Insert for i in a: print(i) to debug. Notice that g does not need a concrete list. Delete list wrapper. Return value goes away. Because I did other things between the last two steps, I did not immediately make the connection and was initially puzzled. Deleting debug code made things work again. Using itertools.tee would have done the same. -- Terry Jan Reedy From rustompmody at gmail.com Mon Feb 3 21:34:16 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 3 Feb 2014 18:34:16 -0800 (PST) Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> Message-ID: <4b9d596b-e20b-4436-a9b0-d98f5b774510@googlegroups.com> On Tuesday, February 4, 2014 12:41:03 AM UTC+5:30, Chris Angelico wrote: > On Tue, Feb 4, 2014 at 6:05 AM, Zachary Ware wrote: > > On Mon, Feb 3, 2014 at 12:48 PM, Chris Angelico wrote: > >> Technically that gets everything you need to compile Python 3.3... > >> wasn't there one more library needed for 3.4? It's still an excellent > >> way to get nearly everything, though. > > I think you're thinking of 3.2 -> 3.3. 3.3 added the lzma module, > > which requires lzma-dev. I think 3.4 has the same requirements as > > 3.3. > Ah, that would be it, thanks. I just remembered I'd recently used > build-dep across versions and had to get something involving data > compression. Went digging for stuff starting with 'z', but missed this > because, well, it doesn't start with 'z' :) Thanks. > ChrisA Just curious: How do you go "digging for stuff starting with 'z'" ? OR: How do you grep inside apt? I know "dpkg -S pattern" It helps to connect pattern with package But no good if pattern is common -- Other day I was struggling with dpkg -S which From rosuav at gmail.com Mon Feb 3 21:45:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 13:45:40 +1100 Subject: Problems compiling Python 3.4 on Ubuntu In-Reply-To: <4b9d596b-e20b-4436-a9b0-d98f5b774510@googlegroups.com> References: <61de065c-ad66-4752-b04f-a27a06bc052d@googlegroups.com> <20140203110816.GA7423@arxnet.hu> <4b9d596b-e20b-4436-a9b0-d98f5b774510@googlegroups.com> Message-ID: On Tue, Feb 4, 2014 at 1:34 PM, Rustom Mody wrote: > Just curious: How do you go "digging for stuff starting with 'z'" ? > > OR: How do you grep inside apt? > > I know "dpkg -S pattern" > > It helps to connect pattern with package > But no good if pattern is common -- Other day I was struggling with > > dpkg -S which dpkg --get-selections will show all installed packages, in alphabetical order. Probably not useful. dpkg --get-selections|grep -- '-dev' will show all -dev packages, which IS useful. Except on a system that I run, in which case you still need to eyeball roughly two hundred installed packages :D Hence my failure to find the one I wanted. ChrisA From rustompmody at gmail.com Mon Feb 3 21:48:30 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 3 Feb 2014 18:48:30 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> Message-ID: <1b65a5a4-f044-479d-8609-2a0339536ef3@googlegroups.com> On Tuesday, February 4, 2014 3:20:06 AM UTC+5:30, Terry Reedy wrote: > name = lambda xxx is poor style because it produces a function object > lacking a proper name. Reusing the function name as a local is also > confusing. The above is equivalent to > def m(k, n): return 1 if k & n else 0 Yeah... Well... Except that I'd put it the other way: the second -- shadowing names -- is MUCH worse than naked lambdas. Unless you're entering an obfuscated python contest :D From rustompmody at gmail.com Mon Feb 3 22:09:23 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 3 Feb 2014 19:09:23 -0800 (PST) Subject: [newbie] copying identical list for a function argument In-Reply-To: References: Message-ID: <25b4ba64-6d8a-4006-ade5-f47561fdfa6a@googlegroups.com> On Tuesday, February 4, 2014 3:06:24 AM UTC+5:30, Jean Dupont wrote: > I have a list like this: > [1,2,3] > The argument of my function should be a repeated version e.g. > [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times repeated also) > what is the prefered method to realize this in Python? Probably not what you are asking... But maybe you want to look at repeat (and other stuff) in itertools >>> from itertools import repeat >>> zip(range(0,10), repeat("hi")) [(0, 'hi'), (1, 'hi'), (2, 'hi'), (3, 'hi'), (4, 'hi'), (5, 'hi'), (6, 'hi'), (7, 'hi'), (8, 'hi'), (9, 'hi')] IOW repeat give you "indefinite-data-repeat" just as "while True:..." gives "indefinite-code-repeat" From t.tchorzewski at gmail.com Mon Feb 3 23:07:48 2014 From: t.tchorzewski at gmail.com (Thomas) Date: Mon, 3 Feb 2014 20:07:48 -0800 (PST) Subject: Logging data from Arduino using PySerial Message-ID: I've written a script to log data from my Arduino to a csv file. The script works well enough but it's very, very slow. I'm quite new to Python and I just wanted to put this out there to see if any Python experts could help optimise my code. Here it is: import serial import re import csv import numpy as np import matplotlib.pyplot as plt portPath = "/dev/ttyACM0" baud = 9600 sample_time = 0.5 sim_time = 30 # Initializing Lists # Data Collection data_log = [] line_data = [] def map(x, in_min, in_max, out_min, out_max): return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + out_min # Establishing Serial Connection connection = serial.Serial(portPath,baud) # Calculating the length of data to collect based on the # sample time and simulation time (set by user) max_length = sim_time/sample_time # Collecting the data from the serial port while True: data_log.append(connection.readline()) if len(data_log) > max_length - 1: break # Cleaning the data_log and storing it in data.csv with open('data.csv','wb') as csvfile: for line in data_log: line_data = re.findall('\d*\.\d*',line) # Find all digits line_data = filter(None,line_data) # Filter out empty strings line_data = [float(x) for x in line_data] # Convert Strings to float for i in range(1,len(line_data)): line_data[i]=map(line_data[i],0,1023,0,5) csvwrite = csv.writer(csvfile) csvwrite.writerow(line_data) plt.clf() plt.close() plt.plotfile('data.csv',(0,1,2),names=['time (s)','voltage2 (V)','voltage1 (V)'],newfig=True) plt.show() I'd appreciate any help/tips you can offer. From rosuav at gmail.com Mon Feb 3 23:47:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 15:47:19 +1100 Subject: Logging data from Arduino using PySerial In-Reply-To: References: Message-ID: On Tue, Feb 4, 2014 at 3:07 PM, Thomas wrote: > I've written a script to log data from my Arduino to a csv file. The script works well enough but it's very, very slow. I'm quite new to Python and I just wanted to put this out there to see if any Python experts could help optimise my code. Here it is: > The most important question is: Have you profiled your code? That is, do you know which part(s) are slow? And the first part of that question is: Define "slow". How long does your program actually take? How much data are you accumulating in that time? By my reading, you're getting 60 lines from the serial port; how long is each line? For a basic back-of-the-envelope timing estimate, work out how long each line is (roughly), and multiply by 60 (number of lines), then divide by 960 (your baud rate, divided by 10, which gives a rough bytes-per-second rate). That'll give you a ball-park figure for how many seconds this loop will take: > # Collecting the data from the serial port > while True: > data_log.append(connection.readline()) > if len(data_log) > max_length - 1: > break If your lines are 80 characters long, give or take, then that works out to 80*60/960 = five seconds just to fetch the data from the serial port. So if the script is taking anywhere from 3 to 8 seconds to run, then you can assume that it's probably spending most of its time right here. Yes, that might feel like it's really slow, but it's all down to your baud rate. You can easily confirm this by surrounding that loop with: import time start_time = time.time() while ... ... append ... print("Time to fetch from serial port:",time.time()-start_time) (If this is Python 2, this will produce slightly ugly output as it'll display it as a tuple. It'll work though.) Put that in, and then run the program with some kind of external timing. On Linux, that would be: $ time python scriptname.py If the total script execution is barely more than the time spent in that loop, don't bother optimizing any of the rest of the code - it's a waste of time improving something that's not materially affecting your total run time. But while I'm here looking at your code, I'll take the liberty of making a few stylistic suggestions :) Feel free to ignore these, but this is the more Pythonic way of writing the code. Starting with the serial port fetch loop: > # Collecting the data from the serial port > while True: > data_log.append(connection.readline()) > if len(data_log) > max_length - 1: > break An infinite loop with a conditional break exactly at one end. This would be clearer written as a straight-forward conditional loop, with the condition inverted: while len(data_log) < max_length: data_log.append(connection.readline()) This isn't strictly identical to your previous version, but since len(data_log) will always be an integer, it is - I believe - functionally equivalent. But make sure I haven't introduced any bugs. :) (There is another difference, in that my version checks the condition on entry where yours would check it only after doing the first append - your version would guarantee a minimum of one line in the log, mine won't. I'm guessing that this won't be significant in normal usage; if it is, go back to your version of the code.) > def map(x, in_min, in_max, out_min, out_max): > return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + out_min This shadows the built-in map() function. It works, but it's usually safer to not do this, in case you subsequently want the default map(). > line_data = re.findall('\d*\.\d*',line) # Find all digits > line_data = filter(None,line_data) # Filter out empty strings > line_data = [float(x) for x in line_data] # Convert Strings to float You can combine these. line_data = [float(x) for x in re.findall('\d*\.\d*',line) if x] Optionally break out the re into a separate line, but definitely I'd go with the conditional comprehension above the separate filter(): line_data = re.findall('\d*\.\d*',line) line_data = [float(x) for x in line_data if x] > for i in range(1,len(line_data)): > line_data[i]=map(line_data[i],0,1023,0,5) Is it deliberate that you start from 1 here? Are you consciously skipping the first element, leaving it unchanged? If not, I would go for another comprehension: line_data = [map(x,0,1023,0,5) for x in line_data] but if so, this warrants a code comment explaining why the first one is special. > plt.clf() > plt.close() > plt.plotfile('data.csv',(0,1,2),names=['time (s)','voltage2 (V)','voltage1 (V)'],newfig=True) > plt.show() This, btw, is the other place that I'd look for a potentially large slab of time. Bracket this with time.time() calls as above, and see whether it's slow enough to mean nothing else is a concern. But I'd first look at the serial port read loop; depending on how long your lines are, that could easily be quite a few seconds of time just on its own. ChrisA From t.tchorzewski at gmail.com Mon Feb 3 23:57:51 2014 From: t.tchorzewski at gmail.com (Thomas) Date: Mon, 3 Feb 2014 20:57:51 -0800 (PST) Subject: Logging data from Arduino using PySerial In-Reply-To: References: Message-ID: Wow...Thanks Chris! I really appreciate your suggestions (including the stylistic ones). I'll definitely be revising my code as soon as I find the time. As far as profiling goes, I've used timeit in the past but it's quite a pain going through any program block by block. I wish there were a program in which you could just toss in a script and it would spit out the bottlenecks in your code (with suggested performance improvements perhaps)... From self at gkayaalp.com Tue Feb 4 00:16:07 2014 From: self at gkayaalp.com (=?utf-8?B?R8O2a3R1xJ8=?= Kayaalp) Date: Tue, 04 Feb 2014 07:16:07 +0200 Subject: Postfix conditionals In-Reply-To: <8SVHu.12417$MB1.2814@fx09.am4> (BartC's message of "Mon, 3 Feb 2014 23:43:57 -0000") References: <8SVHu.12417$MB1.2814@fx09.am4> Message-ID: <87lhxro3u0.fsf@gkayaalp.com> [comments inline] "BartC" writes: > "G?ktu? Kayaalp" wrote in message > news:mailman.4966.1388953508.18130.python-list at python.org... > >> AFAIK, we do not have "postfix conditionals" in Python, i.e. a condition >> appended to a >> statement, which determines whether the statement runs or not: >> >> py> for i in [False]: >> ... break if not i >> >> The above piece of code is equivalent to this in Python: >> >> py> for i in [False]: >> ... if not i >> ... break > >> What are your thoughts on this? > > I develop my own language (not Python, but also dynamic and interpreted). Would love to see that, if possible! > I have this feature, and it's OK, but not indispensible. I varied it a bit > by allowing 'if', 'when' and 'unless' as the conditionals, just to break it > up a little. However, it just maps internally to a regular if-statement. > > In Python though, the normal way of writing 'break if not i' is about the > same length (in my language it's somewhat longer), so I can't see it getting > much support. I do not really think that string length is not of much significance. The actual fact that disallows my proposal from being favoured/implemented is that in Python, `break', `return' and `continue' are statements and the community encourages having one statement per line, so that the source code is easily understandable. With my proposal implemented, the language would would be encouraging having multiple statements in one line, that looks like a single statement, but is indeed a composition of two. I rather dislike the statement-orientedness of Python, but still, it is a good device of easening for the language developers and beginners when the fact that we use indentation to denote blocks is considered. > What would be far more useful would be a proper 'switch' statement, but if > that's not in, then I don't think your proposal will get far! > > (There are various clunky workarounds for switch - one idea is to use an > if-elseif chain, but that's just what it tries to avoid. Switch is > attractive for an interpreted language because - provided all cases > are constants, a bit of a problem in Python, because as soon as you > give a name to something, it's no longer constant - it can be > implemented very efficiently.) > > -- > Bartc From rosuav at gmail.com Tue Feb 4 00:18:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 16:18:11 +1100 Subject: Logging data from Arduino using PySerial In-Reply-To: References: Message-ID: On Tue, Feb 4, 2014 at 3:57 PM, Thomas wrote: > Wow...Thanks Chris! I really appreciate your suggestions (including the stylistic ones). I'll definitely be revising my code as soon as I find the time. As far as profiling goes, I've used timeit in the past but it's quite a pain going through any program block by block. I wish there were a program in which you could just toss in a script and it would spit out the bottlenecks in your code (with suggested performance improvements perhaps)... > Well, timeit is good for microbenchmarking. (How useful microbenchmarking itself is, now, that's a separate question.) For anything where you can "feel" the program's time by human, it's easy enough to use the time.time() function. Add a little helper like this (untested): last_time = time.time() def tt(desc): global last_time cur_time=time.time() print("%s: %f"%(desc,cur_time-last_time)) last_time=cur_time Then put this all through your code: .... # Calculating the length of data to collect based on the # sample time and simulation time (set by user) max_length = sim_time/sample_time tt("Init") # Collecting the data from the serial port while True: data_log.append(connection.readline()) if len(data_log) > max_length - 1: break tt("Serial") ... etc etc. Give it a short description saying what's just happened (because it'll give the time since the previous timepoint), and then just eyeball the results to see where the biggest numbers are. If you do it right, you'll find a whole pile of sections with tiny numbers, which you can easily ignore, and just a handful that even register. Then you dig into those sections and see where the slowness is. Be careful, though. You can easily waste hundreds of expensive dev hours trying to track down an insignificant time delay. :) ChrisA From rosuav at gmail.com Tue Feb 4 00:23:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 16:23:26 +1100 Subject: Postfix conditionals In-Reply-To: <87lhxro3u0.fsf@gkayaalp.com> References: <8SVHu.12417$MB1.2814@fx09.am4> <87lhxro3u0.fsf@gkayaalp.com> Message-ID: On Tue, Feb 4, 2014 at 4:16 PM, G?ktu? Kayaalp wrote: > With my proposal implemented, the language would > would be encouraging having multiple statements in one line, that looks > like a single statement, but is indeed a composition of two. I wouldn't have a problem with if not i: break in Python, as long as the condition is short. In something that reads from a socket until the other end closes, for instance, I'm fine with this: while True: data = sock.read(1024) if not data: break do_stuff_with(data) which will stop as soon as sock.read() returns "", which it does when the other end is gone. (I wrote something doing exactly this today, and did exactly this. Probably could have made the code a bit simpler if I could depend on Python 3.3, but it has to run on 2.7 and maybe 2.6 so I had to stick with their facilities.) Yes, it's two statements, but a list comprehension is a whole pile of statement-y things, and that's usually a single line. If it's doing one conceptual action, it's okay to not split it. ChrisA From wxjmfauth at gmail.com Tue Feb 4 01:51:43 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 3 Feb 2014 22:51:43 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: References: Message-ID: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> Le lundi 3 f?vrier 2014 23:56:43 UTC+1, Ben Finney a ?crit : > Rotwang writes: > > > > > Why on Earth would the ["?", U+00B6 PILCROW SIGN] correspond to an > > > EOL? The section sign and pilcrow have a history of being used to > > > refer to sections and paragraphs respectively, so using them for > > > permalinks to individual sections of a web page makes perfect sense. > > > > Symbols commonly have multiple meanings, derived from usage. > > > > > > > > -- > > \ "Progress might have been all right once, but it's gone on too | > > `\ long." --Ogden Nash | > > _o__) | > > Ben Finney I got it. If I'm visiting a page like this: http://docs.python.org/3/tutorial/index.html#the-python-tutorial 1) To read the page, I'm scrolling down. 2) When I have finished to read the page, I scroll up (or scroll back/up) to the top of the page until I see this "feature" and the title. 3) I click on this "feature". 4) The title, already visible, moves, let's say, "2cm" higher. ...? Having a pilcrow to signal or to display an end of paragraph is one thing. Using a pilcrow as a link seems to me very strange. Especially if the target of that link has nothing to with paragraph, but with "section"! jmf From rosuav at gmail.com Tue Feb 4 01:58:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Feb 2014 17:58:29 +1100 Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> Message-ID: On Tue, Feb 4, 2014 at 5:51 PM, wrote: > 2) When I have finished to read the page, I scroll up > (or scroll back/up) to the top of the page until I see > this "feature" and the title. > 3) I click on this "feature". > 4) The title, already visible, moves, let's say, "2cm" higher. At which point your URL bar shows a hash link to this exact section, which you can then copy and paste into an email, for instance. That's what it's good for. ChrisA From dieter at handshake.de Tue Feb 4 02:30:00 2014 From: dieter at handshake.de (dieter) Date: Tue, 04 Feb 2014 08:30:00 +0100 Subject: Advice needed for Python packaging - can't find required library during installation References: <14a9fb0b-75a8-4d22-8c5b-75b1bf02493e@googlegroups.com> Message-ID: <8738jz9vyf.fsf@handshake.de> thebiggestbangtheory at gmail.com writes: > I am trying to package up a very simple python app. In my setup.py file I have a couple of lines that include the following: > > from setuptools import setup > > setup( > name='ban', > version='0.1', > packages=['ban',], > description='Python Distribution Utilities', > author='Ban', > author_email='ban at tbbt.com', > package_data={'ban': ['data/*.dat']}, > long_description=open('README.txt').read(), > install_requires=['Google-Safe-Browsing-v2-Lookup'], > ) > ... > Processing dependencies for ban==0.1 > Searching for Google-Safe-Browsing-v2-Lookup > Reading http://pypi.python.org/simple/Google-Safe-Browsing-v2-Lookup/ > No local packages or download links found for Google-Safe-Browsing-v2-Lookup > error: Could not find suitable distribution for Requirement.parse('Google-Safe-Browsing-v2-Lookup') > ************************** > > Issue #1 > > Apparently the setup script cannot find the package - Google-Safe-Browsing-v2-Lookup . However, I can install this package via pip. > > What should I specify in the setup.py file instead of install_requires=['Google-Safe-Browsing-v2-Lookup'] so that the library is properly installed ? I suppose that "setuptools" is confused by the "-" in the package names together with these "-" being omitted in the uploaded file (https://pypi.python.org/packages/source/G/Google-Safe-Browsing-v2-Lookup/Google%20Safe%20Browsing%20v2%20Lookup-0.1.0.tar.gz5"). If this supposition is correct, then you would either need to contact the "setuptools" author (to get "setuptools" handle this case) or the "Google Safe Browsing" author to get a filename more in line with the package name. From ikorot01 at gmail.com Tue Feb 4 03:58:52 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Tue, 4 Feb 2014 00:58:52 -0800 Subject: Just compilation Message-ID: Hi, ALL, I'm trying to incorporate the path in http://sourceforge.net/p/mysql-python/bugs/325/. I already modified the source code and now what I need is to produce the pyc code. Running "python --help" I don't see an option to just compile the source into the bytecode. So how do I produce the compiled version of the changed source? What I'm thinking is to compile the file update the archive and reinstall. Please help. Thank you. From jeandupont115 at gmail.com Tue Feb 4 04:14:34 2014 From: jeandupont115 at gmail.com (Jean Dupont) Date: Tue, 4 Feb 2014 01:14:34 -0800 (PST) Subject: [newbie] copying identical list for a function argument In-Reply-To: <52f015fa$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f015fa$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <76a5550d-fef4-48bd-aa36-fc0af75db104@googlegroups.com> Op maandag 3 februari 2014 23:19:39 UTC+1 schreef Steven D'Aprano: > On Mon, 03 Feb 2014 13:36:24 -0800, Jean Dupont wrote: > > I have a list like this: > > [1,2,3] > > > > The argument of my function should be a repeated version e.g. > > [1,2,3],[1,2,3],[1,2,3],[1,2,3] (could be a different number of times > > repeated also) > > > > what is the prefered method to realize this in Python? > > I don't really understand your question. It could mean any of various > things, so I'm going to try to guess what you mean. If my guesses are > wrong, please ask again, giving more detail, and possibly an example of > what you want to do and the result you expect. > I think you mean that you have some function that needs to take (say) > five arguments, and you want to avoid writing: > result = function([1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 23], [1, 2, 3]) > because it's too easy to make a mistake (as I did, deliberately, above -- > can you see it?). > If my guess is correct, try this: > mylist = [1, 2, 3] > result = function(mylist, mylist, mylist, mylist, mylist) > > That's perfectly reasonable for two or three arguments, but not so much > for five. Instead, here's a trick: first we make five identical > references to the same list: > [mylist]*5 # same as [mylist, mylist, mylist, mylist, mylist] > then expand them as arguments to the function: > mylist = [1, 2, 3] > list_of_lists = [mylist]*5 > result = function(*list_of_lists) > (The * operator means multiplication when used between two arguments, and > inside a function call a leading * also does argument expansion.) > > But wait... there's something slightly weird here. Even though there are > five distinct references to mylist, they're all the same list! Change > one, change all. This may be what you want, or it may be a problem. Hard > to tell from your question. > Think about references as being a little bit like names. A *single* > person could be known as "son", "Dad", "Mr Obama", "Barack", "Mr > President", "POTUS", and more. In this case, we have a single list, [1, > 2, 3], which is known by six references: the name "mylist", and five > additional references list_of_lists index 0, list_of_lists index 1, and > so on up to list_of_lists index 4. > We can prove that they all refer to the same list by running a bit of > code in the interactive interpreter: > > py> mylist = [1, 2, 3] > py> list_of_lists = [mylist]*5 > py> list_of_lists > [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] > py> mylist.append(99) > py> list_of_lists > [[1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, 99], [1, 2, 3, > 99]] > > So rather than having five references to the same, identical, list, you > might want five *copies*. You can copy a list using slicing: > mylist = [1, 2, 3] > copy = mylist[:] > Instead of using list multiplication to repeat five identical lists, we > make five copies using a list comprehension: > list_of_lists = [mylist[:] for i in range(5)] > then expand it in the function call as before: > result = function(*list_of_lists) > > Hope this helps, Yes it does, thanks a lot to you and all the others who responded, "the missing link" which until now I wasn't aware of but which was essential for the solution was the "*" in result = function(*list_of_lists) kind regards, jean From jeandupont115 at gmail.com Tue Feb 4 04:18:54 2014 From: jeandupont115 at gmail.com (Jean Dupont) Date: Tue, 4 Feb 2014 01:18:54 -0800 (PST) Subject: [newbie] making rows of table with discrete values for different number systems In-Reply-To: <197d89ae-6a55-4c79-b808-fec3294d0bf6@googlegroups.com> References: <515e582f-ed17-4d4e-9872-f07f1fda6ed2@googlegroups.com> <5757c6ca-57d8-440f-9c55-b3f723b23404@googlegroups.com> <3a8c1dff-5b1d-4567-aaab-a81d37a563fd@googlegroups.com> <12f21916-8228-4826-bb9e-7096c77b294d@googlegroups.com> <197d89ae-6a55-4c79-b808-fec3294d0bf6@googlegroups.com> Message-ID: <5678e9f7-65a8-4b8e-b116-1ac0169650fd@googlegroups.com> Op maandag 3 februari 2014 20:50:04 UTC+1 schreef Asaf Las: > On Monday, February 3, 2014 9:37:36 PM UTC+2, Jean Dupont wrote: > > Op maandag 3 februari 2014 16:34:18 UTC+1 schreef Asaf Las: > > > > Of course you don't have to, but I'm curious and learn well by examples > > :-( > > Hi Jean > > Don't get me wrong i did not mean to be rude (was joking) - i > think if you will do it yourself that will be very good for > you - you can learn a lot from that as i did not very long time ago. > My apologies for inconvenience. no hard feelings, anyway I am programming it myself using normal functions, when I have finished it I'll post it, then maybe you can do it with lamba-notation, it could be interesting to compare execution times for the two approaches kind regards, jean From cs at zip.com.au Tue Feb 4 04:27:44 2014 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 4 Feb 2014 20:27:44 +1100 Subject: Just compilation In-Reply-To: References: Message-ID: <20140204092744.GA47688@cskk.homeip.net> On 04Feb2014 00:58, Igor Korot wrote: > I'm trying to incorporate the path in > http://sourceforge.net/p/mysql-python/bugs/325/. > I already modified the source code and now what I need is to produce > the pyc code. > > Running "python --help" I don't see an option to just compile the > source into the bytecode. > > So how do I produce the compiled version of the changed source? > What I'm thinking is to compile the file update the archive and reinstall. You want the py_compile module, parse of the stdlib. Example: python -m py_compile path/to/foo.py I use this in my personal test suite as a syntax check. See the python docs for this module for further details. Cheers, -- Cameron Simpson A friend of mine in a compiler writing class produced a compiler with one error message "you lied to me when you told me this was a program". - Pete Fenelon From bc at freeuk.com Tue Feb 4 05:00:43 2014 From: bc at freeuk.com (BartC) Date: Tue, 4 Feb 2014 10:00:43 -0000 Subject: Postfix conditionals In-Reply-To: References: <8SVHu.12417$MB1.2814@fx09.am4> Message-ID: "G?ktu?Kayaalp" wrote in message news:mailman.6377.1391490975.18130.python-list at python.org... > "BartC" writes: > >> "G?ktu? Kayaalp" wrote in message >> news:mailman.4966.1388953508.18130.python-list at python.org... >> >>> AFAIK, we do not have "postfix conditionals" in Python, i.e. a condition >>> appended to a >>> statement, which determines whether the statement runs or not: >>> >>> py> for i in [False]: >>> ... break if not i >>> What are your thoughts on this? >> >> I develop my own language (not Python, but also dynamic and interpreted). (First, some apologies; I thought the OP was dated February not January!) > Would love to see that, if possible! (If you're into Python, then I doubt it because I don't have classes or any of those other Pythonic things that people like. However my language is a lot less dynamic and therefore can be much faster. I have a few interesting variations on statements as well; syntax is cheap and I don't know why many languages, Python included, have such a paucity of control and selection statements. I also have a project that translates my syntax into Python; the intention there was to be able to make use of some of its libraries because I don't have many of my own!) >> I have this feature, and it's OK, but not indispensible. I varied it a >> bit >> by allowing 'if', 'when' and 'unless' as the conditionals, just to break >> it >> up a little. However, it just maps internally to a regular if-statement. >> >> In Python though, the normal way of writing 'break if not i' is about the >> same length (in my language it's somewhat longer), so I can't see it >> getting >> much support. > > I do not really think that string length is not of much significance. > The actual fact that disallows my proposal from being favoured/implemented > is that in Python, `break', `return' and `continue' are statements and the > community encourages having one statement per line, so that the source > code > is easily understandable. With my proposal implemented, the language > would > would be encouraging having multiple statements in one line, that looks > like a single statement, but is indeed a composition of two. But, Python already allows you to combine two statements on a line, as in: if a: s while b: t So your: s if a is little different (although s will need to be restricted; 'if b if a' will look a bit odd). And someone mentioned the ternary expression which looks similar to your proposal. I suppose you can also argue that the if-part is not a statement at all, just an expression that is part of the statement (you'd have to redefine break and other statements to have an optional condition). If written as: break(not i) then it certainly won't look like two statements! Your proposal has the advantage in that it gives more dominance to the statement, making the code somewhat clearer, comparing with burying it inside an if-statement. > I rather dislike the statement-orientedness of Python, but still, it is > a good device of easening for the language developers and beginners when > the fact that we use indentation to denote blocks is considered. (I used to have a syntax where statements and expressions were interchangeable. Now I have them distinct, which makes many things much easier, it picks up more errors (and makes it simpler to translate to translate into languages which aren't quite as expressive!)) -- Bartc From ayushidalmia2604 at gmail.com Tue Feb 4 06:28:33 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 03:28:33 -0800 (PST) Subject: Finding size of Variable Message-ID: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Hello, I have 10 files and I need to merge them (using K way merging). The size of each file is around 200 MB. Now suppose I am keeping the merged data in a variable named mergedData, I had thought of checking the size of mergedData using sys.getsizeof() but it somehow doesn't gives the actual value of the memory occupied. For example, if a file in my file system occupies 4 KB of data, if I read all the lines in a list, the size of the list is around 2100 bytes only. Where am I going wrong? What are the alternatives I can try? From __peter__ at web.de Tue Feb 4 06:40:25 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 12:40:25 +0100 Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: Ayushi Dalmia wrote: > I have 10 files and I need to merge them (using K way merging). The size > of each file is around 200 MB. Now suppose I am keeping the merged data in > a variable named mergedData, I had thought of checking the size of > mergedData using sys.getsizeof() but it somehow doesn't gives the actual > value of the memory occupied. > > For example, if a file in my file system occupies 4 KB of data, if I read > all the lines in a list, the size of the list is around 2100 bytes only. > > Where am I going wrong? What are the alternatives I can try? getsizeof() gives you the size of the list only; to complete the picture you have to add the sizes of the lines. However, why do you want to keep track of the actual memory used by variables in your script? You should instead concentrate on the algorithm, and as long as either the size of the dataset is manageable or you can limit the amount of data accessed at a given time you are golden. From ayushidalmia2604 at gmail.com Tue Feb 4 07:39:47 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 04:39:47 -0800 (PST) Subject: fseek In Compressed Files In-Reply-To: References: <68316d1a-e52e-48b5-87df-7119f46ebabc@googlegroups.com> <78213f6b-3311-4487-a611-ecd3de33a168@googlegroups.com> Message-ID: On Tuesday, February 4, 2014 2:27:38 AM UTC+5:30, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > > > On Thursday, January 30, 2014 4:20:26 PM UTC+5:30, Ayushi Dalmia wrote: > > >> Hello, > > >> > > >> > > >> > > >> I need to randomly access a bzip2 or gzip file. How can I set the offset for a line and later retreive the line from the file using the offset. Pointers in this direction will help. > > > > > > This is what I have done: > > > > > > import bz2 > > > import sys > > > from random import randint > > > > > > index={} > > > > > > data=[] > > > f=open('temp.txt','r') > > > for line in f: > > > data.append(line) > > > > > > filename='temp1.txt.bz2' > > > with bz2.BZ2File(filename, 'wb', compresslevel=9) as f: > > > f.writelines(data) > > > > > > prevsize=0 > > > list1=[] > > > offset={} > > > with bz2.BZ2File(filename, 'rb') as f: > > > for line in f: > > > words=line.strip().split(' ') > > > list1.append(words[0]) > > > offset[words[0]]= prevsize > > > prevsize = sys.getsizeof(line)+prevsize > > > > sys.getsizeof looks at internal size of a python object, and is > > totally unrelated to a size on disk of a text line. len () might > > come closer, unless you're on Windows. You really should be using > > tell to define the offsets for later seek. In text mode any other > > calculation is not legal, ie undefined. > > > > > > > > > > > data=[] > > > count=0 > > > > > > with bz2.BZ2File(filename, 'rb') as f: > > > while count<20: > > > y=randint(1,25) > > > print y > > > print offset[str(y)] > > > count+=1 > > > f.seek(int(offset[str(y)])) > > > x= f.readline() > > > data.append(x) > > > > > > f=open('b.txt','w') > > > f.write(''.join(data)) > > > f.close() > > > > > > where temp.txt is the posting list file which is first written in a compressed format and then read later. > > > > I thought you were starting with a compressed file. If you're > > being given an uncompressed file, just deal with it directly. > > > > > > >I am trying to build the index for the entire wikipedia dump which needs to be done in a space and time optimised way. The temp.txt is as follows: > > > > > > 1 456 t0b3c0i0e0:784 t0b2c0i0e0:801 t0b2c0i0e0 > > > 2 221 t0b1c0i0e0:774 t0b1c0i0e0:801 t0b2c0i0e0 > > > 3 455 t0b7c0i0e0:456 t0b1c0i0e0:459 t0b2c0i0e0:669 t0b10c11i3e0:673 t0b1c0i0e0:678 t0b2c0i1e0:854 t0b1c0i0e0 > > > 4 410 t0b4c0i0e0:553 t0b1c0i0e0:609 t0b1c0i0e0 > > > 5 90 t0b1c0i0e0 > > > > So every line begins with its line number in ascii form? If true, > > the dict above called offsets should just be a list. > > > > > > Maybe you should just quote the entire assignment. You're > > probably adding way too much complication to it. > > > > -- > > DaveA Hey! I am new here. Sorry about the incorrect posts. Didn't understand the protocol then. Although, I have the uncompressed text, I cannot start right away with them From ayushidalmia2604 at gmail.com Tue Feb 4 07:43:21 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 04:43:21 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> On Tuesday, February 4, 2014 5:10:25 PM UTC+5:30, Peter Otten wrote: > Ayushi Dalmia wrote: > > > > > I have 10 files and I need to merge them (using K way merging). The size > > > of each file is around 200 MB. Now suppose I am keeping the merged data in > > > a variable named mergedData, I had thought of checking the size of > > > mergedData using sys.getsizeof() but it somehow doesn't gives the actual > > > value of the memory occupied. > > > > > > For example, if a file in my file system occupies 4 KB of data, if I read > > > all the lines in a list, the size of the list is around 2100 bytes only. > > > > > > Where am I going wrong? What are the alternatives I can try? > > > > getsizeof() gives you the size of the list only; to complete the picture you > > have to add the sizes of the lines. > > > > However, why do you want to keep track of the actual memory used by > > variables in your script? You should instead concentrate on the algorithm, > > and as long as either the size of the dataset is manageable or you can limit > > the amount of data accessed at a given time you are golden. As I said, I need to merge large files and I cannot afford more I/O operations. So in order to minimise the I/O operation I am writing in chunks. Also, I need to use the merged files as indexes later which should be loaded in the memory for fast access. Hence the concern. Can you please elaborate on the point of taking lines into consideration? From roegltd at gmail.com Tue Feb 4 07:53:19 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 4 Feb 2014 04:53:19 -0800 (PST) Subject: Finding size of Variable In-Reply-To: <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> Message-ID: On Tuesday, February 4, 2014 2:43:21 PM UTC+2, Ayushi Dalmia wrote: > > As I said, I need to merge large files and I cannot afford more I/O > operations. So in order to minimise the I/O operation I am writing in > chunks. Also, I need to use the merged files as indexes later which > should be loaded in the memory for fast access. Hence the concern. > Can you please elaborate on the point of taking lines into consideration? have you tried os.sendfile()? http://docs.python.org/dev/library/os.html#os.sendfile From davea at davea.name Tue Feb 4 08:09:00 2014 From: davea at davea.name (Dave Angel) Date: Tue, 4 Feb 2014 08:09:00 -0500 (EST) Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> Message-ID: Ayushi Dalmia Wrote in message: >> getsizeof() gives you the size of the list only; to complete the picture you >> >> have to add the sizes of the lines. >> >> >> >> However, why do you want to keep track of the actual memory used by >> >> variables in your script? You should instead concentrate on the algorithm, >> >> and as long as either the size of the dataset is manageable or you can limit >> >> the amount of data accessed at a given time you are golden. > > As I said, I need to merge large files and I cannot afford more I/O operations. So in order to minimise the I/O operation I am writing in chunks. Also, I need to use the merged files as indexes later which should be loaded in the memory for fast access. Hence the concern. > > Can you please elaborate on the point of taking lines into consideration? > Please don't doublespace your quotes. If you must use googlegroups, fix its bugs before posting. There's usually no net gain in trying to 'chunk' your output to a text file. The python file system already knows how to do that for a sequential file. For list of strings just add the getsizeof for the list to the sum of the getsizeof of all the list items. -- DaveA From ayushidalmia2604 at gmail.com Tue Feb 4 08:18:33 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 05:18:33 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> Message-ID: <6b515ace-8a4c-46b4-ab9d-a20922d917cc@googlegroups.com> On Tuesday, February 4, 2014 6:23:19 PM UTC+5:30, Asaf Las wrote: > On Tuesday, February 4, 2014 2:43:21 PM UTC+2, Ayushi Dalmia wrote: > > > > > > As I said, I need to merge large files and I cannot afford more I/O > > > operations. So in order to minimise the I/O operation I am writing in > > > chunks. Also, I need to use the merged files as indexes later which > > > should be loaded in the memory for fast access. Hence the concern. > > > Can you please elaborate on the point of taking lines into consideration? > > > > have you tried os.sendfile()? > > > > http://docs.python.org/dev/library/os.html#os.sendfile os.sendfile will not serve my purpose. I not only need to merge files, but do it in a sorted way. Thus some postprocessing is needed. From ayushidalmia2604 at gmail.com Tue Feb 4 08:19:48 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 05:19:48 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> Message-ID: <40d95427-0c96-46af-9efe-0343953ac460@googlegroups.com> On Tuesday, February 4, 2014 6:39:00 PM UTC+5:30, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > > > > >> getsizeof() gives you the size of the list only; to complete the picture you > > >> > > >> have to add the sizes of the lines. > > >> > > >> > > >> > > >> However, why do you want to keep track of the actual memory used by > > >> > > >> variables in your script? You should instead concentrate on the algorithm, > > >> > > >> and as long as either the size of the dataset is manageable or you can limit > > >> > > >> the amount of data accessed at a given time you are golden. > > > > > > As I said, I need to merge large files and I cannot afford more I/O operations. So in order to minimise the I/O operation I am writing in chunks. Also, I need to use the merged files as indexes later which should be loaded in the memory for fast access. Hence the concern. > > > > > > Can you please elaborate on the point of taking lines into consideration? > > > > > > > Please don't doublespace your quotes. If you must use > > googlegroups, fix its bugs before posting. > > > > There's usually no net gain in trying to 'chunk' your output to a > > text file. The python file system already knows how to do that > > for a sequential file. > > > > For list of strings just add the getsizeof for the list to the sum > > of the getsizeof of all the list items. > > > > -- > > DaveA Hey! I need to chunk out the outputs otherwise it will give Memory Error. I need to do some postprocessing on the data read from the file too. If I donot stop before memory error, I won't be able to perform any more operations on it. From python at mrabarnett.plus.com Tue Feb 4 09:05:06 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Feb 2014 14:05:06 +0000 Subject: Logging data from Arduino using PySerial In-Reply-To: References: Message-ID: <52F0F392.70302@mrabarnett.plus.com> On 2014-02-04 04:07, Thomas wrote: > I've written a script to log data from my Arduino to a csv file. The script works well enough but it's very, very slow. I'm quite new to Python and I just wanted to put this out there to see if any Python experts could help optimise my code. Here it is: > [snip] > # Cleaning the data_log and storing it in data.csv > with open('data.csv','wb') as csvfile: > for line in data_log: > line_data = re.findall('\d*\.\d*',line) # Find all digits > line_data = filter(None,line_data) # Filter out empty strings > line_data = [float(x) for x in line_data] # Convert Strings to float > > for i in range(1,len(line_data)): > line_data[i]=map(line_data[i],0,1023,0,5) > You're doing this for every in line the log: > csvwrite = csv.writer(csvfile) [snip] Try moving before the 'for' loop so it's done only once. From salvatore.didio at gmail.com Tue Feb 4 09:07:15 2014 From: salvatore.didio at gmail.com (Salvatore DI DIO) Date: Tue, 4 Feb 2014 06:07:15 -0800 (PST) Subject: RapydBox Message-ID: <12e7fa75-1d4d-4758-b217-3a6789ef576d@googlegroups.com> Hello, For those of you who are interested by tools like NodeBox or Processing. you can give a try to RapydScript here : https://github.com/artyprog/RapydBox Regards From malaclypse2 at gmail.com Tue Feb 4 09:39:54 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 4 Feb 2014 09:39:54 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> Message-ID: On Tue, Feb 4, 2014 at 1:51 AM, wrote: > I got it. If I'm visiting a page like this: > > http://docs.python.org/3/tutorial/index.html#the-python-tutorial > > 1) To read the page, I'm scrolling down. > 2) When I have finished to read the page, I scroll up > (or scroll back/up) to the top of the page until I see > this "feature" and the title. > 3) I click on this "feature". > 4) The title, already visible, moves, let's say, "2cm" higher. > > ...? Those links aren't for navigation. They're so you can discover anchor links in the page and pass them to someone else. For instance, if I want to point someone to the section of the tutorial that talks about reading and writing files, I could just give them this link: http://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files, instead of pointing them to the main page and instructing them to scroll down until they see Section 7.2 I was able to discover that link by opening the page, highlighting the section header with my mouse, then clicking the pilcrow. That gives me the anchor link to that section header. From thebiggestbangtheory at gmail.com Tue Feb 4 10:01:52 2014 From: thebiggestbangtheory at gmail.com (thebiggestbangtheory at gmail.com) Date: Tue, 4 Feb 2014 07:01:52 -0800 (PST) Subject: Advice needed for Python packaging - can't find required library during installation In-Reply-To: References: <14a9fb0b-75a8-4d22-8c5b-75b1bf02493e@googlegroups.com> Message-ID: <3758bc8c-97bc-4d3a-af10-425972eaf3a7@googlegroups.com> Thank you very much! :-) On Monday, February 3, 2014 11:30:00 PM UTC-8, dieter wrote: > thebiggestbangtheory at gmail.com writes: > > > > > I am trying to package up a very simple python app. In my setup.py file I have a couple of lines that include the following: > > > > > > from setuptools import setup > > > > > > setup( > > > name='ban', > > > version='0.1', > > > packages=['ban',], > > > description='Python Distribution Utilities', > > > author='Ban', > > > author_email='ban at tbbt.com', > > > package_data={'ban': ['data/*.dat']}, > > > long_description=open('README.txt').read(), > > > install_requires=['Google-Safe-Browsing-v2-Lookup'], > > > ) > > > ... > > > Processing dependencies for ban==0.1 > > > Searching for Google-Safe-Browsing-v2-Lookup > > > Reading http://pypi.python.org/simple/Google-Safe-Browsing-v2-Lookup/ > > > No local packages or download links found for Google-Safe-Browsing-v2-Lookup > > > error: Could not find suitable distribution for Requirement.parse('Google-Safe-Browsing-v2-Lookup') > > > ************************** > > > > > > Issue #1 > > > > > > Apparently the setup script cannot find the package - Google-Safe-Browsing-v2-Lookup . However, I can install this package via pip. > > > > > > What should I specify in the setup.py file instead of install_requires=['Google-Safe-Browsing-v2-Lookup'] so that the library is properly installed ? > > > > I suppose that "setuptools" is confused by the "-" in the package > > names together with these "-" being omitted in the uploaded file > > (https://pypi.python.org/packages/source/G/Google-Safe-Browsing-v2-Lookup/Google%20Safe%20Browsing%20v2%20Lookup-0.1.0.tar.gz5"). > > > > If this supposition is correct, then you would either need to > > contact the "setuptools" author (to get "setuptools" handle this case) > > or the "Google Safe Browsing" author to get a filename more > > in line with the package name. From wxjmfauth at gmail.com Tue Feb 4 10:21:25 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 4 Feb 2014 07:21:25 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> Message-ID: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Le mardi 4 f?vrier 2014 15:39:54 UTC+1, Jerry Hill a ?crit?: > On Tue, Feb 4, 2014 at 1:51 AM, wrote: > > > I got it. If I'm visiting a page like this: > > > > > > http://docs.python.org/3/tutorial/index.html#the-python-tutorial > > > > > > 1) To read the page, I'm scrolling down. > > > 2) When I have finished to read the page, I scroll up > > > (or scroll back/up) to the top of the page until I see > > > this "feature" and the title. > > > 3) I click on this "feature". > > > 4) The title, already visible, moves, let's say, "2cm" higher. > > > > > > ...? > > > > Those links aren't for navigation. > > > > They're so you can discover anchor links in the page and pass them to > > someone else. For instance, if I want to point someone to the section > > of the tutorial that talks about reading and writing files, I could > > just give them this link: > > http://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files, > > instead of pointing them to the main page and instructing them to > > scroll down until they see Section 7.2 > > > > I was able to discover that link by opening the page, highlighting the > > section header with my mouse, then clicking the pilcrow. That gives > > me the anchor link to that section header. Useless and really ugly. From torriem at gmail.com Tue Feb 4 10:31:08 2014 From: torriem at gmail.com (Michael Torrie) Date: Tue, 04 Feb 2014 08:31:08 -0700 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: <52F107BC.4090203@gmail.com> On 02/04/2014 08:21 AM, wxjmfauth at gmail.com wrote: > > Useless and really ugly. How do you recommend we discover the anchor links for linking to? From dwightdhutto at gmail.com Tue Feb 4 10:43:23 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Tue, 4 Feb 2014 07:43:23 -0800 (PST) Subject: Calculator Problem In-Reply-To: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On Sunday, February 2, 2014 4:16:44 PM UTC-5, Charlie Winn wrote: > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > def Addition(): > > print('Addition: What are two your numbers?') > > 1 = float(input('First Number:')) > > 2 = float(input('Second Number:')) > > print('Your Final Result is:', 1 + 2) > > > > > > def Subtraction(): > > print('Subtraction: What are two your numbers?') > > 3 = float(input('First Number:')) > > 4 = float(input('Second Number:')) > > print('Your Final Result is:', 3 - 4) > > > > > > def Multiplication(): > > print('Multiplication: What are two your numbers?') > > 5 = float(input('First Number:')) > > 6 = float(input('Second Number:')) > > print('Your Final Result is:', 5 * 6) > > > > > > def Division(): > > print('Division: What are your two numbers?') > > 7 = float(input('First Number:')) > > 8 = float(input('Second Number:')) > > print('Your Final Result is:', 7 / 8) > > > > > > > > print('What type of calculation would you like to do?') > > Question = input('(Add, Subtract, Divide or Multiply)') > > if Question.lower().startswith('a'): > > print(Addition()) > > elif Question.lower().startswith('s'): > > print(Subtraction()) > > elif Question.lower().startswith('d'): > > print(Division()) > > elif Question.lower().startswith('m'): > > print(Multiplication()) > > else: > > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > while Question == 'test': > > Question() Can anyone point out how using an int as a var is possible, unless it's something I miss that changed in 3.3 from 3.2: david at david:~$ python3.2 Python 3.2.3 (default, Sep 25 2013, 18:25:56) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 7 = float(input('First Number:')) File "", line 1 SyntaxError: can't assign to literal >>> david at david:~$ python Python 2.7.3 (default, Sep 26 2013, 20:08:41) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 7 = float(input('First Number:')) File "", line 1 SyntaxError: can't assign to literal >>> From steve+comp.lang.python at pearwood.info Tue Feb 4 10:45:46 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 04 Feb 2014 15:45:46 GMT Subject: Latest Python 3.4 in the source repo is broken? Message-ID: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Before I bother Python-Dev with this, can anyone else confirm that building Python 3.4 from source using the latest version in the source repository fails? # Get the source code hg clone http://hg.python.org/cpython # Build Python (on Unix, sorry Windows and Mac people, you're on your own) ./configure --with-pydebug && make -j2 I get the following errors: libpython3.4dm.a(pythonrun.o): In function `_Py_InitializeEx_Private': /home/steve/python/cpython/Python/pythonrun.c:459: undefined reference to `_PyTraceMalloc_Init' libpython3.4dm.a(pythonrun.o): In function `Py_Finalize': /home/steve/python/cpython/Python/pythonrun.c:648: undefined reference to `_PyTraceMalloc_Fini' collect2: ld returned 1 exit status make: *** [Modules/_testembed] Error 1 Thanks in advance, -- Steven From dwightdhutto at gmail.com Tue Feb 4 10:54:16 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Tue, 4 Feb 2014 10:54:16 -0500 Subject: Calculator Problem In-Reply-To: References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: Missed that it's already pointed out, was looking at the google groups combined email. On Tue, Feb 4, 2014 at 10:43 AM, David Hutto wrote: > On Sunday, February 2, 2014 4:16:44 PM UTC-5, Charlie Winn wrote: > > Hey Guys i Need Help , When i run this program i get the 'None' Under > the program, see what i mean by just running it , can someone help me fix > this > > > > > > > > def Addition(): > > > > print('Addition: What are two your numbers?') > > > > 1 = float(input('First Number:')) > > > > 2 = float(input('Second Number:')) > > > > print('Your Final Result is:', 1 + 2) > > > > > > > > > > > > def Subtraction(): > > > > print('Subtraction: What are two your numbers?') > > > > 3 = float(input('First Number:')) > > > > 4 = float(input('Second Number:')) > > > > print('Your Final Result is:', 3 - 4) > > > > > > > > > > > > def Multiplication(): > > > > print('Multiplication: What are two your numbers?') > > > > 5 = float(input('First Number:')) > > > > 6 = float(input('Second Number:')) > > > > print('Your Final Result is:', 5 * 6) > > > > > > > > > > > > def Division(): > > > > print('Division: What are your two numbers?') > > > > 7 = float(input('First Number:')) > > > > 8 = float(input('Second Number:')) > > > > print('Your Final Result is:', 7 / 8) > > > > > > > > > > > > > > > > print('What type of calculation would you like to do?') > > > > Question = input('(Add, Subtract, Divide or Multiply)') > > > > if Question.lower().startswith('a'): > > > > print(Addition()) > > > > elif Question.lower().startswith('s'): > > > > print(Subtraction()) > > > > elif Question.lower().startswith('d'): > > > > print(Division()) > > > > elif Question.lower().startswith('m'): > > > > print(Multiplication()) > > > > else: > > > > print('Please Enter The First Letter Of The Type Of Calculation > You Would Like To Use') > > > > > > > > while Question == 'test': > > > > Question() > > Can anyone point out how using an int as a var is possible, unless it's > something I miss that changed in 3.3 from 3.2: > > david at david:~$ python3.2 > Python 3.2.3 (default, Sep 25 2013, 18:25:56) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 7 = float(input('First Number:')) > File "", line 1 > SyntaxError: can't assign to literal > >>> > > david at david:~$ python > Python 2.7.3 (default, Sep 26 2013, 20:08:41) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 7 = float(input('First Number:')) > File "", line 1 > SyntaxError: can't assign to literal > >>> > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pylist at gmail.com Tue Feb 4 11:02:38 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 4 Feb 2014 10:02:38 -0600 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Feb 4, 2014 at 9:45 AM, Steven D'Aprano wrote: > Before I bother Python-Dev with this, can anyone else confirm that > building Python 3.4 from source using the latest version in the source > repository fails? > > # Get the source code > hg clone http://hg.python.org/cpython > > # Build Python (on Unix, sorry Windows and Mac people, you're on your own) > ./configure --with-pydebug && make -j2 > > > > I get the following errors: > > libpython3.4dm.a(pythonrun.o): In function `_Py_InitializeEx_Private': > /home/steve/python/cpython/Python/pythonrun.c:459: undefined reference to > `_PyTraceMalloc_Init' > libpython3.4dm.a(pythonrun.o): In function `Py_Finalize': > /home/steve/python/cpython/Python/pythonrun.c:648: undefined reference to > `_PyTraceMalloc_Fini' > collect2: ld returned 1 exit status > make: *** [Modules/_testembed] Error 1 The buildbots[1] don't seem to agree, and it builds fine for me on Windows. In order of destructiveness, try these: make Without -j2, see if there's a race somewhere. make distclean Clear out nearly all generated files. hg purge --all Clear out everything that's not checked in (this includes untracked and ignored files). You may need to enable the purge extension, `hg --config extensions.purge= purge --all` And I would suggest checking the output of `hg purge --all -p` before you do it to make sure you're not obliterating anything you want to keep. hg up null && hg purge --all && hg up default Rebuild the repository from scratch (without a full clone). [1] http://buildbot.python.org/all/waterfall?category=3.x.stable -- Zach From rosuav at gmail.com Tue Feb 4 11:18:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 03:18:45 +1100 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <52F107BC.4090203@gmail.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> <52F107BC.4090203@gmail.com> Message-ID: On Wed, Feb 5, 2014 at 2:31 AM, Michael Torrie wrote: > On 02/04/2014 08:21 AM, wxjmfauth at gmail.com wrote: >> >> Useless and really ugly. > > How do you recommend we discover the anchor links for linking to? Same way you usually do! By right clicking, hitting "View Source", and poking around until you find the right place! I've done exactly that with innumerable web sites. It's a massive luxury to have them explicitly published like that; as well as the convenience, it gives an impression (whether that's true or false) that the hash links are deemed important and will therefore be maintained in the future (unlike, say, a system that has "http://..../....#s4" for the fourth (or fifth) section - inserting a section above this one will break my link) ChrisA . From mailman at hanez.org Tue Feb 4 11:21:57 2014 From: mailman at hanez.org (Johannes Findeisen) Date: Tue, 4 Feb 2014 17:21:57 +0100 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20140204172157.46340d5e@hanez.org> On 04 Feb 2014 15:45:46 GMT Steven D'Aprano wrote: > Before I bother Python-Dev with this, can anyone else confirm that > building Python 3.4 from source using the latest version in the source > repository fails? I can not confirm an error. I checked out the latest sources and ./configure and make executed without any error using exactly your parameters. > Thanks in advance, You are welcome... ;) Regards, Johannes From rosuav at gmail.com Tue Feb 4 11:49:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 03:49:57 +1100 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Feb 5, 2014 at 3:02 AM, Zachary Ware wrote: > On Tue, Feb 4, 2014 at 9:45 AM, Steven D'Aprano > wrote: >> Before I bother Python-Dev with this, can anyone else confirm that >> building Python 3.4 from source using the latest version in the source >> repository fails? >> >> # Build Python (on Unix, sorry Windows and Mac people, you're on your own) >> ./configure --with-pydebug && make -j2 >> > The buildbots[1] don't seem to agree, and it builds fine for me on > Windows. In order of destructiveness, try these: > > [1] http://buildbot.python.org/all/waterfall?category=3.x.stable Are there any buildbots that configure --with-pydebug? This could be a debug-only issue. That said, though, I just did a build without -j2 (on Linux - Debian Wheezy amd64) and it worked fine. Doing another one with -j2 didn't show up any errors either, but if it is a -j problem, then as Zachary says, it could be a race. What commit hash were you building from? It might have been broken and then fixed shortly, and you got into that tiny window. ChrisA From zachary.ware+pylist at gmail.com Tue Feb 4 11:58:51 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 4 Feb 2014 10:58:51 -0600 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Feb 4, 2014 at 10:49 AM, Chris Angelico wrote: > Are there any buildbots that configure --with-pydebug? This could be a > debug-only issue. Only all of them :). As far as I know, the only 'bot that does a non-debug build is the "x86 Gentoo Non-Debug" bot. > That said, though, I just did a build without -j2 (on Linux - Debian > Wheezy amd64) and it worked fine. Doing another one with -j2 didn't > show up any errors either, but if it is a -j problem, then as Zachary > says, it could be a race. > > What commit hash were you building from? It might have been broken and > then fixed shortly, and you got into that tiny window. There was a brief issue this morning, but it was in typeobject.c, not _testembed. See http://hg.python.org/cpython/rev/655d7a55c165 -- Zach From rosuav at gmail.com Tue Feb 4 12:03:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 04:03:59 +1100 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Feb 5, 2014 at 3:58 AM, Zachary Ware wrote: > On Tue, Feb 4, 2014 at 10:49 AM, Chris Angelico wrote: >> Are there any buildbots that configure --with-pydebug? This could be a >> debug-only issue. > > Only all of them :). As far as I know, the only 'bot that does a > non-debug build is the "x86 Gentoo Non-Debug" bot. LOL! Okay. Yeah, I think that settles that part of the question! ChrisA From ethan at stoneleaf.us Tue Feb 4 12:01:15 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 04 Feb 2014 09:01:15 -0800 Subject: Latest Python 3.4 in the source repo is broken? In-Reply-To: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f10b2a$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52F11CDB.2060705@stoneleaf.us> On 02/04/2014 07:45 AM, Steven D'Aprano wrote: > Before I bother Python-Dev with this, can anyone else confirm that > building Python 3.4 from source using the latest version in the source > repository fails? This is the check-out I'm using: ethan at media:~/source/python/cpython$ hg parent ---------------------------------------------------------------------------- rev: 88961:7d0a4f89c6ce branch: default tag: tip user: Vinay Sajip date: 2014-02-04 16:42 +0000 desc: Closes #20509: Merged documentation update from 3.3. ---------------------------------------------------------------------------- These are the settings I always use to make sure I have no weird problems between check-outs: ethan at media:~/source/python/cpython$ make distclean && ./configure --with-pydebug && make -j3 .. .. .. Python build finished successfully! The necessary bits to build these optional modules were not found: _gdbm _lzma To find the necessary bits, look in setup.py in detect_modules() for the module's name. running build_scripts creating build/scripts-3.4 copying and adjusting /home/ethan/source/python/cpython/Tools/scripts/pydoc3 -> build/scripts-3.4 copying and adjusting /home/ethan/source/python/cpython/Tools/scripts/idle3 -> build/scripts-3.4 copying and adjusting /home/ethan/source/python/cpython/Tools/scripts/2to3 -> build/scripts-3.4 copying and adjusting /home/ethan/source/python/cpython/Tools/scripts/pyvenv -> build/scripts-3.4 changing mode of build/scripts-3.4/pydoc3 from 664 to 775 changing mode of build/scripts-3.4/idle3 from 664 to 775 changing mode of build/scripts-3.4/2to3 from 664 to 775 changing mode of build/scripts-3.4/pyvenv from 664 to 775 renaming build/scripts-3.4/pydoc3 to build/scripts-3.4/pydoc3.4 renaming build/scripts-3.4/idle3 to build/scripts-3.4/idle3.4 renaming build/scripts-3.4/2to3 to build/scripts-3.4/2to3-3.4 renaming build/scripts-3.4/pyvenv to build/scripts-3.4/pyvenv-3.4 Hope this helps. -- ~Ethan~ From ned at nedbatchelder.com Tue Feb 4 13:20:34 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 04 Feb 2014 13:20:34 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2/4/14 10:21 AM, wxjmfauth at gmail.com wrote: >> > >> >I was able to discover that link by opening the page, highlighting the >> >section header with my mouse, then clicking the pilcrow. That gives >> >me the anchor link to that section header. > > Useless and really ugly. I'm not sure why you would describe it as useless? It's incredibly useful to have a way to link to a particular section. And ugly? It's a UI that is invisible and unobtrusive, but then elegant once you hover over the element you are interested in. I guess tastes differ... Lots of sites use this technique, it is not particular to the Python docs. -- Ned Batchelder, http://nedbatchelder.com From jimsgibson at gmail.com Tue Feb 4 13:24:30 2014 From: jimsgibson at gmail.com (Jim Gibson) Date: Tue, 04 Feb 2014 10:24:30 -0800 Subject: [OT] Usage of U+00B6 PILCROW SIGN References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: <040220141024303421%jimsgibson@gmail.com> In article , Michael Torrie wrote: > On 02/04/2014 08:21 AM, wxjmfauth at gmail.com wrote: > > > > Useless and really ugly. > > How do you recommend we discover the anchor links for linking to? Use the Table Of Contents panel on the left? -- Jim Gibson From __peter__ at web.de Tue Feb 4 13:40:02 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 19:40:02 +0100 Subject: [OT] Usage of U+00B6 PILCROW SIGN References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> <52F107BC.4090203@gmail.com> Message-ID: Michael Torrie wrote: > On 02/04/2014 08:21 AM, wxjmfauth at gmail.com wrote: >> >> Useless and really ugly. > > How do you recommend we discover the anchor links for linking to? Why not the whole header? Click anywhere on 7.2.1. Regular Expression Syntax instead of the tiny ? symbol beside it. From davea at davea.name Tue Feb 4 14:21:31 2014 From: davea at davea.name (Dave Angel) Date: Tue, 4 Feb 2014 14:21:31 -0500 (EST) Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: Ayushi Dalmia Wrote in message: > > Where am I going wrong? What are the alternatives I can try? You've rejected all the alternatives so far without showing your code, or even properly specifying your problem. To get the "total" size of a list of strings, try (untested): a = sys.getsizeof (mylist ) for item in mylist: a += sys.getsizeof (item) This can be high if some of the strings are interned and get counted twice. But you're not likely to get closer without some knowledge of the data objects and where they come from. -- DaveA From andrea.crotti.0 at gmail.com Tue Feb 4 14:19:06 2014 From: andrea.crotti.0 at gmail.com (andrea crotti) Date: Tue, 4 Feb 2014 19:19:06 +0000 Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: 2014-02-04 : > Le mardi 4 f?vrier 2014 15:39:54 UTC+1, Jerry Hill a ?crit : > > Useless and really ugly. > I think this whole discussion is rather useless instead, why do you care since you're not going to use this tool anyway? From mail at timgolden.me.uk Tue Feb 4 14:28:41 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 04 Feb 2014 19:28:41 +0000 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: <52F13F69.5080507@timgolden.me.uk> On 04/02/2014 19:21, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > >> >> Where am I going wrong? What are the alternatives I can try? > > You've rejected all the alternatives so far without showing your > code, or even properly specifying your problem. > > To get the "total" size of a list of strings, try (untested): > > a = sys.getsizeof (mylist ) > for item in mylist: > a += sys.getsizeof (item) The documentation for sys.getsizeof: http://docs.python.org/dev/library/sys#sys.getsizeof warns about the limitations of this function when applied to a container, and even points to a recipe by Raymond Hettinger which attempts to do a more complete job. TJG From python.list at tim.thechases.com Tue Feb 4 14:29:46 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 4 Feb 2014 13:29:46 -0600 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: <20140204132946.1c89de10@bigbox.christie.dr> On 2014-02-04 14:21, Dave Angel wrote: > To get the "total" size of a list of strings, try (untested): > > a = sys.getsizeof (mylist ) > for item in mylist: > a += sys.getsizeof (item) I always find this sort of accumulation weird (well, at least in Python; it's the *only* way in many other languages) and would write it as a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) -tkc From o.bharath95 at gmail.com Tue Feb 4 14:55:43 2014 From: o.bharath95 at gmail.com (bharath) Date: Tue, 4 Feb 2014 11:55:43 -0800 (PST) Subject: kivy Message-ID: i installed python 2.7 before and installed suitable kivy.. i have also included the .bat file in the send to option.. but my programs are not at all runnning and giving me error when i run it normally or with the .bat file.. it says that there's no module named kivy when i import it.. please help im just frustrated after writing a long code and seeing that it isn't working.. if anyone has suggestions on how to develop android 2d games with python their reply would be greatly appreciated. thank you From python at mrabarnett.plus.com Tue Feb 4 15:21:31 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Feb 2014 20:21:31 +0000 Subject: kivy In-Reply-To: References: Message-ID: <52F14BCB.6020705@mrabarnett.plus.com> On 2014-02-04 19:55, bharath wrote: > i installed python 2.7 before and installed suitable kivy.. i have > also included the .bat file in the send to option.. but my programs > are not at all runnning and giving me error when i run it normally or > with the .bat file.. it says that there's no module named kivy when i > import it.. please help im just frustrated after writing a long code > and seeing that it isn't working.. if anyone has suggestions on how > to develop android 2d games with python their reply would be greatly > appreciated. thank you > Is kivy listed in the Python search paths (sys.path)? From o.bharath95 at gmail.com Tue Feb 4 15:23:47 2014 From: o.bharath95 at gmail.com (bharath) Date: Tue, 4 Feb 2014 12:23:47 -0800 (PST) Subject: kivy In-Reply-To: References: Message-ID: On Wednesday, February 5, 2014 1:51:31 AM UTC+5:30, MRAB wrote: > On 2014-02-04 19:55, bharath wrote: > > > i installed python 2.7 before and installed suitable kivy.. i have > > > also included the .bat file in the send to option.. but my programs > > > are not at all runnning and giving me error when i run it normally or > > > with the .bat file.. it says that there's no module named kivy when i > > > import it.. please help im just frustrated after writing a long code > > > and seeing that it isn't working.. if anyone has suggestions on how > > > to develop android 2d games with python their reply would be greatly > > > appreciated. thank you > > > > > Is kivy listed in the Python search paths (sys.path)? From o.bharath95 at gmail.com Tue Feb 4 15:24:49 2014 From: o.bharath95 at gmail.com (bharath) Date: Tue, 4 Feb 2014 12:24:49 -0800 (PST) Subject: kivy In-Reply-To: References: Message-ID: <5cc76b44-7420-405d-8d16-0125767cbcf7@googlegroups.com> On Wednesday, February 5, 2014 1:51:31 AM UTC+5:30, MRAB wrote: > On 2014-02-04 19:55, bharath wrote: > > > i installed python 2.7 before and installed suitable kivy.. i have > > > also included the .bat file in the send to option.. but my programs > > > are not at all runnning and giving me error when i run it normally or > > > with the .bat file.. it says that there's no module named kivy when i > > > import it.. please help im just frustrated after writing a long code > > > and seeing that it isn't working.. if anyone has suggestions on how > > > to develop android 2d games with python their reply would be greatly > > > appreciated. thank you > > > > > Is kivy listed in the Python search paths (sys.path)? yes From gary.herron at islandtraining.com Tue Feb 4 15:24:34 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 04 Feb 2014 12:24:34 -0800 Subject: kivy In-Reply-To: References: Message-ID: <52F14C82.20804@islandtraining.com> On 02/04/2014 11:55 AM, bharath wrote: > i installed python 2.7 before and installed suitable kivy.. i have also included the .bat file in the send to option.. but my programs are not at all runnning and giving me error when i run it normally or with the .bat file.. it says that there's no module named kivy when i import it.. please help im just frustrated after writing a long code and seeing that it isn't working.. if anyone has suggestions on how to develop android 2d games with python their reply would be greatly appreciated. thank you This is a Python newsgroup. You might find an answer here, but I think you'd have much better luck if you found a kivy specific newsgroup. Good luck, Gary Herron From nick.cash at npcinternational.com Tue Feb 4 15:33:58 2014 From: nick.cash at npcinternational.com (Nick Cash) Date: Tue, 4 Feb 2014 20:33:58 +0000 Subject: kivy In-Reply-To: <5cc76b44-7420-405d-8d16-0125767cbcf7@googlegroups.com> References: <5cc76b44-7420-405d-8d16-0125767cbcf7@googlegroups.com> Message-ID: >> Is kivy listed in the Python search paths (sys.path)? >yes To be extra sure, you can start a python interpreter with the commandline argument -vv, and when you try to import kivy (or any module) it will show you every file/path it checks when trying to find it. This might help you narrow down where the problem lies. -Nick Cash From o.bharath95 at gmail.com Tue Feb 4 16:16:42 2014 From: o.bharath95 at gmail.com (bharath) Date: Tue, 4 Feb 2014 13:16:42 -0800 (PST) Subject: kivy In-Reply-To: References: <5cc76b44-7420-405d-8d16-0125767cbcf7@googlegroups.com> Message-ID: <96294b85-eb41-4651-896b-1f972119c403@googlegroups.com> On Wednesday, February 5, 2014 2:03:58 AM UTC+5:30, Nick Cash wrote: > >> Is kivy listed in the Python search paths (sys.path)? > > > > >yes > > > > To be extra sure, you can start a python interpreter with the commandline argument -vv, and when you try to import kivy (or any module) it will show you every file/path it checks when trying to find it. This might help you narrow down where the problem lies. > > > > -Nick Cash thanks nick that helped. i actually cant express this feeling of gratitude.. thank you very much.this is a wonderful group.. From nimbiotics at gmail.com Tue Feb 4 17:55:52 2014 From: nimbiotics at gmail.com (Mario R. Osorio) Date: Tue, 4 Feb 2014 14:55:52 -0800 (PST) Subject: Calculator Problem In-Reply-To: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: <1df475a5-3125-48e0-8c12-7629dd9c0a06@googlegroups.com> On Sunday, February 2, 2014 4:16:44 PM UTC-5, Charlie Winn wrote: > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > def Addition(): > > print('Addition: What are two your numbers?') > > 1 = float(input('First Number:')) > > 2 = float(input('Second Number:')) > > print('Your Final Result is:', 1 + 2) > > > > > > def Subtraction(): > > print('Subtraction: What are two your numbers?') > > 3 = float(input('First Number:')) > > 4 = float(input('Second Number:')) > > print('Your Final Result is:', 3 - 4) > > > > > > def Multiplication(): > > print('Multiplication: What are two your numbers?') > > 5 = float(input('First Number:')) > > 6 = float(input('Second Number:')) > > print('Your Final Result is:', 5 * 6) > > > > > > def Division(): > > print('Division: What are your two numbers?') > > 7 = float(input('First Number:')) > > 8 = float(input('Second Number:')) > > print('Your Final Result is:', 7 / 8) > > > > > > > > print('What type of calculation would you like to do?') > > Question = input('(Add, Subtract, Divide or Multiply)') > > if Question.lower().startswith('a'): > > print(Addition()) > > elif Question.lower().startswith('s'): > > print(Subtraction()) > > elif Question.lower().startswith('d'): > > print(Division()) > > elif Question.lower().startswith('m'): > > print(Multiplication()) > > else: > > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > while Question == 'test': > > Question() I don't know why people bother trying to help you, when it is YOU that has a ******* rude attitude. You are asking the wrong question to begin with because the posted code could have NEVER given you the stated output. Most of us here are noobs and those that are not, were noobs once; so we all can deal with noobs, but none should have to deal with a*******holes. From tjreedy at udel.edu Tue Feb 4 18:00:59 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Feb 2014 18:00:59 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2/4/2014 1:20 PM, Ned Batchelder wrote: > On 2/4/14 10:21 AM, wxjmfauth at gmail.com wrote: >>> > >>> >I was able to discover that link by opening the page, highlighting the >>> >section header with my mouse, then clicking the pilcrow. That gives >>> >me the anchor link to that section header. > > >> Useless and really ugly. > > I'm not sure why you would describe it as useless? Because, as we should all know by now, when Jim says 'useless', he means 'useless to me, according to my unusual notions of personal usefulness'. He, apparently, does not intend to ever use the pilcrow to get a section link, nor does he care about being able to click on such links presented by others. > It's incredibly useful to have a way to link to a particular section. For many people, but not for Jim. Either he does not care about usefulness to others, or he is completely oblivious to how idiosyncratic his personal idea of usefulness is. In either case, it is useless to argue against his personal opinion. He should, however, add 'to me' since most people take 'useless' in the collective sense. > And ugly? It's a UI that is invisible and unobtrusive, but then elegant > once you hover over the element you are interested in. Having it pop up and disappear when one does not want it and will not use it is not pretty. When scrolling with a mouse wheel, that does happen. > I guess tastes differ... Lots of sites use this technique, it is not > particular to the Python docs. Irrelevant to Jim. -- Terry Jan Reedy From tjreedy at udel.edu Tue Feb 4 18:18:35 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Feb 2014 18:18:35 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2/4/2014 10:21 AM, wxjmfauth at gmail.com wrote: >> I was able to discover that link by opening the page, highlighting the >> section header with my mouse, then clicking the pilcrow. That gives >> me the anchor link to that section header. > > Useless and really ugly. Jim, when you say 'useless', please qualify as 'useless to me'. Otherwise, people may think that you mean 'useless to eveyone', and it is disrespectful to mislead people that way. I hope you are aware that your personal ideas of usefulness to yourself are quite different from other peoples' ideas of usefulness to themselves. I now understand that you consider the FSR useless *to you* because you do not care about the bugginess of narrow builds or about the spacious of wide builds. You do care about uniformity of character size across all strings, and FSR lacks that. You are entitled to make that judgment for yourself. You are not entitled to sabotage others by projecting you personal judgments onto others. The FSR and pilcrow are definitely useful to other people as they judge personal usefulness for themselves. PS. I agree that the pilcrow appearing and disappearing is not pretty when I am not looking to use it. I happen to think that is it tolerable because it is sometimes useful. -- Terry Jan Reedy From tjreedy at udel.edu Tue Feb 4 18:24:04 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Feb 2014 18:24:04 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2/4/2014 2:19 PM, andrea crotti wrote: > 2014-02-04 : >> Useless and really ugly. > I think this whole discussion is rather useless. I agree that responding to Jim's generalized statements such as 'useless' are either sincere personal opinions that are true with respect to himself, delusional statements that are false with respect to the community at large, or intentionally false trolls. I really cannot tell. In any case, I agree that response is pretty useless. -- Terry Jan Reedy From tjreedy at udel.edu Tue Feb 4 18:28:28 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Feb 2014 18:28:28 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2/4/2014 6:24 PM, Terry Reedy wrote: > On 2/4/2014 2:19 PM, andrea crotti wrote: >> 2014-02-04 : >>> Useless and really ugly. > >> I think this whole discussion is rather useless. > > I agree that responding to Jim's generalized statements such as > 'useless' are either sincere personal opinions that are true with > respect to himself, delusional statements that are false with respect to > the community at large, or intentionally false trolls. I really cannot > tell. In any case, I agree that response is pretty useless. Please ignore garbled post as I hit send in mid composition while revising. -- Terry Jan Reedy From rosuav at gmail.com Tue Feb 4 18:35:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 10:35:17 +1100 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On Wed, Feb 5, 2014 at 10:18 AM, Terry Reedy wrote: > PS. I agree that the pilcrow appearing and disappearing is not pretty when I > am not looking to use it. I happen to think that is it tolerable because it > is sometimes useful. Yes, it's not perfect. But neither are the obvious alternatives: * Keeping the symbol there permanently looks weird, and also raises the question of whether or not it should be copied to the clipboard if you select a whole pile of content. (If it is, you get an ugly bit of junk in your text, something that now (being unclickable) has no meaning. If it isn't, why isn't it? It's clearly part of the text!) * Making the whole heading clickable is a bit weird in terms of UI. It makes this text a link to itself, where it looks like it could be a link to somewhere else. I've seen other sites where headings are all links back to their ToC entries (ie the top of the page, or close to), which is also weird, and the fact that it could be either means that people won't know they can click on the heading to get a link to that section. * Having nothing on the section itself does work, but it means that finding a section link requires you to go back up to the top of the page, figure out which Contents entry is the section you want, and click on it. That's how I get section links from a MediaWiki site (eg Wikipedia); yes, it's workable, but it would be nicer to have the link down at the section I'm reading. * Putting a fixed-position piece of text showing the current section is way too intrusive. I've seen sites with that, and I'm sure it's useful, but I'd really prefer something a lot more subtle. All of the above are plausible, but none is perfect. So what do you do? You go with something imperfect and cope with a few issues. ChrisA From ned at nedbatchelder.com Tue Feb 4 18:36:00 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 04 Feb 2014 18:36:00 -0500 Subject: Concepts and Applications of Finite Element Analysis (4th Ed., Cook, Malkus, Plesha & Witt) In-Reply-To: <52f176c4$0$11890$c3e8da3$63ee2bc3@news.astraweb.com> References: <52f176c4$0$11890$c3e8da3$63ee2bc3@news.astraweb.com> Message-ID: On 2/4/14 6:24 PM, yamas wrote: > On Sun, 02 Feb 2014 17:59:29 -0600, kalvinmanual3 wrote: > >> I have solutions manuals to all problems and exercises in these >> textbooks. >> To get one in an electronic format contact me at > > fuck off retard > No matter what you think of the inappropriate post about manuals, this kind of response is completely unacceptable. Please don't do it again. Please read this: http://www.python.org/psf/codeofconduct -- Ned Batchelder, http://nedbatchelder.com From roy at panix.com Tue Feb 4 19:53:52 2014 From: roy at panix.com (Roy Smith) Date: Tue, 04 Feb 2014 19:53:52 -0500 Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: In article , David Hutto wrote: > Can anyone point out how using an int as a var is possible one = 42 (ducking and running) From rosuav at gmail.com Tue Feb 4 20:09:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 12:09:14 +1100 Subject: Calculator Problem In-Reply-To: References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On Wed, Feb 5, 2014 at 11:53 AM, Roy Smith wrote: > In article , > David Hutto wrote: > >> Can anyone point out how using an int as a var is possible > > one = 42 > > (ducking and running) In theory, there might be a Unicode character that's valid as an identifier, but gets converted into U+0031 for ASCIIfication prior to being sent by email. However, I can't find one :) And of course, that assumes that the OP's mail client mangles its input in that way. ASCIIfication shouldn't be necessary. ChrisA From tjreedy at udel.edu Tue Feb 4 20:57:35 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Feb 2014 20:57:35 -0500 Subject: Concepts and Applications of Finite Element Analysis (4th Ed., Cook, Malkus, Plesha & Witt) In-Reply-To: References: <52f176c4$0$11890$c3e8da3$63ee2bc3@news.astraweb.com> Message-ID: On 2/4/2014 6:36 PM, Ned Batchelder wrote: > On 2/4/14 6:24 PM, yamas wrote: >> On Sun, 02 Feb 2014 17:59:29 -0600, kalvinmanual3 wrote: >>> Python-list (and gmane) readers do not see and hence never notice the spam that gets blocked -- about 90%. Since essentially identical messages have appeared before, probably from the same sender, I tweaked the settings a bit. >> The few spam messages that do make it to the list should almost always be ignored and not kept alive by responses. One would have to be ignorant and/or foolish to think that spammers read responses on any of the many lists they spam. So any response is directed at the non-spammer readers. Obnoxious responses like that above constitute trolling. > No matter what you think of the inappropriate post about manuals, this > kind of response is completely unacceptable. Please don't do it again. > > Please read this: http://www.python.org/psf/codeofconduct Please do, and follow it. -- Terry Jan Reedy From dan at tombstonezero.net Tue Feb 4 21:22:53 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Wed, 5 Feb 2014 02:22:53 +0000 (UTC) Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On Tue, 04 Feb 2014 19:53:52 -0500, Roy Smith wrote: > In article , > David Hutto wrote: > >> Can anyone point out how using an int as a var is possible > > one = 42 > > (ducking and running) int = 42 (ducking lower and running faster) From rustompmody at gmail.com Tue Feb 4 22:11:03 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 4 Feb 2014 19:11:03 -0800 (PST) Subject: kivy In-Reply-To: References: Message-ID: <9260af03-210c-4feb-a267-0b8d75a850bb@googlegroups.com> On Wednesday, February 5, 2014 1:25:43 AM UTC+5:30, bharath wrote: > please help im just frustrated after writing a long code and seeing that it isn't working.. Prior to Kernighan and Ritchie people did tend to write 'a long code' and then check that its working (or not). After 'The C programming language' -- which is about 40 years -- starting any programming enterprise without writing AND CHECKING the equivalent of "Hello World" is just never done. IOW you underestimate how many niggling details both of the system and of your understanding are checked by that approach From ayushidalmia2604 at gmail.com Wed Feb 5 00:00:31 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 21:00:31 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <2728aca8-735b-4c38-9e7e-a164e8ed36f9@googlegroups.com> <40d95427-0c96-46af-9efe-0343953ac460@googlegroups.com> Message-ID: On Tuesday, February 4, 2014 7:36:48 PM UTC+5:30, Dennis Lee Bieber wrote: > On Tue, 4 Feb 2014 05:19:48 -0800 (PST), Ayushi Dalmia > > declaimed the following: > > > > > > >I need to chunk out the outputs otherwise it will give Memory Error. I need to do some postprocessing on the data read from the file too. If I donot stop before memory error, I won't be able to perform any more operations on it. > > > > 10 200MB files is only 2GB... Most any 64-bit processor these days can > > handle that. Even some 32-bit systems could handle it (WinXP booted with > > the server option gives 3GB to user processes -- if the 4GB was installed > > in the machine). > > > > However, you speak of an n-way merge. The traditional merge operation > > only reads one record from each file at a time, examines them for "first", > > writes that "first", reads next record from the file "first" came from, and > > then reassesses the set. > > > > You mention needed to chunk the data -- that implies performing a merge > > sort in which you read a few records from each file into memory, sort them, > > and right them out to newFile1; then read the same number of records from > > each file, sort, and write them to newFile2, up to however many files you > > intend to work with -- at that point you go back and append the next chunk > > to newFile1. When done, each file contains chunks of n*r records. You now > > make newFilex the inputs, read/merge the records from those chunks > > outputting to another file1, when you reach the end of the first chunk in > > the files you then read/merge the second chunk into another file2. You > > repeat this process until you end up with only one chunk in one file. > > -- > > Wulfraed Dennis Lee Bieber AF6VN > > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ The way you mentioned for merging the file is an option but that will involve a lot of I/O operation. Also, I do not want the size of the file to increase beyond a certain point. When I reach the file size upto a certain limit, I want to start writing in a new file. This is because I want to store them in memory again later. From ayushidalmia2604 at gmail.com Wed Feb 5 00:15:25 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 21:15:25 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: <723729ee-8e74-4d65-aa6f-742051a94101@googlegroups.com> On Wednesday, February 5, 2014 12:51:31 AM UTC+5:30, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > > > > > > > > Where am I going wrong? What are the alternatives I can try? > > > > You've rejected all the alternatives so far without showing your > > code, or even properly specifying your problem. > > > > To get the "total" size of a list of strings, try (untested): > > > > a = sys.getsizeof (mylist ) > > for item in mylist: > > a += sys.getsizeof (item) > > > > This can be high if some of the strings are interned and get > > counted twice. But you're not likely to get closer without some > > knowledge of the data objects and where they come > > from. > > > > -- > > DaveA Hello Dave, I just thought that saving others time is better and hence I explained only the subset of my problem. Here is what I am trying to do: I am trying to index the current wikipedia dump without using databases and create a search engine for Wikipedia documents. Note, I CANNOT USE DATABASES. My approach: I am parsing the wikipedia pages using SAX Parser, and then, I am dumping the words along with the posting list (a list of doc ids in which the word is present) into different files after reading 'X' number of pages. Now these files may have the same word and hence I need to merge them and write the final index again. Now these final indexes must be of limited size as I need to be of limited size. This is where I am stuck. I need to know how to determine the size of content in a variable before I write into the file. Here is the code for my merging: def mergeFiles(pathOfFolder, countFile): listOfWords={} indexFile={} topOfFile={} flag=[0]*countFile data=defaultdict(list) heap=[] countFinalFile=0 for i in xrange(countFile): fileName = pathOfFolder+'\index'+str(i)+'.txt.bz2' indexFile[i]= bz2.BZ2File(fileName, 'rb') flag[i]=1 topOfFile[i]=indexFile[i].readline().strip() listOfWords[i] = topOfFile[i].split(' ') if listOfWords[i][0] not in heap: heapq.heappush(heap, listOfWords[i][0]) while any(flag)==1: temp = heapq.heappop(heap) for i in xrange(countFile): if flag[i]==1: if listOfWords[i][0]==temp: //This is where I am stuck. I cannot wait until memory //error, as I need to do some postprocessing too. try: data[temp].extend(listOfWords[i][1:]) except MemoryError: writeFinalIndex(data, countFinalFile, pathOfFolder) data=defaultdict(list) countFinalFile+=1 topOfFile[i]=indexFile[i].readline().strip() if topOfFile[i]=='': flag[i]=0 indexFile[i].close() os.remove(pathOfFolder+'\index'+str(i)+'.txt.bz2') else: listOfWords[i] = topOfFile[i].split(' ') if listOfWords[i][0] not in heap: heapq.heappush(heap, listOfWords[i][0]) writeFinalIndex(data, countFinalFile, pathOfFolder) countFile is the number of files and writeFileIndex method writes into the file. From ayushidalmia2604 at gmail.com Wed Feb 5 00:35:05 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 21:35:05 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> Message-ID: <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> On Wednesday, February 5, 2014 12:59:46 AM UTC+5:30, Tim Chase wrote: > On 2014-02-04 14:21, Dave Angel wrote: > > > To get the "total" size of a list of strings, try (untested): > > > > > > a = sys.getsizeof (mylist ) > > > for item in mylist: > > > a += sys.getsizeof (item) > > > > I always find this sort of accumulation weird (well, at least in > > Python; it's the *only* way in many other languages) and would write > > it as > > > > a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) > > > > -tkc This also doesn't gives the true size. I did the following: import sys data=[] f=open('stopWords.txt','r') for line in f: line=line.split() data.extend(line) print sys.getsizeof(data) where stopWords.txt is a file of size 4KB From rustompmody at gmail.com Wed Feb 5 00:45:09 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 4 Feb 2014 21:45:09 -0800 (PST) Subject: Finding size of Variable In-Reply-To: <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 11:05:05 AM UTC+5:30, Ayushi Dalmia wrote: > This also doesn't gives the true size. I did the following: > import sys > data=[] > f=open('stopWords.txt','r') > for line in f: > line=line.split() > data.extend(line) > print sys.getsizeof(data) > where stopWords.txt is a file of size 4KB Try getsizeof("".join(data)) General advice: - You have been recommended (by Chris??) that you should use a database - You say you cant use a database (for whatever reason) Now the fact is you NEED database (functionality) How to escape this catch-22 situation? In computer science its called somewhat sardonically "Greenspun's 10th rule" And the best way out is to 1 isolate those aspects of database functionality you need 2 temporarily forget about your original problem and implement the dbms (subset of) DBMS functionality you need 3 Use 2 above to implement 1 From ayushidalmia2604 at gmail.com Wed Feb 5 01:00:44 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Tue, 4 Feb 2014 22:00:44 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: <691fecec-c02a-4b0c-99ee-711c5371abad@googlegroups.com> On Wednesday, February 5, 2014 11:15:09 AM UTC+5:30, Rustom Mody wrote: > On Wednesday, February 5, 2014 11:05:05 AM UTC+5:30, Ayushi Dalmia wrote: > > > This also doesn't gives the true size. I did the following: > > > > > import sys > > > data=[] > > > f=open('stopWords.txt','r') > > > > > for line in f: > > > line=line.split() > > > data.extend(line) > > > > > print sys.getsizeof(data) > > > > > where stopWords.txt is a file of size 4KB > > > > Try getsizeof("".join(data)) > > > > General advice: > > - You have been recommended (by Chris??) that you should use a database > > - You say you cant use a database (for whatever reason) > > > > Now the fact is you NEED database (functionality) > > How to escape this catch-22 situation? > > In computer science its called somewhat sardonically "Greenspun's 10th rule" > > > > And the best way out is to > > > > 1 isolate those aspects of database functionality you need > > 2 temporarily forget about your original problem and implement the dbms > > (subset of) DBMS functionality you need > > 3 Use 2 above to implement 1 Hello Rustum, Thanks for the enlightenment. I did not know about the Greenspun's Tenth rule. It is interesting to know that. However, it is an academic project and not a research one. Hence I donot have the liberty to choose what to work with. Life is easier with databases though, but I am not allowed to use them. Thanks for the tip. I will try to replicate those functionality. From __peter__ at web.de Wed Feb 5 03:27:15 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Feb 2014 09:27:15 +0100 Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <723729ee-8e74-4d65-aa6f-742051a94101@googlegroups.com> Message-ID: Ayushi Dalmia wrote: > On Wednesday, February 5, 2014 12:51:31 AM UTC+5:30, Dave Angel wrote: >> Ayushi Dalmia Wrote in message: >> >> >> >> > >> >> > Where am I going wrong? What are the alternatives I can try? >> >> >> >> You've rejected all the alternatives so far without showing your >> >> code, or even properly specifying your problem. >> >> >> >> To get the "total" size of a list of strings, try (untested): >> >> >> >> a = sys.getsizeof (mylist ) >> >> for item in mylist: >> >> a += sys.getsizeof (item) >> >> >> >> This can be high if some of the strings are interned and get >> >> counted twice. But you're not likely to get closer without some >> >> knowledge of the data objects and where they come >> >> from. >> >> >> >> -- >> >> DaveA > > Hello Dave, > > I just thought that saving others time is better and hence I explained > only the subset of my problem. Here is what I am trying to do: > > I am trying to index the current wikipedia dump without using databases > and create a search engine for Wikipedia documents. Note, I CANNOT USE > DATABASES. My approach: > > I am parsing the wikipedia pages using SAX Parser, and then, I am dumping > the words along with the posting list (a list of doc ids in which the word > is present) into different files after reading 'X' number of pages. Now > these files may have the same word and hence I need to merge them and > write the final index again. Now these final indexes must be of limited > size as I need to be of limited size. This is where I am stuck. I need to > know how to determine the size of content in a variable before I write > into the file. > > Here is the code for my merging: > > def mergeFiles(pathOfFolder, countFile): > listOfWords={} > indexFile={} > topOfFile={} > flag=[0]*countFile > data=defaultdict(list) > heap=[] > countFinalFile=0 > for i in xrange(countFile): > fileName = pathOfFolder+'\index'+str(i)+'.txt.bz2' > indexFile[i]= bz2.BZ2File(fileName, 'rb') > flag[i]=1 > topOfFile[i]=indexFile[i].readline().strip() > listOfWords[i] = topOfFile[i].split(' ') > if listOfWords[i][0] not in heap: > heapq.heappush(heap, listOfWords[i][0]) At this point you have already done it wrong as your heap contains the complete data and you have done a lot of O(N) tests on the heap. This is both slow and consumes a lot of memory. See http://code.activestate.com/recipes/491285-iterator-merge/ for a sane way to merge sorted data from multiple files. Your code becomes (untested) with open("outfile.txt", "wb") as outfile: infiles = [] for i in xrange(countFile): filename = os.path.join(pathOfFolder, 'index'+str(i)+'.txt.bz2') infiles.append(bz2.BZ2File(filename, "rb")) outfile.writelines(imerge(*infiles)) for infile in infiles: infile.close() Once you have your data in a single file you can read from that file and do the postprocessing you mention below. > while any(flag)==1: > temp = heapq.heappop(heap) > for i in xrange(countFile): > if flag[i]==1: > if listOfWords[i][0]==temp: > > //This is where I am stuck. I cannot wait until memory > //error, as I need to do some postprocessing too. try: > data[temp].extend(listOfWords[i][1:]) > except MemoryError: > writeFinalIndex(data, countFinalFile, > pathOfFolder) data=defaultdict(list) > countFinalFile+=1 > > topOfFile[i]=indexFile[i].readline().strip() > if topOfFile[i]=='': > flag[i]=0 > indexFile[i].close() > os.remove(pathOfFolder+'\index'+str(i)+'.txt.bz2') > else: > listOfWords[i] = topOfFile[i].split(' ') > if listOfWords[i][0] not in heap: > heapq.heappush(heap, listOfWords[i][0]) > writeFinalIndex(data, countFinalFile, pathOfFolder) > > countFile is the number of files and writeFileIndex method writes into the > file. From steve+comp.lang.python at pearwood.info Wed Feb 5 06:00:21 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Feb 2014 11:00:21 GMT Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Feb 2014 21:35:05 -0800, Ayushi Dalmia wrote: > On Wednesday, February 5, 2014 12:59:46 AM UTC+5:30, Tim Chase wrote: >> On 2014-02-04 14:21, Dave Angel wrote: >> >> > To get the "total" size of a list of strings, try (untested): >> >> > >> > a = sys.getsizeof (mylist ) >> > for item in mylist: >> > a += sys.getsizeof (item) >> >> >> I always find this sort of accumulation weird (well, at least in >> Python; it's the *only* way in many other languages) and would write >> it as >> >> a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) >> > > This also doesn't gives the true size. I did the following: What do you mean by "true size"? Do you mean the amount of space a certain amount of data will take in memory? With or without the overhead of object headers? Or do you mean how much space it will take when written to disk? You have not been clear what you are trying to measure. If you are dealing with one-byte characters, you can measure the amount of memory they take up (excluding object overhead) by counting the number of characters: 23 one-byte characters requires 23 bytes. Plus the object overhead gives: py> sys.getsizeof('a'*23) 44 44 bytes (23 bytes for the 23 single-byte characters, plus 21 bytes overhead). One thousand such characters takes: py> sys.getsizeof('a'*1000) 1021 If you write such a string to disk, it will take 1000 bytes (or 1KB), unless you use some sort of compression. > import sys > data=[] > f=open('stopWords.txt','r') > > for line in f: > line=line.split() > data.extend(line) > > print sys.getsizeof(data) This will give you the amount of space taken by the list object. It will *not* give you the amount of space taken by the individual strings. A Python list looks like this: | header | array of pointers | The header is of constant or near-constant size; the array depends on the number of items in the list. It may be bigger than the list, e.g. a list with 1000 items might have allocated space for 2000 items. It will never be smaller. getsizeof(list) only counts the direct size of that list, including the array, but not the things which the pointers point at. If you want the total size, you need to count them as well. > where stopWords.txt is a file of size 4KB My guess is that if you split a 4K file into words, then put the words into a list, you'll probably end up with 6-8K in memory. -- Steven From rosuav at gmail.com Wed Feb 5 06:44:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Feb 2014 22:44:47 +1100 Subject: Finding size of Variable In-Reply-To: <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Feb 5, 2014 at 10:00 PM, Steven D'Aprano wrote: >> where stopWords.txt is a file of size 4KB > > My guess is that if you split a 4K file into words, then put the words > into a list, you'll probably end up with 6-8K in memory. I'd guess rather more; Python strings have a fair bit of fixed overhead, so with a whole lot of small strings, it will get more costly. >>> sys.version '3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 16:23:43) [MSC v.1600 32 bit (Intel)]' >>> sys.getsizeof("asdf") 29 "Stop words" tend to be short, rather than long, words, so I'd look at an average of 2-3 letters per word. Assuming they're separated by spaces or newlines, that means there'll be roughly a thousand of them in the file, for about 25K of overhead. A bit less if the words are longer, but still quite a bit. (Byte strings have slightly less overhead, 17 bytes apiece, but still quite a bit.) ChrisA From davea at davea.name Wed Feb 5 08:33:08 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 08:33:08 -0500 (EST) Subject: kivy References: <9260af03-210c-4feb-a267-0b8d75a850bb@googlegroups.com> Message-ID: Rustom Mody Wrote in message: > On Wednesday, February 5, 2014 1:25:43 AM UTC+5:30, bharath wrote: >> please help im just frustrated after writing a long code and seeing that it isn't working.. > > Prior to Kernighan and Ritchie people did tend to write 'a long code' > and then check that its working (or not). After 'The C programming > language' -- which is about 40 years -- starting any programming > enterprise without writing AND CHECKING the equivalent of "Hello > World" is just never done. > > IOW you underestimate how many niggling details both of the system and > of your understanding are checked by that approach > I recall vividly when turnaround for the cross-assembler (remotely located) was typically close to 2 days. One of the projects I did was to write an assembler that built our code locally. And once the hardware existed, I ported the assembler to run on the target directly. Cut typical module assembly time to less than 5 minutes. 1973-1975 -- DaveA From davea at davea.name Wed Feb 5 08:43:34 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 08:43:34 -0500 (EST) Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: Ayushi Dalmia Wrote in message: > On Wednesday, February 5, 2014 12:59:46 AM UTC+5:30, Tim Chase wrote: >> On 2014-02-04 14:21, Dave Angel wrote: >> >> > To get the "total" size of a list of strings, try (untested): >> >> > >> >> > a = sys.getsizeof (mylist ) >> >> > for item in mylist: >> >> > a += sys.getsizeof (item) >> >> >> >> I always find this sort of accumulation weird (well, at least in >> >> Python; it's the *only* way in many other languages) and would write >> >> it as >> >> >> >> a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) >> >> >> >> -tkc > > This also doesn't gives the true size. I did the following: > > import sys > data=[] > f=open('stopWords.txt','r') > > for line in f: > line=line.split() > data.extend(line) > > print sys.getsizeof(data) > Did you actually READ either of my posts or Tim's? For a container, you can't just use getsizeof on the container. a = sys.getsizeof (data) for item in mylist: a += sys.getsizeof (data) print a -- DaveA From ayushidalmia2604 at gmail.com Wed Feb 5 09:33:00 2014 From: ayushidalmia2604 at gmail.com (Ayushi Dalmia) Date: Wed, 5 Feb 2014 06:33:00 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:13:34 PM UTC+5:30, Dave Angel wrote: > Ayushi Dalmia Wrote in message: > > > On Wednesday, February 5, 2014 12:59:46 AM UTC+5:30, Tim Chase wrote: > > >> On 2014-02-04 14:21, Dave Angel wrote: > > >> > > >> > To get the "total" size of a list of strings, try (untested): > > >> > > >> > > > >> > > >> > a = sys.getsizeof (mylist ) > > >> > > >> > for item in mylist: > > >> > > >> > a += sys.getsizeof (item) > > >> > > >> > > >> > > >> I always find this sort of accumulation weird (well, at least in > > >> > > >> Python; it's the *only* way in many other languages) and would write > > >> > > >> it as > > >> > > >> > > >> > > >> a = getsizeof(mylist) + sum(getsizeof(item) for item in mylist) > > >> > > >> > > >> > > >> -tkc > > > > > > This also doesn't gives the true size. I did the following: > > > > > > import sys > > > data=[] > > > f=open('stopWords.txt','r') > > > > > > for line in f: > > > line=line.split() > > > data.extend(line) > > > > > > print sys.getsizeof(data) > > > > > > > Did you actually READ either of my posts or Tim's? For a > > container, you can't just use getsizeof on the container. > > > > > > a = sys.getsizeof (data) > > for item in mylist: > > a += sys.getsizeof (data) > > print a > > > > -- > > DaveA Yes, I did. I now understand how to find the size. From wxjmfauth at gmail.com Wed Feb 5 09:41:43 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Feb 2014 06:41:43 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> Le mercredi 5 f?vrier 2014 00:18:35 UTC+1, Terry Reedy a ?crit?: > On 2/4/2014 10:21 AM, wxjmfauth at gmail.com wrote: > > > > >> I was able to discover that link by opening the page, highlighting the > > >> section header with my mouse, then clicking the pilcrow. That gives > > >> me the anchor link to that section header. > > > > > > Useless and really ugly. > > > > Jim, when you say 'useless', please qualify as 'useless to me'. > > Otherwise, people may think that you mean 'useless to eveyone', and it > > is disrespectful to mislead people that way. I hope you are aware that > > your personal ideas of usefulness to yourself are quite different from > > other peoples' ideas of usefulness to themselves. > > > > I now understand that you consider the FSR useless *to you* because you > > do not care about the bugginess of narrow builds or about the spacious > > of wide builds. You do care about uniformity of character size across > > all strings, and FSR lacks that. You are entitled to make that judgment > > for yourself. You are not entitled to sabotage others by projecting you > > personal judgments onto others. The FSR and pilcrow are definitely > > useful to other people as they judge personal usefulness for themselves. > > > > PS. I agree that the pilcrow appearing and disappearing is not pretty > > when I am not looking to use it. I happen to think that is it tolerable > > because it is sometimes useful. > > > > -- > > Terry Jan Reedy I do not contest the utility of such a feature. I do not see the utility of such a feature, when visiting the Python doc on line. That's all. I lived years without knowing that one could click on a "pilcrow"! --- If you put the FSR on the table. I think I have a very correct vision of what Unicode should be and *is*. (*) I belong to those who know that latin-1 is unusable for more than ten European languages based on latin scripts. Today, one can add German to these. No offense, you are still stuck and living in the ascii world. (The recent byte string discussion was very informative on that subject). Writing that the FSR does not suit my needs seems to me a little bit exagerated. You should have more concerns about something like "ReportLab" than about my (jmf) software. (*) Luckily, that's already the case for the users using serious tools. jmf From breamoreboy at yahoo.co.uk Wed Feb 5 10:22:54 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Feb 2014 15:22:54 +0000 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> Message-ID: On 05/02/2014 14:33, Ayushi Dalmia wrote: Please stop sending double line spaced messages, just follow the instructions here https://wiki.python.org/moin/GoogleGroupsPython to prevent this happening, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ned at nedbatchelder.com Wed Feb 5 10:23:01 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 05 Feb 2014 10:23:01 -0500 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> Message-ID: On 2/5/14 9:41 AM, wxjmfauth at gmail.com wrote: > If you put the FSR on the table. > I think I have a very correct vision of what Unicode > should be and*is*. (*) > I belong to those who know that latin-1 is unusable for > more than ten European languages based on latin scripts. > Today, one can add German to these. > No offense, you are still stuck and living in > the ascii world. (The recent byte string discussion > was very informative on that subject). > > Writing that the FSR does not suit my needs seems to me > a little bit exagerated. You should have more concerns > about something like "ReportLab" than about my (jmf) software. > > (*) Luckily, that's already the case for the users using > serious tools. We've been over this too many times already, and we won't be discussing it with you again. -- Ned Batchelder, http://nedbatchelder.com From breamoreboy at yahoo.co.uk Wed Feb 5 10:45:04 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Feb 2014 15:45:04 +0000 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> Message-ID: On 05/02/2014 14:41, wxjmfauth at gmail.com wrote: Please stop sending double line spaced messages, just follow the instructions here https://wiki.python.org/moin/GoogleGroupsPython to prevent this happening, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From nevetsreleehw at gmail.com Wed Feb 5 12:52:33 2014 From: nevetsreleehw at gmail.com (nevetsreleehw at gmail.com) Date: Wed, 5 Feb 2014 09:52:33 -0800 (PST) Subject: trivial import question In-Reply-To: References: Message-ID: <7821caaa-eff5-41ef-b5ff-dcec85ade3cd@googlegroups.com> The underscore relative to a prfixed abbb. Is to be noted From joshua at landau.ws Wed Feb 5 13:03:30 2014 From: joshua at landau.ws (Joshua Landau) Date: Wed, 5 Feb 2014 18:03:30 +0000 Subject: Calculator Problem In-Reply-To: References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: On 5 February 2014 02:22, Dan Sommers wrote: > On Tue, 04 Feb 2014 19:53:52 -0500, Roy Smith wrote: > > > In article , > > David Hutto wrote: > > > >> Can anyone point out how using an int as a var is possible > > > > one = 42 > > > > (ducking and running) > > int = 42 > > (ducking lower and running faster) globals()["1"] = 42 (limbo, limbo, limbo like me) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Feb 5 13:15:57 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Feb 2014 19:15:57 +0100 Subject: Calculator Problem References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: Joshua Landau wrote: > On 5 February 2014 02:22, Dan Sommers wrote: > >> On Tue, 04 Feb 2014 19:53:52 -0500, Roy Smith wrote: >> >> > In article , >> > David Hutto wrote: >> > >> >> Can anyone point out how using an int as a var is possible >> > >> > one = 42 >> > >> > (ducking and running) >> >> int = 42 >> >> (ducking lower and running faster) > > > globals()["1"] = 42 > > (limbo, limbo, limbo like me) >>> import sys, ctypes >>> ctypes.memmove(id(42), id(1), sys.getsizeof(42)) 37657512 >>> 42 1 Hm... From dihedral88888 at gmail.com Wed Feb 5 13:30:45 2014 From: dihedral88888 at gmail.com (88888 Dihedral) Date: Wed, 5 Feb 2014 10:30:45 -0800 (PST) Subject: Calculator Problem In-Reply-To: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> References: <608a3384-525b-4879-82d2-5a6414827fa7@googlegroups.com> Message-ID: <75a5766f-8877-4605-b278-cf43bd83264e@googlegroups.com> On Monday, February 3, 2014 5:16:44 AM UTC+8, Charlie Winn wrote: > Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this > > > > def Addition(): > > print('Addition: What are two your numbers?') > > 1 = float(input('First Number:')) > > 2 = float(input('Second Number:')) > > print('Your Final Result is:', 1 + 2) > > > > > > def Subtraction(): > > print('Subtraction: What are two your numbers?') > > 3 = float(input('First Number:')) > > 4 = float(input('Second Number:')) > > print('Your Final Result is:', 3 - 4) > > > > > > def Multiplication(): > > print('Multiplication: What are two your numbers?') > > 5 = float(input('First Number:')) > > 6 = float(input('Second Number:')) > > print('Your Final Result is:', 5 * 6) > > > > > > def Division(): > > print('Division: What are your two numbers?') > > 7 = float(input('First Number:')) > > 8 = float(input('Second Number:')) > > print('Your Final Result is:', 7 / 8) > > > > > > > > print('What type of calculation would you like to do?') > > Question = input('(Add, Subtract, Divide or Multiply)') > > if Question.lower().startswith('a'): > > print(Addition()) > > elif Question.lower().startswith('s'): > > print(Subtraction()) > > elif Question.lower().startswith('d'): > > print(Division()) > > elif Question.lower().startswith('m'): > > print(Multiplication()) > > else: > > print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') > > > > while Question == 'test': > > Question() I suggest just get an input string of the valid python expression type first. Then just use exec and _ or eval to get the result. From tavares at fe.up.pt Wed Feb 5 13:41:44 2014 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Wed, 5 Feb 2014 10:41:44 -0800 (PST) Subject: 4th CompIMAGE - Pittsburgh, USA, Sept. 3-5, 2014 Message-ID: Dear Colleague, The 4th CompIMAGE conference (http://jessicaz.me.cmu.edu/CompImage2014) aims to bring together researchers in the area of computational modeling of objects represented in images. Different approaches, such as level set method, deformable models, optimization, geometric modeling, principal component analysis, stochastic methods, machine learning and fuzzy logic and so on will be discussed by the experts to face with problems from different applications, including medicine, biomechanics, biometrics, material science, robotics, surveillance, and defense. The CompIMAGE'14 conference will be held in Pittsburgh, USA, on Sept. 3-5, 2014. The previous CompIMAGE conferences were held in Rome (2012), Buffalo (2010) and Coimbra (2006). CompIMAGE'14 invites submission of high-quality papers on topics including, but not limited to: - Medical/Biological imaging - 2D and 3D reconstruction - Image processing and analysis - Image segmentation - Data interpolation - Registration and acquisition - Objects tracking - Motion and deformation analysis - Shape modeling - Simulation - Scientific data visualization - Biometric person identification - Visual data mining and knowledge discovery - Vision in robotics and automation - Material science - Satellite data Publications The proceedings book will be published by Springer in Lecture Notes in Computer Science (www.springer.com/lncs). The Authors of the best ranked papers will be invited to submit extended versions to the Taylor & Francis journal: Computer Methods in Biomechanics and Biomedical Engineering: Imaging & Visualization (www.tandfonline.com/tciv) - There will be a meeting with the members of the journal editorial board during CompIMAGE'14. Important Dates - March 15, 2014: Paper submissions - April 30, 2014: Notification of acceptance - May 31, 2014: Final camera-ready papers - May 31, 2014: Early Symposium registration (mandatory for authors) - September 3-5, 2014: Conference dates We are looking forward to see you in Pittsburgh next September. Kind regards, Jessica Zhang, Carnegie Mellon University, USA Joao Manuel R.S. Tavares, Universidade do Porto, Portugal (Conference Co-Chairs) PS. For further details please have a look on the conference website at: http://jessicaz.me.cmu.edu/CompImage2014. From wxjmfauth at gmail.com Wed Feb 5 13:58:02 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 5 Feb 2014 10:58:02 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> <4c10aaa4-f542-4ae6-a7dd-803f2748e632@googlegroups.com> Message-ID: Le mercredi 5 f?vrier 2014 16:23:01 UTC+1, Ned Batchelder a ?crit?: > On 2/5/14 9:41 AM, wxjmfauth at gmail.com wrote: > > > If you put the FSR on the table. > > > I think I have a very correct vision of what Unicode > > > should be and*is*. (*) > > > I belong to those who know that latin-1 is unusable for > > > more than ten European languages based on latin scripts. > > > Today, one can add German to these. > > > No offense, you are still stuck and living in > > > the ascii world. (The recent byte string discussion > > > was very informative on that subject). > > > > > > Writing that the FSR does not suit my needs seems to me > > > a little bit exagerated. You should have more concerns > > > about something like "ReportLab" than about my (jmf) software. > > > > > > (*) Luckily, that's already the case for the users using > > > serious tools. > > > > We've been over this too many times already, and we won't be discussing > > it with you again. > > > > -- > > Ned Batchelder, http://nedbatchelder.com I agree. (but I was a little bit provocated) jmf From neng.zhou at gmail.com Wed Feb 5 17:35:24 2014 From: neng.zhou at gmail.com (neng.zhou at gmail.com) Date: Wed, 5 Feb 2014 14:35:24 -0800 (PST) Subject: Picat Stable Version 0.1 Released Message-ID: We are pleased to announce the release of the first stable version of Picat, version 0.1, on picat-lang.org. This version has undergone intensive testing, using a comprehensive unit-test suite and a collection of several hundred programs of over 70,000 lines of code in total. Picat is a simple, and yet powerful, logic-based multi-paradigm programming language aimed for general-purpose applications. Picat is a rule-based language, in which predicates, functions, and actors are defined with pattern-matching rules. Picat incorporates many declarative language features for better productivity of software development, including explicit non-determinism, explicit unification, functions, list comprehensions, constraints, and tabling. Picat also provides imperative language constructs, such as assignments and loops, for programming everyday things. The Picat implementation, which is based on a well-designed virtual machine and incorporates a memory manager that garbage-collects and expands the stacks and data areas when needed, is efficient and scalable. Picat can be used for not only symbolic computations, which is a traditional application domain of declarative languages, but also for scripting and modeling tasks. Example programs for various kinds of domains, ranging from scripting, dynamic programming, constraint solving with CP and SAT, to planning, are available at: http://picat-lang.org/projects.html http://www.hakank.org/picat/ As demonstrated by these examples, Picat offers many advantages over other languages. Compared with functional and scripting languages, the support of explicit unification, explicit non-determinism, tabling, and constraints makes Picat more suitable for symbolic computations. Compared with Prolog, Picat is arguably more expressive and scalable: thanks to the availability of loops and list comprehension, it is not rare to find problems for which Picat requires an order of magnitude fewer lines of code to describe than Prolog, and Picat can be significantly faster than Prolog because pattern-matching facilitates indexing of rules. Picat can be used for any fair purpose, including commercial applications. The C source code is available to registered developers and users free of charge. The project is open to anybody and you are welcome to join, as a developer, a sponsor, a user, or a reviewer. Please contact picat at picat-lang.org. The next version will focus on interoperability with other systems. Please stay tuned. Sincerely, The Picat Team From roegltd at gmail.com Wed Feb 5 18:31:58 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 15:31:58 -0800 (PST) Subject: Python installation/cleanup management Message-ID: <8f6fdbfb-d8d6-48bc-a7dc-a410e165c1a7@googlegroups.com> Hi What is the best way to manage Python isolated from /bin /usr/bin ... installations done via source code compilation on yum/rpm based systems? there are some alternatives i guess could be done: * configure --prefix, then delete * checkinstall * fpm (questionable for python?) * make altinstall and diff fs for pre post changes * diving into rpm spec file ------------------- * any other? main objective is to figure out upgrade or python release test methods done in least painless way. have searched issue but either missed or there is no much comparison of above. Thanks Asaf From zhen.zhang.uoft at gmail.com Wed Feb 5 19:10:16 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Wed, 5 Feb 2014 16:10:16 -0800 (PST) Subject: parse a csv file into a text file Message-ID: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Hi, every one. I am a second year EE student. I just started learning python for my project. I intend to parse a csv file with a format like 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 into a text file like the following Toronto 2503281 Montreal 1620693 Vancouver 578041 I am extracting the 1st and 5th column and save it into a text file. This is what i have so far. [code] import csv file = open('raw.csv') reader = csv.reader(file) f = open('NicelyDone.text','w') for line in reader: f.write("%s %s"%line[1],%line[5]) [/code] This is not working for me, I was able to extract the data from the csv file as line[1],line[5]. (I am able to print it out) But I dont know how to write it to a .text file in the format i wanted. Also, I have to process the first column eg, "Toronto (Ont.)" into "Toronto". I am familiar with the function find(), I assume that i could extract Toronto out of Toronto(Ont.) using "(" as the stopping character, but based on my research , I have no idea how to use it and ask it to return me the string(Toronto). Here is my question: 1:What is the data format for line[1], if it is string how come f.write()does not work. if it is not string, how do i convert it to a string? 2:How do i extract the word Toronto out of Toronto(Ont) into a string form using find() or other methods. My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. So i can use f.write() to write into a file ;) Sorry if my questions sounds too easy or stupid. Thanks ahead Zhen From roegltd at gmail.com Wed Feb 5 19:17:17 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 16:17:17 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Thursday, February 6, 2014 2:10:16 AM UTC+2, Zhen Zhang wrote: > Hi, every one. > Zhen str_t = '3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1' list_t = str_t.split(',') print(list_t) print("split result ", list_t[1], list_t[5]) print(list_t[1].split('"')[1]) From roy at panix.com Wed Feb 5 19:33:00 2014 From: roy at panix.com (Roy Smith) Date: Wed, 05 Feb 2014 19:33:00 -0500 Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: In article <5c268845-003f-4e24-b27a-c89e9fbfcc6c at googlegroups.com>, Zhen Zhang wrote: > [code] > > import csv > file = open('raw.csv') > reader = csv.reader(file) > > f = open('NicelyDone.text','w') > > for line in reader: > f.write("%s %s"%line[1],%line[5]) > > [/code] Are you using Python 2 or 3? > Here is my question: > 1:What is the data format for line[1], That's something you can easily figure out by printing out the intermediate values. Try something like: > for line in reader: > print type(line[1]), repr(line(1)) See if that prints what you expect. > how come f.write() does not work. What does "does not work" mean? What does get written to the file? Or do you get some sort of error? I'm pretty sure I see your error, but I'm trying to lead you to being able to diagnose it yourself :-) From python at mrabarnett.plus.com Wed Feb 5 19:34:57 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 06 Feb 2014 00:34:57 +0000 Subject: parse a csv file into a text file In-Reply-To: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <52F2D8B1.8060309@mrabarnett.plus.com> On 2014-02-06 00:10, Zhen Zhang wrote: > Hi, every one. > > I am a second year EE student. > I just started learning python for my project. > > I intend to parse a csv file with a format like > > 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 > 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 > 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 > 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 > > into a text file like the following > > Toronto 2503281 > Montreal 1620693 > Vancouver 578041 > > I am extracting the 1st and 5th column and save it into a text file. > > This is what i have so far. > > > [code] > > import csv > file = open('raw.csv') > reader = csv.reader(file) > > f = open('NicelyDone.text','w') > > for line in reader: > f.write("%s %s"%line[1],%line[5]) > > [/code] > > This is not working for me, I was able to extract the data from the csv file as line[1],line[5]. (I am able to print it out) > But I dont know how to write it to a .text file in the format i wanted. > % is an operator. When used with a format string on its left, its arguments go on its right. In the general case, those arguments should be put in a tuple, although if there's only one argument and it's not a tuple, you can write just that argument: f.write("%s %s" % (line[1], line[5])) > Also, I have to process the first column eg, "Toronto (Ont.)" into "Toronto". > I am familiar with the function find(), I assume that i could extract Toronto out of Toronto(Ont.) using "(" as the stopping character, > but based on my research , I have no idea how to use it and ask it to return me the string(Toronto). > Use find to tell you the index of the "(" (if there isn't one then it'll return -1) and then slice the string to get the part preceding it. Another way is to use the "partition" method. Also, have a look at the "strip"/"lstrip"/"rstrip" methods. > Here is my question: > 1:What is the data format for line[1], if it is string how come f.write()does not work. if it is not string, how do i convert it to a string? > 2:How do i extract the word Toronto out of Toronto(Ont) into a string form using find() or other methods. > > My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. > So i can use f.write() to write into a file ;) > > Sorry if my questions sounds too easy or stupid. > > Thanks ahead > > Zhen > From python.list at tim.thechases.com Wed Feb 5 19:46:04 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 5 Feb 2014 18:46:04 -0600 Subject: parse a csv file into a text file In-Reply-To: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <20140205184604.37046227@bigbox.christie.dr> On 2014-02-05 16:10, Zhen Zhang wrote: > import csv > file = open('raw.csv') Asaf recommended using string methods to split the file. Keep doing what you're doing (using the csv module), as it attends to a lot of edge-cases that will trip you up otherwise. I learned this the hard way several years into my Python career. :-) > reader = csv.reader(file) > > f = open('NicelyDone.text','w') > > for line in reader: > f.write("%s %s"%line[1],%line[5]) Here, I'd start by naming the pieces that you get, so do for line in reader: location = line[1] value = line[5] > Also, I have to process the first column eg, "Toronto (Ont.)" into > "Toronto". I am familiar with the function find(), I assume that i > could extract Toronto out of Toronto(Ont.) using "(" as the > stopping character, but based on my research , I have no idea how > to use it and ask it to return me the string(Toronto). You can use the .split() method to split a string, so you could do something like if '(' in location: bits = location.split('(') # at this point, bits = ['Toronto ', 'Ont.)'] location = bits[0].strip() # also strip it to remove whitespace > 1:What is the data format for line[1], if it is string how come > f.write()does not work. if it is not string, how do i convert it to > a string? The problem is not that "it is not a string" but that you passing multiple parameters, the second of which is invalid Python because it has an extra percent-sign. First create the one string that you want to output: output = "%s %s\n" % (location, bits) and then write it out to the file: f.write(output) rather than trying to do it all in one pass. -tkc From breamoreboy at yahoo.co.uk Wed Feb 5 19:50:57 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Feb 2014 00:50:57 +0000 Subject: parse a csv file into a text file In-Reply-To: <20140205184604.37046227@bigbox.christie.dr> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <20140205184604.37046227@bigbox.christie.dr> Message-ID: On 06/02/2014 00:46, Tim Chase wrote: > On 2014-02-05 16:10, Zhen Zhang wrote: >> import csv >> file = open('raw.csv') > > Asaf recommended using string methods to split the file. Keep doing > what you're doing (using the csv module), as it attends to a lot of > edge-cases that will trip you up otherwise. I learned this the hard > way several years into my Python career. :-) +1 -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Wed Feb 5 19:57:26 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 19:57:26 -0500 (EST) Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: Zhen Zhang Wrote in message: > Hi, every one. > > I am a second year EE student. > I just started learning python for my project. > > I intend to parse a csv file with a format like > > 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 > 2466023,"Montr??al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 > 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 > 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 > > into a text file like the following > > Toronto 2503281 > Montreal 1620693 > Vancouver 578041 > > I am extracting the 1st and 5th column and save it into a text file. Looks to me like columns 1 and 6. > > This is what i have so far. > > > [code] > > import csv > file = open('raw.csv') > reader = csv.reader(file) > > f = open('NicelyDone.text','w') > > for line in reader: > f.write("%s %s"%line[1],%line[5]) Why not use print to file f? The approach for redirection is different between python 2 and 3, and you neglected to say which you're using. > > > My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. And don't forget the "\n" at end of line. > So i can use f.write() to write into a file ;) Or use print, which defaults to adding in a newline. > Sorry if my questions sounds too easy or stupid. > Not in the least. > > -- DaveA From roegltd at gmail.com Wed Feb 5 20:19:00 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 17:19:00 -0800 (PST) Subject: Python installation/cleanup management In-Reply-To: <8f6fdbfb-d8d6-48bc-a7dc-a410e165c1a7@googlegroups.com> References: <8f6fdbfb-d8d6-48bc-a7dc-a410e165c1a7@googlegroups.com> Message-ID: On Thursday, February 6, 2014 1:31:58 AM UTC+2, Asaf Las wrote: > > Asaf Epel repository provides paco for CentOS. Guess RH does same. paco x86_64 2.0.9-6.el6 (yet there are couple of other tools based on interception of copied files during make install) From roegltd at gmail.com Wed Feb 5 20:20:14 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 17:20:14 -0800 (PST) Subject: Python installation/cleanup management In-Reply-To: References: <8f6fdbfb-d8d6-48bc-a7dc-a410e165c1a7@googlegroups.com> Message-ID: On Thursday, February 6, 2014 3:19:00 AM UTC+2, Asaf Las wrote: > On Thursday, February 6, 2014 1:31:58 AM UTC+2, Asaf Las wrote: so far smallest footprint one: http://my.opera.com/ruario/blog/2012/02/15/tracking-software-that-you-have-compiled-locally From daveandem2000 at gmail.com Wed Feb 5 21:21:29 2014 From: daveandem2000 at gmail.com (dave em) Date: Wed, 5 Feb 2014 18:21:29 -0800 (PST) Subject: Help with TypeError: Can't convert 'list' object to str implicitly Message-ID: <6d3d99f8-637f-4249-a696-ab856b1b8682@googlegroups.com> Hello, Background. My 11 y/o son and I have taken on the task to learn python and work our way through the http://inventwithpython.com/chapters/ book. - We are currently on Chapter 9 and trying to modify the hangman program. - the first challenge was to modify the word list into a dictionary. So we changed our words variable into a dictionary -- I believe we did this correctly. - But we somehow broke the game. All of the words are only two letters and the program crashes on exit with the following error. Traceback (most recent call last): File "/media/.../Python/hangman.py", line 155, in print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"') TypeError: Can't convert 'list' object to str implicitly -I can't see why this wouldn't work. By definition isn't this the cast: 1) len(correctLetters) //returns the lengths of the variable as an int 2) str(len(correctLetters)) // converts the integer into a string. Applicable code is here: # Check if player has guessed too many times and lost if len(missedLetters) == len(HANGMANPICS) - 1: displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord) print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"') gameIsDone = True Any help to get us past this error message is most appreciated. Thanks in advance, Dave From daveandem2000 at gmail.com Wed Feb 5 21:49:19 2014 From: daveandem2000 at gmail.com (dave em) Date: Wed, 5 Feb 2014 18:49:19 -0800 (PST) Subject: [Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly In-Reply-To: <6d3d99f8-637f-4249-a696-ab856b1b8682@googlegroups.com> References: <6d3d99f8-637f-4249-a696-ab856b1b8682@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:21:29 PM UTC-7, dave em wrote: > Hello, > > > > Background. My 11 y/o son and I have taken on the task to learn python and work our way through the http://inventwithpython.com/chapters/ book. > > - We are currently on Chapter 9 and trying to modify the hangman program. > > > > - the first challenge was to modify the word list into a dictionary. So we changed our words variable into a dictionary > > -- I believe we did this correctly. > > > > - But we somehow broke the game. All of the words are only two letters and the program crashes on exit with the following error. > > > > Traceback (most recent call last): > > File "/media/.../Python/hangman.py", line 155, in > > print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"') > > TypeError: Can't convert 'list' object to str implicitly > > > > -I can't see why this wouldn't work. By definition isn't this the cast: > > > > 1) len(correctLetters) //returns the lengths of the variable as an int > > 2) str(len(correctLetters)) // converts the integer into a string. > > > > Applicable code is here: > > # Check if player has guessed too many times and lost > > if len(missedLetters) == len(HANGMANPICS) - 1: > > displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord) > > print('You have run out of guesses! \n After ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"') > > gameIsDone = True > > > > Any help to get us past this error message is most appreciated. > > > > Thanks in advance, > > Dave Fixed the error and am now onto the next issue. Solution was to return a list (I think) and then break out the components of the list and put in the variable. Here is how we did it: secretWord = getRandomWord(words) print('The secretWord is ' + str(secretWord[0])) print('The secretKey is ' + str(secretWord[1])) #Change secretWord from a list to a str secretWord = secretWord[1] def getRandomWord(wordDict): # This function returns a random string from the passed dictionary of lists of strings, and the key also. # First, randomly select a key from the dictionary: wordKey = random.choice(list(wordDict.keys())) print('The wordKey is ' + wordKey) # Second, randomly select a word from the key's list in the dictionary: wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) print('The wordIndex is ' + str(wordIndex)) print('The word is ' + wordDict[wordKey][wordIndex]) return [wordDict[wordKey][wordIndex], wordKey] Cheers, Dave From tjreedy at udel.edu Wed Feb 5 22:01:06 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Feb 2014 22:01:06 -0500 Subject: parse a csv file into a text file In-Reply-To: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On 2/5/2014 7:10 PM, Zhen Zhang wrote: > Hi, every one. > > I am a second year EE student. > I just started learning python for my project. > > I intend to parse a csv file with a format like > > 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 > 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 > 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 > 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 > > into a text file like the following > > Toronto 2503281 > Montreal 1620693 > Vancouver 578041 > > I am extracting the 1st and 5th column and save it into a text file. > > This is what i have so far. > > > [code] > > import csv > file = open('raw.csv') > reader = csv.reader(file) > > f = open('NicelyDone.text','w') > > for line in reader: > f.write("%s %s"%line[1],%line[5]) f.write("%s %s\n" % (line[1], line[5])) should do better. > > [/code] > > This is not working for me, Always say how something is not working. If there is a traceback, cut and paste after reading it carefully. I was able to extract the data from the csv file as line[1],line[5]. (I am able to print it out) > But I dont know how to write it to a .text file in the format i wanted. > > Also, I have to process the first column eg, "Toronto (Ont.)" into "Toronto". > I am familiar with the function find(), I assume that i could extract Toronto out of Toronto(Ont.) using "(" as the stopping character, > but based on my research , I have no idea how to use it and ask it to return me the string(Toronto). > > Here is my question: > 1:What is the data format for line[1], if it is string how come f.write()does not work. if it is not string, how do i convert it to a string? > 2:How do i extract the word Toronto out of Toronto(Ont) into a string form using find() or other methods. > > My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. > So i can use f.write() to write into a file ;) > > Sorry if my questions sounds too easy or stupid. > > Thanks ahead > > Zhen > -- Terry Jan Reedy From msustik at gmail.com Wed Feb 5 22:02:09 2014 From: msustik at gmail.com (msustik at gmail.com) Date: Wed, 5 Feb 2014 19:02:09 -0800 (PST) Subject: how to reduce bugs due to incorrect indentation Message-ID: I had a bug in a Python script recently. The code in question was something along the lines of: if a == 1: x = y else: x = z y = z + y z = z + 1 While editing this file I accidentally pushed TAB on the line with 'y = z + y'. My changes were elsewhere and I did not notice the above one line change when I looked at the diffs before commit. I should have noticed it... It was rare that a was 1 and therefore the problem did not show up for a while. (I know I should have had tests exercising all cases...) When the bug showed up, it was kind of difficult to remember what was the original intent. Fortunately, looking at old versions allowed me to find the problem commit and the bug. Any suggestion on how to avoid this type of error in the future? Thanks! From dan at tombstonezero.net Wed Feb 5 22:08:31 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 6 Feb 2014 03:08:31 +0000 (UTC) Subject: how to reduce bugs due to incorrect indentation References: Message-ID: On Wed, 05 Feb 2014 19:02:09 -0800, msustik wrote: > My changes were elsewhere and I did not notice the above one line > change when I looked at the diffs before commit. I should have noticed > it... > > It was rare that a was 1 and therefore the problem did not show up for > a while. (I know I should have had tests exercising all cases...) > > When the bug showed up, it was kind of difficult to remember what was > the original intent. Fortunately, looking at old versions allowed me > to find the problem commit and the bug. > > Any suggestion on how to avoid this type of error in the future? I think you just mentioned the best suggestions: (a) have a good collection of unit tests (where "good" means data and branch coverage), and (b) look carefully, or have someone else look carefully, at every commit. Dan From roegltd at gmail.com Wed Feb 5 22:59:30 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 19:59:30 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <6a865ea9-c3e3-486a-a43e-31a28b4ac3a6@googlegroups.com> On Thursday, February 6, 2014 2:46:04 AM UTC+2, Tim Chase wrote: > On 2014-02-05 16:10, Zhen Zhang wrote: > Asaf recommended using string methods to split the file. Keep doing > what you're doing (using the csv module), as it attends to a lot of > edge-cases that will trip you up otherwise. I learned this the hard > way several years into my Python career. :-) i did not recommend anything :-) import io import csv str_t = '''3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 ''' file_t = io.StringIO(str_t) csv_t = csv.reader(file_t, delimiter = ',') for row in csv_t: print("split result ", row[1].strip('"'), row[5]) From python.list at tim.thechases.com Wed Feb 5 23:09:52 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 5 Feb 2014 22:09:52 -0600 Subject: parse a csv file into a text file In-Reply-To: <6a865ea9-c3e3-486a-a43e-31a28b4ac3a6@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <6a865ea9-c3e3-486a-a43e-31a28b4ac3a6@googlegroups.com> Message-ID: <20140205220952.2e6b6e74@bigbox.christie.dr> On 2014-02-05 19:59, Asaf Las wrote: > On Thursday, February 6, 2014 2:46:04 AM UTC+2, Tim Chase wrote: > > On 2014-02-05 16:10, Zhen Zhang wrote: > > Asaf recommended using string methods to split the file. Keep > > doing what you're doing (using the csv module), as it attends to > > a lot of edge-cases that will trip you up otherwise. I learned > > this the hard way several years into my Python career. :-) > > i did not recommend anything :-) From your code, list_t = str_t.split(',') It might have been a short-hand for obtaining the results of a CSV row, but it might be better written something like list_t = csv.reader([str_t]) -tkc From roegltd at gmail.com Wed Feb 5 23:17:40 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 20:17:40 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <6a865ea9-c3e3-486a-a43e-31a28b4ac3a6@googlegroups.com> Message-ID: On Thursday, February 6, 2014 6:09:52 AM UTC+2, Tim Chase wrote: > On 2014-02-05 19:59, Asaf Las wrote: > From your code, > list_t = str_t.split(',') > It might have been a short-hand for obtaining the results of a CSV > row, but it might be better written something like > list_t = csv.reader([str_t]) > -tkc i was too fast to reply. you are correct! /Asaf From rosuav at gmail.com Wed Feb 5 23:47:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Feb 2014 15:47:14 +1100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: On Thu, Feb 6, 2014 at 2:08 PM, Dan Sommers wrote: > On Wed, 05 Feb 2014 19:02:09 -0800, msustik wrote: > >> My changes were elsewhere and I did not notice the above one line >> change when I looked at the diffs before commit. I should have noticed >> it... >> >> It was rare that a was 1 and therefore the problem did not show up for >> a while. (I know I should have had tests exercising all cases...) >> >> When the bug showed up, it was kind of difficult to remember what was >> the original intent. Fortunately, looking at old versions allowed me >> to find the problem commit and the bug. >> >> Any suggestion on how to avoid this type of error in the future? > > I think you just mentioned the best suggestions: (a) have a good > collection of unit tests (where "good" means data and branch coverage), > and (b) look carefully, or have someone else look carefully, at every > commit. Yep, I'd agree with that. Additionally, a habit of small and conceptual commits helps hugely, even if you don't look at them too carefully as they go through; get familiar with 'git gui blame' or whatever the equivalent is for your system (or just browsing through 'gitk filename.py' or equiv) and you can go back in time to pin down bugs. I had to fight heavily to get my boss to understand this, because he said he _never_ went back through the repo's history; meanwhile, I was doing so frequently, and knowing exactly what code was changed, when, and why. His attitude to bugs was "don't make any, and you're a bad programmer if you do". My attitude to bugs was, and is, "be honest with yourself, you will make them, so design your systems to handle that". When your commits are small and tidy, you can often find bugs really REALLY easily just by looking at the commit that changed some particular line. With gitk, I'll often make a dummy edit to a line, then highlight the red "this line deleted" line in the uncommitted changes display, right-click, "Show origin of this line". Alternatively, 'git blame' or other annotation can work, but I generally find that annotating a whole file is overkill and trying to ask for annotations of one small section is tedious. But whichever way you do it, you should be able to VERY quickly go from "Hmm, I wonder why this is indented like this?" to "Here's the commit that made it like that", and then you can easily decide whether it was right or not. Of course, your commit messages have to be useful. I can't honestly say my own commit messages are perfect, but at least they're not like these: https://github.com/douglascrockford/JSLint/commits/master Note to future readers: That link will take you to the most recent commits on that repo. It may be (it may be!) that, by the time you look at it, he'll have changed his practice and started writing exemplary messages. If so, just page back through the history and find how it looked in 2014. :) ChrisA From roegltd at gmail.com Thu Feb 6 00:23:29 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 5 Feb 2014 21:23:29 -0800 (PST) Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: <2b9a24ea-3cc9-4c7a-b37c-b7521f6d2735@googlegroups.com> On Thursday, February 6, 2014 5:02:09 AM UTC+2, msu... at gmail.com wrote: > I had a bug in a Python script recently. The code in question was > something along the lines of: > if a == 1: > x = y > else: > x = z > y = z + y > z = z + 1 > > While editing this file I accidentally pushed TAB on the line with > 'y = z + y'. > My changes were elsewhere and I did not notice the above one line > change when I looked at the diffs before commit. I should have noticed > it... > > It was rare that a was 1 and therefore the problem did not show up > for a while. (I know I should have had tests exercising all cases...) > When the bug showed up, it was kind of difficult to remember what > was the original intent. Fortunately, looking at old versions allowed > me to find the problem commit and the bug. > Any suggestion on how to avoid this type of error in the future? > Thanks! I see. The only solution to mimic C style curly brackets comes to my mind is to use hash to mark start and stop of your block as: if a == 1:# x = y # else:# x = z # y = z + y z = z + 1 and PEP ... Nulla poena sine lege :-) /Asaf From davea at davea.name Thu Feb 6 01:08:38 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 01:08:38 -0500 (EST) Subject: [Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly References: <6d3d99f8-637f-4249-a696-ab856b1b8682@googlegroups.com> Message-ID: dave em Wrote in message: > > > Fixed the error and am now onto the next issue. > > Solution was to return a list (I think) and then break out the components of the list and put in the variable. Here is how we did it: > > secretWord = getRandomWord(words) > print('The secretWord is ' + str(secretWord[0])) > print('The secretKey is ' + str(secretWord[1])) > #Change secretWord from a list to a str > secretWord = secretWord[1] > > > def getRandomWord(wordDict): > # This function returns a random string from the passed dictionary of lists of strings, and the key also. > # First, randomly select a key from the dictionary: > wordKey = random.choice(list(wordDict.keys())) > print('The wordKey is ' + wordKey) > # Second, randomly select a word from the key's list in the dictionary: > wordIndex = random.randint(0, len(wordDict[wordKey]) - 1) > print('The wordIndex is ' + str(wordIndex)) > print('The word is ' + wordDict[wordKey][wordIndex]) > return [wordDict[wordKey][wordIndex], wordKey] > Much better is to change the name of the function to match what it's really doing. But I'll leave that to you. Make the return logic look like: word = [wordDict[wordKey][wordIndex] return word, wordKey Then the calling logic should be: secretWord, key = getRandomSomethings (words) print('The secretWord is ' + secretWord print('The secretKey is ' + key This way a name is not used for contradictory purposes. -- DaveA From rosuav at gmail.com Thu Feb 6 01:23:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Feb 2014 17:23:27 +1100 Subject: [Solved]Re: Help with TypeError: Can't convert 'list' object to str implicitly In-Reply-To: References: <6d3d99f8-637f-4249-a696-ab856b1b8682@googlegroups.com> Message-ID: On Thu, Feb 6, 2014 at 5:08 PM, Dave Angel wrote: > print('The secretWord is ' + secretWord > print('The secretKey is ' + key )) http://xkcd.com/859/ ChrisA From zhen.zhang.uoft at gmail.com Thu Feb 6 02:52:43 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Wed, 5 Feb 2014 23:52:43 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:33:00 PM UTC-5, Roy Smith wrote: > In article <5c268845-003f-4e24-b27a-c89e9fbfcc6c at googlegroups.com>, > > Zhen Zhang wrote: > > > > > [code] > > > > > > import csv > > > file = open('raw.csv') > > > reader = csv.reader(file) > > > > > > f = open('NicelyDone.text','w') > > > > > > for line in reader: > > > f.write("%s %s"%line[1],%line[5]) > > > > > > [/code] > > > > Are you using Python 2 or 3? > > > > > Here is my question: > > > 1:What is the data format for line[1], > > > > That's something you can easily figure out by printing out the > > intermediate values. Try something like: > > > > > for line in reader: > > > print type(line[1]), repr(line(1)) > > > > See if that prints what you expect. > > > > > how come f.write() does not work. > > > > What does "does not work" mean? What does get written to the file? Or > > do you get some sort of error? > > > > I'm pretty sure I see your error, but I'm trying to lead you to being > > able to diagnose it yourself :-) Hi Roy , Thank you so much for the reply, I am currenly running python 2.7 i run the print type(line[1]), repr(line(1)) It tells me that 'list object is not callable It seems the entire line is a data type of list instead of a data type of "line" as i thought. The line[1] is a string element of list after all. f.write("%s %s %s" %(output,location,output))works great, as MRAB mentioned, I have to do write it in term of tuples. This is the code I am currently using for line in reader: location ="%s"%(line[1]) if '(' in location: # at this point, bits = ['Toronto ', 'Ont.)'] bits = location.split('(') location = bits[0].strip() output = "%s %s\n" %(location,line[5]) f.write("%s" %(output)) It extracts desired information into a text file as i wanted. however, the python program gives me a Error after the execution. location="%s"%(line[1]) IndexError: list index out of range I failed to figure out why. From zhen.zhang.uoft at gmail.com Thu Feb 6 02:56:51 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Wed, 5 Feb 2014 23:56:51 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:17:17 PM UTC-5, Asaf Las wrote: > On Thursday, February 6, 2014 2:10:16 AM UTC+2, Zhen Zhang wrote: > > > Hi, every one. > > > Zhen > > str_t = '3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1' > > list_t = str_t.split(',') > > print(list_t) > > print("split result ", list_t[1], list_t[5]) > > print(list_t[1].split('"')[1]) Thanks for the reply, I did not get the line str_t = '3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1' I am processing a entire file not a line, so should i do str_t=line? maybe list_t = str_t.split(',') I think you are trying to spit a line into list. but the line is already a list format right? that is why it allows me to do something like line[1]. but I am not sure. From wilsonmonde at gmail.com Thu Feb 6 03:01:30 2014 From: wilsonmonde at gmail.com (wilsonmonde at gmail.com) Date: Thu, 6 Feb 2014 00:01:30 -0800 (PST) Subject: TypeError: 'list' object is not callable Message-ID: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> import csv date1 = [] open = [] high = [] low = [] close = [] data = [] with open("C:/Documents and Settings/wilson/My Documents/Downloads/execution.csv", "rb") as csvfile: fastreader = csv.reader(csvfile, delimiter = ",", skipinitialspace=True) count = 0 for row in fastreader: date1.append(row[0]) count = count + 1 TypeError: 'list' object is not callable From zhen.zhang.uoft at gmail.com Thu Feb 6 03:01:35 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Thu, 6 Feb 2014 00:01:35 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <4cb12232-5677-442a-8ffb-5af3ea05e203@googlegroups.com> On Wednesday, February 5, 2014 7:34:57 PM UTC-5, MRAB wrote: > On 2014-02-06 00:10, Zhen Zhang wrote: > > > Hi, every one. > > > > > > I am a second year EE student. > > > I just started learning python for my project. > > > > > > I intend to parse a csv file with a format like > > > > > > 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 > > > 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 > > > 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 > > > 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 > > > > > > into a text file like the following > > > > > > Toronto 2503281 > > > Montreal 1620693 > > > Vancouver 578041 > > > > > > I am extracting the 1st and 5th column and save it into a text file. > > > > > > This is what i have so far. > > > > > > > > > [code] > > > > > > import csv > > > file = open('raw.csv') > > > reader = csv.reader(file) > > > > > > f = open('NicelyDone.text','w') > > > > > > for line in reader: > > > f.write("%s %s"%line[1],%line[5]) > > > > > > [/code] > > > > > > This is not working for me, I was able to extract the data from the csv file as line[1],line[5]. (I am able to print it out) > > > But I dont know how to write it to a .text file in the format i wanted. > > > > > % is an operator. When used with a format string on its left, its > > arguments go on its right. In the general case, those arguments should > > be put in a tuple, although if there's only one argument and it's not a > > tuple, you can write just that argument: > > > > f.write("%s %s" % (line[1], line[5])) > > > > > Also, I have to process the first column eg, "Toronto (Ont.)" into "Toronto". > > > I am familiar with the function find(), I assume that i could extract Toronto out of Toronto(Ont.) using "(" as the stopping character, > > > but based on my research , I have no idea how to use it and ask it to return me the string(Toronto). > > > > > Use find to tell you the index of the "(" (if there isn't one then > > it'll return -1) and then slice the string to get the part preceding it. > > > > Another way is to use the "partition" method. > > > > Also, have a look at the "strip"/"lstrip"/"rstrip" methods. > > > > > Here is my question: > > > 1:What is the data format for line[1], if it is string how come f.write()does not work. if it is not string, how do i convert it to a string? > > > 2:How do i extract the word Toronto out of Toronto(Ont) into a string form using find() or other methods. > > > > > > My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. > > > So i can use f.write() to write into a file ;) > > > > > > Sorry if my questions sounds too easy or stupid. > > > > > > Thanks ahead > > > > > > Zhen > > > Thanks for the reply, especially the tuple parts, I was not familiar with this data format, but i guess i should :) From tjreedy at udel.edu Thu Feb 6 03:09:01 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Feb 2014 03:09:01 -0500 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: On 2/5/2014 10:02 PM, msustik at gmail.com wrote: > if a == 1: > x = y > else: > x = z > y = z + y > z = z + 1 > > While editing this file I accidentally pushed TAB on the line with 'y = z + y'. In this particular case, remove the indentation with x = y if a == 1 else z and indenting the next line is syntax error. -- Terry Jan Reedy From zhen.zhang.uoft at gmail.com Thu Feb 6 03:07:29 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Thu, 6 Feb 2014 00:07:29 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:46:04 PM UTC-5, Tim Chase wrote: > On 2014-02-05 16:10, Zhen Zhang wrote: > > > import csv > > > file = open('raw.csv') > > > > Asaf recommended using string methods to split the file. Keep doing > > what you're doing (using the csv module), as it attends to a lot of > > edge-cases that will trip you up otherwise. I learned this the hard > > way several years into my Python career. :-) > > > > > reader = csv.reader(file) > > > > > > f = open('NicelyDone.text','w') > > > > > > for line in reader: > > > f.write("%s %s"%line[1],%line[5]) > > > > Here, I'd start by naming the pieces that you get, so do > > > > for line in reader: > > location = line[1] > > value = line[5] > > > > > Also, I have to process the first column eg, "Toronto (Ont.)" into > > > "Toronto". I am familiar with the function find(), I assume that i > > > could extract Toronto out of Toronto(Ont.) using "(" as the > > > stopping character, but based on my research , I have no idea how > > > to use it and ask it to return me the string(Toronto). > > > > You can use the .split() method to split a string, so you could do > > something like > > > > if '(' in location: > > bits = location.split('(') > > # at this point, bits = ['Toronto ', 'Ont.)'] > > location = bits[0].strip() # also strip it to remove whitespace > > > > > 1:What is the data format for line[1], if it is string how come > > > f.write()does not work. if it is not string, how do i convert it to > > > a string? > > > > The problem is not that "it is not a string" but that you passing > > multiple parameters, the second of which is invalid Python because it > > has an extra percent-sign. First create the one string that you > > want to output: > > > > output = "%s %s\n" % (location, bits) > > > > and then write it out to the file: > > > > f.write(output) > > > > rather than trying to do it all in one pass. > > > > -tkc Hi Tim, Thanks for the reply, Does the split make a list or tuple? also, when i do location=line[1], it gives me a error even though the program did run correctly and output the correct file. location=line[1] IndexError: list index out of range when i do print line[1], there is no error. it is really strange From zhen.zhang.uoft at gmail.com Thu Feb 6 03:12:37 2014 From: zhen.zhang.uoft at gmail.com (Zhen Zhang) Date: Thu, 6 Feb 2014 00:12:37 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Wednesday, February 5, 2014 7:57:26 PM UTC-5, Dave Angel wrote: > Zhen Zhang Wrote in message: > > > Hi, every one. > > > > > > I am a second year EE student. > > > I just started learning python for my project. > > > > > > I intend to parse a csv file with a format like > > > > > > 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 > > > 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 > > > 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 > > > 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 > > > > > > into a text file like the following > > > > > > Toronto 2503281 > > > Montreal 1620693 > > > Vancouver 578041 > > > > > > I am extracting the 1st and 5th column and save it into a text file. > > > > Looks to me like columns 1 and 6. > > > > > > > > This is what i have so far. > > > > > > > > > [code] > > > > > > import csv > > > file = open('raw.csv') > > > reader = csv.reader(file) > > > > > > f = open('NicelyDone.text','w') > > > > > > for line in reader: > > > f.write("%s %s"%line[1],%line[5]) > > > > Why not use print to file f? The approach for redirection is > > different between python 2 and 3, and you neglected to say which > > you're using. > > > > > > > > > > > My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted. > > > > And don't forget the "\n" at end of line. > > > > > So i can use f.write() to write into a file ;) > > > > Or use print, which defaults to adding in a newline. > > > > > Sorry if my questions sounds too easy or stupid. > > > > > > > Not in the least. > > > > > > > > > > > > > > -- > > DaveA Hi Dave Thanks for the reply, I am currently running python 2.7. Yes, i thought there must be a print function in python like fprint in C++ that allows you to print into a file directly. But i google about "print string into text file" I got answers using f.write() instead. :) From roegltd at gmail.com Thu Feb 6 03:15:14 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 00:15:14 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <2039ab62-d18a-4127-8fc0-917fdb0fe00a@googlegroups.com> On Thursday, February 6, 2014 9:52:43 AM UTC+2, Zhen Zhang wrote: > On Wednesday, February 5, 2014 7:33:00 PM UTC-5, Roy Smith wrote: > I failed to figure out why. OK, you had to look to what i posted second time. The first one is irrelevant. Note that file was emulated using StringIO. in your case it will be file name. You can grab script below and run directly as python script: <------------------------------------ start of script import io import csv str_t = '''3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 2466023,"Montr?al (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28 ''' file_t = io.StringIO(str_t) csv_t = csv.reader(file_t, delimiter = ',') for row in csv_t: print("split result ", row[1].strip('"').split('(')[0] , row[5]) <----------------------------- end of script Output must be (i got it after run): split result Toronto 2481494 split result Montr?al 1583590 split result Vancouver 545671 split result Richmond Hill 132030 row[1].strip('"').split('(')[0] is City name row[5] is digits at pos 5 wished Both are strings, so save them later into file. Regarding this one - you can split operations as below to see what is happening: row[1] row[1].strip('"') row[1].strip('"').split('(') row[1].strip('"').split('(')[0] Have a nice day /Asaf From __peter__ at web.de Thu Feb 6 03:22:45 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Feb 2014 09:22:45 +0100 Subject: TypeError: 'list' object is not callable References: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> Message-ID: wilsonmonde at gmail.com wrote: > TypeError: 'list' object is not callable Hint: > open = [] [...] > with open(..., "rb") as csvfile: From roegltd at gmail.com Thu Feb 6 03:48:12 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 00:48:12 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: <2039ab62-d18a-4127-8fc0-917fdb0fe00a@googlegroups.com> References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <2039ab62-d18a-4127-8fc0-917fdb0fe00a@googlegroups.com> Message-ID: On Thursday, February 6, 2014 10:15:14 AM UTC+2, Asaf Las wrote: > On Thursday, February 6, 2014 9:52:43 AM UTC+2, Zhen Zhang wrote: > case it will be file name. little correction not a file name - file object, file_t is result from open() as you did in your example From jpiitula at ling.helsinki.fi Thu Feb 6 03:49:59 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 06 Feb 2014 10:49:59 +0200 Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: Zhen Zhang writes: ... > I am currently running python 2.7. > > Yes, i thought there must be a print function in python like fprint > in C++ that allows you to print into a file directly. > > But i google about "print string into text file" I got answers using > f.write() instead. :) Indeed. The first Python hit for me with that query was the tutorial page on I/O in Python 2, and it does exactly that. That page does refer to the spec of the print statement, where you can find the way to redirect the output to a file, but you need to be able to read formal syntax specifications like this: print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]]) The relevant pattern is the second alternative, after the vertical bar, which can be instantiated this way: print >> f, e0, e1 There is one object f with a .write method, and one or more expressions whose values get written using f.write; the effect of an optional comma at end is also specified there. Not tutorial-level. But I use the newer print function even if I have to use 2.7, something like this: from __future__ import print_function f = open("test.txt", "w") print("hello?", "see me?", file=f) f.close() It does a modest amount of formatting: the value of the keyword argument sep is written between the values, and the value of end is written at end. From gary.herron at islandtraining.com Thu Feb 6 03:53:58 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Thu, 06 Feb 2014 00:53:58 -0800 Subject: TypeError: 'list' object is not callable In-Reply-To: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> References: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> Message-ID: <52F34DA6.1070408@islandtraining.com> On 02/06/2014 12:01 AM, wilsonmonde at gmail.com wrote: > import csv > > date1 = [] > open = [] > high = [] > low = [] > close = [] > data = [] > with open("C:/Documents and Settings/wilson/My Documents/Downloads/execution.csv", "rb") as csvfile: > fastreader = csv.reader(csvfile, delimiter = ",", skipinitialspace=True) > count = 0 > for row in fastreader: > date1.append(row[0]) > count = count + 1 > > > TypeError: 'list' object is not callable I'd be glad to help, but I'm not interested in guessing. Pleas take the time to tell us what line produced that error? That is: cut and paste the *full* traceback instead of hiding useful information when you are asking for help. Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From wilsonmonde at gmail.com Thu Feb 6 04:11:13 2014 From: wilsonmonde at gmail.com (wilsonmonde at gmail.com) Date: Thu, 6 Feb 2014 01:11:13 -0800 (PST) Subject: TypeError: 'list' object is not callable In-Reply-To: References: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> Message-ID: <21fdab4b-8b08-4f18-bcd4-678eb04b03ac@googlegroups.com> Peter Otten? 2014?2?6????UTC+8??4?22?45???? > wilsonmonde at gmail.com wrote: > > > > > TypeError: 'list' object is not callable > > > > Hint: > > > > > open = [] > > > > [...] > > > > > with open(..., "rb") as csvfile: i follow in http://www.dyinglovegrape.com/data_analysis/part1/1da3.php still have error what is the correct writing? From roegltd at gmail.com Thu Feb 6 04:24:11 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 01:24:11 -0800 (PST) Subject: TypeError: 'list' object is not callable In-Reply-To: <21fdab4b-8b08-4f18-bcd4-678eb04b03ac@googlegroups.com> References: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> <21fdab4b-8b08-4f18-bcd4-678eb04b03ac@googlegroups.com> Message-ID: <84d210a0-d78b-4aef-b971-78cde85a1254@googlegroups.com> On Thursday, February 6, 2014 11:11:13 AM UTC+2, wilso... at gmail.com wrote: > i follow in > http://www.dyinglovegrape.com/data_analysis/part1/1da3.php > still have error > what is the correct writing? give another name to list 'open' at line 'open= []' change it to dopen or whatever. you make name conflict with builtin function open(). Names can't be used freely. From jpiitula at ling.helsinki.fi Thu Feb 6 04:34:24 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 06 Feb 2014 11:34:24 +0200 Subject: TypeError: 'list' object is not callable References: <38411b43-0f2b-451c-a4ac-1379b5cc8607@googlegroups.com> <21fdab4b-8b08-4f18-bcd4-678eb04b03ac@googlegroups.com> Message-ID: wilsonmonde at gmail.com writes: > Peter Otten wrote: > > wilsonmonde at gmail.com wrote: > > > > > TypeError: 'list' object is not callable > > > > Hint: > > > > > open = [] > > > > [...] > > > > with open(..., "rb") as csvfile: > > i follow in > http://www.dyinglovegrape.com/data_analysis/part1/1da3.php > > still have error > > what is the correct writing? One way: # open = [] with open(..., "rb") as csvfile: Commenting out the assignment statement prevents it from doing the damage before you try to access the original value of open. Another way: with [](..., "rb") as csvfile: This doesn't work any better but it makes the error stand out. Yet another way: avaa = open open = [] with avaa(..., "rb") as csvfile: That is, save the original value of open in another variable, which I here called avaa. The best way is to omit the whole assignment altogether. Were you using the list called open for something? Oh, one more way! with open(..., "rb") as csvfile: ... open = [] That is, only shoot yourself in the foot after the work has been done! Though, really, best not do it at all. The page you referred to, doesn't. From wxjmfauth at gmail.com Thu Feb 6 05:15:01 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 6 Feb 2014 02:15:01 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Le mercredi 5 f?vrier 2014 12:44:47 UTC+1, Chris Angelico a ?crit : > On Wed, Feb 5, 2014 at 10:00 PM, Steven D'Aprano > > wrote: > > >> where stopWords.txt is a file of size 4KB > > > > > > My guess is that if you split a 4K file into words, then put the words > > > into a list, you'll probably end up with 6-8K in memory. > > > > I'd guess rather more; Python strings have a fair bit of fixed > > overhead, so with a whole lot of small strings, it will get more > > costly. > > > > >>> sys.version > > '3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 16:23:43) [MSC v.1600 32 > > bit (Intel)]' > > >>> sys.getsizeof("asdf") > > 29 > > > > "Stop words" tend to be short, rather than long, words, so I'd look at > > an average of 2-3 letters per word. Assuming they're separated by > > spaces or newlines, that means there'll be roughly a thousand of them > > in the file, for about 25K of overhead. A bit less if the words are > > longer, but still quite a bit. (Byte strings have slightly less > > overhead, 17 bytes apiece, but still quite a bit.) > > > > ChrisA >>> sum([sys.getsizeof(c) for c in ['a']]) 26 >>> sum([sys.getsizeof(c) for c in ['a', 'a EURO']]) 68 >>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO']]) 112 >>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO', 'aaa EURO']]) 158 >>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO', 'aaa EURO', 'aaaaaaaaaaaaaaaaaaaa EURO']]) 238 >>> >>> >>> sum([sys.getsizeof(c.encode('utf-32-be')) for c in ['a']]) 21 >>> sum([sys.getsizeof(c.encode('utf-32-be')) for c in ['a', 'a EURO']]) 46 >>> sum([sys.getsizeof(c.encode('utf-32-be')) for c in ['a', 'a EURO', 'aa EURO']]) 75 >>> sum([sys.getsizeof(c.encode('utf-32-be')) for c in ['a', 'a EURO', 'aa EURO', 'aaa EURO']]) 108 >>> sum([sys.getsizeof(c.encode('utf-32-be')) for c in ['a', 'a EURO', 'aa EURO', 'aaa EURO', 'aaaaaaaaaaaaaaaaaaaa EURO']]) 209 >>> >>> >>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO']*3]) 336 >>> sum([sys.getsizeof(c) for c in ['aa EURO aa EURO']*3]) 150 >>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['a', 'a EURO', 'aa EURO']*3]) 261 >>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['aa EURO aa EURO']*3]) 135 >>> jmf From ned at nedbatchelder.com Thu Feb 6 06:10:08 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 06 Feb 2014 06:10:08 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2/6/14 5:15 AM, wxjmfauth at gmail.com wrote: >>>> >>>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO']*3]) > 336 >>>> sum([sys.getsizeof(c) for c in ['aa EURO aa EURO']*3]) > 150 >>>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['a', 'a EURO', 'aa EURO']*3]) > 261 >>>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['aa EURO aa EURO']*3]) > 135 >>>> > > jmf > JMF, we've told you I-don't-know-how-many-times to stop this. Seriously: think hard about what your purpose is in sending these absurd benchmarks. I guarantee you are not accomplishing it. -- Ned Batchelder, http://nedbatchelder.com From davea at davea.name Thu Feb 6 06:35:20 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 06:35:20 -0500 (EST) Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: Zhen Zhang Wrote in message: > > I am currently running python 2.7. > > Yes, i thought there must be a print function in python like fprint in C++ that allows you to print into a file directly. > But i google about "print string into text file" I got answers using f.write() instead. :) > -- > > In python 2.x, Instead of f.write (a + " " + b) you can use print >> f, a, b -- DaveA From davea at davea.name Thu Feb 6 06:53:25 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 06:53:25 -0500 (EST) Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: Dave Angel Wrote in message: > Zhen Zhang Wrote in message: >> > >> I am currently running python 2.7. >> >> Yes, i thought there must be a print function in python like fprint in C++ that allows you to print into a file directly. >> But i google about "print string into text file" I got answers using f.write() instead. :) >> -- >> Oops. Forgot the newline. > In python 2.x, > > Instead of > f.write (a + " " + b) f.write (a + " " + b + "\n") > you can use > print >> f, a, b > print will add in the space and newline, just as it does to sys.stdout. -- DaveA From rustompmody at gmail.com Thu Feb 6 07:23:03 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 04:23:03 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On Tuesday, February 4, 2014 8:51:25 PM UTC+5:30, jmf wrote: > Useless and really ugly. Evidently one can do worse: http://www.pip-installer.org/en/latest/installing.html#requirements From python at mrabarnett.plus.com Thu Feb 6 08:16:37 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 06 Feb 2014 13:16:37 +0000 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <52F38B35.5020301@mrabarnett.plus.com> On 2014-02-06 07:52, Zhen Zhang wrote:> On Wednesday, February 5, 2014 7:33:00 PM UTC-5, Roy Smith wrote: >> In article <5c268845-003f-4e24-b27a-c89e9fbfcc6c at googlegroups.com>, >> Zhen Zhang wrote: >> >> > [code] >> > >> > import csv >> > file = open('raw.csv') >> > reader = csv.reader(file) >> > >> > f = open('NicelyDone.text','w') >> > >> > for line in reader: >> > f.write("%s %s"%line[1],%line[5]) >> > >> > [/code] >> >> Are you using Python 2 or 3? >> >> > Here is my question: >> > 1:What is the data format for line[1], >> >> That's something you can easily figure out by printing out the >> intermediate values. Try something like: >> >> > for line in reader: >> > print type(line[1]), repr(line(1)) >> >> See if that prints what you expect. >> >> > how come f.write() does not work. >> >> What does "does not work" mean? What does get written to the file? >> Or do you get some sort of error? >> >> I'm pretty sure I see your error, but I'm trying to lead you to being >> able to diagnose it yourself :-) > > Hi Roy , > > Thank you so much for the reply, > I am currenly running python 2.7 > > i run the > print type(line[1]), repr(line(1)) > It tells me that 'list object is not callable > "line" is a list and within repr you're using (...) (parentheses) instead of [...] (square brackets). It might be clearer if you call the variable "row" because the CSV reader returns rows, and each row is a list of strings. > It seems the entire line is a data type of list instead of a data > type of "line" as i thought. > > The line[1] is a string element of list after all. > > f.write("%s %s %s" %(output,location,output))works great, > as MRAB mentioned, I have to do write it in term of tuples. > > This is the code I am currently using > > for line in reader: > location ="%s"%(line[1]) > if '(' in location: > # at this point, bits = ['Toronto ', 'Ont.)'] > bits = location.split('(') > location = bits[0].strip() > output = "%s %s\n" %(location,line[5]) > f.write("%s" %(output)) > A 1-tuple (a tuple containing one item) is: (item, ) It's actually the comma that makes it a tuple (except for the 0-tuple "()"); it's just that it's often necessary to wrap it in (...), and people then think it's those that are making it a tuple, but it's not! > It extracts desired information into a text file as i wanted. > however, the python program gives me a Error after the execution. > location="%s"%(line[1]) > IndexError: list index out of range > > I failed to figure out why. > What is the value of "line" at that point? From rustompmody at gmail.com Thu Feb 6 08:20:21 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 05:20:21 -0800 (PST) Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On Thursday, February 6, 2014 6:46:37 PM UTC+5:30, MRAB wrote: > > It's actually the comma that makes it a tuple (except for the 0-tuple > "()"); it's just that it's often necessary to wrap it in (...), and > people then think it's those that are making it a tuple, but it's not! Interesting viewpoint -- didn't know that! From wxjmfauth at gmail.com Thu Feb 6 08:27:41 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 6 Feb 2014 05:27:41 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: <06ee2e8e-e9bb-4392-8092-1b6a443fa071@googlegroups.com> Le jeudi 6 f?vrier 2014 13:23:03 UTC+1, Rustom Mody a ?crit?: > On Tuesday, February 4, 2014 8:51:25 PM UTC+5:30, jmf wrote: > > > > > Useless and really ugly. > > > > Evidently one can do worse: > > > > http://www.pip-installer.org/en/latest/installing.html#requirements or http://cx-freeze.readthedocs.org/en/latest/index.html From cuongpn at gmail.com Thu Feb 6 08:30:54 2014 From: cuongpn at gmail.com (Sam) Date: Thu, 6 Feb 2014 05:30:54 -0800 (PST) Subject: python and matlab Message-ID: is it able to utilize functions written in Python in Matlab? From wxjmfauth at gmail.com Thu Feb 6 08:51:54 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 6 Feb 2014 05:51:54 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> Le jeudi 6 f?vrier 2014 12:10:08 UTC+1, Ned Batchelder a ?crit : > On 2/6/14 5:15 AM, wxjmfauth at gmail.com wrote: > > > > >>>> > > >>>> sum([sys.getsizeof(c) for c in ['a', 'a EURO', 'aa EURO']*3]) > > > 336 > > >>>> sum([sys.getsizeof(c) for c in ['aa EURO aa EURO']*3]) > > > 150 > > >>>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['a', 'a EURO', 'aa EURO']*3]) > > > 261 > > >>>> sum([sys.getsizeof(c.encode('utf-32')) for c in ['aa EURO aa EURO']*3]) > > > 135 > > >>>> > > > > > > jmf > > > > > > > JMF, we've told you I-don't-know-how-many-times to stop this. > > Seriously: think hard about what your purpose is in sending these absurd > > benchmarks. I guarantee you are not accomplishing it. > > > > -- > > Ned Batchelder, http://nedbatchelder.com Sorry, I'm only pointing you may lose memory when working with short strings as it was explained. I really, very really, do not see what is absurd or obsure in: >>> sys.getsizeof('abc' + 'EURO') 46 >>> sys.getsizeof(('abc' + 'EURO').encode('utf-32')) 37 I apologize for the " a EURO" which should have been a real "EURO". No idea, what's happend. jmf From sturla.molden at gmail.com Thu Feb 6 08:55:09 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Thu, 6 Feb 2014 13:55:09 +0000 (UTC) Subject: python and matlab References: Message-ID: <808175426413387625.065823sturla.molden-gmail.com@news.gmane.org> Sam wrote: > is it able to utilize functions written in Python in Matlab? Yes, if you embed the Python interpreter in a MEX-file. From neilc at norwich.edu Thu Feb 6 09:02:31 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 6 Feb 2014 14:02:31 +0000 (UTC) Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On 2014-02-06, Zhen Zhang wrote: > Hi, every one. > > I am a second year EE student. > I just started learning python for my project. > > I intend to parse a csv file with a format like > > 3520005,"Toronto (Ont.)",C > ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1 [...] into a text file like the following > > Toronto 2503281 [...] > This is what i have so far. > > > [code] > > import csv > file = open('raw.csv') You must open the file in binary mode, as that is what the csv module expects in Python 2.7. newline handling can be enscrewed if you forget. file = open('raw.csv', 'b') -- Neil Cerutti From wxjmfauth at gmail.com Thu Feb 6 09:15:51 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 6 Feb 2014 06:15:51 -0800 (PST) Subject: Finding size of Variable In-Reply-To: <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> Message-ID: <806bd38d-27a2-41fd-a456-a85966f0cea3@googlegroups.com> Some mysterious problem with the "euro". Let's take a real "French" char. >>> sys.getsizeof('abc' + '?') 46 >>> sys.getsizeof(('abc' + '?').encode('utf-32')) 37 or a "German" char, ????? >>> sys.getsizeof('abc' + '\N{LATIN CAPITAL LETTER SHARP S}') 46 >>> sys.getsizeof(('abc' + '\N{LATIN CAPITAL LETTER SHARP S}').encode('utf-32')) 37 From cuongpn at gmail.com Thu Feb 6 09:18:36 2014 From: cuongpn at gmail.com (Sam Adams) Date: Thu, 6 Feb 2014 06:18:36 -0800 (PST) Subject: python and matlab In-Reply-To: References: Message-ID: <239c6022-9c8d-48d4-8ddf-cae552ab1e3d@googlegroups.com> On Thursday, February 6, 2014 8:55:09 AM UTC-5, Sturla Molden wrote: > Sam wrote: > > > is it able to utilize functions written in Python in Matlab? > > > > Yes, if you embed the Python interpreter in a MEX-file. Thanks Sturla, could you please explain in more details, I am new to Python :) From invalid at invalid.invalid Thu Feb 6 09:49:54 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 6 Feb 2014 14:49:54 +0000 (UTC) Subject: how to reduce bugs due to incorrect indentation References: Message-ID: On 2014-02-06, msustik at gmail.com wrote: > I had a bug in a Python script recently. The code in question was something along the lines of: > > if a == 1: > x = y > else: > x = z > y = z + y > z = z + 1 > > While editing this file I accidentally pushed TAB on the line > with 'y = z + y'. > > Any suggestion on how to avoid this type of error in the future? The best advice is to pay closer attention to what you're doing. Look at the code while you're editing, not your fingers. Before you commit the change, spend some time looking carefully at it to verify that changes were intentional. -- Grant Edwards grant.b.edwards Yow! I left my WALLET in at the BATHROOM!! gmail.com From rosuav at gmail.com Thu Feb 6 12:23:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 04:23:20 +1100 Subject: [OT] Usage of U+00B6 PILCROW SIGN (was: generator slides review and Python doc (+/- text bug)) In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On Thu, Feb 6, 2014 at 11:23 PM, Rustom Mody wrote: > On Tuesday, February 4, 2014 8:51:25 PM UTC+5:30, jmf wrote: > >> Useless and really ugly. > > Evidently one can do worse: > > http://www.pip-installer.org/en/latest/installing.html#requirements Aside from using a little "chain link" icon rather than a typographer's symbol, that looks exactly the same. How's it worse? ChrisA From breamoreboy at yahoo.co.uk Thu Feb 6 12:40:19 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 06 Feb 2014 17:40:19 +0000 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: On 06/02/2014 14:02, Neil Cerutti wrote: > > You must open the file in binary mode, as that is what the csv > module expects in Python 2.7. newline handling can be enscrewed > if you forget. > > file = open('raw.csv', 'b') > I've never opened a file in binary mode to read with the csv module using any Python version. Where does it state that you must do this? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From python.list at tim.thechases.com Thu Feb 6 12:51:16 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 6 Feb 2014 11:51:16 -0600 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <20140206115116.69553ffe@bigbox.christie.dr> On 2014-02-06 17:40, Mark Lawrence wrote: > On 06/02/2014 14:02, Neil Cerutti wrote: > > > > You must open the file in binary mode, as that is what the csv > > module expects in Python 2.7. newline handling can be enscrewed > > if you forget. > > > > file = open('raw.csv', 'b') > > > > I've never opened a file in binary mode to read with the csv module > using any Python version. Where does it state that you must do > this? While the docs don't currently say anything about it, all the examples at [1] use 'rb' or 'wb' when opening the file. I've long wondered about that. Especially as I've passed non-file objects like lists/iterators to the csv.reader/csv.DictReader and had them work just fine (and would be a little perturbed if they broke). -tkc [1] http://docs.python.org/2/library/csv.html From jeanmichel at sequans.com Thu Feb 6 12:32:13 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 6 Feb 2014 18:32:13 +0100 (CET) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: <2121463586.3290593.1391706773216.JavaMail.root@sequans.com> Message-ID: <1007676733.3292144.1391707932990.JavaMail.root@sequans.com> Greetings, Assuming I have a debian workstation for which I don't have any sudo rights, i n order to be able to install / remove python packages, should I be using virtualenv ? Is it a suited solution ? JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Feb 6 13:05:08 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 06 Feb 2014 18:05:08 +0000 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <52F3CED4.5010802@timgolden.me.uk> On 06/02/2014 17:40, Mark Lawrence wrote: > On 06/02/2014 14:02, Neil Cerutti wrote: >> >> You must open the file in binary mode, as that is what the csv >> module expects in Python 2.7. newline handling can be enscrewed >> if you forget. >> >> file = open('raw.csv', 'b') >> > > I've never opened a file in binary mode to read with the csv module > using any Python version. Where does it state that you must do this? > If you don't, you tend to get interleaved blank lines. (Presumably unless your .csv is using \n-only linefeeds). TJG From jcasale at activenetwerx.com Thu Feb 6 13:24:17 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Thu, 6 Feb 2014 18:24:17 +0000 Subject: Logging from a multiprocess application Message-ID: <40dacd41a28d4c849074455946cfbdca@exch.activenetwerx.com> I have a module that has one operation that benefits greatly from being multiprocessed. Its a console based module and as such I have a stream handler and filter associated to the console, obviously the mp based instances need special handling, so I have been experimenting with a socket server in a thread in order for the remaining application to carry on. How have others tackled this problem? The portion of the code made to use multiprocessing can not be switched to threading as it performs worse than simply serializing each task. Thanks, jlc From neilc at norwich.edu Thu Feb 6 13:34:55 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 6 Feb 2014 18:34:55 +0000 (UTC) Subject: parse a csv file into a text file References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <20140206115116.69553ffe@bigbox.christie.dr> Message-ID: On 2014-02-06, Tim Chase wrote: > On 2014-02-06 17:40, Mark Lawrence wrote: >> On 06/02/2014 14:02, Neil Cerutti wrote: >> > >> > You must open the file in binary mode, as that is what the csv >> > module expects in Python 2.7. newline handling can be enscrewed >> > if you forget. >> > >> > file = open('raw.csv', 'b') >> > >> >> I've never opened a file in binary mode to read with the csv module >> using any Python version. Where does it state that you must do >> this? > > While the docs don't currently say anything about it, all the > examples at [1] use 'rb' or 'wb' when opening the file. I've > long wondered about that. Especially as I've passed non-file > objects like lists/iterators to the csv.reader/csv.DictReader > and had them work just fine (and would be a little perturbed if > they broke). They do actually mention it. From: http://docs.python.org/2/library/csv.html csv.reader(csvfile, dialect='excel', **fmtparams) Return a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called ? file objects and list objects are both suitable. If csvfile is a file object, it must be opened with the ?b? flag on platforms where that makes a difference. So it's stipulated only for file objects on systems where it might make a difference. -- Neil Cerutti From python.list at tim.thechases.com Thu Feb 6 13:49:28 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 6 Feb 2014 12:49:28 -0600 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> Message-ID: <20140206124928.42457043@bigbox.christie.dr> [first, it looks like you're posting via Google Groups which annoyingly double-spaces everything in your reply. It's possible to work around this, but you might want to subscribe via email or an actual newsgroup client. You can read more at https://wiki.python.org/moin/GoogleGroupsPython ] On 2014-02-06 00:07, Zhen Zhang wrote: > Does the split make a list or tuple? In this case, it happens to return a list, which you can check with print type("one two three".split()) However, also in this case, it doesn't matter, since either indexes just fine. > when i do location=line[1], > it gives me a error even though the program did run correctly and > output the correct file. location=line[1] > IndexError: list index out of range Then it looks like you've got a blank line that doesn't actually have data in it, so when it tries index into it, the only thing there is [0], not [1]. As the message suggests :) -tkc From python.list at tim.thechases.com Thu Feb 6 13:51:34 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 6 Feb 2014 12:51:34 -0600 Subject: parse a csv file into a text file In-Reply-To: References: <5c268845-003f-4e24-b27a-c89e9fbfcc6c@googlegroups.com> <20140206115116.69553ffe@bigbox.christie.dr> Message-ID: <20140206125134.61a7636f@bigbox.christie.dr> On 2014-02-06 18:34, Neil Cerutti wrote: > They do actually mention it. > > From: http://docs.python.org/2/library/csv.html > > If csvfile is a file object, it must be opened with > the ?b? flag on platforms where that makes a difference. > > So it's stipulated only for file objects on systems where it > might make a difference. Ah, I *knew* I'd read that somewhere but my searches in firefox (for "binary", "rb" and "wb") didn't manage to catch that particular instance. Thanks for disinterring that. -tkc From msustik at gmail.com Thu Feb 6 13:51:28 2014 From: msustik at gmail.com (msustik at gmail.com) Date: Thu, 6 Feb 2014 10:51:28 -0800 (PST) Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: <962185c1-a3e0-4176-bd2e-f09d6fdfef17@googlegroups.com> Thanks for all the suggestions! Best, -Matyas From robert.kern at gmail.com Thu Feb 6 14:29:19 2014 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 06 Feb 2014 19:29:19 +0000 Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: On 2014-02-06 17:23, Chris Angelico wrote: > On Thu, Feb 6, 2014 at 11:23 PM, Rustom Mody wrote: >> On Tuesday, February 4, 2014 8:51:25 PM UTC+5:30, jmf wrote: >> >>> Useless and really ugly. >> >> Evidently one can do worse: >> >> http://www.pip-installer.org/en/latest/installing.html#requirements > > Aside from using a little "chain link" icon rather than a > typographer's symbol, that looks exactly the same. How's it worse? When I looked at it earlier today, I got a default "cannot find this glyph" box instead of the chain icon. I assumed that is what Rustom was referring to. It's working for me now. -- 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 betz.mark at gmail.com Thu Feb 6 14:45:29 2014 From: betz.mark at gmail.com (Mark Betz) Date: Thu, 6 Feb 2014 11:45:29 -0800 (PST) Subject: Logging from a multiprocess application In-Reply-To: References: Message-ID: On Thursday, February 6, 2014 1:24:17 PM UTC-5, Joseph L. Casale wrote: > I have a module that has one operation that benefits greatly from being multiprocessed. > Its a console based module and as such I have a stream handler and filter associated to > the console, obviously the mp based instances need special handling, so I have been > experimenting with a socket server in a thread in order for the remaining application to > carry on. > > How have others tackled this problem? The portion of the code made to use multiprocessing > can not be switched to threading as it performs worse than simply serializing each task. > > Thanks, > jlc Maybe check out logstash (http://logstash.net/). It's part of elastic search now. Using the python-logstash module (https://pypi.python.org/pypi/python-logstash) you can either log directly to the logstash daemon using the provided event formatter and http, or you can do as I did and set up a redis server to host a list. Logstash has an included redis input plugin that will blpop a list to get events. I use the formatter from the logstash module to format the events and then write them into redis as json. Logstash picks them up from redis and indexes them into its embedded elastic search instance. You can then connect to the embedded kibana web server to view a dashboard with event information. It's pretty cool and doesn't take long to set up. From roel at roelschroeven.net Thu Feb 6 15:29:36 2014 From: roel at roelschroeven.net (Roel Schroeven) Date: Thu, 06 Feb 2014 21:29:36 +0100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: msustik at gmail.com schreef: > I had a bug in a Python script recently. The code in question was something along the lines of: > > if a == 1: > x = y > else: > x = z > y = z + y > z = z + 1 > > While editing this file I accidentally pushed TAB on the line with 'y = z + y'. > > My changes were elsewhere and I did not notice the above one line change when I looked at the diffs before commit. I should have noticed it... > > It was rare that a was 1 and therefore the problem did not show up for a while. (I know I should have had tests exercising all cases...) > > When the bug showed up, it was kind of difficult to remember what was the original intent. Fortunately, looking at old versions allowed me to find the problem commit and the bug. > > Any suggestion on how to avoid this type of error in the future? My suggestion: configure your editor to insert the appropriate amount of spaces instead of a tab when you press the tab key. Best regards, Roel -- "Met een spitsvondig citaat bewijs je niets." -- Voltaire From larry.martell at gmail.com Thu Feb 6 15:36:30 2014 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 6 Feb 2014 15:36:30 -0500 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: On Thu, Feb 6, 2014 at 3:29 PM, Roel Schroeven wrote: > msustik at gmail.com schreef: >> >> I had a bug in a Python script recently. The code in question was >> something along the lines of: >> >> if a == 1: >> x = y >> else: >> x = z >> y = z + y >> z = z + 1 >> >> While editing this file I accidentally pushed TAB on the line with 'y = z >> + y'. >> >> My changes were elsewhere and I did not notice the above one line change >> when I looked at the diffs before commit. I should have noticed it... >> >> It was rare that a was 1 and therefore the problem did not show up for a >> while. (I know I should have had tests exercising all cases...) >> >> When the bug showed up, it was kind of difficult to remember what was the >> original intent. Fortunately, looking at old versions allowed me to find the >> problem commit and the bug. >> >> Any suggestion on how to avoid this type of error in the future? > > > My suggestion: configure your editor to insert the appropriate amount of > spaces instead of a tab when you press the tab key. +1 - tabs are evil. From vinay_sajip at yahoo.co.uk Thu Feb 6 15:53:59 2014 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 6 Feb 2014 20:53:59 +0000 (GMT) Subject: ANN: A new version (0.3.6) of python-gnupg has been released. Message-ID: <1391720039.68301.YahooMailBasic@web172403.mail.ir2.yahoo.com> A new version of the Python module which wraps GnuPG has been released. What Changed? ============= This is an enhancement and bug-fix release, but the bug-fixes include some security improvements, so all users are encouraged to upgrade. See the project website ( http://code.google.com/p/python-gnupg/ ) for more information. Summary: Enabled fast random tests on gpg as well as gpg2. Avoided deleting temporary file to preserve its permissions. Avoided writing passphrase to log. Added export-minimal and armor options when exporting keys. Added verify_data() method to allow verification of signatures in memory. Regularised end-of-line characters in ths source code. Rectified problems with earlier fix for shell injection. The current version passes all tests on Windows (CPython 2.4, 2.5, 2.6, 3.1, 2.7 and Jython 2.5.1) and Ubuntu (CPython 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2). On Windows, GnuPG 1.4.11 has been used for the tests. What Does It Do? ================ The gnupg module allows Python programs to make use of the functionality provided by the Gnu Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP. This module is expected to be used with Python versions >= 2.4, as it makes use of the subprocess module which appeared in that version of Python. This module is a newer version derived from earlier work by Andrew Kuchling, Richard Jones and Steve Traugott. A test suite using unittest is included with the source distribution. Simple usage: >>> import gnupg >>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') >>> gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) ']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) ']}] >>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A']) >>> str(encrypted) '-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -----END PGP MESSAGE-----\n' >>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret') >>> str(decrypted) 'Hello, world!' >>> signed = gpg.sign("Goodbye, world!", passphrase='secret') >>> verified = gpg.verify(str(signed)) >>> print "Verified" if verified else "Not verified" 'Verified' For more information, visit http://code.google.com/p/python-gnupg/ - as always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. From jcasale at activenetwerx.com Thu Feb 6 16:38:18 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Thu, 6 Feb 2014 21:38:18 +0000 Subject: Logging from a multiprocess application In-Reply-To: References: , Message-ID: <62e9b352335f438c877a8ecd633aba67@exch.activenetwerx.com> > Maybe check out logstash (http://logstash.net/). That looks pretty slick, I am constrained to using something provided by the packaged modules in this scenario. I think I have it pretty close except for the fact that the LogRecordStreamHandler from the cookbook excepts when the sending process ends, aside from the obvious, I am sure there is a more robust performance oriented approach to this. I've yet to work with the SocketServer module so I am lacking any experience. Thanks for the pointer, jlc From roegltd at gmail.com Thu Feb 6 16:39:53 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 13:39:53 -0800 (PST) Subject: ANN: A new version (0.3.6) of python-gnupg has been released. In-Reply-To: References: Message-ID: On Thursday, February 6, 2014 10:53:59 PM UTC+2, Vinay Sajip wrote: > A new version of the Python module which wraps GnuPG has been > released. > Cheers > > Vinay Sajip > > Red Dove Consultants Ltd. Hi Good job! One question - is this package runs executable when particular function must be invoked in GnuPG? library calls? Regards Asaf From ethan at stoneleaf.us Thu Feb 6 16:32:01 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 06 Feb 2014 13:32:01 -0800 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: <52F3FF51.3050502@stoneleaf.us> On 02/06/2014 12:36 PM, Larry Martell wrote: > On Thu, Feb 6, 2014 at 3:29 PM, Roel Schroeven wrote: >> msustik at gmail.com schreef: >>> >>> While editing this file I accidentally pushed TAB on the line with 'y = z >>> + y'. >> >> My suggestion: configure your editor to insert the appropriate amount of >> spaces instead of a tab when you press the tab key. > > +1 - tabs are evil. Tabs are not evil, and an argument can be made that tabs are better (a decent editor can be configured to show x many spaces per tab, then users could decide how much indentation they preferred to see... but I digress). Using spaces instead of tabs would also have not prevented the error that Msustik encountered, and for that matter we don't know whether he was using tabs or spaces in his source file, only that he hit the Tab key -- surely you are not suggesting everyone rip out their tab key and just hit the space bar four times for each level of indentation? ;) -- ~Ethan~ From larry.martell at gmail.com Thu Feb 6 17:09:43 2014 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 6 Feb 2014 17:09:43 -0500 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: <52F3FF51.3050502@stoneleaf.us> References: <52F3FF51.3050502@stoneleaf.us> Message-ID: On Thu, Feb 6, 2014 at 4:32 PM, Ethan Furman wrote: > On 02/06/2014 12:36 PM, Larry Martell wrote: >> >> On Thu, Feb 6, 2014 at 3:29 PM, Roel Schroeven wrote: >>> >>> msustik at gmail.com schreef: >>>> >>>> >>>> While editing this file I accidentally pushed TAB on the line with 'y = >>>> z >>>> + y'. >>> >>> >>> My suggestion: configure your editor to insert the appropriate amount of >>> spaces instead of a tab when you press the tab key. >> >> >> +1 - tabs are evil. > > > Tabs are not evil, and an argument can be made that tabs are better (a > decent editor can be configured to show x many spaces per tab, then users > could decide how much indentation they preferred to see... but I digress). > > Using spaces instead of tabs would also have not prevented the error that > Msustik encountered, and for that matter we don't know whether he was using > tabs or spaces in his source file, only that he hit the Tab key -- surely > you are not suggesting everyone rip out their tab key and just hit the space > bar four times for each level of indentation? ;) The Tab key is not evil, it's the tab character (Ctrl-I). I have been bitten by this many time when I had to work on a program written by another. They had their tab stops set at 5 or 6, mine is set at 4, or they did not have expandtab set, but I did. So you get either a script that looks misaligned, but works, or one that does not look misaligned but doesn't work. When I have to pick up someone else's script the first thing I do is replace the tabs with spaces. From rosuav at gmail.com Thu Feb 6 17:30:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 09:30:17 +1100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: <52F3FF51.3050502@stoneleaf.us> Message-ID: On Fri, Feb 7, 2014 at 9:09 AM, Larry Martell wrote: > The Tab key is not evil, it's the tab character (Ctrl-I). I have been > bitten by this many time when I had to work on a program written by > another. They had their tab stops set at 5 or 6, mine is set at 4, or > they did not have expandtab set, but I did. So you get either a script > that looks misaligned, but works, or one that does not look misaligned > but doesn't work. When I have to pick up someone else's script the > first thing I do is replace the tabs with spaces. All you've proven is that *mixing* spaces and tabs is evil. It's like arguing that oil is evil because, when you mix it with water, weird stuff happens. But that doesn't mean I want to fry my bacon in water. Mmm, bacon. Sorry. I'm back now. Ahem. Arguably, a better fix is to replace spaces with tabs, because they're more obvious. But mainly, just be consistent. Whatever one file uses, it uses exclusively. It'd be pretty easy to create a git commit hook that checks files for leading indentation and rejects the commit if it's mismatched; I would guess the same is true in Mercurial. But none of this would solve the OP's original issue. Whether it's a tab or spaces, unexpectedly indenting a line of code is a problem. It's no different from accidentally hitting Ctrl-T in SciTE and reordering two lines, when one line depends on the other. It's a bug. So you look at your commits before you make them (to give yourself a chance to catch it quickly), and you make sure you can always look back over your commits (in case you didn't catch it quickly). Much better than blaming the characters involved. Poor innocent U+0009. ChrisA From roegltd at gmail.com Thu Feb 6 18:01:47 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 15:01:47 -0800 (PST) Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: <52F3FF51.3050502@stoneleaf.us> Message-ID: <069af054-f864-4d58-a6d1-c3b0e9cd32fa@googlegroups.com> On Friday, February 7, 2014 12:30:17 AM UTC+2, Chris Angelico wrote: > On Fri, Feb 7, 2014 at 9:09 AM, Larry Martell wrote: > > > The Tab key is not evil, it's the tab character (Ctrl-I). I have been > > bitten by this many time when I had to work on a program written by > > another. They had their tab stops set at 5 or 6, mine is set at 4, or > > they did not have expandtab set, but I did. So you get either a script > > that looks misaligned, but works, or one that does not look misaligned > > but doesn't work. When I have to pick up someone else's script the > > first thing I do is replace the tabs with spaces. > > All you've proven is that *mixing* spaces and tabs is evil. It's like > arguing that oil is evil because, when you mix it with water, weird > stuff happens. But that doesn't mean I want to fry my bacon in water. > Mmm, bacon. > Sorry. I'm back now. Ahem. Arguably, a better fix is to replace spaces > with tabs, because they're more obvious. But mainly, just be > consistent. Whatever one file uses, it uses exclusively. It'd be > pretty easy to create a git commit hook that checks files for leading > indentation and rejects the commit if it's mismatched; I would guess > the same is true in Mercurial. > > But none of this would solve the OP's original issue. Whether it's a > tab or spaces, unexpectedly indenting a line of code is a problem. > It's no different from accidentally hitting Ctrl-T in SciTE and > reordering two lines, when one line depends on the other. It's a bug. > So you look at your commits before you make them (to give yourself a > chance to catch it quickly), and you make sure you can always look > back over your commits (in case you didn't catch it quickly). Much > better than blaming the characters involved. Poor innocent U+0009. > ChrisA pep8 pushed \t to dark side in Python. though it is better that spaces sometimes. let say someone's indented code with 2 spaces and user is comfortable with 4. if \t then it is done by editor's conf without touching code. /Asaf From piet at vanoostrum.org Thu Feb 6 18:40:08 2014 From: piet at vanoostrum.org (Piet van Oostrum) Date: Fri, 07 Feb 2014 00:40:08 +0100 Subject: ANN: A new version (0.3.6) of python-gnupg has been released. References: Message-ID: Vinay Sajip writes: > A new version of the Python module which wraps GnuPG has been > released. > There seem to be 2 gnupg modules for Python. The other one has version number 1.2.5. Very confusing! -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From ram.rachum at gmail.com Thu Feb 6 18:59:13 2014 From: ram.rachum at gmail.com (cool-RR) Date: Thu, 6 Feb 2014 15:59:13 -0800 (PST) Subject: Question about `list.insert` Message-ID: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Hi, I'm curious. If I append an item to a list from the left using `list.insert`, will Python always move the entire list one item to the right (which can be super-slow) or will it check first to see whether it can just allocate more memory to the left of the list and put the item there, saving a lot of resources? Thanks, Ram. From rosuav at gmail.com Thu Feb 6 19:08:21 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 11:08:21 +1100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: <069af054-f864-4d58-a6d1-c3b0e9cd32fa@googlegroups.com> References: <52F3FF51.3050502@stoneleaf.us> <069af054-f864-4d58-a6d1-c3b0e9cd32fa@googlegroups.com> Message-ID: On Fri, Feb 7, 2014 at 10:01 AM, Asaf Las wrote: > pep8 pushed \t to dark side in Python. Only for the Python stdlib, and only because a decision has to be made one way or the other. I believe Guido stated at one point that there was only a very weak push toward "spaces only" rather than "tabs only", just that it had to be one of those. ChrisA From tjreedy at udel.edu Thu Feb 6 19:40:00 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Feb 2014 19:40:00 -0500 Subject: Question about `list.insert` In-Reply-To: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: On 2/6/2014 6:59 PM, cool-RR wrote: > Hi, > > I'm curious. If I append an item to a list from the left using > `list.insert`, will Python always move the entire list one item to > the right (which can be super-slow) or will it check first to see > whether it can just allocate more memory to the left of the list and > put the item there, saving a lot of resources? "It depends on the implementation" Assume O(n), which I am sure it is for CPython, but easy enough to check. -- Terry Jan Reedy From python at mrabarnett.plus.com Thu Feb 6 19:42:04 2014 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 Feb 2014 00:42:04 +0000 Subject: Question about `list.insert` In-Reply-To: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: <52F42BDC.7000907@mrabarnett.plus.com> On 2014-02-06 23:59, cool-RR wrote: > Hi, > > I'm curious. If I append an item to a list from the left using > `list.insert`, will Python always move the entire list one item to > the right (which can be super-slow) or will it check first to see > whether it can just allocate more memory to the left of the list and > put the item there, saving a lot of resources? > If it needs more space it resizes. It then moves the items. From swdunning at cox.net Thu Feb 6 20:22:00 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Feb 2014 18:22:00 -0700 Subject: Python 2.7.6 help with white spaces? Message-ID: I am having trouble figuring out how to remove spaces?. Assume variables exist for minutes and seconds. Each variable is an integer. How would you create a string in the format, 3:11 with no spaces. where 3 is minutes and 11 is seconds. Obviously when I? print minutes, ?:?, seconds I get 3 : 11 how can I get it to print with no spaces? 3:11 I?m VERY new to python and coding in general and this is a question for a class I?m in for a test review. So, the most basic answer would be appreciated. Thanks for any help!! Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From msustik at gmail.com Thu Feb 6 20:20:22 2014 From: msustik at gmail.com (msustik at gmail.com) Date: Thu, 6 Feb 2014 17:20:22 -0800 (PST) Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: On Thursday, February 6, 2014 12:29:36 PM UTC-8, Roel Schroeven wrote: > > My suggestion: configure your editor to insert the appropriate amount of > > spaces instead of a tab when you press the tab key. You misunderstood the problem, but managed to start a Tab war! :-) My emacs inserts 4 spaces in python mode when I press the tab key. Python uses the indentation to decide how many lines following the else are executed in the else branch or after the else branch (always that is). By pressing inadvertently the Tab key I changed the semantics of the code while it is still syntactically correct and PEP8 compliant. This was indeed a user error and my question was towards practices reducing the chance of this happening again. Based on the responses I arrived to the conclusion that there is no better solution than trying to be careful and have good testing suites. It would be possible to disable the Tab key completely and type in the spaces all the time. (It is much less likely that one would press the space bar accidentally four times or hold it down to get 4 spaces by mistake.) Unfortunately this means giving up the indentation help of the editor and that will slow down coding. It will also lead to many indentation mistakes during development (most of which will be caught right away however. Maybe a coloring of the background based on tab position could assist in this. I also considered adding an extra blank line after the if-else block (similarly for loops) in the hope that it would reduce the chance of missing an inadvertent indentation after the block. However, this defeats somewhat the python paradigm that got rid of closing braces and endif-s etc. used in other languages to allow more compact code. -Matyas > > > > > > Best regards, > > Roel > > > > -- > > "Met een spitsvondig citaat bewijs je niets." > > -- Voltaire From roy at panix.com Thu Feb 6 20:25:47 2014 From: roy at panix.com (Roy Smith) Date: Thu, 06 Feb 2014 20:25:47 -0500 Subject: Python 2.7.6 help with white spaces? References: Message-ID: In article , Scott W Dunning wrote: > I am having trouble figuring out how to remove spaces?. > > Assume variables exist for minutes and seconds. Each variable is an integer. > How would you create a string in the format, > > 3:11 > > with no spaces. where 3 is minutes and 11 is seconds. > > > Obviously when I? > > print minutes, ?:?, seconds > > I get 3 : 11 > > how can I get it to print with no spaces? > > 3:11 print "%d:%02d" % (minutes, seconds) The "02" for the seconds specifier makes sure you get exactly two digits, with a leading zero if needed. From rosuav at gmail.com Thu Feb 6 20:37:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 12:37:46 +1100 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: Message-ID: On Fri, Feb 7, 2014 at 12:22 PM, Scott W Dunning wrote: > Assume variables exist for minutes and seconds. Each variable is an integer. > How would you create a string in the format, > > 3:11 > > with no spaces. where 3 is minutes and 11 is seconds. > > > Obviously when I? > > print minutes, ?:?, seconds > > I get 3 : 11 > > how can I get it to print with no spaces? > > 3:11 The print statement isn't right for what you're doing here. You need to create a single string with that result, which you could then print out. There are two easy ways to do this. First one is to create a string from the number of minutes, create a string from the number of seconds, and concatenate them, with a third string (the colon) in between. Do you know how to turn an integer into a string, and do you know how to add strings together? The second way is to format the values directly into a single string. You can use printf codes for this. Check this out: http://docs.python.org/2/library/stdtypes.html#string-formatting-operations ChrisA From rosuav at gmail.com Thu Feb 6 20:57:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 12:57:50 +1100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: On Fri, Feb 7, 2014 at 12:20 PM, wrote: > It would be possible to disable the Tab key completely and type in the spaces all the time. (It is much less likely that one would press the space bar accidentally four times or hold it down to get 4 spaces by mistake.) > > Unfortunately this means giving up the indentation help of the editor and that will slow down coding. It will also lead to many indentation mistakes during development (most of which will be caught right away however. Maybe a coloring of the background based on tab position could assist in this. > I don't know that it'd really help much anyway. You might reduce one chance of making errors by hitting a single key, but at the cost of stupid syntactic salt (indentation requires hitting a key four times? No thanks), and your fingers would just get used to whack-whack-whack-whack. No change. You can spend all your time trying to warp your coding style around preventing this bug or that bug from happening, or you can just acknowledge that bugs WILL happen and handle them after the event. (Hence, source control.) Suppose you come up with a solution to the accidental-indentation problem. What are you going to do about this one? def foo(bar): if not bar: bat = [0] for x in bar: print(len(bar),x) Now, why is your empty-list handling not working? Oh, there was a typo. How are you going to deal with that? Well, you could bring in C-style variable declarations; then you'd get an immediate error ('bat' is undeclared), but somehow I don't think most Python programmers would prefer this :) Now personally, I do quite like declared variables, because they allow infinitely-nested scoping, and I find that feature worth the effort of declaring all my locals; but it's a tradeoff, and I wouldn't go to that level of effort *just* to catch typos in variable names. What if there had been a 'bat' at a higher scope? Then the typo just means the code does something else wrong. No fundamental difference. There was a scheme posted to this list a little while ago to have variable names shown in different colors, which might have helped. (I disagree with the author's idea that similar names should be in similar colors - I think that similar names should be in DISsimilar colors, specifically to catch this sort of error. But anyway.) That's a theory that might help... but it still might not. And what if your error is in a literal string that later gets parsed? No, there's no way that you can catch everything beforehand. Bugs happen. Find 'em, fix 'em. ChrisA From tjreedy at udel.edu Thu Feb 6 21:48:36 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Feb 2014 21:48:36 -0500 Subject: Question about `list.insert` In-Reply-To: <52F42BDC.7000907@mrabarnett.plus.com> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> <52F42BDC.7000907@mrabarnett.plus.com> Message-ID: On 2/6/2014 7:42 PM, MRAB wrote: > On 2014-02-06 23:59, cool-RR wrote: >> Hi, >> >> I'm curious. If I append an item to a list from the left using >> `list.insert`, will Python always move the entire list one item to >> the right (which can be super-slow) or will it check first to see >> whether it can just allocate more memory to the left of the list and >> put the item there, saving a lot of resources? >> > If it needs more space it resizes. It then moves the items. The OP apparently knows that there is usually extra space at the right (end), so that reallocation is usually not needed. He wanted to know whether extra space is also kept at the left (beginning) to make left appends as efficient as right appends. This has been proposed and the answer was to use collections.deque if it really matters. CPython lists are asymmetric re-sizable stacks -- Terry Jan Reedy From davea at davea.name Thu Feb 6 21:54:42 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 21:54:42 -0500 (EST) Subject: Question about `list.insert` References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: cool-RR Wrote in message: > Hi, > > I'm curious. If I append an item to a list from the left using `list.insert`, will Python always move the entire list one item to the right (which can be super-slow) or will it check first to see whether it can just allocate more memory to the left of the list and put the item there, saving a lot of resources? > Excellent question. list does not promise better than O (1) behavior, and CPython in particular will copy, I'm pretty sure. However that's exactly what collections.deque is for. -- DaveA From roy at panix.com Thu Feb 6 22:00:56 2014 From: roy at panix.com (Roy Smith) Date: Thu, 06 Feb 2014 22:00:56 -0500 Subject: Question about `list.insert` References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: In article , Dave Angel wrote: > list does not promise better than O(1) behavior I'm not aware of any list implementations, in any language, that promises better than O(1) behavior for any operations. Perhaps there is O(j), where you just imagine the operation was performed? From rustompmody at gmail.com Thu Feb 6 22:05:45 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 19:05:45 -0800 (PST) Subject: [OT] Usage of U+00B6 PILCROW SIGN In-Reply-To: References: <9aafd758-8c54-4abf-9ac4-46e970158131@googlegroups.com> <777aae72-b8f1-499a-84a5-197285847042@googlegroups.com> Message-ID: <6f84a448-5e85-430d-bcab-a13b07688ca5@googlegroups.com> On Friday, February 7, 2014 12:59:19 AM UTC+5:30, Robert Kern wrote: > When I looked at it earlier today, I got a default "cannot find this glyph" box > instead of the chain icon. I assumed that is what Rustom was referring to. > It's working for me now. Yes I was getting unicode number-boxes; which is now working From rustompmody at gmail.com Thu Feb 6 22:08:32 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 19:08:32 -0800 (PST) Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: On Friday, February 7, 2014 8:30:56 AM UTC+5:30, Roy Smith wrote: > Dave Angel wrote: > > > list does not promise better than O(1) behavior > > I'm not aware of any list implementations, in any language, that > promises better than O(1) behavior for any operations. Perhaps there is > O(j), where you just imagine the operation was performed? I believe Oracle has such a product on offer The price too is by imagination From python.list at tim.thechases.com Thu Feb 6 22:11:30 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 6 Feb 2014 21:11:30 -0600 Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: <20140206211130.3ec5b0d8@bigbox.christie.dr> On 2014-02-06 22:00, Roy Smith wrote: > > list does not promise better than O(1) behavior > > I'm not aware of any list implementations, in any language, that > promises better than O(1) behavior for any operations. Perhaps > there is O(j), where you just imagine the operation was performed? Pish...there's always O(0) which is achieved by *not* performing some unneeded operation ;-) -tkc From rosuav at gmail.com Thu Feb 6 22:14:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 14:14:43 +1100 Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: On Fri, Feb 7, 2014 at 2:00 PM, Roy Smith wrote: > In article , > Dave Angel wrote: > >> list does not promise better than O(1) behavior > > I'm not aware of any list implementations, in any language, that > promises better than O(1) behavior for any operations. Perhaps there is > O(j), where you just imagine the operation was performed? I have a printer that executes in O(1/N) time, where N is the number of marbles the sysadmin (me!) has lost. The less sanity I have, the more printouts it produces. And the less printouts it produces, the more marbles I lose trying to figure out WHY? WHY? WHY?!? Okay, I'm done ranting about Windows and 1990s accounting packages and modern PostScript printers. ChrisA From roy at panix.com Thu Feb 6 22:12:50 2014 From: roy at panix.com (Roy Smith) Date: Thu, 06 Feb 2014 22:12:50 -0500 Subject: Question about `list.insert` References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: In article , Tim Chase wrote: > On 2014-02-06 22:00, Roy Smith wrote: > > > list does not promise better than O(1) behavior > > > > I'm not aware of any list implementations, in any language, that > > promises better than O(1) behavior for any operations. Perhaps > > there is O(j), where you just imagine the operation was performed? > > Pish...there's always O(0) which is achieved by *not* performing some > unneeded operation ;-) O(-1). In Soviet Russia, operation performs you! From rosuav at gmail.com Thu Feb 6 22:20:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 14:20:43 +1100 Subject: Question about `list.insert` In-Reply-To: <20140206211130.3ec5b0d8@bigbox.christie.dr> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> <20140206211130.3ec5b0d8@bigbox.christie.dr> Message-ID: On Fri, Feb 7, 2014 at 2:11 PM, Tim Chase wrote: > On 2014-02-06 22:00, Roy Smith wrote: >> > list does not promise better than O(1) behavior >> >> I'm not aware of any list implementations, in any language, that >> promises better than O(1) behavior for any operations. Perhaps >> there is O(j), where you just imagine the operation was performed? > > Pish...there's always O(0) which is achieved by *not* performing some > unneeded operation ;-) > > -tkc Ooh! Ooh! I got it! class fast_list(list): def append(self,obj,randrange=random.randrange): if len(self) and randrange(len(self)): return return super().append(obj) Repeated appends to this list are amortized O(0)! ChrisA From john_ladasky at sbcglobal.net Thu Feb 6 22:25:57 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 6 Feb 2014 19:25:57 -0800 (PST) Subject: trivial import question In-Reply-To: <7821caaa-eff5-41ef-b5ff-dcec85ade3cd@googlegroups.com> References: <7821caaa-eff5-41ef-b5ff-dcec85ade3cd@googlegroups.com> Message-ID: <4babca33-da90-42dc-8408-87b058022587@googlegroups.com> On Wednesday, February 5, 2014 9:52:33 AM UTC-8, nevets... at gmail.com wrote: > The underscore relative to a prfixed abbb. Is to be noted Reviving a fourteen year-old thread? That has to be some kind of record. From roegltd at gmail.com Thu Feb 6 22:28:32 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 19:28:32 -0800 (PST) Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: On Friday, February 7, 2014 5:00:56 AM UTC+2, Roy Smith wrote: > In article , > > Dave Angel wrote: > > list does not promise better than O(1) behavior > I'm not aware of any list implementations, in any language, that > promises better than O(1) behavior for any operations. Perhaps there is > O(j), where you just imagine the operation was performed? Archimedes once said "Give me whereon to stand and I will move the earth" he said that for lists, specifically he meant "give me enough RAM and list will perform O(1)." From rustompmody at gmail.com Thu Feb 6 22:29:50 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 19:29:50 -0800 (PST) Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> <20140206211130.3ec5b0d8@bigbox.christie.dr> Message-ID: <2ff6e4a4-dfe0-436c-b34f-0ba682e6c8de@googlegroups.com> On Friday, February 7, 2014 8:44:43 AM UTC+5:30, Chris Angelico wrote: > On Fri, Feb 7, 2014 at 2:00 PM, Roy Smith wrote: > > Dave Angel wrote: > >> list does not promise better than O(1) behavior > > I'm not aware of any list implementations, in any language, that > > promises better than O(1) behavior for any operations. Perhaps there is > > O(j), where you just imagine the operation was performed? > I have a printer that executes in O(1/N) time, where N is the number > of marbles the sysadmin (me!) has lost. The less sanity I have, the > more printouts it produces. And the less printouts it produces, the > more marbles I lose trying to figure out WHY? WHY? WHY?!? Heh! Nice to know I have company! Thought I was the only one who lost hair at the printer's free-paper-munificience From rosuav at gmail.com Thu Feb 6 22:45:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 14:45:58 +1100 Subject: Question about `list.insert` In-Reply-To: <2ff6e4a4-dfe0-436c-b34f-0ba682e6c8de@googlegroups.com> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> <20140206211130.3ec5b0d8@bigbox.christie.dr> <2ff6e4a4-dfe0-436c-b34f-0ba682e6c8de@googlegroups.com> Message-ID: On Fri, Feb 7, 2014 at 2:29 PM, Rustom Mody wrote: > On Friday, February 7, 2014 8:44:43 AM UTC+5:30, Chris Angelico wrote: >> On Fri, Feb 7, 2014 at 2:00 PM, Roy Smith wrote: >> > Dave Angel wrote: >> >> list does not promise better than O(1) behavior >> > I'm not aware of any list implementations, in any language, that >> > promises better than O(1) behavior for any operations. Perhaps there is >> > O(j), where you just imagine the operation was performed? > >> I have a printer that executes in O(1/N) time, where N is the number >> of marbles the sysadmin (me!) has lost. The less sanity I have, the >> more printouts it produces. And the less printouts it produces, the >> more marbles I lose trying to figure out WHY? WHY? WHY?!? > > Heh! Nice to know I have company! > > Thought I was the only one who lost hair at the printer's > free-paper-munificience See, here's the deal. I have a nice, modern, CUPS-based printer. It supports all the modern protocols (IPP, JetDirect, whatever), and when I point one of my Linux boxes in its direction and say "Print", a sheet of paper comes out in fairly short order. Nice, right? Okay, now let's mix in the problem ingredients. We have an ancient accounting package, supporting a rather old and winding-down business. It's not worth upgrading to a newer version of the program (that costs money), and certainly not worth migrating to a completely different program (that takes time), because the business just isn't operating at that level any more. It's a Windows 16-bit application. The physical hardware is decently modern, and is running Debian Jessie (the latest, not even stable yet, because I wanted something else relating to scanning - that's a separate point). Debian is running VirtualBox, and inside the VM is running OS/2 (eComStation). OS/2 will run the old accounting package in a Win-OS/2 session. Now, OS/2 will talk to the printer. I can fire up DeScribe Word Processor, type in some text, hit Print, and a sheet of paper comes out with a representation of that text. The recent versions of OS/2 are quite good at that. But Windows? Windows? Oh no. It won't be that courteous. No, it claims to have printed the document, and everything I can see suggests that the data has passed through on its way to the printer, but no paper comes out. My best guess is that there's some flaw in the PostScript engine in Windows, because I can generate output successfully by a complex dance involving freezing the printer's output, printing from Windows, printing an unrelated document (anything at all) from OS/2, and then releasing all the printed data at once. Current suggestions awaiting experimentation including slaughtering a black goat at midnight, waving a rubber chicken, and throwing salt over my shoulder in the direction of the full moon. ChrisA From swdunning at cox.net Thu Feb 6 23:09:31 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Feb 2014 21:09:31 -0700 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: Message-ID: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Is this what you?re talking about? minutes = ?3? seconds = ?11? print int(minutes), ?:" int(seconds) That?s what you mean by turning a string into an int right? Not sure how to add strings together though. On Feb 6, 2014, at 6:37 PM, Chris Angelico wrote: > On Fri, Feb 7, 2014 at 12:22 PM, Scott W Dunning wrote: >> Assume variables exist for minutes and seconds. Each variable is an integer. >> How would you create a string in the format, >> >> 3:11 >> >> with no spaces. where 3 is minutes and 11 is seconds. >> >> >> Obviously when I? >> >> print minutes, ?:?, seconds >> >> I get 3 : 11 >> >> how can I get it to print with no spaces? >> >> 3:11 > > The print statement isn't right for what you're doing here. You need > to create a single string with that result, which you could then print > out. > > There are two easy ways to do this. First one is to create a string > from the number of minutes, create a string from the number of > seconds, and concatenate them, with a third string (the colon) in > between. Do you know how to turn an integer into a string, and do you > know how to add strings together? > > The second way is to format the values directly into a single string. > You can use printf codes for this. Check this out: > > http://docs.python.org/2/library/stdtypes.html#string-formatting-operations > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From swdunning at cox.net Thu Feb 6 23:12:08 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Feb 2014 21:12:08 -0700 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: Message-ID: <699CF5DD-1D51-4712-900D-70B94950305A@cox.net> what exactly is the ?%d:%02d?% saying? On Feb 6, 2014, at 6:25 PM, Roy Smith wrote: > In article , > Scott W Dunning wrote: > >> I am having trouble figuring out how to remove spaces?. >> >> Assume variables exist for minutes and seconds. Each variable is an integer. >> How would you create a string in the format, >> >> 3:11 >> >> with no spaces. where 3 is minutes and 11 is seconds. >> >> >> Obviously when I? >> >> print minutes, ?:?, seconds >> >> I get 3 : 11 >> >> how can I get it to print with no spaces? >> >> 3:11 > > print "%d:%02d" % (minutes, seconds) > > The "02" for the seconds specifier makes sure you get exactly two > digits, with a leading zero if needed. > -- > https://mail.python.org/mailman/listinfo/python-list From greg.ewing at canterbury.ac.nz Thu Feb 6 23:18:52 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 07 Feb 2014 17:18:52 +1300 Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: Roy Smith wrote: > O(-1). In Soviet Russia, operation performs you! It's rumoured that the PSU is developing a time machine module that can achieve O(-n), but From roy at panix.com Thu Feb 6 23:26:37 2014 From: roy at panix.com (Roy Smith) Date: Thu, 6 Feb 2014 23:26:37 -0500 Subject: Python 2.7.6 help with white spaces? In-Reply-To: <699CF5DD-1D51-4712-900D-70B94950305A@cox.net> References: <699CF5DD-1D51-4712-900D-70B94950305A@cox.net> Message-ID: On Feb 6, 2014, at 11:12 PM, Scott W Dunning wrote: > what exactly is the ?%d:%02d?% saying? Python uses string format specifiers similar to C's printf() %d means, "convert an integer to a decimal string" %2d means the same, plus, "make the result 2 columns wide" and, finally, %02d means, "and, if it would normally be less than 2 columns, zero-pad it on the left". So, putting that all together, we've got: "%d" --> decimal integer ":" --> a literal ":" "%02d" --> another decimal integer, this time zero-padded to two columns > > > > On Feb 6, 2014, at 6:25 PM, Roy Smith wrote: > >> In article , >> Scott W Dunning wrote: >> >>> I am having trouble figuring out how to remove spaces?. >>> >>> Assume variables exist for minutes and seconds. Each variable is an integer. >>> How would you create a string in the format, >>> >>> 3:11 >>> >>> with no spaces. where 3 is minutes and 11 is seconds. >>> >>> >>> Obviously when I? >>> >>> print minutes, ?:?, seconds >>> >>> I get 3 : 11 >>> >>> how can I get it to print with no spaces? >>> >>> 3:11 >> >> print "%d:%02d" % (minutes, seconds) >> >> The "02" for the seconds specifier makes sure you get exactly two >> digits, with a leading zero if needed. >> -- >> https://mail.python.org/mailman/listinfo/python-list > -- Roy Smith roy at panix.com From rosuav at gmail.com Thu Feb 6 23:45:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 15:45:55 +1100 Subject: Python 2.7.6 help with white spaces? In-Reply-To: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: On Fri, Feb 7, 2014 at 3:09 PM, Scott W Dunning wrote: > Is this what you?re talking about? > > minutes = ?3? > seconds = ?11? > > print int(minutes), ?:" int(seconds) > > That?s what you mean by turning a string into an int right? Not sure how to add strings together though. > Well, that's what I would have meant, if I'd talked about turning a string into an int :) Now, can you do the opposite? Turn an int into a string? It's done in very much the same way. Adding strings together is done in the same way as adding integers, lists, or anything else: >>> 'foo' + 'bar' 'foobar' And remember this, whatever else you do: The interactive interpreter is your friend. Keep it handy. On Windows, you'll find IDLE in your Start menu - it's awesome for this sort of thing. On Linux, you might need to explicitly install IDLE. Either way, you can also just type "python" at the command line, and you'll get something that lets you type stuff in and see the result, like I showed above; it's called a Read-Evaluate-Print Loop, or REPL. ChrisA From drsalists at gmail.com Thu Feb 6 23:52:24 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 6 Feb 2014 20:52:24 -0800 Subject: Question about `list.insert` In-Reply-To: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: On Thu, Feb 6, 2014 at 3:59 PM, cool-RR wrote: > Hi, > > I'm curious. If I append an item to a list from the left using `list.insert`, will Python always move the entire list one item to the right (which can be super-slow) or will it check first to see whether it can just allocate more memory to the left of the list and put the item there, saving a lot of resources? I'm pretty sure it'll slide all the existing elements right one position, and add at the leftmost position just opened up - assuming you're inserting at position 0. As was already mentioned, collections.deque is good for this sort of thing. It's implemented as a fancy doubly-linked list. Or rather, a doubly-linked list of smallish arrays/lists. For a singly-linked list: http://stackoverflow.com/questions/280243/python-linked-list http://stromberg.dnsalias.org/~strombrg/linked-list/ HTH From swdunning at cox.net Fri Feb 7 00:01:23 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Feb 2014 22:01:23 -0700 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: Oops, thought you said turning a str into an int. Yeah, I?m actually using Idle on a mac. I keep trying differnt things but, I?m just very new to this. Is this what you?re talking about? minutes=3 seconds=11 print str(minutes) + ?:? + str(seconds) Unfortunately I keep getting an error. Also, not really clear on the reasoning behind changing the int to a string? On Feb 6, 2014, at 9:45 PM, Chris Angelico wrote: > On Fri, Feb 7, 2014 at 3:09 PM, Scott W Dunning wrote: >> Is this what you?re talking about? >> >> minutes = ?3? >> seconds = ?11? >> >> print int(minutes), ?:" int(seconds) >> >> That?s what you mean by turning a string into an int right? Not sure how to add strings together though. >> > > Well, that's what I would have meant, if I'd talked about turning a > string into an int :) Now, can you do the opposite? Turn an int into a > string? It's done in very much the same way. > > Adding strings together is done in the same way as adding integers, > lists, or anything else: > >>>> 'foo' + 'bar' > 'foobar' > > And remember this, whatever else you do: The interactive interpreter > is your friend. Keep it handy. On Windows, you'll find IDLE in your > Start menu - it's awesome for this sort of thing. On Linux, you might > need to explicitly install IDLE. Either way, you can also just type > "python" at the command line, and you'll get something that lets you > type stuff in and see the result, like I showed above; it's called a > Read-Evaluate-Print Loop, or REPL. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From rosuav at gmail.com Fri Feb 7 00:06:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 7 Feb 2014 16:06:49 +1100 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: On Fri, Feb 7, 2014 at 4:01 PM, Scott W Dunning wrote: > Oops, thought you said turning a str into an int. Yeah, I?m actually using Idle on a mac. I keep trying differnt things but, I?m just very new to this. > > Is this what you?re talking about? > > minutes=3 > seconds=11 > > print str(minutes) + ?:? + str(seconds) > > Unfortunately I keep getting an error. Also, not really clear on the reasoning behind changing the int to a string? Here's another fundamental of Python: Error messages are really REALLY useful. In this case, I can figure out what's going on without seeing it, but normally, post the whole traceback. The problem here is because you're using "smart quotes" of some sort. Use ordinary apostrophes and double quotes, and it'll work fine. As to the reason for changing the int to a string... try skipping it! Then you'll know. You'll get a nice tidy error, pointing you to the exact cause of the problem. >>> print minutes + ':' + seconds See what happens! ChrisA From roegltd at gmail.com Fri Feb 7 00:18:28 2014 From: roegltd at gmail.com (Asaf Las) Date: Thu, 6 Feb 2014 21:18:28 -0800 (PST) Subject: Question about `list.insert` In-Reply-To: References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: <0c12b7bb-9800-4e2e-b4e8-3d66e54fad9c@googlegroups.com> On Friday, February 7, 2014 6:52:24 AM UTC+2, Dan Stromberg wrote: > On Thu, Feb 6, 2014 at 3:59 PM, cool-RR wrote: > > I'm pretty sure it'll slide all the existing elements right one > position, and add at the leftmost position just opened up - assuming > you're inserting at position 0. > > As was already mentioned, collections.deque is good for this sort of > thing. It's implemented as a fancy doubly-linked list. Or rather, a > doubly-linked list of smallish arrays/lists. > For a singly-linked list: > http://stackoverflow.com/questions/280243/python-linked-list > http://stromberg.dnsalias.org/~strombrg/linked-list/ > > HTH the Py list is just 2 members (as declared in corresponding header) structure where only one double pointer serves addressing towards most probably dynamically allocated array of pointers towards python objects. so adding could expensive as it should copy all pointers in array into new bigger one during expanding as array needs to be contiguous. so it looks more array than list. but i could be wrong in my conclusion. /Asaf From ben+python at benfinney.id.au Fri Feb 7 00:24:34 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 Feb 2014 16:24:34 +1100 Subject: Python 2.7.6 help with white spaces? References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: <8561orebql.fsf@benfinney.id.au> Scott W Dunning writes: > I keep trying differnt things but, I?m just very new to this. A few things that will make your communications more fruitful: * Please don't top-post. Trim the quoted material to the parts relevant for your response, and respond inline like a normal discussion. * Ensure that your message composer doesn't munge your text. The code you show us needs to be *exactly* what the Python interpreter will see; turn off anything which replaces one character with another (such as quotation marks), or wraps the code lines. * When asking about an error, *show us* the error by pasting exactly what the error is, including the part where it shows what line raised the exception. * Tell us what you expected the code to do, and how its behaviour is violating your expectations. Thanks for joining discussions here, hopefully you can become a good part of this community. -- \ ?If I haven't seen as far as others, it is because giants were | `\ standing on my shoulders.? ?Hal Abelson | _o__) | Ben Finney From sturla.molden at gmail.com Fri Feb 7 00:28:26 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Fri, 7 Feb 2014 05:28:26 +0000 (UTC) Subject: python and matlab References: <239c6022-9c8d-48d4-8ddf-cae552ab1e3d@googlegroups.com> Message-ID: <226582382413442570.573339sturla.molden-gmail.com@news.gmane.org> Sam Adams wrote: > Thanks Sturla, could you please explain in more details, I am new to Python :) All the information you need to extend or embed Python is in the docs. Apart from that, why do you need Matlab? A distro like Enthought Canopy or Anaconda has all the tools you will ever need for scientific programming. Embedding Python is almost never the right solution to a problem. But if you really need Matlab, you will be far better off by calling Matlab engine from Python (e.g. using ctypes or Cython). There are also packages like mlab and matlabwrap that will help you embed Matlab in Python: https://pypi.python.org/pypi/mlab http://mlabwrap.sourceforge.net Apart from that, you can also invoke Python from Matlab like this: arg1 = 'script.py'; s = system(sprintf('python %s', arg1)); or arg1 = 'some Python code'; s = system(sprintf('python -c "%s"', arg1)); Or if you are on Windows, you can use pywin32 to create an ActiveX server with Python, and invoke that from Matlab. Sturla From swdunning at cox.net Fri Feb 7 00:37:05 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 6 Feb 2014 22:37:05 -0700 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: > > A few things that will make your communications more fruitful: > > * Please don't top-post. Trim the quoted material to the parts relevant > for your response, and respond inline like a normal discussion. Oh, ok sorry about that. Like this? > > * Ensure that your message composer doesn't munge your text. Anyway to check on my mail composer to see it it muges my text? Also should I erase everything else in the message that I?m not responding to? Thanks for your advice. From ben+python at benfinney.id.au Fri Feb 7 00:55:07 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 07 Feb 2014 16:55:07 +1100 Subject: Python 2.7.6 help with white spaces? References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> Message-ID: <851tzfeabo.fsf@benfinney.id.au> Scott W Dunning writes: > > * Please don't top-post. Trim the quoted material to the parts > > relevant for your response, and respond inline like a normal > > discussion. > > Oh, ok sorry about that. Like this? Yes. You also need to preserve the attribution lines (the lines inserted for each quoted message like ?Fred Nurk wrote:?, or similar) at each level so we can see who wrote what. > > * Ensure that your message composer doesn't munge your text. > > Anyway to check on my mail composer to see it it muges my text? You should consult the documentation for whatever you're using to compose a message, looking for things like ?auto-correct? or anything else which suggests it will automatically change what you type. > Also should I erase everything else in the message that I?m not > responding to? Yes. All that should remain is the quoted text you're responding to, the attribution lines for whatever you've quoted, and what you write yourself. > Thanks for your advice. No problems, thanks for the effort! -- \ ?Geeks like to think that they can ignore politics. You can | `\ leave politics alone, but politics won't leave you alone.? | _o__) ?Richard Stallman, 2002-07-26 | Ben Finney From rustompmody at gmail.com Fri Feb 7 01:06:38 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 6 Feb 2014 22:06:38 -0800 (PST) Subject: python and matlab In-Reply-To: References: <239c6022-9c8d-48d4-8ddf-cae552ab1e3d@googlegroups.com> Message-ID: <413fb74f-ea38-44e9-b898-dae888af1866@googlegroups.com> On Friday, February 7, 2014 10:58:26 AM UTC+5:30, Sturla Molden wrote: > Sam Adams wrote: > > Thanks Sturla, could you please explain in more details, I am new to Python :) > All the information you need to extend or embed Python is in the docs. > Apart from that, why do you need Matlab? A distro like Enthought Canopy or > Anaconda has all the tools you will ever need for scientific programming. > Embedding Python is almost never the right solution to a problem. But if > you really need Matlab, you will be far better off by calling Matlab engine > from Python (e.g. using ctypes or Cython). Dont know the software involved so only some general comments When you connect two disparate pieces of significant software there is inherently an impedance mismatch. What Sturla is probably saying is that the matmab-python imp-mismatch is so high that jumping across is almost certainly not worth the trouble. And BTW have you seen sage? http://www.sagemath.org/ From __peter__ at web.de Fri Feb 7 03:25:10 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Feb 2014 09:25:10 +0100 Subject: Question about `list.insert` References: <4041bba7-91bc-4803-9150-2fcf14ecb5a9@googlegroups.com> Message-ID: cool-RR wrote: > I'm curious. If I append an item to a list from the left using > `list.insert`, will Python always move the entire list one item to the > right (which can be super-slow) or will it check first to see whether it > can just allocate more memory to the left of the list and put the item > there, saving a lot of resources? Let's see: $ python3.4 -m timeit -s 'a = [None]' 'a.insert(0, None); del a[0]' 1000000 loops, best of 3: 0.596 usec per loop $ python3.4 -m timeit -s 'a = [None]*1000' 'a.insert(0, None); del a[0]' 100000 loops, best of 3: 2.59 usec per loop $ python3.4 -m timeit -s 'a = [None]*10000' 'a.insert(0, None); del a[0]' 10000 loops, best of 3: 24.7 usec per loop $ python3.4 -m timeit -s 'a = [None]*100000' 'a.insert(0, None); del a[0]' 1000 loops, best of 3: 508 usec per loop $ python3.4 -m timeit -s 'a = [None]*1000000' 'a.insert(0, None); del a[0]' 100 loops, best of 3: 7.61 msec per loop $ python3.4 -m timeit -s 'from collections import deque; a = deque([None]*1000000)' 'a.appendleft(None); a.popleft()' 1000000 loops, best of 3: 0.263 usec per loop From sturla.molden at gmail.com Fri Feb 7 06:07:04 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Fri, 7 Feb 2014 11:07:04 +0000 (UTC) Subject: python and matlab References: <413fb74f-ea38-44e9-b898-dae888af1866@googlegroups.com> Message-ID: <849353249413462715.213823sturla.molden-gmail.com@news.gmane.org> Rustom Mody wrote: > What Sturla is probably saying is that the matmab-python imp-mismatch is > so high that jumping across is almost certainly not worth the trouble. I am saying that the abundance of Python packages for numerical and scientific computing (NumPy et al.) and their quality is now so good that binding Python to Matlab is not worth the effort. The only reason to do this would be if Matlab is needed for a very special reason. E.g. there might be a toolbox only available for Matlab, or there might be an administrative decision to use Matlab albeit a Python package is needed. But if it is just a general feeling that Python lacks the tools needed for numerical computing, then it is a false assumption and not worth it. Note that hardly any of the tools used for numerical computing with Python is in the standard library. They are all focused around NumPy as the central package. See scipy.org for further information. > And BTW have you seen sage? > http://www.sagemath.org/ Sage is supposed to be a computer algebra system, i.e. a free alternative to Maple or Mathematica. Matlab is not a CAS system but a scripting environment for numerical computing. Enthought Canopy and Anaconda are similar environments based on Python. enthought.com continuum.io While they require a payed license, it is also possible to hand-pick the needed packages and install them ourselves. But for libraries like NumPy to be liked against high-performance libraries like Intel MKL, we must build them ourselves or use one of the commercial Python distros for scientific computing. Sturla From dfnsonfsduifb at gmx.de Fri Feb 7 13:06:36 2014 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 07 Feb 2014 19:06:36 +0100 Subject: Possible bug with stability of mimetypes.guess_* function output Message-ID: Hi group, I'm using Python 3.3.2+ (default, Oct 9 2013, 14:50:09) [GCC 4.8.1] on linux and have found what is very peculiar behavior at best and a bug at worst. It regards the mimetypes module and in particular the guess_all_extensions and guess_extension functions. I've found that these do not return stable output. When running the following commands, it returns one of: $ python3 -c 'import mimetypes; print(mimetypes.guess_all_extensions("text/html"), mimetypes.guess_extension("text/html"))' ['.htm', '.html', '.shtml'] .htm $ python3 -c 'import mimetypes; print(mimetypes.guess_all_extensions("text/html"), mimetypes.guess_extension("text/html"))' ['.html', '.htm', '.shtml'] .html So guess_extension(x) seems to always return guess_all_extensions(x)[0]. Curiously, "shtml" is never the first element. The other two are mixed with a probability of around 50% which leads me to believe they're internally managed as a set and are therefore affected by the (relatively new) nondeterministic hashing function initialization. I don't know if stable output is guaranteed for these functions, but it sure would be nice. Messes up a whole bunch of things otherwise :-/ Please let me know if this is a bug or expected behavior. Best regards, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht ?ffentlich! Ah, der neueste und bis heute genialste Streich unsere gro?en Kosmologen: Die Geheim-Vorhersage. - Karl Kaos ?ber R?diger Thomas in dsa From roegltd at gmail.com Fri Feb 7 14:09:19 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 11:09:19 -0800 (PST) Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: References: Message-ID: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> On Friday, February 7, 2014 8:06:36 PM UTC+2, Johannes Bauer wrote: > Hi group, > > I'm using Python 3.3.2+ (default, Oct 9 2013, 14:50:09) [GCC 4.8.1] on > linux and have found what is very peculiar behavior at best and a bug at > worst. It regards the mimetypes module and in particular the > guess_all_extensions and guess_extension functions. > > I've found that these do not return stable output. When running the > following commands, it returns one of: > > $ python3 -c 'import mimetypes; > print(mimetypes.guess_all_extensions("text/html"), > mimetypes.guess_extension("text/html"))' > ['.htm', '.html', '.shtml'] .htm > > $ python3 -c 'import mimetypes; > print(mimetypes.guess_all_extensions("text/html"), > mimetypes.guess_extension("text/html"))' > ['.html', '.htm', '.shtml'] .html > > So guess_extension(x) seems to always return guess_all_extensions(x)[0]. > > Curiously, "shtml" is never the first element. The other two are mixed > with a probability of around 50% which leads me to believe they're > internally managed as a set and are therefore affected by the > (relatively new) nondeterministic hashing function initialization. > > > I don't know if stable output is guaranteed for these functions, but it > sure would be nice. Messes up a whole bunch of things otherwise :-/ > > Please let me know if this is a bug or expected behavior. > > Best regards, > > Johannes dictionary. same for v3.3.3 as well. it might be you could try to query using sequence below : import mimetypes mimetypes.init() mimetypes.guess_extension("text/html") i got only 'htm' for 5 consequitive attempts /Asaf From roegltd at gmail.com Fri Feb 7 14:17:25 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 11:17:25 -0800 (PST) Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: <01c8e74a-5451-40a8-958a-c58c86a9f77f@googlegroups.com> btw, had seen this after own post - example usage includes mimetypes.init() before call to module functions. From breamoreboy at yahoo.co.uk Fri Feb 7 14:28:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 07 Feb 2014 19:28:01 +0000 Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: <01c8e74a-5451-40a8-958a-c58c86a9f77f@googlegroups.com> References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> <01c8e74a-5451-40a8-958a-c58c86a9f77f@googlegroups.com> Message-ID: On 07/02/2014 19:17, Asaf Las wrote: > btw, had seen this after own post - > example usage includes mimetypes.init() > before call to module functions. > From http://docs.python.org/3/library/mimetypes.html#module-mimetypes third paragraph "The functions described below provide the primary interface for this module. If the module has not been initialized, they will call init() if they rely on the information init() sets up." Draw your own conclusions :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From dfnsonfsduifb at gmx.de Fri Feb 7 14:39:27 2014 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Fri, 07 Feb 2014 20:39:27 +0100 Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: On 07.02.2014 20:09, Asaf Las wrote: > it might be you could try to query using sequence below : > > import mimetypes > mimetypes.init() > mimetypes.guess_extension("text/html") > > i got only 'htm' for 5 consequitive attempts Doesn't change anything. With this: #!/usr/bin/python3 import mimetypes mimetypes.init() print(mimetypes.guess_extension("application/msword")) And a call like this: $ for i in `seq 100`; do ./x.py ; done | sort | uniq -c I get 35 .doc 24 .dot 41 .wiz Regards, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht ?ffentlich! Ah, der neueste und bis heute genialste Streich unsere gro?en Kosmologen: Die Geheim-Vorhersage. - Karl Kaos ?ber R?diger Thomas in dsa From __peter__ at web.de Fri Feb 7 14:40:06 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Feb 2014 20:40:06 +0100 Subject: Possible bug with stability of mimetypes.guess_* function output References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: Asaf Las wrote: > On Friday, February 7, 2014 8:06:36 PM UTC+2, Johannes Bauer wrote: >> Hi group, >> >> I'm using Python 3.3.2+ (default, Oct 9 2013, 14:50:09) [GCC 4.8.1] on >> linux and have found what is very peculiar behavior at best and a bug at >> worst. It regards the mimetypes module and in particular the >> guess_all_extensions and guess_extension functions. >> >> I've found that these do not return stable output. When running the >> following commands, it returns one of: >> >> $ python3 -c 'import mimetypes; >> print(mimetypes.guess_all_extensions("text/html"), >> mimetypes.guess_extension("text/html"))' >> ['.htm', '.html', '.shtml'] .htm >> >> $ python3 -c 'import mimetypes; >> print(mimetypes.guess_all_extensions("text/html"), >> mimetypes.guess_extension("text/html"))' >> ['.html', '.htm', '.shtml'] .html >> >> So guess_extension(x) seems to always return guess_all_extensions(x)[0]. >> >> Curiously, "shtml" is never the first element. The other two are mixed >> with a probability of around 50% which leads me to believe they're >> internally managed as a set and are therefore affected by the >> (relatively new) nondeterministic hashing function initialization. >> >> >> I don't know if stable output is guaranteed for these functions, but it >> sure would be nice. Messes up a whole bunch of things otherwise :-/ >> >> Please let me know if this is a bug or expected behavior. >> >> Best regards, >> >> Johannes > > dictionary. same for v3.3.3 as well. > > it might be you could try to query using sequence below : > > import mimetypes > mimetypes.init() > mimetypes.guess_extension("text/html") > > i got only 'htm' for 5 consequitive attempts As Johannes mentioned, this depends on the hash seed: $ PYTHONHASHSEED=0 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' .html $ PYTHONHASHSEED=1 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' .htm $ PYTHONHASHSEED=2 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' .shtml You never see ".shtml" as the guessed extension because it is not in the original mimetypes.types_map dict, but instead programmaticaly read from a file like /etc/mime.types and then added to a list of extensions. Johanes, I'd like the guessed extension to be consistent, too, but even if that is rejected the current behaviour should be documented. Please file a bug report. From roegltd at gmail.com Fri Feb 7 15:25:52 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 12:25:52 -0800 (PST) Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: On Friday, February 7, 2014 9:40:06 PM UTC+2, Peter Otten wrote: > As Johannes mentioned, this depends on the hash seed: > $ PYTHONHASHSEED=0 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' > .html > $ PYTHONHASHSEED=1 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' > .htm > $ PYTHONHASHSEED=2 python3 -c 'print({".htm", ".html", ".shtml"}.pop())' > .shtml > > You never see ".shtml" as the guessed extension because it is not in the > original mimetypes.types_map dict, but instead programmaticaly read from a > file like /etc/mime.types and then added to a list of extensions. > as there are bunch of files in mimetypes.py the only repeatability could be achieved on particular machine level. "/etc/mime.types", "/etc/httpd/mime.types", "/etc/httpd/conf/mime.types", "/etc/apache/mime.types", "/etc/apache2/mime.types", "/usr/local/etc/httpd/conf/mime.types", "/usr/local/lib/netscape/mime.types", "/usr/local/etc/httpd/conf/mime.types", "/usr/local/etc/mime.types" From dante.signal31 at gmail.com Fri Feb 7 15:45:32 2014 From: dante.signal31 at gmail.com (Dante Signal31) Date: Fri, 7 Feb 2014 21:45:32 +0100 Subject: Python 2.7.6 help with white spaces? In-Reply-To: <851tzfeabo.fsf@benfinney.id.au> References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> <851tzfeabo.fsf@benfinney.id.au> Message-ID: 2014-02-07 6:55 GMT+01:00 Ben Finney : > Scott W Dunning writes: > > > > * Please don't top-post. Trim the quoted material to the parts > > > relevant for your response, and respond inline like a normal > > > discussion. > > > > Oh, ok sorry about that. Like this? > > Yes. You also need to preserve the attribution lines (the lines inserted > for each quoted message like "Fred Nurk wrote:", or similar) at each > level so we can see who wrote what. > > > > * Ensure that your message composer doesn't munge your text. > > > > Anyway to check on my mail composer to see it it muges my text? > > You should consult the documentation for whatever you're using to > compose a message, looking for things like "auto-correct" or anything > else which suggests it will automatically change what you type. > > > Also should I erase everything else in the message that I'm not > > responding to? > > Yes. All that should remain is the quoted text you're responding to, the > attribution lines for whatever you've quoted, and what you write > yourself. > > > Thanks for your advice. > > No problems, thanks for the effort! > > -- > \ "Geeks like to think that they can ignore politics. You can | > `\ leave politics alone, but politics won't leave you alone." | > _o__) --Richard Stallman, 2002-07-26 | > Ben Finney > > -- > https://mail.python.org/mailman/listinfo/python-list > Just one more solution for original question, surely not the best but only to cover all possibilities: print("{0}:{1}".format(minutes,seconds)) -- Dante *Blogger (espa?ol):* http://danteslab.blogspot.com/ *Blogger (english):* http://danteslab-eng.blogspot.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Feb 7 16:11:37 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 07 Feb 2014 21:11:37 +0000 Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> <851tzfeabo.fsf@benfinney.id.au> Message-ID: On 07/02/2014 20:45, Dante Signal31 wrote: > > Just one more solution for original question, surely not the best but > only to cover all possibilities: > > print("{0}:{1}".format(minutes,seconds)) > > -- > Dante Fancy wasting two whole characters when this will suffice print("{}:{}".format(minutes,seconds)) :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From visphatesjava at gmail.com Fri Feb 7 16:20:42 2014 From: visphatesjava at gmail.com (johannes falcone) Date: Fri, 7 Feb 2014 13:20:42 -0800 (PST) Subject: anyone have a nagare based website up I can see? comment on experience of using? Message-ID: <5f0cbe49-5a26-4a31-88b8-f60c231bdc70@googlegroups.com> looks cool http://www.nagare.org/trac/wiki/NagareFeatures From roegltd at gmail.com Fri Feb 7 16:45:21 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 13:45:21 -0800 (PST) Subject: Python 2.7.6 help with white spaces? In-Reply-To: References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> <851tzfeabo.fsf@benfinney.id.au> Message-ID: <1907f236-a7f0-4c55-b0ed-752005726bec@googlegroups.com> On Friday, February 7, 2014 11:11:37 PM UTC+2, Mark Lawrence wrote: > > Fancy wasting two whole characters when this will suffice > > print("{}:{}".format(minutes,seconds)) :) > > > Mark Lawrence Hmmmm, got error: File "", line 1 print("{}:{}".format(minutes,seconds)) :) ^ SyntaxError: invalid syntax :-) From roel at roelschroeven.net Fri Feb 7 17:06:53 2014 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 07 Feb 2014 23:06:53 +0100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: <52F3FF51.3050502@stoneleaf.us> Message-ID: Chris Angelico schreef: > But none of this would solve the OP's original issue. Whether it's a > tab or spaces, unexpectedly indenting a line of code is a problem. I had misread. I thought the problem was that the OP did want to indent, but accidentally used the tab key instead of the space bar to do so, introducing the dreaded mixing of tabs and spaces. Remapping the tab key would solve that problem. But the real problem was different, so my advice was indeed not a solution to the problem. I should've read better. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From breamoreboy at yahoo.co.uk Fri Feb 7 17:09:08 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 07 Feb 2014 22:09:08 +0000 Subject: Python 2.7.6 help with white spaces? In-Reply-To: <1907f236-a7f0-4c55-b0ed-752005726bec@googlegroups.com> References: <504A0CAE-42E4-495E-96AA-C8A45559E139@cox.net> <851tzfeabo.fsf@benfinney.id.au> <1907f236-a7f0-4c55-b0ed-752005726bec@googlegroups.com> Message-ID: On 07/02/2014 21:45, Asaf Las wrote: > On Friday, February 7, 2014 11:11:37 PM UTC+2, Mark Lawrence wrote: >> >> Fancy wasting two whole characters when this will suffice >> >> print("{}:{}".format(minutes,seconds)) :) >> >> >> Mark Lawrence > > Hmmmm, got error: > > File "", line 1 > print("{}:{}".format(minutes,seconds)) :) > ^ > SyntaxError: invalid syntax > > :-) > I think we'd all better ease up with the humour. This will suit the people who want this list turned into something bland and boring that can only discuss Python code written to conform to PEP 8 and anything else is by definition off topic :( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From roel at roelschroeven.net Fri Feb 7 17:08:10 2014 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 07 Feb 2014 23:08:10 +0100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: msustik at gmail.com schreef: > On Thursday, February 6, 2014 12:29:36 PM UTC-8, Roel Schroeven wrote: >> My suggestion: configure your editor to insert the appropriate amount of >> >> spaces instead of a tab when you press the tab key. > > You misunderstood the problem, but managed to start a Tab war! :-) Indeed I did; sorry for both :-) -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From cs at zip.com.au Fri Feb 7 20:18:02 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 8 Feb 2014 12:18:02 +1100 Subject: Using virtualenv to bypass sudoer issues In-Reply-To: <1007676733.3292144.1391707932990.JavaMail.root@sequans.com> References: <1007676733.3292144.1391707932990.JavaMail.root@sequans.com> Message-ID: <20140208011802.GA36145@cskk.homeip.net> On 06Feb2014 18:32, Jean-Michel Pichavant wrote: > Assuming I have a debian workstation for which I don't have any > sudo rights, in order to be able to install / remove python packages, > should I be using virtualenv ? Is it a suited solution ? It is well suited. You can also do far simpler (and far smaller setups) like this: mkdir -p $HOME/lib/python and in your environment (eg $HOME/.profile or $HOME/.bash_profile) add: PYTHONPATH=$HOME/lib/python:$PYTHON_PATH export PYTHONPATH and simply install (copy) packages into that directory. This is conceptually the same as having a $HOME/bin with commands or your own in it, etc. If you're getting your packages from pypi, virutalenv may be easier to use in the long run. besides, it lets you make multiple environments for different flavours of Python (2 vs 3, etc). Cheers, -- Cameron Simpson I just kept it wide-open thinking it would correct itself. Then I ran out of talent. - C. Fittipaldi From steve+comp.lang.python at pearwood.info Fri Feb 7 21:48:12 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 08 Feb 2014 02:48:12 GMT Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> Message-ID: <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> On Thu, 06 Feb 2014 05:51:54 -0800, wxjmfauth wrote: > Sorry, I'm only pointing you may lose memory when working with short > strings as it was explained. I really, very really, do not see what is > absurd or obsure in: > >>>> sys.getsizeof('abc' + 'EURO') > 46 >>>> sys.getsizeof(('abc' + 'EURO').encode('utf-32')) > 37 Why do you care about NINE bytes? The least amount of memory in any PC that I know about is 500000000 bytes, more than fifty million times more. And you are whinging about wasting nine bytes? If you care about that lousy nine bytes, Python is not the language for you. Go and program in C, where you can spent ten or twenty times longer programming, but save nine bytes in every string. Nobody cares about your memory "benchmark" except you. Python is not designed to save memory, Python is designed to use as much memory as needed to give the programmer an easier job. In C, I can store a single integer in a single byte. In Python, horror upon horrors, it takes 14 bytes!!! py> sys.getsizeof(1) 14 We consider it A GOOD THING that Python spends memory for programmer convenience and safety. Python looks for memory optimizations when it can save large amounts of memory, not utterly trivial amounts. So in a Python wide build, a ten-thousand block character string requires a little bit more than 40KB. In Python 3.3, that can be reduced to only 10KB for a purely Latin-1 string, or 20K for a string without any astral characters. That's the sort of memory savings that are worthwhile, reducing memory usage by 75%. Could Python save memory by using UTF-8? Yes. But it would cost complexity and time, strings would be even slower than they are now. That is not a trade-off that the core developers have chosen to make, and I agree with them. -- Steven From roegltd at gmail.com Fri Feb 7 22:03:51 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 19:03:51 -0800 (PST) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: References: <1007676733.3292144.1391707932990.JavaMail.root@sequans.com> Message-ID: On Saturday, February 8, 2014 3:18:02 AM UTC+2, Cameron Simpson wrote: > On 06Feb2014 18:32, Jean-Michel Pichavant wrote: > > > Assuming I have a debian workstation for which I don't have any > > sudo rights, in order to be able to install / remove python packages, > > should I be using virtualenv ? Is it a suited solution ? > > It is well suited. > > You can also do far simpler (and far smaller setups) like this: > > mkdir -p $HOME/lib/python > > and in your environment (eg $HOME/.profile or $HOME/.bash_profile) add: > > PYTHONPATH=$HOME/lib/python:$PYTHON_PATH > export PYTHONPATH > and simply install (copy) packages into that directory. > > This is conceptually the same as having a $HOME/bin with commands > or your own in it, etc. > > If you're getting your packages from pypi, virutalenv may be easier > to use in the long run. besides, it lets you make multiple > environments for different flavours of Python (2 vs 3, etc). > > Cheers, > > Cameron Simpson > > I just kept it wide-open thinking it would correct itself. > Then I ran out of talent. - C. Fittipaldi Hi Does this approach work with mixed packages comprising non python code? /Asaf From cs at zip.com.au Fri Feb 7 22:32:22 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 8 Feb 2014 14:32:22 +1100 Subject: Using virtualenv to bypass sudoer issues In-Reply-To: References: Message-ID: <20140208033222.GA67640@cskk.homeip.net> On 07Feb2014 19:03, Asaf Las wrote: > On Saturday, February 8, 2014 3:18:02 AM UTC+2, Cameron Simpson wrote: > > On 06Feb2014 18:32, Jean-Michel Pichavant wrote: > > > > > Assuming I have a debian workstation for which I don't have any > > > sudo rights, in order to be able to install / remove python packages, > > > should I be using virtualenv ? Is it a suited solution ? > > > > It is well suited. > > > > You can also do far simpler (and far smaller setups) like this: > > mkdir -p $HOME/lib/python > > and in your environment (eg $HOME/.profile or $HOME/.bash_profile) add: > > PYTHONPATH=$HOME/lib/python:$PYTHON_PATH > > export PYTHONPATH > > and simply install (copy) packages into that directory. > > This is conceptually the same as having a $HOME/bin with commands > > or your own in it, etc. [...] > > Does this approach work with mixed packages comprising non python > code? Persuming you are asking about "just make a lib directory and point $PYTHONPATH at it" instead of virtualenv, in principle yes. But it is more work; virtualenv is essentially a well standardised and more thorough version. Most such mixed packages install with a setup.py that compiles the relevant bits, and you'll need to tell setup.py where to install things, so it is not as easy as just copying in the files. I think such packages are about the point where I would consider virtualenv; once you have the virtualenv set up, installing packages is more automatic. For pure python packages, just copying them into your personal lib works well, and is very simple. As soon as you get mixed packages, it is probably more worthwhile to use virtualenv. I think. Virtualenv looks like a bit of a leap to set up to start with, but I found it easier than I expected. As I recall, you can do two basic types of virtualenv: a "complete" one which installs copies of all the system packages, or a much smaller one that itself hooks into the system python packages. Cheers, -- Cameron Simpson Life IS pain, highness... anyone who tries to tell you different is trying to sell you something. - Wesley, The_Princess_Bride From ethan at stoneleaf.us Fri Feb 7 22:02:09 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 07 Feb 2014 19:02:09 -0800 Subject: Finding size of Variable In-Reply-To: <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52F59E31.1020407@stoneleaf.us> On 02/07/2014 06:48 PM, Steven D'Aprano wrote: > > That is not a trade-off that the core developers have chosen to make, > and I agree with them. Even though you haven't broken all the build-bots yet, you can still stop saying "them". ;) -- ~Ethan~ From roegltd at gmail.com Fri Feb 7 23:31:27 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 20:31:27 -0800 (PST) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: References: Message-ID: <76eaff32-0167-4e57-b9f8-73c88250518c@googlegroups.com> On Saturday, February 8, 2014 5:32:22 AM UTC+2, Cameron Simpson wrote: > On 07Feb2014 19:03, Asaf Las wrote: > > Persuming you are asking about "just make a lib directory and point > $PYTHONPATH at it" instead of virtualenv, in principle yes. > But it is more work; virtualenv is essentially a well standardised and more > thorough version. > > Most such mixed packages install with a setup.py that compiles the > relevant bits, and you'll need to tell setup.py where to install > things, so it is not as easy as just copying in the files. > > I think such packages are about the point where I would consider > virtualenv; once you have the virtualenv set up, installing packages > is more automatic. > > For pure python packages, just copying them into your personal lib > works well, and is very simple. As soon as you get mixed packages, > it is probably more worthwhile to use virtualenv. I think. > > Virtualenv looks like a bit of a leap to set up to start with, but > I found it easier than I expected. As I recall, you can do two basic > types of virtualenv: a "complete" one which installs copies of all > the system packages, or a much smaller one that itself hooks into > the system python packages. > > > Cheers, > > Cameron Simpson Thanks still there are changes http://docs.python.org/3.4/library/venv.html i hope one day it will be possible to deploy app over net by just unpacking tar ball done at test machine on production one, though this seems questionable: http://www.virtualenv.org/en/latest/virtualenv.html#making-environments-relocatable it might be for some packages relying on 3rd party libs such as lxml, root account had to be provided. or may be there are some acceptable hacks similar to patching RPATH on bin's? Regards Asaf From swdunning at cox.net Fri Feb 7 23:44:10 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 7 Feb 2014 21:44:10 -0700 Subject: Python 2.7.6 help with modules Message-ID: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> I have a question that was a part of my homework and I got it correct but the teacher urged me to do it using the % sign rather than subtracting everything, for some reason I?m having issues getting it to calculate correctly. I?ll put the question below, and what I originally had and below that what I?ve been working on with the %. create a python script for 'Enter the number of Seconds' and get results in weeks, days, hours, minutes and seconds. This is what I originally submitted for my homework. seconds = raw_input("Enter the number of seconds:") seconds = int(seconds) weeks = seconds / (7*24*60*60) seconds = seconds - weeks*7*24*60*60 days = seconds / (24*60*60) seconds = seconds - days*24*60*60 hours = seconds / (60*60) seconds = seconds - hours*60*60 minutes = seconds / 60 seconds = seconds - minutes *60 print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds' - This is what I?ve been working with. I get the correct answers for minutes and seconds then it goes to shit after that. seconds = raw_input("Enter the number of seconds:") seconds = int(seconds) minutes = seconds/60 seconds = seconds % 60 minutes = minutes % 60 hours = seconds/3600 hours = seconds % 3600 days = seconds/86400 days = seconds % 86400 weeks = seconds/604800 weeks = seconds % 604800 print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds' Any help is greatly appreciated! Thanks again! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Sat Feb 8 00:05:49 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 7 Feb 2014 21:05:49 -0800 (PST) Subject: Python 2.7.6 help with modules In-Reply-To: References: Message-ID: <78b976da-4ca0-4a65-b28d-e9e575939864@googlegroups.com> On Saturday, February 8, 2014 10:14:10 AM UTC+5:30, Scott W Dunning wrote: > I have a question that was a part of my homework and I got it correct but the teacher urged me to do it using the % sign rather than subtracting everything, for some reason I'm having issues getting it to calculate correctly. I'll put the question below, and what I originally had and below that what I've been working on with the %. Simple hint When you divide a by b, you get a quotient(q) and remainder(r) satisfying the equation a = qb + r Instead of keeping on calculating r by doing r= a - qb you can use python's builtin divmod which will give you q and r together >>> t=65 >>> divmod(t,60) (1, 5) which basically means that 65 secs is 1 min and 5 secs From rosuav at gmail.com Sat Feb 8 00:10:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 16:10:03 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: On Sat, Feb 8, 2014 at 3:44 PM, Scott W Dunning wrote: > - This is what I?ve been working with. I get the correct answers for > minutes and seconds then it goes to shit after that. > > seconds = raw_input("Enter the number of seconds:") > seconds = int(seconds) > minutes = seconds/60 > seconds = seconds % 60 > minutes = minutes % 60 > hours = seconds/3600 > hours = seconds % 3600 > days = seconds/86400 > days = seconds % 86400 > weeks = seconds/604800 > weeks = seconds % 604800 > print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', > seconds, 'seconds' > > Any help is greatly appreciated! Thanks again! It might be easiest to think in terms of a single "divide into quotient and remainder" operation. Let's leave aside weeks/days/hours/minutes/seconds and split a number up into its digits. (This is actually not as useless as you might think; in low level programming, this is how to display a number on the screen, for instance.) number = int(raw_input("Enter a five-digit number: ")) Now we begin to split it up: foo = number % 10 bar = number / 10 Do you know, without running the code, what 'foo' and 'bar' will be? Give those two variables better names (hint: one of them would be appropriately named "last_digit"), and then work on some more pieces of the puzzle. You should be able to get this to the point of writing out five separate values, which are the original five digits. Each one is worth 10 of the previous value. At every step, do both halves of the division. (Python actually has a function 'divmod' which makes this a bit more efficient and maybe clearer and tidier, but leave that aside for the moment and just use / and %.) Can you work out what it's doing more easily this way? You should then be able to follow the same principles in working out the time unit problem. Apart from being all different factors (60, 24, and 7), it's the same fundamental as the 10-based digit split. If you get stuck, tell us how far you got and we can help you over the next hump. ChrisA From rosuav at gmail.com Sat Feb 8 00:12:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 16:12:13 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: On Sat, Feb 8, 2014 at 3:44 PM, Scott W Dunning wrote: > I have a question that was a part of my homework and I got it correct but > the teacher urged me to do it using the % sign rather than subtracting > everything, for some reason I?m having issues getting it to calculate > correctly. Oh by the way... Your subject line says "modules", but the % operator calculates "modulo". Modules are sections of Python-callable code - there's a "sys" module, a "math" module, and so on - and you can call them up with the "import" statement: import sys import math etc. Modulo means remainder (a bit of handwaving there - look it up on Wikipedia if you care about the specifics), which is what you're doing here. ChrisA From roegltd at gmail.com Sat Feb 8 00:21:41 2014 From: roegltd at gmail.com (Asaf Las) Date: Fri, 7 Feb 2014 21:21:41 -0800 (PST) Subject: Python 2.7.6 help with modules In-Reply-To: <78b976da-4ca0-4a65-b28d-e9e575939864@googlegroups.com> References: <78b976da-4ca0-4a65-b28d-e9e575939864@googlegroups.com> Message-ID: On Saturday, February 8, 2014 7:05:49 AM UTC+2, Rustom Mody wrote: > On Saturday, February 8, 2014 10:14:10 AM UTC+5:30, Scott W Dunning wrote: > > > I have a question that was a part of my homework > > and I got it correct but the teacher urged me to do it using the > > % sign rather than subtracting everything, for some reason I'm > > having issues getting it to calculate correctly. I'll put the > > question below, and what I originally had and below that what > > I've been working on with the %. > > just 2 lines, they are self explanatory days = int((seconds % (60 * 60 * 24 * 7))/(60 * 60 * 24)) hours = int((seconds % (60 * 60 * 24))/(60 * 60)) feel free to ask /Asaf From swdunning at cox.net Sat Feb 8 00:53:24 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 7 Feb 2014 22:53:24 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: On Feb 7, 2014, at 10:10 PM, Chris Angelico wrote: > It might be easiest to think in terms of a single "divide into > quotient and remainder" operation. Let's leave aside > weeks/days/hours/minutes/seconds and split a number up into its > digits. (This is actually not as useless as you might think; in low > level programming, this is how to display a number on the screen, for > instance.) > > number = int(raw_input("Enter a five-digit number: ")) > > Now we begin to split it up: > > foo = number % 10 > bar = number / 10 > > Do you know, without running the code, what 'foo' and 'bar' will be? > Give those two variables better names (hint: one of them would be > appropriately named "last_digit"), and then work on some more pieces > of the puzzle. So, if I use the five digit # 50000, bar = 5000, and foo = 0 because there is no remainder after dividing by 10? Does it make a difference weather foo or bar are written first? Thanks for the help Chris! > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Sat Feb 8 00:50:54 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 7 Feb 2014 21:50:54 -0800 (PST) Subject: Python 2.7.6 help with modules In-Reply-To: <78b976da-4ca0-4a65-b28d-e9e575939864@googlegroups.com> References: <78b976da-4ca0-4a65-b28d-e9e575939864@googlegroups.com> Message-ID: <8bedc6f1-9bf1-448f-9055-68c47d4eb058@googlegroups.com> On Saturday, February 8, 2014 10:35:49 AM UTC+5:30, Rustom Mody wrote: > On Saturday, February 8, 2014 10:14:10 AM UTC+5:30, Scott W Dunning wrote: > > > I have a question that was a part of my homework and I got it correct but the teacher urged me to do it using the % sign rather than subtracting everything, for some reason I'm having issues getting it to calculate correctly. I'll put the question below, and what I originally had and below that what I've been working on with the %. One more general hint. If you write code with inputs and prints, you will end up writing messy code. The better alternative is to write pure functions -- inputs in arguments, outputs returned, not printed. To see the difference, look at a trivial subset of your problem: Convert seconds into minutes and seconds. I'll write it in your (print version) and an rv (return version) >>> def secs2minsec(): ... sec = int(raw_input("Enter number of secs ")) ... min, sec = divmod(sec,60) ... print min, "mins", sec, "secs" >>> def secs2minsecsrv(sec): return divmod(sec,60) Now you may think the second one is trivial and useless. However if you slightly increase the problem to adding hours, you will find that you can REUSE secs2minsecsrv whereas secs2minsec is more or less useless From swdunning at cox.net Sat Feb 8 00:55:47 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 7 Feb 2014 22:55:47 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: <098CDDFE-26B5-416B-AD9B-404D2E9C8282@cox.net> On Feb 7, 2014, at 10:10 PM, Chris Angelico wrote: > > You should be able to get this to the point of writing out five > separate values, which are the original five digits. Each one is worth > 10 of the previous value. At every step, do both halves of the > division. What do you mean by at each step do both halves of the division? > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 00:56:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 16:56:37 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: On Sat, Feb 8, 2014 at 4:53 PM, Scott W Dunning wrote: > So, if I use the five digit # 50000, bar = 5000, and foo = 0 because there > is no remainder after dividing by 10? Does it make a difference weather foo > or bar are written first? That's correct. It'll be more visible if you use a five-digit number with no zeroes in it. And no, it makes no difference, because you're reading from one place and storing somewhere else. ChrisA From rosuav at gmail.com Sat Feb 8 00:58:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 16:58:05 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <098CDDFE-26B5-416B-AD9B-404D2E9C8282@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <098CDDFE-26B5-416B-AD9B-404D2E9C8282@cox.net> Message-ID: On Sat, Feb 8, 2014 at 4:55 PM, Scott W Dunning wrote: > On Feb 7, 2014, at 10:10 PM, Chris Angelico wrote: > > > You should be able to get this to the point of writing out five > separate values, which are the original five digits. Each one is worth > 10 of the previous value. At every step, do both halves of the > division. > > > What do you mean by at each step do both halves of the division? > Taking the quotient (with the / operator) and the remainder (with %). You'll find it's clearer to start by doing distinct, separate operations, where each one is both division and modulo. ChrisA From swdunning at cox.net Sat Feb 8 01:27:12 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 7 Feb 2014 23:27:12 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> Message-ID: <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> > > On Feb 7, 2014, at 10:10 PM, Chris Angelico wrote: >> >> number = int(raw_input("Enter a five-digit number: ")) >> >> Now we begin to split it up: >> >> foo = number % 10 >> bar = number / 10 >> Ok, so it this what you?re talking about? number = int(raw_input(?Enter a five digit number:)) foo = number % 10 bar = number / 10 digit = foo / 10 rem = bar % 10 ???? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 01:29:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 17:29:47 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> Message-ID: On Sat, Feb 8, 2014 at 5:27 PM, Scott W Dunning wrote: > Ok, so it this what you?re talking about? > > > number = int(raw_input(?Enter a five digit number:)) > foo = number % 10 > bar = number / 10 > > digit = foo / 10 > rem = bar % 10 > Close! But if you print out foo and bar, you'll see that you're naming them backwards in the second one. The last digit is the remainder (modulo), the rest is the quotient. ChrisA From ikorot01 at gmail.com Sat Feb 8 02:06:37 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Fri, 7 Feb 2014 23:06:37 -0800 Subject: Sorting dictionary by datetime value Message-ID: Hi, ALL, I'm trying to do a very easy task: sort python dictionary by value where value is a datetime object. When trying to do that in Python shell everthing works as expected. C:\Documents and Settings\Igor.FORDANWORK>python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = {} >>> import datetime >>> a['1'] = datetime.datetime(2012,12,28,12,15,30,100) >>> a['2'] = datetime.datetime(2012,12,28,12,17,29,100) >>> a['3'] = datetime.datetime(2012,12,28,12,16,44,100) >>> sorted(a.items(), key=a.get) [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', datetime.datetim e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, 12, 17, 29, 100))] >>> However, trying to do the same thing from the script does not sort the dictionary: sorted(my_dict.items(), key=my_dict.get, reverse=False) for key, value in my_dict.items(): print value, key the dictionary prints with unsorted items. I am trying to run it on Windows XP and the data are coming from the DB. What am I missing? Thank you. From rosuav at gmail.com Sat Feb 8 02:09:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 18:09:36 +1100 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot wrote: >>>> sorted(a.items(), key=a.get) > [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', datetime.datetim > e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, 12, 17, > 29, 100))] >>>> > > However, trying to do the same thing from the script does not sort the > dictionary: > > sorted(my_dict.items(), key=my_dict.get, reverse=False) > for key, value in my_dict.items(): > print value, key > > the dictionary prints with unsorted items. The sorted() function returns a sorted list. You're then going back to the original dictionary. Instead, just iterate over the sorted items: items = sorted(my_dict.items(), key=my_dict.get, reverse=False) for key, value in items: print value, key ChrisA From cstrutton11 at gmail.com Sat Feb 8 02:41:53 2014 From: cstrutton11 at gmail.com (cstrutton11 at gmail.com) Date: Fri, 7 Feb 2014 23:41:53 -0800 (PST) Subject: What is the most pythonic way to build up large strings? Message-ID: I am writing a couple of class methods to build up several lines of html. Some of the lines are conditional and most need variables inserted in them. Searching the web has given me a few ideas. Each has its pro's and cons. The best I have come up with is: def output_header_js(self, jquery=True, theme=None): if self.static_path is None : return None if jquery is True: output = '"'% static > output += '"'% static > > if theme is not None: > output += ' > output += 'rel="stylesheet" type="text/css" />' > > output += '"' % "static" > > I realize that a lot of the above looks repetitive but it is > designed to eliminate boilerplate HTML. > note, due to strings are immutable - for every line in sum operation above you produce new object and throw out older one. you can write one string spanned at multiple lines in very clear form. /Asaf From rosuav at gmail.com Sat Feb 8 03:18:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 19:18:08 +1100 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 7:03 PM, Frank Millman wrote: > I am using python3. I don't know if that makes a difference, but I cannot > get it to work. > >>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>>> sorted(d.items(), key=d.get) > Traceback (most recent call last): > File "", line 1, in > TypeError: unorderable types: NoneType() < NoneType() >>>> You probably hadn't seen my subsequent post yet, in which I explain what's going on here. In Python 2, "None > None" is simply False. (So is "None < None", incidentally.) Py3 makes that an error. But in all your examples, you're effectively trying to sort the list [None, None, None], which is never going to be useful. What you can do, though, is either sort items using itemgetter to sort by the second element of the tuple, or sort keys using dict.get. Using 3.4.0b2: >>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>> sorted(d.keys(), key=d.get) [1, 3, 2] You don't get the values that way, but you get the keys in their correct order, so you can iterate over that and fetch the corresponding values. Alternatively, this is a bit more verbose, but works on items(): >>> import operator >>> sorted(d.items(), key=operator.itemgetter(1)) [(1, 'abc'), (3, 'pqr'), (2, 'xyz')] operator.itemgetter(1) returns a callable that, when passed some object, returns that_object[1]. ChrisA From frank at chagford.com Sat Feb 8 03:22:05 2014 From: frank at chagford.com (Frank Millman) Date: Sat, 8 Feb 2014 10:22:05 +0200 Subject: Sorting dictionary by datetime value References: Message-ID: "Frank Millman" wrote in message news:ld4ocf$9rg$1 at ger.gmane.org... > > "Chris Angelico" wrote in message > news:CAPTjJmqDusdFC1eLbU6LF5-up__LAE-63ii0UUvAGGNem9U4+w at mail.gmail.com... >> On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot wrote: >>>>>> sorted(a.items(), key=a.get) >>> [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', >>> datetime.datetim >>> e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, >>> 12, 17, >>> 29, 100))] > > That seemed like a neat trick, so I thought I would try to understand it a > bit better in case I could use it some day. > > I am using python3. I don't know if that makes a difference, but I cannot > get it to work. > >>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>>> sorted(d.items(), key=d.get) > Traceback (most recent call last): > File "", line 1, in > TypeError: unorderable types: NoneType() < NoneType() >>>> > > I know that python3 is stricter regarding ordering of non-comparable > types, but I don't see where None is coming from. > > I have python 2.7.3 on another machine. Here are the results - > >>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>>> sorted(d.items(), key=d.get) > [(1, 'abc'), (2, 'xyz'), (3, 'pqr')] > > It did not crash, but it did not sort. > > Then I changed the keys to strings, to match Igor's example - > >>>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'} >>>> sorted(d.items(), key=d.get) > [('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')] > > It works - now I am even more confused. > As Chris replied in another post - > The problem here is actually your key function. my_dict.items() > returns a series of two-item tuples, none of which exists in your > dictionary; so you're actually sorting [None, None, None], which isn't > very useful. > > Try this: > > sorted_items = sorted(my_dict.keys(), key=my_dict.get) > for key in sorted_items: > print my_dict[key], key > Without realising it, you have answered all my questions - thanks very much. Frank From roegltd at gmail.com Sat Feb 8 03:24:08 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 00:24:08 -0800 (PST) Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: On Saturday, February 8, 2014 9:51:48 AM UTC+2, Peter Otten wrote: > > At least the mimetypes already defined in the module could easily produce > the same guessed extension consistently. imho one workaround for OP could be to supply own map file in init() thus ensure unambiguous mapping across every platform and distribution. guess some libraries already doing that. or write wrapper and process all_guesses to eliminate ambiguity up to needed requirement. that is in case if bug request will be rejected. From ikorot01 at gmail.com Sat Feb 8 03:25:43 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 8 Feb 2014 00:25:43 -0800 Subject: Fwd: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Igor Korot Date: Sat, Feb 8, 2014 at 12:25 AM Subject: Re: Sorting dictionary by datetime value To: Chris Angelico Chris, On Fri, Feb 7, 2014 at 11:58 PM, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 6:53 PM, Igor Korot wrote: > > Chris, > > > > On Fri, Feb 7, 2014 at 11:09 PM, Chris Angelico > wrote: > >> On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot wrote: > >>>>>> sorted(a.items(), key=a.get) > >>> [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', > datetime.datetim > >>> e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, > 28, 12, 17, > >>> 29, 100))] > >>>>>> > >>> > >>> However, trying to do the same thing from the script does not sort the > >>> dictionary: > >>> > >>> sorted(my_dict.items(), key=my_dict.get, reverse=False) > >>> for key, value in my_dict.items(): > >>> print value, key > >>> > >>> the dictionary prints with unsorted items. > >> > >> The sorted() function returns a sorted list. You're then going back to > >> the original dictionary. Instead, just iterate over the sorted items: > >> > >> items = sorted(my_dict.items(), key=my_dict.get, reverse=False) > >> for key, value in items: > >> print value, key > > > > Still does not work. It prints: > > > > ======= > > DATE TIME - EVENT > > 058f63666438&0 - Instance ID > > Original values > > 2013-11-15 15:42:27.000499 User Datetime > > 2013-07-14 16:42:18.000637 Property Keys > > 2013-11-15 15:42:17.000938 Volume Device > > 2013-07-14 16:42:22.000276 Last Modify Reg Times 1 > > Sorted values > > 2013-11-15 15:42:27.000499 User Datetime > > 2013-07-14 16:42:18.000637 Property Keys > > 2013-11-15 15:42:17.000938 Volume Device > > 2013-07-14 16:42:22.000276 Last Modify Reg Times 1 > > > > Code is as follows: > > > > sorted_items = sorted(my_dict.items(), key=my_dict.get, reverse=False) > > print row[19], " - Instance ID" > > print "Original values" > > for key, value in my_dict.items(): > > print value, key > > print "Sorted values" > > for key, value in sorted_items: > > print value, key > > > > Thank you. > > Assuming you sent that privately only by mistake - hope you don't mind > me responding on-list. > > The problem here is actually your key function. my_dict.items() > returns a series of two-item tuples, none of which exists in your > dictionary; so you're actually sorting [None, None, None], which isn't > very useful. > > Try this: > > sorted_items = sorted(my_dict.keys(), key=my_dict.get) > for key in sorted_items: > print my_dict[key], key > This code fail. sorted_item is a list of tuples. And so iterating the list in the for loop I will get a tuple. It probably should be: for key[1] in sorted_items: Let me try that. Thank you. > > Note that reverse=False is the default, so you don't need to specify that. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Feb 8 03:27:20 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Feb 2014 09:27:20 +0100 Subject: Sorting dictionary by datetime value References: Message-ID: Frank Millman wrote: > > "Chris Angelico" wrote in message > news:CAPTjJmqDusdFC1eLbU6LF5-up__LAE-63ii0UUvAGGNem9U4+w at mail.gmail.com... >> On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot wrote: >>>>>> sorted(a.items(), key=a.get) >>> [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', >>> datetime.datetim >>> e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, >>> 12, 17, >>> 29, 100))] > > That seemed like a neat trick, so I thought I would try to understand it a > bit better in case I could use it some day. > > I am using python3. I don't know if that makes a difference, but I cannot > get it to work. > >>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>>> sorted(d.items(), key=d.get) > Traceback (most recent call last): > File "", line 1, in > TypeError: unorderable types: NoneType() < NoneType() >>>> > > I know that python3 is stricter regarding ordering of non-comparable > types, but I don't see where None is coming from. > > I have python 2.7.3 on another machine. Here are the results - > >>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'} >>>> sorted(d.items(), key=d.get) > [(1, 'abc'), (2, 'xyz'), (3, 'pqr')] > > It did not crash, but it did not sort. > > Then I changed the keys to strings, to match Igor's example - > >>>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'} >>>> sorted(d.items(), key=d.get) > [('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')] > > It works - now I am even more confused. > > Any hints will be appreciated. Chris has already explained it. Here you can watch the key calculation at work: >>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'} >>> def sortkey(value): ... key = d.get(value) ... print "value:", value, "sort-key:", key ... return key ... >>> sorted(d.items(), key=sortkey) value: ('1', 'abc') sort-key: None value: ('3', 'pqr') sort-key: None value: ('2', 'xyz') sort-key: None [('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')] Can you change the dict to make d.get return non-None values? The OP was probably trying to mimic sorted(d, key=d.get) which sorts the dict keys by the associated dict values: >>> sorted(d, key=sortkey) value: 1 sort-key: abc value: 3 sort-key: pqr value: 2 sort-key: xyz ['1', '3', '2'] From rosuav at gmail.com Sat Feb 8 03:29:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 19:29:09 +1100 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 7:25 PM, Igor Korot wrote: >> Try this: >> >> sorted_items = sorted(my_dict.keys(), key=my_dict.get) >> for key in sorted_items: >> print my_dict[key], key > > > This code fail. > sorted_item is a list of tuples. And so iterating the list in the for loop I > will get a tuple. > It probably should be: > > for key[1] in sorted_items: > > Let me try that. > Actually, it's a list of keys - notice that I changed my_dict.items() into my_dict.keys()? ChrisA From ikorot01 at gmail.com Sat Feb 8 03:35:28 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 8 Feb 2014 00:35:28 -0800 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: Thank you. That worked. And no, I didn't notice that change. :( On Sat, Feb 8, 2014 at 12:29 AM, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 7:25 PM, Igor Korot wrote: > >> Try this: > >> > >> sorted_items = sorted(my_dict.keys(), key=my_dict.get) > >> for key in sorted_items: > >> print my_dict[key], key > > > > > > This code fail. > > sorted_item is a list of tuples. And so iterating the list in the for > loop I > > will get a tuple. > > It probably should be: > > > > for key[1] in sorted_items: > > > > Let me try that. > > > > Actually, it's a list of keys - notice that I changed my_dict.items() > into my_dict.keys()? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Feb 8 03:39:06 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Feb 2014 09:39:06 +0100 Subject: Possible bug with stability of mimetypes.guess_* function output References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: Asaf Las wrote: > On Saturday, February 8, 2014 9:51:48 AM UTC+2, Peter Otten wrote: >> >> At least the mimetypes already defined in the module could easily produce >> the same guessed extension consistently. > > imho one workaround for OP could be to supply own map file in init() thus > ensure unambiguous mapping across every platform and distribution. guess > some libraries already doing that. or write wrapper and process > all_guesses to eliminate ambiguity up to needed requirement. > that is in case if bug request will be rejected. You also have to set mimetypes.types_map and mimetypes.common_types to an empty dict (or an OrderedDict). From rustompmody at gmail.com Sat Feb 8 03:35:34 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 8 Feb 2014 00:35:34 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: References: Message-ID: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> On Saturday, February 8, 2014 1:11:53 PM UTC+5:30, cstru... at gmail.com wrote: > I am writing a couple of class methods to build up several lines of html. Some of the lines are conditional and most need variables inserted in them. Searching the web has given me a few ideas. Each has its pro's and cons. For creating html the method of choice is a template engine -- cheetah, mako and a dozen others You can of course roll your own (poor mans version) template engine For that look up 1. triple quoted strings 2. format operator From ikorot01 at gmail.com Sat Feb 8 03:40:59 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 8 Feb 2014 00:40:59 -0800 Subject: datetime formatting output Message-ID: Hi, ALL, I am reading data from the DB (mySQL) where the datetime field is stored as: 2012-12-12 23:59:59.099 When I retrieve this date I am successfully see under debugger the dateteime object with (2012, 12, 12, 23, 59, 59, 099) However as you can see from my previous post this date shows up incorrectly as: 2012-12-12 23:59:59.000099 Notice 3 extra 0's in the milliseconds field. How do I display this datetime object properly? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 03:45:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 19:45:41 +1100 Subject: datetime formatting output In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 7:40 PM, Igor Korot wrote: > I am reading data from the DB (mySQL) where the datetime field is stored as: > > 2012-12-12 23:59:59.099 > > When I retrieve this date I am successfully see under debugger the dateteime > object with (2012, 12, 12, 23, 59, 59, 099) > > However as you can see from my previous post this date shows up incorrectly > as: > > 2012-12-12 23:59:59.000099 > > Notice 3 extra 0's in the milliseconds field. It's not a milliseconds field, that's why :) The real question is: Why is the datetime you're getting from MySQL putting milliseconds into the microseconds field? Possibly if you show your code for generating those datetime objects, that would help. ChrisA From __peter__ at web.de Sat Feb 8 03:51:19 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Feb 2014 09:51:19 +0100 Subject: What is the most pythonic way to build up large strings? References: Message-ID: cstrutton11 at gmail.com wrote: > I am writing a couple of class methods to build up several lines of html. > Some of the lines are conditional and most need variables inserted in > them. Searching the web has given me a few ideas. Each has its pro's and > cons. > > The best I have come up with is: > > > def output_header_js(self, jquery=True, theme=None): > if self.static_path is None : > return None > > if jquery is True: > output = '"'% static > output += '"'% static > > if theme is not None: > output += ' theme output += 'rel="stylesheet" type="text/css" />' > > output += '"' % "static" > > > I realize that a lot of the above looks repetitive but it is designed to > eliminate boilerplate HTML. I sometimes use a variation of the above def output_header(...): if jquery: yield """src=...""" if theme is not None: yield """ I have another method that will build some javascript that looks like > this: > > $('#StudentTableContainer').jtable({ > title: 'The Student List', > paging: true, //Enable paging > pageSize: 10, //Set page size (default: 10) > sorting: true, //Enable sorting > defaultSorting: 'Name ASC', //Set default sorting > actions: { > listAction: '/Demo/StudentList', > deleteAction: '/Demo/DeleteStudent', > updateAction: '/Demo/UpdateStudent', > createAction: '/Demo/CreateStudent' > }, > fields: { > StudentId: { > key: true, > create: false, > edit: false, > list: false > }, > Name: { > title: 'Name', > width: '23%' > }, > EmailAddress: { > title: 'Email address', > list: false > }, > ... > > Almost every line in this code will require variable insertion or if > statements. > > Any thoughts on how to improve this? Thanks in advance. Chris Again, you can build this with Python proper "... title: {title} ...".format(title="The Student List", ...) but a template language will make sure that your data is escaped properly, think "... title: {title} ...".format(title="The Student's List", ...) From lightaiyee at gmail.com Sat Feb 8 03:52:36 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 8 Feb 2014 00:52:36 -0800 (PST) Subject: Why use _mysql module and not use MySQLdb directly? Message-ID: I am writing my first python script to access MySQL database. With reference to http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects Why is it advisable to use _mysql and not MySQLdb module directly? From lightaiyee at gmail.com Sat Feb 8 03:55:23 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 8 Feb 2014 00:55:23 -0800 (PST) Subject: What is the recommended python module for SQL database access? Message-ID: Is MySQLdb the recommended python module for SQL database access? Are there other modules? What I want in a module is to be able to write readable and maintainable code. From rosuav at gmail.com Sat Feb 8 04:00:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 20:00:58 +1100 Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 7:52 PM, Sam wrote: > I am writing my first python script to access MySQL database. With reference to http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects > > Why is it advisable to use _mysql and not MySQLdb module directly? Other way around. It's advisable to ignore _mysql, which is a fairly direct representation of the MySQL C API, and use MySQLdb instead. When you use MySQLdb, you can fairly easily switch over to another database engine (like PostgreSQL, which for most purposes is superior to MySQL anyway), without changing most of your code. The only reason to use _mysql would be if you need your code to be really similar to other MySQL code in some other language - maybe you're using Python to prototype a C application, and want to keep everything as close as you can. Normally, use the higher level module. ChrisA From rosuav at gmail.com Sat Feb 8 04:04:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 20:04:07 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 7:55 PM, Sam wrote: > Is MySQLdb the recommended python module for SQL database access? Are there other modules? What I want in a module is to be able to write readable and maintainable code. > As long as you use some module that speaks the Python Database API (PEP 249, if a quick Google search has given me the right number), use whatever talks to the database back-end you want - all your code will be basically the same. Are you starting a completely new project and creating its database? Go with SQLite or PostgreSQL (the former if your needs are simple, the latter if you want a full-featured database engine); both are open source and excellent. Are you connecting to an existing database? Use that database engine, obviously :) ChrisA From ikorot01 at gmail.com Sat Feb 8 04:06:30 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 8 Feb 2014 01:06:30 -0800 Subject: Fwd: datetime formatting output In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: Igor Korot Date: Sat, Feb 8, 2014 at 1:06 AM Subject: Re: datetime formatting output To: Chris Angelico Chris, On Sat, Feb 8, 2014 at 12:45 AM, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 7:40 PM, Igor Korot wrote: > > I am reading data from the DB (mySQL) where the datetime field is stored > as: > > > > 2012-12-12 23:59:59.099 > > > > When I retrieve this date I am successfully see under debugger the > dateteime > > object with (2012, 12, 12, 23, 59, 59, 099) > > > > However as you can see from my previous post this date shows up > incorrectly > > as: > > > > 2012-12-12 23:59:59.000099 > > > > Notice 3 extra 0's in the milliseconds field. > > It's not a milliseconds field, that's why :) The real question is: Why > is the datetime you're getting from MySQL putting milliseconds into > the microseconds field? Possibly if you show your code for generating > those datetime objects, that would help. > Nothing fancy, really. ;-) import MySQLdb as mdb self.conn = mdb.connect() self.cur = self.conn.cursor() self.cur.execute("SELECT * FROM mytable") db_results = self.cur.fetchall() for row in db_results: my_dict = {} #Fill in my_dict if row[3] is not None: my_dict["Install"] = row[3] That's all. P.S.: Maybe its a problem with the datetime module which formats the datetime incorrectly? > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 04:10:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 20:10:48 +1100 Subject: datetime formatting output In-Reply-To: References: Message-ID: On Sat, Feb 8, 2014 at 8:06 PM, Igor Korot wrote: > P.S.: Maybe its a problem with the datetime module which formats the > datetime incorrectly? No, I'm pretty sure datetime.datetime really is meant to be working with microseconds. I'm not very familiar with MySQLdb, haven't used it in years; it could be a bug there, or it could be something different again. ChrisA From cstrutton11 at gmail.com Sat Feb 8 04:51:40 2014 From: cstrutton11 at gmail.com (cstrutton11 at gmail.com) Date: Sat, 8 Feb 2014 01:51:40 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> References: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> Message-ID: On Saturday, February 8, 2014 3:35:34 AM UTC-5, Rustom Mody wrote: > On Saturday, February 8, 2014 1:11:53 PM UTC+5:30, cstru... at gmail.com wrote: > > > I am writing a couple of class methods to build up several lines of html. Some of the lines are conditional and most need variables inserted in them. Searching the web has given me a few ideas. Each has its pro's and cons. > > > > For creating html the method of choice is a template engine -- cheetah, mako > > and a dozen others > > > > You can of course roll your own (poor mans version) template engine > > For that look up > > 1. triple quoted strings > > 2. format operator I am using this with a template engine. This method is going into a pyramid view class which will be rendered with chameleon or any other template engine. Actually it is going into a base class to be inherited into a view class. The idea is to setup all the parameters for the HTML when the view class is created and reuse all that info for the initial page as well as all the ajax calls. I didn't realize I could use formatting with triple quoted strings. I will look into that. From ikorot01 at gmail.com Sat Feb 8 04:50:18 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Sat, 8 Feb 2014 01:50:18 -0800 Subject: datetime formatting output In-Reply-To: References: Message-ID: Thank you Chris. On Sat, Feb 8, 2014 at 1:10 AM, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 8:06 PM, Igor Korot wrote: > > P.S.: Maybe its a problem with the datetime module which formats the > > datetime incorrectly? > > No, I'm pretty sure datetime.datetime really is meant to be working > with microseconds. I'm not very familiar with MySQLdb, haven't used it > in years; it could be a bug there, or it could be something different > again. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cstrutton11 at gmail.com Sat Feb 8 04:56:46 2014 From: cstrutton11 at gmail.com (cstrutton11 at gmail.com) Date: Sat, 8 Feb 2014 01:56:46 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: References: Message-ID: <3b40b99f-bc11-4cda-af1a-ecde1a6c960e@googlegroups.com> On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote: > > note, due to strings are immutable - for every line in sum operation > > above you produce new object and throw out older one. you can write > > one string spanned at multiple lines in very clear form. > I get what your saying here about immutable strings. Is there anyway efficiently build large strings with lots of conditional inclusions, repetative sections built dynamically by looping (see the field section above)etc. Is there a mutable string class? From cstrutton11 at gmail.com Sat Feb 8 05:11:55 2014 From: cstrutton11 at gmail.com (cstrutton11 at gmail.com) Date: Sat, 8 Feb 2014 02:11:55 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: References: Message-ID: On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote: > > note, due to strings are immutable - for every line in sum operation > > above you produce new object and throw out older one. you can write > > one string spanned at multiple lines in very clear form. > > /Asaf I think I going to rewrite this to build up a list of strings and then run a join on them at the end. Each section can be conditionally built up with variable insertions as required. This should be more efficient and will scale nicely as required. From zondo42 at gmail.com Sat Feb 8 05:23:32 2014 From: zondo42 at gmail.com (Glenn Hutchings) Date: Sat, 08 Feb 2014 10:23:32 +0000 Subject: Using virtualenv to bypass sudoer issues References: Message-ID: On 06/02/14 17:32, Jean-Michel Pichavant wrote: > Assuming I have a debian workstation for which I don't have any sudo > rights, in order to be able to install / remove python packages, should > I be using virtualenv ? Is it a suited solution ? It depends on whether you need to share the installation with anyone else. If not, you could also install packages using: python setup.py install --user This will install in your home directory, in the '.local' subdirectory. And to run any scripts that get installed, add ~/.local/bin to your PATH. Glenn From roegltd at gmail.com Sat Feb 8 05:59:58 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 02:59:58 -0800 (PST) Subject: Possible bug with stability of mimetypes.guess_* function output In-Reply-To: References: <03a2c4c8-313f-4382-8be9-5163d8bf644c@googlegroups.com> Message-ID: <3ca96b6c-ff2d-4fe2-8492-e0a8ff961ede@googlegroups.com> On Saturday, February 8, 2014 10:39:06 AM UTC+2, Peter Otten wrote: > Asaf Las wrote: > > On Saturday, February 8, 2014 9:51:48 AM UTC+2, Peter Otten wrote: > >> At least the mimetypes already defined in the module could easily produce > >> the same guessed extension consistently. > > imho one workaround for OP could be to supply own map file in init() thus > > ensure unambiguous mapping across every platform and distribution. guess > > some libraries already doing that. or write wrapper and process > > all_guesses to eliminate ambiguity up to needed requirement. > > that is in case if bug request will be rejected. > > You also have to set mimetypes.types_map and mimetypes.common_types to an > empty dict (or an OrderedDict). Hmmm, yes. then the quickest workaround is to get all guesses list then sort it and use the one at index 0. From steve+comp.lang.python at pearwood.info Sat Feb 8 06:06:24 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 08 Feb 2014 11:06:24 GMT Subject: What is the most pythonic way to build up large strings? References: <3b40b99f-bc11-4cda-af1a-ecde1a6c960e@googlegroups.com> Message-ID: <52f60fb0$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sat, 08 Feb 2014 01:56:46 -0800, cstrutton11 wrote: > On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote: >> note, due to strings are immutable - for every line in sum operation >> above you produce new object and throw out older one. you can write >> one string spanned at multiple lines in very clear form. >> > I get what your saying here about immutable strings. Is there anyway > efficiently build large strings with lots of conditional inclusions, > repetative sections built dynamically by looping (see the field section > above)etc. Yes. Build up all the substrings individually, storing them in a list. Then, when you are ready to actually use the string, assemble it in one go. substrings = [] for x in whatever(): if condition(): substrings.append("something") process("".join(substrings)) > Is there a mutable string class? No. Well, actually there is, but it's a toy, and operates under the hood by creating new immutable strings, so there's no point using it. It may even have been removed from more recent versions of Python. -- Steven From roegltd at gmail.com Sat Feb 8 06:09:32 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 03:09:32 -0800 (PST) Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: References: Message-ID: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> On Saturday, February 8, 2014 10:52:36 AM UTC+2, Sam wrote: > I am writing my first python script to access MySQL database. > With reference to http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects > Why is it advisable to use _mysql and not MySQLdb module directly? I used this one from Oracle and it was OK for simple test case and supports from 2.6 till 3.3: http://dev.mysql.com/doc/connector-python/en/index.html https://pypi.python.org/pypi/mysql-connector-python/1.1.5 yet there is page to bunch of others but i have never tried them: https://wiki.python.org/moin/MySQL Are there hidden issues about Oracle provided connector? From jurko.gospodnetic at pke.hr Sat Feb 8 06:11:32 2014 From: jurko.gospodnetic at pke.hr (=?UTF-8?B?SnVya28gR29zcG9kbmV0acSH?=) Date: Sat, 08 Feb 2014 12:11:32 +0100 Subject: how to reduce bugs due to incorrect indentation In-Reply-To: References: Message-ID: Hi, On 7.2.2014. 2:20, msustik at gmail.com wrote: > Based on the responses I arrived to the conclusion that there > is no better solution than trying to be careful and have good > testing suites. > > It would be possible to disable the Tab key completely > ...[snipped]... > Maybe a coloring of the background based on tab position > ...[snipped]... > I also considered > ...[snipped]... YMMV, but for me, just reading through this fun thread took more time then ever debugging issues caused by bad Python code indentation. :-D So, my suggestion would be to just ignore the problem and deal with any resulting issues as they occur. Clean coding & development practices, some of which have been mentioned earlier in this thread and are useful for many other reasons as well, will additionally reduce the chance of such errors causing any non-trivial issues. Best regards, Jurko Gospodneti? From rosuav at gmail.com Sat Feb 8 06:25:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 22:25:15 +1100 Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> References: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> Message-ID: On Sat, Feb 8, 2014 at 10:09 PM, Asaf Las wrote: > I used this one from Oracle and it was OK for simple test case and > supports from 2.6 till 3.3: > http://dev.mysql.com/doc/connector-python/en/index.html > https://pypi.python.org/pypi/mysql-connector-python/1.1.5 > > > yet there is page to bunch of others but i have never tried them: > https://wiki.python.org/moin/MySQL > > Are there hidden issues about Oracle provided connector? I don't know. The first thing I'd look for is compatibility with the Python Database API. I flipped through the docs without finding anything obvious either direction; it seems to be similar, at least, but it's not declaring that it complies, which I would have thought would be an important boast. Also check for platform availability. If one package is available on Linux, Mac, Windows, and myriad others, and the other is available on only a few platforms, that's a mark in favour of the first. But I suspect that won't be an issue with most of what you'll find. My suspicion, without any proof, is that it's going to come down to a matter of taste, or maybe some tangential features. The core will most likely work just fine with pretty much any module you choose to use. ChrisA From roegltd at gmail.com Sat Feb 8 06:28:03 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 03:28:03 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: <3b40b99f-bc11-4cda-af1a-ecde1a6c960e@googlegroups.com> References: <3b40b99f-bc11-4cda-af1a-ecde1a6c960e@googlegroups.com> Message-ID: On Saturday, February 8, 2014 11:56:46 AM UTC+2, cstru... at gmail.com wrote: > On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote: > > > > > > > > note, due to strings are immutable - for every line in sum operation > > > > > > above you produce new object and throw out older one. you can write > > > > > > one string spanned at multiple lines in very clear form. > > > > > > > I get what your saying here about immutable strings. > Is there anyway efficiently build large strings with > lots of conditional inclusions, repetitive sections > built dynamically by looping (see the field section above)etc. > Is there a mutable string class? Check this approach if it suits you: str_t= '' \ ''.format('bella', 'donna') print(str_t) From roegltd at gmail.com Sat Feb 8 06:32:30 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 03:32:30 -0800 (PST) Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: References: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> Message-ID: <145766f5-6e5f-40c7-be92-3adbf1015731@googlegroups.com> On Saturday, February 8, 2014 1:25:15 PM UTC+2, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 10:09 PM, Asaf Las wrote: > > > I used this one from Oracle and it was OK for simple test case and > > supports from 2.6 till 3.3: > > http://dev.mysql.com/doc/connector-python/en/index.html > > https://pypi.python.org/pypi/mysql-connector-python/1.1.5 > > yet there is page to bunch of others but i have never tried them: > > https://wiki.python.org/moin/MySQL > > > Are there hidden issues about Oracle provided connector? > > I don't know. The first thing I'd look for is compatibility with the > Python Database API. I flipped through the docs without finding > anything obvious either direction; it seems to be similar, at least, > but it's not declaring that it complies, which I would have thought > would be an important boast. > Also check for platform availability. If one package is available on > Linux, Mac, Windows, and myriad others, and the other is available on > only a few platforms, that's a mark in favour of the first. But I > suspect that won't be an issue with most of what you'll find. > > My suspicion, without any proof, is that it's going to come down to a > matter of taste, or maybe some tangential features. The core will most > likely work just fine with pretty much any module you choose to use. > ChrisA Hi Chris The doc says https://pypi.python.org/pypi/mysql-connector-python/1.1.5 MySQL driver written in Python which does not depend on MySQL C client libraries and implements the DB API v2.0 specification (PEP-249). it is pure one and confirms to PEP. though of course i can't say for sure any side impact. /Asaf From rosuav at gmail.com Sat Feb 8 06:42:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 8 Feb 2014 22:42:30 +1100 Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: <145766f5-6e5f-40c7-be92-3adbf1015731@googlegroups.com> References: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> <145766f5-6e5f-40c7-be92-3adbf1015731@googlegroups.com> Message-ID: On Sat, Feb 8, 2014 at 10:32 PM, Asaf Las wrote: > Hi Chris > The doc says > https://pypi.python.org/pypi/mysql-connector-python/1.1.5 > > MySQL driver written in Python which does not depend on MySQL C > client libraries and implements the DB API v2.0 specification (PEP-249). Ah. And that links to dev.mysql.com, so it's presumably the same thing... would be nice if they'd say that on their own site. That's what I was looking for, anyhow. Confirms the suspicion. There may well be performance differences between pure-Python implementations and ones that go via C, but having used a pure-high-level-language implementation of PostgreSQL's wire protocol (granted, that was Pike, which is a somewhat higher performance language than Python, but same difference), I can assure you of what ought to be obvious anyway: that performance is dominated by the server's throughput and thus (usually) by disk speed. So it's going to be pretty much the same with all of them; look for ancillary features that might make your life easier, otherwise pick whichever you like. ChrisA From roegltd at gmail.com Sat Feb 8 07:09:08 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 04:09:08 -0800 (PST) Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: References: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> <145766f5-6e5f-40c7-be92-3adbf1015731@googlegroups.com> Message-ID: <58c461a7-bf08-4258-af29-2b1d7778a85c@googlegroups.com> On Saturday, February 8, 2014 1:42:30 PM UTC+2, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 10:32 PM, Asaf Las wrote: > > > Hi Chris > > The doc says > > https://pypi.python.org/pypi/mysql-connector-python/1.1.5 > > MySQL driver written in Python which does not depend on MySQL C > > client libraries and implements the DB API v2.0 specification (PEP-249). > > Ah. And that links to dev.mysql.com, so it's presumably the same > thing... would be nice if they'd say that on their own site. That's > what I was looking for, anyhow. Confirms the suspicion. > > There may well be performance differences between pure-Python > implementations and ones that go via C, but having used a > pure-high-level-language implementation of PostgreSQL's wire protocol > (granted, that was Pike, which is a somewhat higher performance > language than Python, but same difference), I can assure you of what > ought to be obvious anyway: that performance is dominated by the > server's throughput and thus (usually) by disk speed. So it's going to > be pretty much the same with all of them; look for ancillary features > that might make your life easier, otherwise pick whichever you like. > > ChrisA Hmmm, they say : http://dev.mysql.com/doc/connector-python/en/connector-python-introduction.html "MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python DB API version 2.0. It is written in pure Python and does not have any dependencies except for the Python Standard Library..." i guess with Oracle connector there could be one advantage - they will try to be most compliant to their product in every aspect as they would raiser promote their DB instead of discouraging from it. /Asaf From roy at panix.com Sat Feb 8 07:15:56 2014 From: roy at panix.com (Roy Smith) Date: Sat, 08 Feb 2014 07:15:56 -0500 Subject: What is the most pythonic way to build up large strings? References: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> Message-ID: In article <3157d511-48d1-4e4d-be4c-2c461fc17466 at googlegroups.com>, Rustom Mody wrote: > On Saturday, February 8, 2014 1:11:53 PM UTC+5:30, cstru... at gmail.com wrote: > > I am writing a couple of class methods to build up several lines of html. > > Some of the lines are conditional and most need variables inserted in them. > > Searching the web has given me a few ideas. Each has its pro's and cons. > > For creating html the method of choice is a template engine -- cheetah, mako > and a dozen others Absolutely agree. No need to reinvent a wheel which has already been invented in so many shapes, sizes, and colors. We use http://jinja.pocoo.org/, but like Rustom said, there are many to pick from. Any of them is likely to be a better solution than what you would roll yourself. From rustompmody at gmail.com Sat Feb 8 07:33:10 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 8 Feb 2014 04:33:10 -0800 (PST) Subject: What is the most pythonic way to build up large strings? In-Reply-To: References: <3b40b99f-bc11-4cda-af1a-ecde1a6c960e@googlegroups.com> Message-ID: <701265bf-cb39-4eec-9677-49a6b47630a7@googlegroups.com> On Saturday, February 8, 2014 4:58:03 PM UTC+5:30, Asaf Las wrote: > Check this approach if it suits you: > str_t= '' \ > ''.format('bella', 'donna') > print(str_t) Many people prefer this >>> str_t= ( '' ... '' ... ) >>> str_t '' Which is to say use the fact that adjacent string constants get automatically concatenated. You avoid the ugly \ at EOL though you then need an enclosing paren. However this is still C programmer style Triple quotes are better And templating engine is still better And for more heavy duty use of format, it may be better to use named-formats + a dict >>> dc={'pth':'bella', 'file':'donna'} >>> formatstr='' >>> formatstr % dc '' From breamoreboy at yahoo.co.uk Sat Feb 8 08:17:08 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Feb 2014 13:17:08 +0000 Subject: Finding size of Variable In-Reply-To: <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 08/02/2014 02:48, Steven D'Aprano wrote: > On Thu, 06 Feb 2014 05:51:54 -0800, wxjmfauth wrote: > >> Sorry, I'm only pointing you may lose memory when working with short >> strings as it was explained. I really, very really, do not see what is >> absurd or obsure in: >> >>>>> sys.getsizeof('abc' + 'EURO') >> 46 >>>>> sys.getsizeof(('abc' + 'EURO').encode('utf-32')) >> 37 > > > Why do you care about NINE bytes? The least amount of memory in any PC > that I know about is 500000000 bytes, more than fifty million times more. > And you are whinging about wasting nine bytes? > > If you care about that lousy nine bytes, Python is not the language for > you. Go and program in C, where you can spent ten or twenty times longer > programming, but save nine bytes in every string. > > Nobody cares about your memory "benchmark" except you. Python is not > designed to save memory, Python is designed to use as much memory as > needed to give the programmer an easier job. In C, I can store a single > integer in a single byte. In Python, horror upon horrors, it takes 14 > bytes!!! > > py> sys.getsizeof(1) > 14 > > We consider it A GOOD THING that Python spends memory for programmer > convenience and safety. Python looks for memory optimizations when it can > save large amounts of memory, not utterly trivial amounts. So in a Python > wide build, a ten-thousand block character string requires a little bit > more than 40KB. In Python 3.3, that can be reduced to only 10KB for a > purely Latin-1 string, or 20K for a string without any astral characters. > That's the sort of memory savings that are worthwhile, reducing memory > usage by 75%. > > Could Python save memory by using UTF-8? Yes. But it would cost > complexity and time, strings would be even slower than they are now. That > is not a trade-off that the core developers have chosen to make, and I > agree with them. > > > This is a C +1 to save memory when compared against this Python +1 :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Sat Feb 8 08:34:38 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Feb 2014 13:34:38 +0000 Subject: What is the most pythonic way to build up large strings? In-Reply-To: References: Message-ID: On 08/02/2014 10:11, cstrutton11 at gmail.com wrote: > On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote: > >> >> note, due to strings are immutable - for every line in sum operation >> >> above you produce new object and throw out older one. you can write >> >> one string spanned at multiple lines in very clear form. >> >> /Asaf > > I think I going to rewrite this to build up a list of strings and then run a join on them at the end. Each section can be conditionally built up with variable insertions as required. This should be more efficient and will scale nicely as required. > An alternative is to use io.Stringio which is available in Python 2.7 and 3.x. Also would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing above, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From lightaiyee at gmail.com Sat Feb 8 09:02:54 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 8 Feb 2014 06:02:54 -0800 (PST) Subject: What does """ means in python? Message-ID: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> For string, one uses "" to represent string. Below is a code fragment that uses """ instead. cursor.execute("""SELECT name, phone_number FROM coworkers WHERE name=%s AND clue > %s LIMIT 5""", (name, clue_threshold)) What does """ means in python? From roy at panix.com Sat Feb 8 09:08:09 2014 From: roy at panix.com (Roy Smith) Date: Sat, 08 Feb 2014 09:08:09 -0500 Subject: What does """ means in python? References: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> Message-ID: In article <72a7dd52-7619-4520-991e-20db7ce55ba3 at googlegroups.com>, Sam wrote: > For string, one uses "" to represent string. Below is a code fragment that > uses """ instead. > > cursor.execute("""SELECT name, phone_number > FROM coworkers > WHERE name=%s > AND clue > %s > LIMIT 5""", > (name, clue_threshold)) > > What does """ means in python? This is what's known as a "triple quoted string" It's just like a regular string, except that it run across newlines. Very handy for things like embedding SQL code in a Python program! It works with single quotes too (i.e. '''this is a very long string spread out over several lines''' From python.list at tim.thechases.com Sat Feb 8 09:11:53 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 8 Feb 2014 08:11:53 -0600 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: <20140208081153.5c850aba@bigbox.christie.dr> On 2014-02-08 19:29, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 7:25 PM, Igor Korot > wrote: > >> Try this: > >> > >> sorted_items = sorted(my_dict.keys(), key=my_dict.get) > > > > This code fail. > > Actually, it's a list of keys - notice that I changed > my_dict.items() into my_dict.keys()? Unless you need to make a copy (for purposes of altering the original while iterating), that's the default behavior of iterating over a dict, so it could be simplified to sorted_items = sorted(my_dict, key=my_dict.get) -tkc From dejmail at gmail.com Sat Feb 8 09:16:17 2014 From: dejmail at gmail.com (dejmail at gmail.com) Date: Sat, 8 Feb 2014 06:16:17 -0800 (PST) Subject: .pyc file import errors Message-ID: <7faaba33-8eb3-4da9-b99f-ccd909d5edec@googlegroups.com> hi everyone I have a Flask app (in virtualenv, installed with --no-site-packages) running on Apache 2.4 with mod_wsgi, python2.7. When I leave it up to Apache to activate the Virtualenv, and I perform the URL request, I start getting alot of errors in the logs. It seems to want to create .pyc files in the /usr/lib/python2.7 directory, but can't for some reason (probably permissions). I don't know why it would want to do this. The program still returns "Hello World" as it should though. Peculiarly, this doesn't occur on every repeat of the same URL request. Here are some examples of the output in http://bpaste.net/show/176199/ As the output on bpaste shows, for the packages or files it tries to import from the virtualenv directories, I don't see these errors. It only has a problem with those it tries to access in the system python directory. Is this normal ? I would think Apache has activated the virtualenv just fine if it is returning the output as it should, but I don't understand the presence of all the log errors. Perhaps they are just warnings I can ignore. I have unset the default $PYTHON_PATH, and a Django app on the same system does not have these problems. Any ideas, because I'm out of them. many thanks Liam From davea at davea.name Sat Feb 8 09:25:31 2014 From: davea at davea.name (Dave Angel) Date: Sat, 8 Feb 2014 09:25:31 -0500 (EST) Subject: What is the most pythonic way to build up large strings? References: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> Message-ID: cstrutton11 at gmail.com Wrote in message: > > I didn't realize I could use formatting with triple quoted strings. I will look into that. > You probably realize this, but formatting does not work on literals of any kind. It works on str objects, which can be created by any kind of literal, or by concatenation, or by conversion, or by I/O, or ... So all 16 (?) variants of string literals may be used. -- DaveA From jpiitula at ling.helsinki.fi Sat Feb 8 09:29:40 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 08 Feb 2014 16:29:40 +0200 Subject: Using virtualenv to bypass sudoer issues References: Message-ID: Glenn Hutchings writes: > On 06/02/14 17:32, Jean-Michel Pichavant wrote: > > > Assuming I have a debian workstation for which I don't have any > > sudo rights, in order to be able to install / remove python > > packages, should I be using virtualenv ? Is it a suited solution > > ? > > It depends on whether you need to share the installation with anyone > else. If not, you could also install packages using: > > python setup.py install --user > > This will install in your home directory, in the '.local' > subdirectory. And to run any scripts that get installed, add > ~/.local/bin to your PATH. I've used this recently. There's a catch: setup.py requires setuptools, which also is not in the standard library and cannot be installed this way unless it has already been installed. There's a solution: there's a special ez_setup.py for installing setuptools. With --user, both `python setup.py install' and `python ez_setup.py' install in site.USER_BASE, which is ~/.local for me; site is in standard library; the python interpreter determines the version of python for which the installation is done, so I actually ran these: $ python3 ez_setup.py --user $ cd openpyxl-1.8.1 $ python3 setup.py install --user These installed "eggs" in ~/.local/lib/python3.2/site-packages/, and in ~/.local/bin a couple of scripts called easy_install, which I consider poor names to have on my PATH, assuming they are specific to Python (so I don't ~/.local/bin on my PATH). Try to import setuptools to see if you have setuptools already. (On one system, my 2.7 had them, but 3 didn't.) The nice thing about --user is that the python3 interpreter knows to add eggs from this location to its sys.path without any further hassle. There are other options (--home, --prefix) for greater control. I chased the links from and to learn all this and find the tools. From esj at harvee.org Sat Feb 8 09:42:31 2014 From: esj at harvee.org (Eric S. Johansson) Date: Sat, 08 Feb 2014 09:42:31 -0500 Subject: What is the most pythonic way to build up large strings? In-Reply-To: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> References: <3157d511-48d1-4e4d-be4c-2c461fc17466@googlegroups.com> Message-ID: <52F64257.8030505@harvee.org> On 2/8/2014 3:35 AM, Rustom Mody wrote: > On Saturday, February 8, 2014 1:11:53 PM UTC+5:30, cstru... at gmail.com wrote: >> I am writing a couple of class methods to build up several lines of html. Some of the lines are conditional and most need variables inserted in them. Searching the web has given me a few ideas. Each has its pro's and cons. > For creating html the method of choice is a template engine -- cheetah, mako > and a dozen others > > You can of course roll your own (poor mans version) template engine > For that look up > 1. triple quoted strings > 2. format operator as so happens, I'm traveling down a similar path myself. My goal is to use it to generate code for disabled, speech recognition using programmers (like myself). I believe my best route is using a modified version of string.Template but I wonder if my biases keep me from seeing a good alternative. I believe the following characteristics are essential: Easy to speak output generated with the right indentation recursive expansion can list substitution names Here's an example of use. The current model for visual output is a split screen simulated as text between two long lines of --------------------------------: Saying: add method ----------------------- in the GUI/editor ----------------------------------------- method_name??undefined ------------------------- def method_name(): ----------------------------------------------------------------------------------------- Saying: add three arguments ----------------------- in the GUI/editor ----------------------------------------- method_name??undefined argument_1??undefined argument_2??undefined argument_3??undefined ------------------------- def method_name(argument_1, argument_2, argument_3): ----------------------------------------------------------------------------------------- Saying: fix undefined ----------------------- in the GUI/editor ----------------------------------------- method_name??^ argument_1??undefined argument_2??undefined argument_3??undefined ------------------------- def method_name(argument_1, argument_2, argument_3): ----------------------------------------------------------------------------------------- Saying some method name ----------------------- in the GUI/editor ----------------------------------------- method_name??some method name argument_1??undefined argument_2??undefined argument_3??undefined ------------------------- def some method name(argument_1, argument_2, argument_3): ----------------------------------------------------------------------------------------- You repeat the process saying "fix undefined"until all of the substitution names were filled in and the expanded template in the lower window was correct. The conversion from string names such as "some method argument" to codenames (SmMnm) happens in a different part of the process. The problem am working on now is if I change something in the list of substitution names (upper window) how does that affect the code generated and shown in the lower window? The vast majority of the time, deleting a substitution name resets it to undefined. But deleting argument is special. At the moment, I'm going with explicit alteration of an argument list rather than inferring the argument list from the arguments in the substitution name window. I'm reasonably sure that templates, some sort, are the way to go for reducing vocal load. What I'm still wrestling with is the kind of overhead I impose on the programmer and that, in turn, defines the kind of templates I need for programming by speech. Solving this problem has made me curse one feature of Python which is it's type system. Something, more static, would make things much easier because the type information could be used to predict what will be said next thereby reducing the number of hacks, such as templates, necessary to write code. However, given that one can write Python reasonably well using ordinary speech recognition, I can almost live with its type system. :-) but, if somebody knows a way to make an empirical determination of type, I wouldn't turn away the help From mcepl at redhat.com Sat Feb 8 10:22:10 2014 From: mcepl at redhat.com (=?UTF-8?Q?Mat=C4=9Bj?= Cepl) Date: Sat, 8 Feb 2014 16:22:10 +0100 Subject: urllib2: correct way how to add a header to the *initial* request? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, this is probably a dumb question but I just cannot find a way how to create AuthHandler which would add Authorization header to the FIRST request. The only thing I see in urllib2.py are various http_error handler which add Authorization header to the ADDITIONAL request which handles the error. However, when looking at http://www.ietf.org/rfc/rfc2617.txt, section 2, I see this: A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. And really many servers (e.g., api.github.com) expect the Authorization header to be sent with the initial request, and actually they broken (http://developer.github.com/v3/auth/#basic-authentication) so instead of 401 they send 404 status code. Anybody has any idea how to subclass *AuthHandler so that it would add the header on the initial request? Best, Mat?j -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) iD8DBQFS9kui4J/vJdlkhKwRAqH1AJ9884WT6pjdu/U54khpHUUVWRcFkgCdEQn9 TNtb2lcc4Nrf1zmftn5u8Zg= =4R/2 -----END PGP SIGNATURE----- From mcepl at redhat.com Sat Feb 8 12:29:19 2014 From: mcepl at redhat.com (=?utf-8?B?TWF0xJtq?= Cepl) Date: Sat, 8 Feb 2014 18:29:19 +0100 Subject: urllib2: correct way how to add a header to the *initial* request? Message-ID: <20140208172918.GA17632@wycliff.ceplovi.cz> Hi, this is probably a dumb question but I just cannot find a way how to create AuthHandler which would add Authorization header to the FIRST request. The only thing I see in urllib2.py are various http_error handler which add Authorization header to the ADDITIONAL request which handles the error. However, when looking at http://www.ietf.org/rfc/rfc2617.txt, section 2, I see this: A client MAY preemptively send the corresponding Authorization header with requests for resources in that space without receipt of another challenge from the server. And really many servers (e.g., api.github.com) expect the Authorization header to be sent with the initial request, and actually they broken (http://developer.github.com/v3/auth/#basic-authentication) so instead of 401 they send 404 status code. Anybody has any idea how to subclass *AuthHandler so that it would add the header on the initial request? Best, Mat?j -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From eric.jacoboni at gmail.com Sat Feb 8 13:06:31 2014 From: eric.jacoboni at gmail.com (Eric Jacoboni) Date: Sat, 08 Feb 2014 19:06:31 +0100 Subject: Python3, __slots__ and serialization Message-ID: Hi, Say i want create a class with a __slots__ tuple in order to prevent creation of new attributes from outside the class. Say i want to serialize instances of this class... With pickle, all is ok : i can dump an object to a file, then reload it. With PyYAML, i can dump an object to a file, but trying to reload it fails. If i comment out the __slots__ tuple, all is fine but, then, the class is "open"... Is there some magic to have both a __slots__ tuple and a working yaml.load() ? From ned at nedbatchelder.com Sat Feb 8 13:29:34 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 08 Feb 2014 13:29:34 -0500 Subject: Python3, __slots__ and serialization In-Reply-To: References: Message-ID: On 2/8/14 1:06 PM, Eric Jacoboni wrote: > Hi, > > Say i want create a class with a __slots__ tuple in order to prevent > creation of new attributes from outside the class. > > Say i want to serialize instances of this class... With pickle, all is > ok : i can dump an object to a file, then reload it. > > With PyYAML, i can dump an object to a file, but trying to reload it fails. > > If i comment out the __slots__ tuple, all is fine but, then, the class > is "open"... Is there some magic to have both a __slots__ tuple and a > working yaml.load() ? > Preventing attribute creation runs counter to Python's philosophy, so it doesn't surprise me that it causes problems. There might be a way to make it all work together, but I don't know. __slots__ wasn't meant to be a way to prevent attribute creation, it was meant as a way to save space by avoiding the need for an attributes dictionary. Why do you need to prevent attribute creation? If someone uses your class and wants to use it in ways you didn't anticipate, why should you try to stop them? -- Ned Batchelder, http://nedbatchelder.com From ned at nedbatchelder.com Sat Feb 8 13:39:43 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 08 Feb 2014 13:39:43 -0500 Subject: Python3, __slots__ and serialization In-Reply-To: References: Message-ID: <52F679EF.8040009@nedbatchelder.com> On 2/8/14 1:29 PM, Ned Batchelder wrote: > On 2/8/14 1:06 PM, Eric Jacoboni wrote: >> Hi, >> >> Say i want create a class with a __slots__ tuple in order to prevent >> creation of new attributes from outside the class. >> >> Say i want to serialize instances of this class... With pickle, all is >> ok : i can dump an object to a file, then reload it. >> >> With PyYAML, i can dump an object to a file, but trying to reload it >> fails. >> >> If i comment out the __slots__ tuple, all is fine but, then, the class >> is "open"... Is there some magic to have both a __slots__ tuple and a >> working yaml.load() ? >> > > Preventing attribute creation runs counter to Python's philosophy, so it > doesn't surprise me that it causes problems. There might be a way to > make it all work together, but I don't know. > > __slots__ wasn't meant to be a way to prevent attribute creation, it was > meant as a way to save space by avoiding the need for an attributes > dictionary. > > Why do you need to prevent attribute creation? If someone uses your > class and wants to use it in ways you didn't anticipate, why should you > try to stop them? > I also looked at why it fails. I get this error: Traceback (most recent call last): File "", line 1, in File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/__init__.py", line 71, in load return loader.get_single_data() File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 39, in get_single_data return self.construct_document(node) File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 43, in construct_document data = self.construct_object(node) File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 90, in construct_object data = constructor(self, tag_suffix, node) File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 610, in construct_python_object_new return self.construct_python_object_apply(suffix, node, newobj=True) File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 601, in construct_python_object_apply self.set_python_instance_state(instance, state) File "/usr/local/virtualenvs/lab/lib/python2.7/site-packages/yaml/constructor.py", line 563, in set_python_instance_state setattr(object, key, value) TypeError: can't set attributes of built-in/extension type 'object' This is set_python_instance_state, the failing code: def set_python_instance_state(self, instance, state): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else: slotstate = {} if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): instance.__dict__.update(state) elif state: slotstate.update(state) for key, value in slotstate.items(): setattr(object, key, value) Two things seem clear to me: 1) you can define __setstate__ to do what you need to do, and 2) this code is simply wrong. The last line should use "instance", not "object", and it might be that the last two lines should really be indented withing the elif. All that said, skip __slots__: it isn't helping you with any actual problem, and it's forcing you to jump through hoops, or run code that most Python programs don't run. -- Ned Batchelder, http://nedbatchelder.com From lele at metapensiero.it Sat Feb 8 14:38:14 2014 From: lele at metapensiero.it (Lele Gaifax) Date: Sat, 08 Feb 2014 20:38:14 +0100 Subject: ur'foo' syntax under Python 3 Message-ID: <87d2ixo0nt.fsf@nautilus.nautilus> Hi all, I'm using Python 3.3, and I was surprised to realize that it does not support the old Python 2 syntax ur"literal-raw-unicode-strings". Is there any trick to write such literals in a Python2+3 compatible source? Is there a rationale behind the invalid syntax or is it just a glitch? thanks in advance, bye, lele. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From breamoreboy at yahoo.co.uk Sat Feb 8 14:50:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Feb 2014 19:50:43 +0000 Subject: ur'foo' syntax under Python 3 In-Reply-To: <87d2ixo0nt.fsf@nautilus.nautilus> References: <87d2ixo0nt.fsf@nautilus.nautilus> Message-ID: On 08/02/2014 19:38, Lele Gaifax wrote: > Hi all, > > I'm using Python 3.3, and I was surprised to realize that it does not > support the old Python 2 syntax ur"literal-raw-unicode-strings". > > Is there any trick to write such literals in a Python2+3 compatible > source? > > Is there a rationale behind the invalid syntax or is it just a glitch? > > thanks in advance, > bye, lele. > From http://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals "Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially. Given that Python 2.x?s raw unicode literals behave differently than Python 3.x?s the 'ur' syntax is not supported." -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Sat Feb 8 14:52:45 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Feb 2014 20:52:45 +0100 Subject: ur'foo' syntax under Python 3 References: <87d2ixo0nt.fsf@nautilus.nautilus> Message-ID: Lele Gaifax wrote: > I'm using Python 3.3, and I was surprised to realize that it does not > support the old Python 2 syntax ur"literal-raw-unicode-strings". > > Is there any trick to write such literals in a Python2+3 compatible > source? > > Is there a rationale behind the invalid syntax or is it just a glitch? This is intentional: http://www.python.org/dev/peps/pep-0414/#exclusion-of-raw-unicode-literals From walterhurry at gmail.com Sat Feb 8 14:55:19 2014 From: walterhurry at gmail.com (Walter Hurry) Date: Sat, 8 Feb 2014 19:55:19 +0000 (UTC) Subject: What does """ means in python? References: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> Message-ID: Roy Smith wrote: > In article <72a7dd52-7619-4520-991e-20db7ce55ba3 at googlegroups.com>, > Sam wrote: > >> For string, one uses "" to represent string. Below is a code fragment that >> uses """ instead. >> >> cursor.execute("""SELECT name, phone_number >> FROM coworkers >> WHERE name=%s >> AND clue > %s >> LIMIT 5""", >> (name, clue_threshold)) >> >> What does """ means in python? > > This is what's known as a "triple quoted string" It's just like a > regular string, except that it run across newlines. Very handy for > things like embedding SQL code in a Python program! > > It works with single quotes too (i.e. '''this is > a very long string > spread out over several lines''' PMFJI. When I asked (here) about this a while ago, some kind soul suggested textwrap.dedent. Any advice as to the pros and cons of the respective approaches (esp. for SQL)? From rosuav at gmail.com Sat Feb 8 16:40:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 08:40:25 +1100 Subject: What does """ means in python? In-Reply-To: References: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> Message-ID: On Sun, Feb 9, 2014 at 6:55 AM, Walter Hurry wrote: > When I asked (here) about this a while ago, some kind soul suggested textwrap.dedent. > > Any advice as to the pros and cons of the respective approaches (esp. for SQL)? For SQL? Ignore the extra spaces, it's a free-form language. The only reason to consider dedent() would be if you're worried about how your log files will look. The actual execution of SQL won't be bothered by newlines and spaces/tabs. ChrisA From dwightdhutto at gmail.com Sat Feb 8 17:45:50 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sat, 8 Feb 2014 17:45:50 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 8, 2014 at 8:17 AM, Mark Lawrence wrote: > On 08/02/2014 02:48, Steven D'Aprano wrote: > >> On Thu, 06 Feb 2014 05:51:54 -0800, wxjmfauth wrote: >> >> Sorry, I'm only pointing you may lose memory when working with short >>> strings as it was explained. I really, very really, do not see what is >>> absurd or obsure in: >>> >>> sys.getsizeof('abc' + 'EURO') >>>>>> >>>>> 46 >>> >>>> sys.getsizeof(('abc' + 'EURO').encode('utf-32')) >>>>>> >>>>> 37 >>> >> >> >> Why do you care about NINE bytes? The least amount of memory in any PC >> that I know about is 500000000 bytes, more than fifty million times more. >> And you are whinging about wasting nine bytes? >> > One could argue that if you're parsing a particular file, a very large one, that those 9 bytes can go into the optimization of parsing aforementioned file. Of, course we have faster processors, so why care? Because it goes into the optimization of the code one is 'developing' in python. > >> If you care about that lousy nine bytes, Python is not the language for >> you. Go and program in C, where you can spent ten or twenty times longer >> programming, but save nine bytes in every string. >> >> Nobody cares about your memory "benchmark" except you. Python is not >> designed to save memory, Python is designed to use as much memory as >> needed to give the programmer an easier job. In C, I can store a single >> integer in a single byte. In Python, horror upon horrors, it takes 14 >> bytes!!! >> >> py> sys.getsizeof(1) >> 14 >> >> We consider it A GOOD THING that Python spends memory for programmer >> convenience and safety. Python looks for memory optimizations when it can >> save large amounts of memory, not utterly trivial amounts. So in a Python >> wide build, a ten-thousand block character string requires a little bit >> more than 40KB. In Python 3.3, that can be reduced to only 10KB for a >> purely Latin-1 string, or 20K for a string without any astral characters. >> That's the sort of memory savings that are worthwhile, reducing memory >> usage by 75%. >> >> Could Python save memory by using UTF-8? Yes. But it would cost >> complexity and time, strings would be even slower than they are now. That >> is not a trade-off that the core developers have chosen to make, and I >> agree with them. >> >> >> >> > This is a C +1 to save memory when compared against this Python +1 :) > > -- > My fellow Pythonistas, ask not what our language can do for you, ask what > you can do for our language. > > Mark Lawrence > > --- > This email is free from viruses and malware because avast! Antivirus > protection is active. > http://www.avast.com > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From lele at metapensiero.it Sat Feb 8 18:34:17 2014 From: lele at metapensiero.it (Lele Gaifax) Date: Sun, 09 Feb 2014 00:34:17 +0100 Subject: ur'foo' syntax under Python 3 References: <87d2ixo0nt.fsf@nautilus.nautilus> Message-ID: <878utlnpqe.fsf@nautilus.nautilus> Thank you Peter and Mark for the links. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From james.time4tea at gmail.com Sat Feb 8 18:42:18 2014 From: james.time4tea at gmail.com (james.time4tea at gmail.com) Date: Sat, 8 Feb 2014 15:42:18 -0800 (PST) Subject: Using asyncio for serial port Message-ID: Hiya I'm looking at using asyncio for creating an socket <-> serial protocol bridge, but looking at the current implementation of asyncio it looks to be quite socket specific. I can't see any way to get it to support a simple serial device. Any advice on where to proceed would be very much appreciated! Thanks! James From lightaiyee at gmail.com Sat Feb 8 18:54:30 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 8 Feb 2014 15:54:30 -0800 (PST) Subject: What are the kinds of software that are not advisable to be developed using Python? Message-ID: I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? From denismfmcmahon at gmail.com Sat Feb 8 19:09:40 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 9 Feb 2014 00:09:40 +0000 (UTC) Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: On Sat, 08 Feb 2014 15:54:30 -0800, Sam wrote: > I got to know about Python a few months ago and today, I want to develop > only using Python because of its code readability. This is not a healthy > bias. To play my own devil's advocate, I have a question. What are the > kinds of software that are not advisable to be developed using Python? OS Kernels. Hardware drivers. -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Sat Feb 8 19:11:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 11:11:19 +1100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 10:54 AM, Sam wrote: > I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? > Device drivers and operating systems. Definitely don't try writing those in pure Python. Anything that provides a C API is usually easier to program in C, so you would want to write a Python-callable glue module. Sometimes you'll find that there's nothing else to do but the module, in which case you've pretty much written your app in C, but often you can write a tiny driver script that calls on your functions - which means you can, later on, write a GUI app that calls on the same functions. But using ctypes for that is pretty messy and tedious. (Note that you might be able to write your glue module using Cython. I've never done this, but that's a sort of half-way mark between Python and C, with most of the code feeling like Python but the facilities being like C. Some day, I must try it.) Projects that are already partly written in some other language, or which should be written to use libraries in another language, usually should be written in that language. Modifying your PHPBB forum should probably be done in PHP, no matter what you think of that language (and who doesn't). Web applications that need to run on cheap web hosts usually need to be written in PHP, too, but Python is available on a good few "not-so-cheap" hosts, so that might not be a problem. Heavy computation might be unideal in Python, but if you can grunge it into NumPy operations, that won't be a problem. For the rest, Python's probably a fine language. Applications, servers, pretty much anything will work. Have at it! ChrisA From rosuav at gmail.com Sat Feb 8 19:56:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 11:56:06 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <07C379F9-3BD4-4DC4-8FEF-BA3B0067A7B1@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <07C379F9-3BD4-4DC4-8FEF-BA3B0067A7B1@cox.net> Message-ID: On Sun, Feb 9, 2014 at 11:28 AM, Scott W Dunning wrote: > So, this is more like what you?re talking about? > >>>> first = number / 10 >>>> second = number % 10 >>>> last = first %10 >>>> rest = second / 10 > > I feel stupid saying this and it?s probably because of the variables I?m using but I?m not sure what the above is doing. For some reason it?s confusing me. I used the number 55664, so the variable (first) is saying take 55664 and / it by 10, then (second) is saying take the original number divide it by 10 and spit out the remainder? Then from there (last) is saying take the original number / it by 10 then take that number and divide it by 10 again and give me the remainder? Then finally (rest) is saying take the remainder of the original number after dividing by ten and divide that number by 10? I guess I?m confused on the result I?m looking for. > Let's try them in the interactive interpreter: >>> number = 16384 >>> number / 10 1638 >>> number % 10 4 The first division and modulo splits the last digit off the number, and gives us the rest of the number. So here's what I'd name them: >>> last_digit = number % 10 >>> all_but_last = number / 10 Now we can get the next digit: >>> second_last = all_but_last % 10 >>> all_but_last_two = all_but_last / 10 And so on, through five more steps (at the end of which, the "all but" will have nothing in it). (Aside: notice that we're not using 'number' any more. So we can simply put the quotient back into number, and we can make this a loop that goes until there's nothing left: >>> while number: print number % 10 number = number / 10 # or: number /= 10 4 8 3 6 1 Et voila! That's how assembly language programmers display long numbers. (Converting a single digit into an ASCII character is simply a matter of adding 48 (hex 30), and then that can be written out.) End of aside.) So, going back to the units-of-time problem. We start with a total number of seconds; note that this is a bit confusing, so let's call that "total_seconds" and then we can use the name "seconds" to mean just the seconds component, which will be less than 60. [1] Then we need to get minutes, hours, and days; whatever remains will be weeks (so if you want to count the time from the beginning of 1970 to now, you'll have over two thousand weeks). total_seconds = 1907043 Okay. How do we get the last digit, pretending that that's in base 60? Because, if we treat that number as base 60, the last digit is the number of seconds, and the rest is what we need to split up into minutes, hours, etc. seconds = total_seconds % 60 minutes_etcetera = total_seconds / 60 Carry on with that method - work out the number of minutes, and then the "hours_etc" which has the rest. Then do the same to split off hours, and then days. See how you go! ChrisA [1] For the purposes of this exercise, I'm pretending that this is Unix time and has no leap seconds. Technically, when you write out HH:MM:SS, the HH field can go from 00 to 23, the MM field can go from 00 to 59, and the SS field can go from 00 to 61 - yes, it's possible to have *two* consecutive leap seconds, although this has never yet happened. But for this, we're working in a system that has seconds going from 00 to 59. From rustompmody at gmail.com Sat Feb 8 20:25:45 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 8 Feb 2014 17:25:45 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> On Sunday, February 9, 2014 4:15:50 AM UTC+5:30, David Hutto wrote: > One could argue that if you're parsing a particular file, a very large one, that those 9 bytes can go into the optimization of parsing aforementioned file. Of, course we have faster processors, so why care? > Because it goes into the optimization of the code one is 'developing' in python. Yes... There are cases when python is an inappropriate language to use... So??? Its good to get a bit of context here. loop: jmf says python is inappropriate. Someone asks him: Is it? In what case? jmf: No answer After a delay of few days jmp to start of loop [BTW: In my book this classic trolling] From swdunning at cox.net Sat Feb 8 20:46:11 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 8 Feb 2014 18:46:11 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <07C379F9-3BD4-4DC4-8FEF-BA3B0067A7B1@cox.net> Message-ID: <8C13948E-1A2A-4221-89D3-C117B4A10F78@cox.net> On Feb 8, 2014, at 5:56 PM, Chris Angelico wrote: > > Carry on with that method - work out the number of minutes, and then > the "hours_etc" which has the rest. Then do the same to split off > hours, and then days. See how you go! I did it similar to that but I went backwards. I started with number of weeks and went down to seconds remaining. Would the result still be the same if the order of the code went the other way (i.e.. from minutes to weeks instead of the way I did it from weeks to seconds)? > [1] For the purposes of this exercise, I'm pretending that this is > Unix time and has no leap seconds. Technically, when you write out > HH:MM:SS, the HH field can go from 00 to 23, the MM field can go from > 00 to 59, and the SS field can go from 00 to 61 - yes, it's possible > to have *two* consecutive leap seconds, although this has never yet > happened. But for this, we're working in a system that has seconds > going from 00 to 59 I honestly do not know what leap seconds are but I?ll take your word for it. lol Thanks again!!! Scott From rosuav at gmail.com Sat Feb 8 20:46:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 12:46:27 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: On Sun, Feb 9, 2014 at 12:21 PM, Scott W Dunning wrote: > I figured it out! Thanks Chris! Taking it one step at a time with the five digit number really helped me to see how to break it all up! Are you a teacher? I appreciate the help and the patients! I like that you don?t just give me the answer that you break it down and help me so that I can figure it out on my own! Thanks to all of you for all of your help, you guys are helping me a lot and I really appreciate it! > Awesome! No, I'm not a teacher by profession, but I was homeschooled, and since I'm the second of seven children [1], I got used to teaching things to my siblings. Also, every week I run a Dungeons and Dragons campaign online, which requires similar skills. (Teaching maths is way easier than getting my players to figure out some puzzles. I had no idea that, in a group of half a dozen nerds, nobody would recognize this broken text: "In brightest day, in blackest night / No evil ...... sight / Let .... worship .... mi.... / .... my power .... tern...." - I'd have thought the first line alone would be enough for anyone who's at least mildly nerdy and/or geeky.) (We start in fifteen minutes. Want to come watch? Just telnet to minstrelhall.com port 221!) > Here is how I did it if you?re curious.?. > > seconds = raw_input("Enter the number of seconds:") > seconds = int(seconds) > weeks = seconds/604800 > weeks_rem = seconds % 604800 > days = weeks_rem / 86400 > days_rem = seconds % 86400 > hours = days_rem / 3600 > hours_rem = seconds % 3600 > minutes = hours_rem / 60 > minutes_rem = seconds % 60 > seconds = minutes_rem % 60 > > print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds' > > Not sure if that?s the correct way to do it but it works! If there is any other advice I?ll take it. That's certainly effective. It's going to give you the right result. I would be inclined to start from the small end and strip off the seconds first, then the minutes, etc, because then you're working with smaller divisors (60, 60, 24, 7 instead of 604800, 86400, 3600, 60); most people will understand that a week is 7 days, but only people who work with DNS will know that it's 604800 seconds. But both work. You'll also note that you're trimming off bits and leaving "residual seconds". I would put all the "_rem" values back into "seconds", which would let you use augmented assignment: weeks = seconds/604800 seconds %= 604800 days = seconds / 86400 seconds %= 86400 hours = seconds / 3600 seconds %= 3600 minutes = seconds / 60 seconds %= 60 This emphasizes that you're stripping components off and keeping the number of remaining seconds for the next step. But that's pretty minor. Main thing is, you know what you're doing; you have to not just get the right answer, but know WHY you get that answer. ChrisA [1] Our father's not a captain, but there's still nothing about being a non-captain with seven children. And that movie is definitely one of our favorite things. From rosuav at gmail.com Sat Feb 8 20:50:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 12:50:01 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <8C13948E-1A2A-4221-89D3-C117B4A10F78@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <07C379F9-3BD4-4DC4-8FEF-BA3B0067A7B1@cox.net> <8C13948E-1A2A-4221-89D3-C117B4A10F78@cox.net> Message-ID: On Sun, Feb 9, 2014 at 12:46 PM, Scott W Dunning wrote: > On Feb 8, 2014, at 5:56 PM, Chris Angelico wrote: >> >> Carry on with that method - work out the number of minutes, and then >> the "hours_etc" which has the rest. Then do the same to split off >> hours, and then days. See how you go! > > I did it similar to that but I went backwards. I started with number of weeks and went down to seconds remaining. Would the result still be the same if the order of the code went the other way (i.e.. from minutes to weeks instead of the way I did it from weeks to seconds)? > The result will be the same. You can work either way. Working from the smallest up lets you work in different formats - maybe you want to suppress "0 weeks, 0 days" if it's less than a day, for instance. Working from the largest down means you can simply write things out as you get them, and they'll be in the right order for a human to read (look back up to my aside where I show assembly-language number display, and you'll see that the digits come out in the wrong order). >> [1] For the purposes of this exercise, I'm pretending that this is >> Unix time and has no leap seconds. Technically, when you write out >> HH:MM:SS, the HH field can go from 00 to 23, the MM field can go from >> 00 to 59, and the SS field can go from 00 to 61 - yes, it's possible >> to have *two* consecutive leap seconds, although this has never yet >> happened. But for this, we're working in a system that has seconds >> going from 00 to 59 > > > I honestly do not know what leap seconds are but I?ll take your word for it. lol Heh. I mentioned them for completeness only. Look 'em up on Wikipedia if you like; some years are a smidge longer than 365 or 366 days, by either one or two seconds. Almost NEVER significant to every-day work, but you'll see some time formatting libraries that mention them (mainly because the SS field can go up to 61). ChrisA From swdunning at cox.net Sat Feb 8 20:21:54 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 8 Feb 2014 18:21:54 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> Message-ID: <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> I figured it out! Thanks Chris! Taking it one step at a time with the five digit number really helped me to see how to break it all up! Are you a teacher? I appreciate the help and the patients! I like that you don?t just give me the answer that you break it down and help me so that I can figure it out on my own! Thanks to all of you for all of your help, you guys are helping me a lot and I really appreciate it! Here is how I did it if you?re curious.?. seconds = raw_input("Enter the number of seconds:") seconds = int(seconds) weeks = seconds/604800 weeks_rem = seconds % 604800 days = weeks_rem / 86400 days_rem = seconds % 86400 hours = days_rem / 3600 hours_rem = seconds % 3600 minutes = hours_rem / 60 minutes_rem = seconds % 60 seconds = minutes_rem % 60 print weeks, 'weeks', days, 'days', hours, 'hours', minutes, 'minutes', seconds, 'seconds' Not sure if that?s the correct way to do it but it works! If there is any other advice I?ll take it. On Feb 7, 2014, at 11:29 PM, Chris Angelico wrote: > On Sat, Feb 8, 2014 at 5:27 PM, Scott W Dunning wrote: >> Ok, so it this what you?re talking about? >> >> >> number = int(raw_input(?Enter a five digit number:)) >> foo = number % 10 >> bar = number / 10 >> >> digit = foo / 10 >> rem = bar % 10 >> > > Close! But if you print out foo and bar, you'll see that you're naming > them backwards in the second one. The last digit is the remainder > (modulo), the rest is the quotient. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From swdunning at cox.net Sat Feb 8 19:28:15 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 8 Feb 2014 17:28:15 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> Message-ID: <07C379F9-3BD4-4DC4-8FEF-BA3B0067A7B1@cox.net> On Feb 7, 2014, at 11:29 PM, Chris Angelico wrote > Close! But if you print out foo and bar, you'll see that you're naming > them backwards in the second one. The last digit is the remainder > (modulo), the rest is the quotient. So, this is more like what you?re talking about? >>> first = number / 10 >>> second = number % 10 >>> last = first %10 >>> rest = second / 10 I feel stupid saying this and it?s probably because of the variables I?m using but I?m not sure what the above is doing. For some reason it?s confusing me. I used the number 55664, so the variable (first) is saying take 55664 and / it by 10, then (second) is saying take the original number divide it by 10 and spit out the remainder? Then from there (last) is saying take the original number / it by 10 then take that number and divide it by 10 again and give me the remainder? Then finally (rest) is saying take the remainder of the original number after dividing by ten and divide that number by 10? I guess I?m confused on the result I?m looking for. I know I?m asking very elementary questions so I really do appreciate not only all of your help but, your patients too!! From swdunning at cox.net Sat Feb 8 21:07:12 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 8 Feb 2014 19:07:12 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: On Feb 8, 2014, at 6:46 PM, Chris Angelico wrote: > No, I'm not a teacher by profession, but I was homeschooled, and since > I'm the second of seven children [1], I got used to teaching things to > my siblings. Also, every week I run a Dungeons and Dragons campaign > online, which requires similar skills. (Teaching maths is way easier > than getting my players to figure out some puzzles. Well, you?re very good at it! Like I said I like that you don?t just give me the answer you help me figure it out which is what I need. > I had no idea > that, in a group of half a dozen nerds, nobody would recognize this > broken text: "In brightest day, in blackest night / No evil ...... > sight / Let .... worship .... mi.... / .... my power .... tern...." - > I'd have thought the first line alone would be enough for anyone who's > at least mildly nerdy and/or geeky.) Green Lantern oath right? > > (We start in fifteen minutes. Want to come watch? Just telnet to > minstrelhall.com port 221!) Awesome, I may stop by and check it out. > > That's certainly effective. It's going to give you the right result. I > would be inclined to start from the small end and strip off the > seconds first, then the minutes, etc, because then you're working with > smaller divisors (60, 60, 24, 7 instead of 604800, 86400, 3600, 60); > most people will understand that a week is 7 days, but only people who > work with DNS will know that it's 604800 seconds. But both work. Yeah I had to look up how many seconds were in weeks and days. > > You'll also note that you're trimming off bits and leaving "residual > seconds". I would put all the "_rem" values back into "seconds", which > would let you use augmented assignment: Not sure what augmented assignments are but I?ll look that up. I?m gonna try and figure it out that way also just for the heck of it. > > weeks = seconds/604800 > seconds %= 604800 Is the -> seconds %= 604800 Saying -> seconds = seconds % 604800? > days = seconds / 86400 > seconds %= 86400 > hours = seconds / 3600 > seconds %= 3600 > minutes = seconds / 60 > seconds %= 60 > > > [1] Our father's not a captain, but there's still nothing about being > a non-captain with seven children. And that movie is definitely one of > our favorite things. Seven children is a lot. It definitely takes a Captain to raise seven children. : ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 21:14:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 13:14:52 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: On Sun, Feb 9, 2014 at 1:07 PM, Scott W Dunning wrote: > > On Feb 8, 2014, at 6:46 PM, Chris Angelico wrote: > > I had no idea > that, in a group of half a dozen nerds, nobody would recognize this > broken text: "In brightest day, in blackest night / No evil ...... > sight / Let .... worship .... mi.... / .... my power .... tern...." - > I'd have thought the first line alone would be enough for anyone who's > at least mildly nerdy and/or geeky.) > > Green Lantern oath right? Correct! (In this particular case, they were facing a magically-locked vault; by shining a green light on it - say, from a candle inside a green bottle - they could see how to open it.) > You'll also note that you're trimming off bits and leaving "residual > seconds". I would put all the "_rem" values back into "seconds", which > would let you use augmented assignment: > > > Not sure what augmented assignments are but I?ll look that up. I?m gonna > try and figure it out that way also just for the heck of it. > > > weeks = seconds/604800 > seconds %= 604800 > > > Is the -> seconds %= 604800 > Saying -> seconds = seconds % 604800? Pretty much, yeah. If you think about it in English as "Divide seconds by 604800", most people will think that "seconds" will end up smaller; so that's represented by augmented assignment. There are also some optimizations that can be done, and some differences as regards mutable objects, but with simple arithmetic, it's what you say. > [1] Our father's not a captain, but there's still nothing about being > a non-captain with seven children. And that movie is definitely one of > our favorite things. > > > Seven children is a lot. It definitely takes a Captain to raise seven > children. : ) > Not sure if you're familiar with the book, musical, or film, "The Sound of Music", about Captain von Trapp and Maria and their children. Maria sings (in the film) "A captain with seven children - what's so fearsome about that?", and somehow my fingers left out the key word "fearsome" in the above reference, which doesn't make it very clear. There's nothing *fearsome* about being a non-captain, etc. Also, now that you know I'm talking about the Sound of Music, you'll know why I described it as one of our favorite things. :) ChrisA From roy at panix.com Sat Feb 8 21:53:00 2014 From: roy at panix.com (Roy Smith) Date: Sat, 08 Feb 2014 21:53:00 -0500 Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: In article , Sam wrote: > I got to know about Python a few months ago and today, I want to develop only > using Python because of its code readability. This is not a healthy bias. To > play my own devil's advocate, I have a question. What are the kinds of > software that are not advisable to be developed using Python? If execution speed is the most important thing, Python would be the wrong choice. If you need to get very close to the hardware (such as when writing an operating system), Python would be the wrong choice. If you are writing software for an environment which has a single-language ecosystem (i.e. iOS -> Objective C, or Android -> Java), Python would be the wrong choice. If, for security/business reasons, shipping only the executable, without the end user having access to your original source, Python would be the wrong language. From dwightdhutto at gmail.com Sat Feb 8 21:56:07 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sat, 8 Feb 2014 21:56:07 -0500 Subject: Finding size of Variable In-Reply-To: <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On Sat, Feb 8, 2014 at 8:25 PM, Rustom Mody wrote: > On Sunday, February 9, 2014 4:15:50 AM UTC+5:30, David Hutto wrote: > > One could argue that if you're parsing a particular file, a very large > one, that those 9 bytes can go into the optimization of parsing > aforementioned file. Of, course we have faster processors, so why care? > > Because it goes into the optimization of the code one is 'developing' in > python. > > Yes... There are cases when python is an inappropriate language to use... > So??? > I didn't say she couldn't optimize in another language, and was just prototyping in Python. I just said she was optimizing her python code...dufus. > > Its good to get a bit of context here. > > loop: > jmf says python is inappropriate. > Someone asks him: Is it? In what case? > jmf: No answer > After a delay of few days jmp to start of loop > > loop: mov head,up_your_ass push repeat pop repeat jmp loop [BTW: In my book this classic trolling] > -- > And the title of this book would be..."Pieces of Cliche Bullshit Internet Arguments for Dummies" https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Feb 8 21:59:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 13:59:19 +1100 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On Sun, Feb 9, 2014 at 1:56 PM, David Hutto wrote: >> >> Yes... There are cases when python is an inappropriate language to use... >> So??? > > > I didn't say she couldn't optimize in another language, and was just > prototyping in Python. I just said she was optimizing her python > code...dufus. And there are a *lot* of cases where that is inappropriate language to use. Please don't. ChrisA From dwightdhutto at gmail.com Sat Feb 8 22:07:04 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sat, 8 Feb 2014 22:07:04 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On Sat, Feb 8, 2014 at 9:59 PM, Chris Angelico wrote: > On Sun, Feb 9, 2014 at 1:56 PM, David Hutto > wrote: > >> > >> Yes... There are cases when python is an inappropriate language to > use... > >> So??? > > > > > > I didn't say she couldn't optimize in another language, and was just > > prototyping in Python. I just said she was optimizing her python > > code...dufus. > > And there are a *lot* of cases where that is inappropriate language to > use. Please don't. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > it's also inappropriate for him to call people trolls, while they're just commenting on why what she might be using is a necessity for her particular case of developing in Python, and not using another language, yet. "He started it!" :P -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From ned at nedbatchelder.com Sat Feb 8 22:09:18 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 08 Feb 2014 22:09:18 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On 2/8/14 9:56 PM, David Hutto wrote: > > > > On Sat, Feb 8, 2014 at 8:25 PM, Rustom Mody > wrote: > > On Sunday, February 9, 2014 4:15:50 AM UTC+5:30, David Hutto wrote: > > One could argue that if you're parsing a particular file, a very > large one, that those 9 bytes can go into the optimization of > parsing aforementioned file. Of, course we have faster processors, > so why care? > > Because it goes into the optimization of the code one is > 'developing' in python. > > Yes... There are cases when python is an inappropriate language to > use... > So??? > > > I didn't say she couldn't optimize in another language, and was just > prototyping in Python. I just said she was optimizing her python > code...dufus. Please keep the discussion respectful. Misunderstandings are easy, I suspect this is one of them. There's no reason to start calling people names. > > > Its good to get a bit of context here. > > loop: > jmf says python is inappropriate. > Someone asks him: Is it? In what case? > jmf: No answer > After a delay of few days jmp to start of loop > > loop: > mov head,up_your_ass > push repeat > pop repeat > jmp loop Please keep in mind the Code of Conduct: http://www.python.org/psf/codeofconduct Thanks. > > [BTW: In my book this classic trolling] > -- > > > And the title of this book would be..."Pieces of Cliche Bullshit > Internet Arguments for Dummies" > > https://mail.python.org/mailman/listinfo/python-list > > > > > -- > Best Regards, > David Hutto > /*CEO:*/ _http://www.hitwebdevelopment.com_ > > -- Ned Batchelder, http://nedbatchelder.com From dwightdhutto at gmail.com Sat Feb 8 22:09:40 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sat, 8 Feb 2014 22:09:40 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: Maybe I'll just roll my fat, bald, troll arse out from under the bridge, and comment back, off list, next time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ned at nedbatchelder.com Sat Feb 8 22:16:50 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 08 Feb 2014 22:16:50 -0500 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On 2/8/14 10:09 PM, David Hutto wrote: > Maybe I'll just roll my fat, bald, troll arse out from under the bridge, > and comment back, off list, next time. > > I'm not sure what happened in this thread. It might be that you think Rustom Mody was referring to you when he said, "BTW: In my book this classic trolling." I don't think he was, I think he was referring to JMF. In any case, perhaps it would be best to just take a break? -- Ned Batchelder, http://nedbatchelder.com From rustompmody at gmail.com Sat Feb 8 22:30:57 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 8 Feb 2014 19:30:57 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <984cd62e-5a16-43fd-b6e0-f644d51aa450@googlegroups.com> Message-ID: On Sunday, February 9, 2014 8:46:50 AM UTC+5:30, Ned Batchelder wrote: > On 2/8/14 10:09 PM, David Hutto wrote: > > Maybe I'll just roll my fat, bald, troll arse out from under the bridge, > > and comment back, off list, next time. > I'm not sure what happened in this thread. It might be that you think > Rustom Mody was referring to you when he said, "BTW: In my book this > classic trolling." I don't think he was, I think he was referring to JMF. Of course! And given the turn of this thread, we must hand it to jmf for being even better at trolling than I thought :-) See the first para http://en.wikipedia.org/wiki/Troll_%28Internet%29 From steve+comp.lang.python at pearwood.info Sat Feb 8 22:43:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Feb 2014 03:43:47 GMT Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sat, 08 Feb 2014 21:53:00 -0500, Roy Smith wrote: > In article , > Sam wrote: > >> I got to know about Python a few months ago and today, I want to >> develop only using Python because of its code readability. This is not >> a healthy bias. To play my own devil's advocate, I have a question. >> What are the kinds of software that are not advisable to be developed >> using Python? > > If execution speed is the most important thing, Python would be the > wrong choice. PyPy can generate code which is comparable to compiled C in speed. Perhaps you mean, "if execution speed is the most important thing, using a naive Python interpreter may not be fast enough". > If you need to get very close to the hardware (such as when writing an > operating system), Python would be the wrong choice. > > If you are writing software for an environment which has a > single-language ecosystem (i.e. iOS -> Objective C, or Android -> Java), > Python would be the wrong choice. https://github.com/kivy/python-for-android https://ep2013.europython.eu/conference/talks/developing-android-apps-completely-in-python https://python-for-android.readthedocs.org/en/latest/ http://qpython.com/ > If, for security/business reasons, shipping only the executable, without > the end user having access to your original source, Python would be the > wrong language. Security by obscurity. Nevertheless, although security by obscurity is ineffective[1], Python supports it. You can ship only the .pyc files. For added obscurity, you could put the .pyc files in a .zip file and ship that. For even more obscurity, you could write a custom importer, and then ship your python byte-code hidden in a mp3 or TIFF file. [1] Shipping only compiled executables hasn't made Windows any more secure, prevented viruses and malware from taking advantage of zero-day exploits, or prevented software piracy. -- Steven From torriem at gmail.com Sat Feb 8 23:08:26 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 08 Feb 2014 21:08:26 -0700 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: Message-ID: <52F6FF3A.8010903@gmail.com> On 02/08/2014 05:11 PM, Chris Angelico wrote: > On Sun, Feb 9, 2014 at 10:54 AM, Sam wrote: >> I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? >> > > Device drivers and operating systems. Definitely don't try writing > those in pure Python. That all depends. Driving a USB device using libusb and Python might just be the ticket to get things up and running quickly. At one time someone wrote a Linux kernel module that allowed you to use Perl to implement some kinds of driver things. From roegltd at gmail.com Sat Feb 8 23:09:28 2014 From: roegltd at gmail.com (Asaf Las) Date: Sat, 8 Feb 2014 20:09:28 -0800 (PST) Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4fb34e9b-d2f0-432b-852e-55177a38167c@googlegroups.com> On Sunday, February 9, 2014 5:43:47 AM UTC+2, Steven D'Aprano wrote: > Nevertheless, although security by obscurity is ineffective[1], Python > supports it. You can ship only the .pyc files. For added obscurity, you > could put the .pyc files in a .zip file and ship that. For even more > obscurity, you could write a custom importer, and then ship your python > byte-code hidden in a mp3 or TIFF file. There are some code obfuscator for python but i never used them. btw, Python could be language of choice for embedded systems if small footprint vm could be developed. had seen similar for java having 10-20 KB byte sized interpreter with very limited set of functions. From rosuav at gmail.com Sat Feb 8 23:14:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 15:14:36 +1100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <52F6FF3A.8010903@gmail.com> References: <52F6FF3A.8010903@gmail.com> Message-ID: On Sun, Feb 9, 2014 at 3:08 PM, Michael Torrie wrote: > On 02/08/2014 05:11 PM, Chris Angelico wrote: >> On Sun, Feb 9, 2014 at 10:54 AM, Sam wrote: >>> I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? >>> >> >> Device drivers and operating systems. Definitely don't try writing >> those in pure Python. > > That all depends. Driving a USB device using libusb and Python might > just be the ticket to get things up and running quickly. At one time > someone wrote a Linux kernel module that allowed you to use Perl to > implement some kinds of driver things. That's not the same; libusb is doing the low-level handling for you. That's not the sense of "device driver" that gets really close to the metal. I'm talking about real-time response to signals, I/O port and interrupt handling, that kind of thing. The device driver will then expose a higher-level API, maybe as a /dev/something openable, and Python can control the device using that. And that's something that Python *is* good at. I wouldn't use Python to write a device driver for an RTL8169 card, but if I have that card in my computer, I will totally use Python to create a network connection and transfer data. I'm just not going to concern myself with the low-level details when I do. :) ChrisA From Windows7IsOK at DreamPC2006.com Sun Feb 9 00:17:03 2014 From: Windows7IsOK at DreamPC2006.com (Skybuck Flying) Date: Sun, 9 Feb 2014 06:17:03 +0100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: Message-ID: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> " I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? " Anything that needs to be super reliable. My experience so far with Python versus Delphi has shown that Python requires way more time to debug than Delphi. The reason for this is the interpreter versus the compiler. Delphi's compiler will catch many bugs in branches that have not been executed or tested. While Python's interpreter will mostly catch bugs in executed and tested branches. Most of the code that has not been executed yet could contain bugs and even syntax/typos/non declared variables and so forth. Which means that the entire Python program will have to be re-executed from the start to ultimately end up in branches that were not executed the last time. This way of debugging will require many many many many many many many many runs of the same Python program before it's somewhat debugged. This is time lost in the debugging phase. Having said that... time is gained in the programming phase thanks to it's shortened syntax. However there is more... Python may lack some technical language elements like, call by reference, and perhaps other low level codes, like 8 bit, 16 bit, 32 bit integers which play a roll with interfacing with hardware. Types of software which would not go onto my python list: operating systems, drivers, perhaps also virtual machines and even compilers, python slow execution speed hampers that as well. Bye, Skybuck. From orgnut at yahoo.com Sun Feb 9 00:33:15 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sat, 08 Feb 2014 21:33:15 -0800 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: On 02/07/2014 11:06 PM, Igor Korot wrote: > Hi, ALL, > I'm trying to do a very easy task: sort python dictionary by value > where value is a datetime object. > > When trying to do that in Python shell everthing works as expected. > > C:\Documents and Settings\Igor.FORDANWORK>python > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = {} >>>> import datetime >>>> a['1'] = datetime.datetime(2012,12,28,12,15,30,100) >>>> a['2'] = datetime.datetime(2012,12,28,12,17,29,100) >>>> a['3'] = datetime.datetime(2012,12,28,12,16,44,100) >>>> sorted(a.items(), key=a.get) > [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', datetime.datetim > e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, 12, 17, > 29, 100))] >>>> > > However, trying to do the same thing from the script does not sort the > dictionary: > > sorted(my_dict.items(), key=my_dict.get, reverse=False) > for key, value in my_dict.items(): > print value, key > > the dictionary prints with unsorted items. > > I am trying to run it on Windows XP and the data are coming from the DB. > > What am I missing? > > Thank you. > You are missing the difference between sorted and sort. The sorted function returns a new list, but leaves the original unchanged. The sort method changes the list in place, and returns None. In your first, interactive example, the returned sorted list is automatically displayed -- that's why you see the sorted list. In your script, however, you are sorting the list but not saving the result -- it's immediately thrown away. In effect, your "sorted(...)" line is a no-op. You follow this by displaying the original, unsorted dictionary. Secondly, your sorting key is wrong. You are sorting a list not a dictionary. It is a list of (key,value) tuples, which you want to sort on the second element of the tuple. You can do this with a simple lambda expression: key=lambda t:t[1] Finally, change your for loop to print the data from this sorted list of tuples, not from the dictionary. -=- Larry -=- From rosuav at gmail.com Sun Feb 9 00:41:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 16:41:44 +1100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> References: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> Message-ID: On Sun, Feb 9, 2014 at 4:17 PM, Skybuck Flying wrote: > Anything that needs to be super reliable. > > My experience so far with Python versus Delphi has shown that Python > requires way more time to debug than Delphi. > > The reason for this is the interpreter versus the compiler. > > Delphi's compiler will catch many bugs in branches that have not been > executed or tested. > > While Python's interpreter will mostly catch bugs in executed and tested > branches. What this means is that Python forces you to have a good test suite. Yes, that is a cost; but it's nothing to do with compiled vs interpreted. These days, language engines aren't strictly one or the other, they're on a scale. Python will catch syntactic errors at compile time, but will catch most other forms of error at run time... except for the ones that, regardless of the language used, simply result in wrong data. So if you're not testing your code, you can't rely on it, and that's nothing to do with the language. A language with typed variable declarations can catch at compile-time a class of error that Python can't catch until run-time. Yep. But that doesn't actually answer the question: what should Python not be used for. If you need to trust your code, you need to test it. > However there is more... Python may lack some technical language elements > like, call by reference, and perhaps other low level codes, like 8 bit, 16 > bit, 32 bit integers which play a roll with interfacing with hardware. I've never yet found a desperate need for call-by-reference. In toy examples, the equivalent functionality can be achieved by treating a one-element list as a pointer, and dereferencing it just like you would in C, with [0] at the end. Never needed it in production code, though. But again, this doesn't cut out a class of application, just a style of coding. As to strict-size integers, Python does have a struct module, and ctypes, both of which are designed for interfacing with hardware or low-level APIs. For normal work, you don't need to care about that at all. > Types of software which would not go onto my python list: operating systems, > drivers, perhaps also virtual machines and even compilers, python slow > execution speed hampers that as well. A virtual machine where machine code is executed in Python? Well, depends on how fast you need it to be, but yes, that's quite likely to demand more oomph than your typical Python interpreter can give you. Although you could probably play ancient 8088 games, actually interpreting it all on the fly; on modern hardware, you could probably get up to the speed of those old CPUs. Of course, if you can get most of the work done at a lower level, then it's not that kind of VM, and performance is completely different. Compilers... yes, on big projects, you'd probably want to write the compiler in C. I generally say that C is for writing operating systems and high level languages, and those high level languages are for writing everything else in. But look at PyPy. It's possible to write a Python compiler in Python, which can often out-perform CPython. So it's not so clear-cut :) ChrisA From gvanem at yahoo.no Sun Feb 9 00:49:31 2014 From: gvanem at yahoo.no (Gisle Vanem) Date: Sun, 9 Feb 2014 05:49:31 +0000 (GMT) Subject: Vedr: What does """ means in python? In-Reply-To: References: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> Message-ID: <1391924971.76178.YahooMailNeo@web28703.mail.ir2.yahoo.com> ? Gisle V. "Computers are useless. They can only give answers" --Pablo Picasso Chris Angelico wrote: > For SQL? Ignore the extra spaces, it's a free-form language. The only > reason to consider dedent() would be if you're worried about how your > log files will look. The actual execution of SQL won't be bothered by > newlines and spaces/tabs. Regrading handy uses of ''', you learned me one trick when using Python? code in a Windows .bat file: ? rem = ''' ? @echo off ? echo This is batch ? \python32\python %0 ? echo All done ? exit /b ? rem ''' ? import sys ? print("This is Python") ? for i,p in enumerate(sys.path): ? ? ?print('sys.path[%2d]: %s' % (i, p)) ? print("Python done") You'll have a variable in Python called 'rem' which contains all your batch code :) It exploits the fact that 'rem' makes a one-line comment, but the triple quotes go across multiple lines. From swdunning at cox.net Sun Feb 9 01:00:13 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 8 Feb 2014 23:00:13 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: On Feb 8, 2014, at 6:46 PM, Chris Angelico wrote: > That's certainly effective. It's going to give you the right result. I > would be inclined to start from the small end and strip off the > seconds first, then the minutes, etc, because then you're working with > smaller divisors (60, 60, 24, 7 instead of 604800, 86400, 3600, 60); > most people will understand that a week is 7 days, but only people who > work with DNS will know that it's 604800 seconds. But both work. How would working from the small end (seconds) first and going up to weeks allow me to work with the smaller divisors? Wouldn?t it still have to be in seconds? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Feb 9 01:30:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 17:30:11 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: On Sun, Feb 9, 2014 at 5:00 PM, Scott W Dunning wrote: > On Feb 8, 2014, at 6:46 PM, Chris Angelico wrote: > > That's certainly effective. It's going to give you the right result. I > would be inclined to start from the small end and strip off the > seconds first, then the minutes, etc, because then you're working with > smaller divisors (60, 60, 24, 7 instead of 604800, 86400, 3600, 60); > most people will understand that a week is 7 days, but only people who > work with DNS will know that it's 604800 seconds. But both work. > > > How would working from the small end (seconds) first and going up to weeks > allow me to work with the smaller divisors? Wouldn?t it still have to be in > seconds? Here's how to do it from the small end up: time = int(raw_input("Enter number of seconds: ")) seconds = time % 60 time /= 60 minutes = time % 60 time /= 60 hours = time % 24 time /= 24 days = time % 7 time /= 7 weeks = time # Alternative way to format for display: print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds)) Enter number of seconds: 123456789 204 weeks, 0 days, 21:33:09 Produces the same result, has the same amount of division in it, but the time keeps shifting down: after the first pair, it's a number of minutes, after the second pair it's a number of hours, and so on. By the way, here's the divmod version of the above code: time = int(raw_input("Enter number of seconds: ")) time, seconds = divmod(time, 60) time, minutes = divmod(time, 60) time, hours = divmod(time, 24) weeks, days = divmod(time, 7) print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds)) It's now fairly clear what's going on. Each time unit is on the same line as the number of that time unit that make up the next one. The same thing, going down, looks like this: seconds = int(raw_input("Enter number of seconds: ")) weeks, seconds = divmod(seconds, 604800) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds)) Also fairly clear; each time unit is on the same line as the number of seconds that make up that unit. Both methods make sense, in their own way. ChrisA From pavlovevidence at gmail.com Sun Feb 9 01:30:18 2014 From: pavlovevidence at gmail.com (pavlovevidence at gmail.com) Date: Sat, 8 Feb 2014 22:30:18 -0800 (PST) Subject: python and matlab In-Reply-To: References: Message-ID: On Thursday, February 6, 2014 5:30:54 AM UTC-8, Sam Adams wrote: > is it able to utilize functions written in Python in Matlab? If it's on Windows, and if it's pure-Python 2.x code, the easiest solution would be to use Iron Python or Jython. Matlab can call Java and .NET code natively. From frank at chagford.com Sun Feb 9 01:48:23 2014 From: frank at chagford.com (Frank Millman) Date: Sun, 9 Feb 2014 08:48:23 +0200 Subject: Sorting dictionary by datetime value References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:ld4pon$ni9$1 at ger.gmane.org... > Frank Millman wrote: > > Here you can watch the key calculation at work: > >>>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'} >>>> def sortkey(value): > ... key = d.get(value) > ... print "value:", value, "sort-key:", key > ... return key > ... >>>> sorted(d.items(), key=sortkey) > value: ('1', 'abc') sort-key: None > value: ('3', 'pqr') sort-key: None > value: ('2', 'xyz') sort-key: None > [('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')] > Thanks for that, Peter. That is a clever debugging technique I must use more often! Not only do I now understand it, but I realise that Igor's original example worked by sheer coincidence - $python -V Python 2.7.3 $python -c "print({'1': None, '2': None, '3': None})" {'1': None, '3': None, '2': None} $python -c "print({'1': None, '2': None, '3': None})" {'1': None, '3': None, '2': None} $python -c "print({'1': None, '2': None, '3': None})" {'1': None, '3': None, '2': None} Keys of '1', '2', '3' are always stored in the sequence '1', 3', '2'. $python3 -V Python 3.3.2 $python3 -c "print({'1': None, '2': None, '3': None})" {'2': None, '3': None, '1': None} $python3 -c "print({'1': None, '2': None, '3': None})" {'3': None, '2': None, '1': None} $python3 -c "print({'1': None, '2': None, '3': None})" {'1': None, '2': None, '3': None} Due to the new 'hash randomisation' feature, the order is different every time. In both versions, integer keys of 1, 2, 3 are always stored in the sequence 1, 2, 3. Frank From orgnut at yahoo.com Sun Feb 9 02:00:41 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sat, 08 Feb 2014 23:00:41 -0800 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> Message-ID: <_LednUQQ4rwHumrPnZ2dnUVZ_t-dnZ2d@giganews.com> On 02/08/2014 05:21 PM, Scott W Dunning wrote: > I figured it out! Thanks Chris! Taking it one step at a time with the five digit number really helped me to see how to break it all up! Are you a teacher? I appreciate the help and the patients! I like that you don?t just give me the answer that you break it down and help me so that I can figure it out on my own! Thanks to all of you for all of your help, you guys are helping me a lot and I really appreciate it! > > Here is how I did it if you?re curious.?. > > seconds = raw_input("Enter the number of seconds:") > seconds = int(seconds) ... One very trivial nit... Add one or two spaces at the end of your prompt string. Simply as a matter of aesthetics--it looks nicer if your input doesn't butt up solidly against the prompt. (Personally, I like two spaces, but YMMV...) ;-) Of course, this is just for the appearance, it makes absolutely no difference in your results. -=- Larry -=- From worthingtonclinton at gmail.com Sun Feb 9 02:07:50 2014 From: worthingtonclinton at gmail.com (worthingtonclinton at gmail.com) Date: Sat, 8 Feb 2014 23:07:50 -0800 (PST) Subject: Dictionaries Message-ID: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> why in a for loop can i access values for a dict that i did not address in the for loop. example: a = {blah:blah} b = {blah:blah} for x in a: print a[x] #here's what i don't understand print b[x] # it would print the value for dict b even though it wasn't called upon in the for loop! Thanks in advance. From gary.herron at islandtraining.com Sun Feb 9 02:18:56 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Sat, 08 Feb 2014 23:18:56 -0800 Subject: Dictionaries In-Reply-To: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> References: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> Message-ID: <52F72BE0.1060002@islandtraining.com> On 02/08/2014 11:07 PM, worthingtonclinton at gmail.com wrote: > why in a for loop can i access values for a dict that i did not address in the for loop. > > example: > > a = {blah:blah} > b = {blah:blah} > > for x in a: > > print a[x] > > #here's what i don't understand > > print b[x] > > # it would print the value for dict b even though it wasn't called upon in the for loop! > > > Thanks in advance. The lookup of a value in dictionary b does not care where the index comes from. Quite simply, x has the value of 'blah', and b has 'blah' as a key, so b[x] works. If a and b had different keys, then you would get an error: >>> a = {'a':1} >>> b = {'b':2} >>> for x in a: ... print x ... print a[x] ... print b[x] ... a 1 Traceback (most recent call last): File "", line 4, in KeyError: 'a' Gary Herron From frank at chagford.com Sun Feb 9 02:27:37 2014 From: frank at chagford.com (Frank Millman) Date: Sun, 9 Feb 2014 09:27:37 +0200 Subject: Dictionaries References: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> Message-ID: wrote in message news:891d3696-4e4e-44cc-a491-6b8fef47fcd9 at googlegroups.com... > why in a for loop can i access values for a dict that i did not address in > the for loop. > > example: > > a = {blah:blah} > b = {blah:blah} > > for x in a: > > print a[x] > > #here's what i don't understand > > print b[x] > > # it would print the value for dict b even though it wasn't called upon > in the for loop! > Iterating over a dictionary returns the keys of the dictionary. When you say 'for x in a', each iteration sets 'x' to the next key in dictionary 'a'. 'x' is a reference to a normal python object. It does not 'know' that it came from dictionary 'a', so you can do whatever you like with it. If you use it to retrieve a value in dictionary 'b', and the key happens to exist, it will return the value. Otherwise it will raise KeyError. HTH Frank Millman From worthingtonclinton at gmail.com Sun Feb 9 02:45:21 2014 From: worthingtonclinton at gmail.com (worthingtonclinton at gmail.com) Date: Sat, 8 Feb 2014 23:45:21 -0800 (PST) Subject: Dictionaries In-Reply-To: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> References: <891d3696-4e4e-44cc-a491-6b8fef47fcd9@googlegroups.com> Message-ID: <7b94121f-bf16-4f38-93c5-a65aa9c5e903@googlegroups.com> greatly appreciated guys. thanks! From marcelgmr at gmail.com Sun Feb 9 05:20:47 2014 From: marcelgmr at gmail.com (Marcel Rodrigues) Date: Sun, 9 Feb 2014 08:20:47 -0200 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: As Chris said, if your needs are simple, use SQLite back-end. It's probably already installed on your computer and Python has a nice interface to it in its standard library. [1] If you decide to use MySQL back-end instead, consider using PyMySQL [2]. It's compatible with both Python 2 and Python 3. Also, being written in pure Python, it's easier to install compared to MySQLdb. [1] http://docs.python.org/3/library/sqlite3.html#module-sqlite3 [2] https://pypi.python.org/pypi/PyMySQL 2014-02-08 6:55 GMT-02:00 Sam : > Is MySQLdb the recommended python module for SQL database access? Are > there other modules? What I want in a module is to be able to write > readable and maintainable code. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roegltd at gmail.com Sun Feb 9 05:39:51 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 02:39:51 -0800 (PST) Subject: system wide mutex Message-ID: Hi Which one is most recommended to use for mutex alike locking to achieve atomic access to single resource: - fcntl.lockf - os.open() with O_SHLOCK and O_EXLOCK - https://pypi.python.org/pypi/lockfile/0.9.1 - https://pypi.python.org/pypi/zc.lockfile/1.1.0 - any other ? Thanks /Asaf From marcelgmr at gmail.com Sun Feb 9 05:40:05 2014 From: marcelgmr at gmail.com (Marcel Rodrigues) Date: Sun, 9 Feb 2014 08:40:05 -0200 Subject: Why use _mysql module and not use MySQLdb directly? In-Reply-To: <58c461a7-bf08-4258-af29-2b1d7778a85c@googlegroups.com> References: <429f41e0-7fe8-4792-82f2-e438917a3add@googlegroups.com> <145766f5-6e5f-40c7-be92-3adbf1015731@googlegroups.com> <58c461a7-bf08-4258-af29-2b1d7778a85c@googlegroups.com> Message-ID: Another option is PyMySQL [1]. It's developed in the open at GitHub [2]. It's pure Python, compatible with both Python 2 and Python 3. It's DB-API 2 compliant. It also implements some non-standard bits that are present in MySQLdb, in order to be compatible with legacy code, notably Django (personally, I consider the use of non-standard API from a DB adapter a bug, but while the big projects don't fix it, we have to work around it). [1] https://pypi.python.org/pypi/PyMySQL [2] https://github.com/PyMySQL/PyMySQL 2014-02-08 10:09 GMT-02:00 Asaf Las : > On Saturday, February 8, 2014 1:42:30 PM UTC+2, Chris Angelico wrote: > > On Sat, Feb 8, 2014 at 10:32 PM, Asaf Las wrote: > > > > > Hi Chris > > > The doc says > > > https://pypi.python.org/pypi/mysql-connector-python/1.1.5 > > > MySQL driver written in Python which does not depend on MySQL C > > > client libraries and implements the DB API v2.0 specification > (PEP-249). > > > > Ah. And that links to dev.mysql.com, so it's presumably the same > > thing... would be nice if they'd say that on their own site. That's > > what I was looking for, anyhow. Confirms the suspicion. > > > > There may well be performance differences between pure-Python > > implementations and ones that go via C, but having used a > > pure-high-level-language implementation of PostgreSQL's wire protocol > > (granted, that was Pike, which is a somewhat higher performance > > language than Python, but same difference), I can assure you of what > > ought to be obvious anyway: that performance is dominated by the > > server's throughput and thus (usually) by disk speed. So it's going to > > be pretty much the same with all of them; look for ancillary features > > that might make your life easier, otherwise pick whichever you like. > > > > ChrisA > > Hmmm, they say : > > http://dev.mysql.com/doc/connector-python/en/connector-python-introduction.html > > "MySQL Connector/Python enables Python programs to access MySQL databases, > using an API that is compliant with the Python DB API version 2.0. It > is written in pure Python and does not have any dependencies except for > the Python Standard Library..." > > i guess with Oracle connector there could be one advantage - they will > try to be most compliant to their product in every aspect as they would > raiser promote their DB instead of discouraging from it. > > /Asaf > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wxjmfauth at gmail.com Sun Feb 9 05:47:03 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 9 Feb 2014 02:47:03 -0800 (PST) Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> References: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> Message-ID: Le dimanche 9 f?vrier 2014 06:17:03 UTC+1, Skybuck Flying a ?crit?: > " > > > > > However there is more... Python may lack some technical language elements > > like, call by reference, and perhaps other low level codes, like 8 bit, 16 > > bit, 32 bit integers which play a roll with interfacing with hardware. > > > Or, pure software, interfacing with the unicode transformation units! jmf From skip at pobox.com Sun Feb 9 06:00:39 2014 From: skip at pobox.com (Skip Montanaro) Date: Sun, 9 Feb 2014 05:00:39 -0600 Subject: system wide mutex In-Reply-To: References: Message-ID: > Which one is most recommended to use for mutex alike locking to > achieve atomic access to single resource: > > - fcntl.lockf > - os.open() with O_SHLOCK and O_EXLOCK > - https://pypi.python.org/pypi/lockfile/0.9.1 > - https://pypi.python.org/pypi/zc.lockfile/1.1.0 > - any other ? As the author of lockfile, I can tell you it only implements advisory locking. All programs needing to access the locked resources must cooperate. It also has bugs which have been reported which I have yet to spend any time fixing. Beyond that, your question isn't really detailed enough to answer completely. You don't identify what sort of systems you need this to work on (Windows, Mac, various flavors of Unix?), whether programs written in other languages will be involved (you did say "system wide"), and whether you need to use it in the face of network file systems like NFS or Samba. Skip From rosuav at gmail.com Sun Feb 9 06:00:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 22:00:58 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 9:20 PM, Marcel Rodrigues wrote: > As Chris said, if your needs are simple, use SQLite back-end. It's probably > already installed on your computer and Python has a nice interface to it in > its standard library. Already installed? I thought the point of SQLite3 being in the Python stdlib was that Python actually included the entire engine (that's why there's no, for instance, PostgreSQL client in the stdlib - because there's no server; I disagree with the reasoning, but it is consistent and valid), so you don't need _anything_ externally installed. In any case, SQLite is ideal for really simple databasing. Back in the 1990s, I had DB2, DB2, and DB2, for all my database work. I wanted a way to query a dictionary of English words using SQL, so I created a DB2 database and threw ~60K rows into a table. Massive overkill for a one-column table. These days, I could use SQLite (or more likely, just use grep on /usr/share/dict/words - grep does everything that I wanted SQL for, if you include piping from one grep into another), cutting the overhead down enormously. The biggest downside of SQLite3 is concurrency. I haven't dug into the exact details of the pager system and such, but it seems to be fairly coarse in its locking. Also, stuff gets a bit complicated when you do a single transaction involving multiple files. So if you have lots of processes writing to the same set of SQLite tables, you'll see pretty poor performance. PostgreSQL handles that situation far better, but has a lot more overhead, so it's a poor choice for a single simple application. MySQL's locking/concurrency system is specifically optimized for a model that's common for web applications: a huge number of readers and a tiny number of writers (sometimes referred to as Data Warehousing, because you basically stuff a warehouse full of data and then everyone comes looking for it). For the write-heavy model (sometimes called OLTP or On-Line Transaction Processing), PostgreSQL will hugely outperform MySQL, thanks to its MVCC model. Broad recommendation: Single application, tiny workload, concurrency not an issue, simplicity desired? Go SQLite. Big complex job, need performance, lots of things reading and writing at once, want networked access? Go PGSQL. And don't go MySQL if PG is an option. And definitely don't go for a non-free option (MS-SQL, DB2, etc) unless you've looked into it really closely and you are absolutely thoroughly *sure* that you need that system (which probably means you need your app to integrate with someone else's, and that other app demands one particular database). ChrisA From roegltd at gmail.com Sun Feb 9 06:00:41 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 03:00:41 -0800 (PST) Subject: system wide mutex In-Reply-To: References: Message-ID: <8452cd9e-601a-49f6-9dc4-2eb921ee7c28@googlegroups.com> Forget to mentioned - CentOS 6.5 Python v3.3. From roegltd at gmail.com Sun Feb 9 06:07:56 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 03:07:56 -0800 (PST) Subject: system wide mutex In-Reply-To: References: Message-ID: On Sunday, February 9, 2014 1:00:39 PM UTC+2, Skip Montanaro wrote: > > Which one is most recommended to use for mutex alike locking to > > achieve atomic access to single resource: > > > > - fcntl.lockf > > - os.open() with O_SHLOCK and O_EXLOCK > > - https://pypi.python.org/pypi/lockfile/0.9.1 > > - https://pypi.python.org/pypi/zc.lockfile/1.1.0 > > - any other ? > > As the author of lockfile, I can tell you it only implements advisory > locking. All programs needing to access the locked resources must > cooperate. It also has bugs which have been reported which I have yet > to spend any time fixing. > Beyond that, your question isn't really detailed enough to answer > completely. You don't identify what sort of systems you need this to > work on (Windows, Mac, various flavors of Unix?), whether programs > written in other languages will be involved (you did say "system > wide"), and whether you need to use it in the face of network file > systems like NFS or Samba. > Skip Hi Yes i realized that missed info. The lock is needed for 2 independently spawned processes to update set of files and non non thread safe db /Asaf From okko.willeboordse at gmail.com Sun Feb 9 06:53:04 2014 From: okko.willeboordse at gmail.com (Okko Willeboordse) Date: Sun, 9 Feb 2014 03:53:04 -0800 (PST) Subject: Event::wait with timeout gives delay Message-ID: <8a3b2f81-d1d3-4bd5-8e83-4603e24fc3e3@googlegroups.com> Running Python 2.6 and 2.7 on Windows 7 and Server 2012 Event::wait causes a delay when used with a timeout that is not triggered because event is set in time. I don't understand why. Can someone explain? The following program shows this; '''Shows that using a timeout in Event::wait (same for Queue::wait) causes a delay. This is perhaps caused by a polling loop inside the wait implementation. This polling loop sleeps some time depending on the timeout. Probably wait timeout > 1ms => sleep = 1ms A wait with timeout can take at least this sleep time even though the event is set or queue filled much faster.''' import threading event1 = threading.Event() event2 = threading.Event() def receiver(): '''wait 4 event2, clear event2 and set event1.''' while True: event2.wait() event2.clear() event1.set() receiver_thread = threading.Thread(target = receiver) receiver_thread.start() def do_transaction(timeout): '''Performs a transaction; clear event1, set event2 and wait for thread to set event1.''' event1.clear() event2.set() event1.wait(timeout = timeout) while True: # With timeout None this runs fast and CPU bound. # With timeout set to some value this runs slow and not CPU bound. do_transaction(timeout = 10.0) From marcelgmr at gmail.com Sun Feb 9 07:04:40 2014 From: marcelgmr at gmail.com (Marcel Rodrigues) Date: Sun, 9 Feb 2014 10:04:40 -0200 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: I just checked in the Python sources and apparently you're right about SQLite3. The Python distribution includes pysqlite which seems to be a self-contained SQLite engine. No external dependencies. Sorry for the confusion. 2014-02-09 9:00 GMT-02:00 Chris Angelico : > On Sun, Feb 9, 2014 at 9:20 PM, Marcel Rodrigues > wrote: > > As Chris said, if your needs are simple, use SQLite back-end. It's > probably > > already installed on your computer and Python has a nice interface to it > in > > its standard library. > > Already installed? I thought the point of SQLite3 being in the Python > stdlib was that Python actually included the entire engine (that's why > there's no, for instance, PostgreSQL client in the stdlib - because > there's no server; I disagree with the reasoning, but it is consistent > and valid), so you don't need _anything_ externally installed. > > In any case, SQLite is ideal for really simple databasing. Back in the > 1990s, I had DB2, DB2, and DB2, for all my database work. I wanted a > way to query a dictionary of English words using SQL, so I created a > DB2 database and threw ~60K rows into a table. Massive overkill for a > one-column table. These days, I could use SQLite (or more likely, just > use grep on /usr/share/dict/words - grep does everything that I wanted > SQL for, if you include piping from one grep into another), cutting > the overhead down enormously. > > The biggest downside of SQLite3 is concurrency. I haven't dug into the > exact details of the pager system and such, but it seems to be fairly > coarse in its locking. Also, stuff gets a bit complicated when you do > a single transaction involving multiple files. So if you have lots of > processes writing to the same set of SQLite tables, you'll see pretty > poor performance. PostgreSQL handles that situation far better, but > has a lot more overhead, so it's a poor choice for a single simple > application. MySQL's locking/concurrency system is specifically > optimized for a model that's common for web applications: a huge > number of readers and a tiny number of writers (sometimes referred to > as Data Warehousing, because you basically stuff a warehouse full of > data and then everyone comes looking for it). For the write-heavy > model (sometimes called OLTP or On-Line Transaction Processing), > PostgreSQL will hugely outperform MySQL, thanks to its MVCC model. > > Broad recommendation: Single application, tiny workload, concurrency > not an issue, simplicity desired? Go SQLite. Big complex job, need > performance, lots of things reading and writing at once, want > networked access? Go PGSQL. And don't go MySQL if PG is an option. > > And definitely don't go for a non-free option (MS-SQL, DB2, etc) > unless you've looked into it really closely and you are absolutely > thoroughly *sure* that you need that system (which probably means you > need your app to integrate with someone else's, and that other app > demands one particular database). > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Feb 9 07:13:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 23:13:56 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 11:04 PM, Marcel Rodrigues wrote: > I just checked in the Python sources and apparently you're right about > SQLite3. The Python distribution includes pysqlite which seems to be a > self-contained SQLite engine. No external dependencies. Sorry for the > confusion. Comes to the same thing, anyhow. If anything, that strengthens your original point: it's easy, it's right there, you can give it a go. ChrisA From nispray at gmail.com Sun Feb 9 07:13:50 2014 From: nispray at gmail.com (Wesley) Date: Sun, 9 Feb 2014 04:13:50 -0800 (PST) Subject: Sort one sequence by O(n) in time and O(1) in space Message-ID: Hi guys, Here is one question related to algorithm. Details here: here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). Any comments will be appreciated. Thanks. Wesley From mozthecos at gmail.com Sun Feb 9 07:25:16 2014 From: mozthecos at gmail.com (Moz) Date: Sun, 9 Feb 2014 04:25:16 -0800 (PST) Subject: Help! Message-ID: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> I have studied python(2.7.2) till classes. I have covered most of the the general topics. But i do not know how to apply this. Can someone help me? I want to make something that can aid me financially. If you have done something like this please can you provide me with the resources and the libraries so that i may study even further. Thanks You! From roegltd at gmail.com Sun Feb 9 07:29:34 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 04:29:34 -0800 (PST) Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: On Sunday, February 9, 2014 2:13:50 PM UTC+2, Wesley wrote: > Hi guys, > Here is one question related to algorithm. > Details here: > > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). > > Any comments will be appreciated. > > Thanks. > > Wesley if space O(1) is needed they don't have to be merged - list alike class keeping series as members returning a[i] if i is odd and b[i] if i is even would be enough. then constructing such sequence (or class instance) will be done in O(1) as well. /Asaf From rosuav at gmail.com Sun Feb 9 07:39:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 23:39:39 +1100 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 11:13 PM, Wesley wrote: > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). The two halves of the list are already sorted, yes? Then you don't need a sort operation, just a zip. def flip_list(lst): offset = len(lst)//2 for i in range(offset): yield lst[i] yield lst[i+offset] start = ['a1','a2','a3','a4','b1','b2','b3','b4'] result = list(flip_list(start)) print(result) Alternatively, you could arrange this as some kind of swap operation, modifying the list in place, but I think the more Pythonic way will be to create a new list. Note that, with the function defined as I have above, you can iterate over the flipped list without actually coalescing it in memory. That gives effective O(1) space, and it's definitely O(n) time as it simply iterates over the whole list once. ChrisA From rosuav at gmail.com Sun Feb 9 07:42:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Feb 2014 23:42:09 +1100 Subject: Help! In-Reply-To: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> References: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> Message-ID: On Sun, Feb 9, 2014 at 11:25 PM, Moz wrote: > I have studied python(2.7.2) till classes. I have covered most of the the general topics. But i do not know how to apply this. Can someone help me? I want to make something that can aid me financially. If you have done something like this please can you provide me with the resources and the libraries so that i may study even further. > Thanks You! The best way to apply your new knowledge is to find some problem and use Python to solve it. What are you doing every day, manually, that could be automated? Or maybe it's not something you do every day, but when you do it, you have a batch of them. Find some job that you think "A computer ought to be able to do this!" about, and teach the computer to do it :) Once you get into the habit of doing that, you'll be a programmer/sysadmin with a comfortable set of tools and an attitude that lends itself well to getting the job done efficiently. ChrisA From roegltd at gmail.com Sun Feb 9 07:47:20 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 04:47:20 -0800 (PST) Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Sunday, February 9, 2014 1:00:58 PM UTC+2, Chris Angelico wrote: > The biggest downside of SQLite3 is concurrency. I haven't dug into the > exact details of the pager system and such, but it seems to be fairly > coarse in its locking. Also, stuff gets a bit complicated when you do > a single transaction involving multiple files. So if you have lots of > processes writing to the same set of SQLite tables, you'll see pretty > poor performance. > ChrisA Hi Chris i simply tested running 2 independent processes started at same time in parallel towards same sqlite database and never get 20000 in that row though used exclusive lock on DB. might be i did something wrong. p.s. threading locks don't do anything in this example. import sqlite3 import threading #from threading import Lock # Constants CNT_DB_NAME = "messageid.db" class MessageId: ''' -------------------------------------------------------------------------- Following must be done in advance: - Create DB sqlite3 sqlite_msgd.db - Create table CREATE TABLE msgid (id INTEGER PRIMARY KEY, val INTEGER); - Inser def INSERT INTO msgid VALUES (0, 0); --------------------------------------------------------------------------''' def __init__(self, dflag = False, dbname = 'messageid.db'): #print(type(self)) #print(id(self)) self._debug = dflag self._lock = threading.Lock() self._dbname = dbname if self._debug: print("MessageId.__init__(dbname = {0})".format(dbname)) def get_msgid(self): ''' -------------------------------------------------------------------------- - Acquire lock - Connect to database - Select current value SELECT val FROM msgid WHERE id = 0; - Increment current value - Insert a row of data UPDATE msgid SET val = 1 WHERE id = new_val; --------------------------------------------------------------------------''' self._lock.acquire(True, 1) conn = sqlite3.connect('example.db', 10.0, True, "EXCLUSIVE") c = conn.cursor() c.execute("SELECT val FROM msgid WHERE id = 0") tint = int(c.fetchone()[0]) + 1 c.execute("UPDATE msgid SET val={0} WHERE id = 0".format(tint)) conn.commit() conn.close() self._lock.release() if self._debug: print("MessageId.get_msgid() = ", tint) return tint tclass = MessageId() for k in range(10000): tclass.get_msgid() From mozthecos at gmail.com Sun Feb 9 07:48:35 2014 From: mozthecos at gmail.com (Moz) Date: Sun, 9 Feb 2014 04:48:35 -0800 (PST) Subject: Help! In-Reply-To: References: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> Message-ID: On Sunday, February 9, 2014 5:42:09 PM UTC+5, Chris Angelico wrote: > On Sun, Feb 9, 2014 at 11:25 PM, Moz wrote: > > > I have studied python(2.7.2) till classes. I have covered most of the the general topics. But i do not know how to apply this. Can someone help me? I want to make something that can aid me financially. If you have done something like this please can you provide me with the resources and the libraries so that i may study even further. > > > Thanks You! > > > > The best way to apply your new knowledge is to find some problem and > > use Python to solve it. What are you doing every day, manually, that > > could be automated? Or maybe it's not something you do every day, but > > when you do it, you have a batch of them. Find some job that you think > > "A computer ought to be able to do this!" about, and teach the > > computer to do it :) Once you get into the habit of doing that, you'll > > be a programmer/sysadmin with a comfortable set of tools and an > > attitude that lends itself well to getting the job done efficiently. > > > > ChrisA Thanks :) From bagratte at live.com Sun Feb 9 07:05:59 2014 From: bagratte at live.com (bagrat lazaryan) Date: Sun, 9 Feb 2014 16:05:59 +0400 Subject: imperative mood in docstrings Message-ID: pep 257 -- docstring conventions, as well as a myriad of books and other resources, recommend documenting a function's or method's effect as a command ("do this", "return that"), not as a description ("does this", "returns that"). what's the logic behind this recommendation? bagratte From roegltd at gmail.com Sun Feb 9 07:54:16 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 04:54:16 -0800 (PST) Subject: Help! In-Reply-To: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> References: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> Message-ID: <3ad7e7ec-2b27-4417-84a3-342c29df5dab@googlegroups.com> On Sunday, February 9, 2014 2:25:16 PM UTC+2, Moz wrote: > I want to make something that can aid me financially. If you have > done something like this please can you provide me with the resources > and the libraries so that i may study even further. > > Thanks You! you can try similar to this : http://www.rent-acoder.com find the task you can't do but can figure out and gain in knowledge i never used such sites, only sporadic references from from whom i know. From rosuav at gmail.com Sun Feb 9 08:14:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 00:14:50 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 11:47 PM, Asaf Las wrote: > i simply tested running 2 independent processes started at same time in > parallel towards same sqlite database and never get 20000 in that row > though used exclusive lock on DB. might be i did something wrong. The threading locks aren't doing anything, because you don't have multiple threads here; what you need is SQLite locks, which you'll already have. I don't know why it wouldn't work. Unfortunately I wasn't able to test your code directly - SQLite complained that the table didn't exist, despite my having created it (at least, so I thought) in interactive Python. So probably I mucked something up there. Someone who actually knows SQLite might be better able to explain. A few points, though. > c.execute("UPDATE msgid SET val={0} WHERE id = 0".format(tint)) Don't do this; instead, let c.execute() do the interpolation, by giving it extra args rather than using .format(). It makes no difference when you're working with integers, but with strings, it makes the difference between safe and not-safe (or easy and unnecessarily fiddly, if you actually take the time to get your escaping right). Also, you're connecting and disconnecting repeatedly... oh, I see why it didn't work when I tried. You're also using two completely different database names: 'messageid.db' which is named in a constant and in the default argument, and 'example.db' which is what you actually use. Should have a single source of truth, otherwise you confuse the people who might otherwise be able to test your code :) Anyway. This code is extremely inefficient: > conn = sqlite3.connect('example.db', 10.0, True, "EXCLUSIVE") > c = conn.cursor() > c.execute("SELECT val FROM msgid WHERE id = 0") > tint = int(c.fetchone()[0]) + 1 > c.execute("UPDATE msgid SET val={0} WHERE id = 0".format(tint)) > conn.commit() > conn.close() Much more common would be to retain a connection and repeatedly perform queries. Then you won't need to open it EXCLUSIVE, and you can simply query, update, and then commit (all your locks should be released at the commit). Do that, and you should see at least reasonable performance, plus everything should work correctly. ChrisA From roegltd at gmail.com Sun Feb 9 08:27:01 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 05:27:01 -0800 (PST) Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: <12584a07-33ea-4c12-846c-6b336ce002a1@googlegroups.com> On Sunday, February 9, 2014 3:14:50 PM UTC+2, Chris Angelico wrote: > On Sun, Feb 9, 2014 at 11:47 PM, Asaf Las wrote: > Thanks > > Also, you're connecting and disconnecting repeatedly... oh, I see why > it didn't work when I tried. You're also using two completely > different database names: 'messageid.db' which is named in a constant > and in the default argument, and 'example.db' which is what you > actually use. Should have a single source of truth, otherwise you > confuse the people who might otherwise be able to test your code :) my apologies , it was deep night, when i got disappointed and forget to update names so left as it is and did not check when posted :-) > Anyway. This code is extremely inefficient: > > > conn = sqlite3.connect('example.db', 10.0, True, "EXCLUSIVE") > > c = conn.cursor() > > c.execute("SELECT val FROM msgid WHERE id = 0") > > tint = int(c.fetchone()[0]) + 1 > > c.execute("UPDATE msgid SET val={0} WHERE id = 0".format(tint)) > > conn.commit() > > conn.close() > > Much more common would be to retain a connection and repeatedly > perform queries. Then you won't need to open it EXCLUSIVE, and you can > simply query, update, and then commit (all your locks should be > released at the commit). Do that, and you should see at least > reasonable performance, plus everything should work correctly. > ChrisA i did it just to test sqlite3 behavior and actually test was related to simulation of unique incremental sequence number/counter for independently spawned tasks accessing counter in non deterministic manner. /Asaf From rosuav at gmail.com Sun Feb 9 08:36:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 00:36:25 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: <12584a07-33ea-4c12-846c-6b336ce002a1@googlegroups.com> References: <12584a07-33ea-4c12-846c-6b336ce002a1@googlegroups.com> Message-ID: On Mon, Feb 10, 2014 at 12:27 AM, Asaf Las wrote: > i did it just to test sqlite3 behavior and actually test was related to > simulation of unique incremental sequence number/counter for > independently spawned tasks accessing counter in non deterministic manner. Sure. I would expect that you'd get steadily increasing sequence IDs, but that they might be a major bottleneck. SQLite is (far as I can tell, at least - haven't personally tested it) quite solid with its locking; at the expense of performance, but carefully reliable. ChrisA From oscar.j.benjamin at gmail.com Sun Feb 9 08:41:35 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 9 Feb 2014 13:41:35 +0000 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: On 9 February 2014 12:13, Wesley wrote: > Hi guys, > Here is one question related to algorithm. > Details here: > > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). Do you mean that you have a list and you want to rearrange the elements in-place without creating a new list? Oscar From mozthecos at gmail.com Sun Feb 9 08:52:59 2014 From: mozthecos at gmail.com (Moz) Date: Sun, 9 Feb 2014 05:52:59 -0800 (PST) Subject: Help! In-Reply-To: <3ad7e7ec-2b27-4417-84a3-342c29df5dab@googlegroups.com> References: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> <3ad7e7ec-2b27-4417-84a3-342c29df5dab@googlegroups.com> Message-ID: On Sunday, February 9, 2014 5:54:16 PM UTC+5, Asaf Las wrote: > On Sunday, February 9, 2014 2:25:16 PM UTC+2, Moz wrote: > > > I want to make something that can aid me financially. If you have > > > done something like this please can you provide me with the resources > > > and the libraries so that i may study even further. > > > > > > Thanks You! > > > > you can try similar to this : > > > > http://www.rent-acoder.com > > > > find the task you can't do but can figure out and gain in knowledge > > i never used such sites, only sporadic references from from whom i know. Thanks :) From python.list at tim.thechases.com Sun Feb 9 09:31:20 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 9 Feb 2014 08:31:20 -0600 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: <20140209083120.33c5e677@bigbox.christie.dr> On 2014-02-09 22:00, Chris Angelico wrote: > On Sun, Feb 9, 2014 at 9:20 PM, Marcel Rodrigues > wrote: > > As Chris said, if your needs are simple, use SQLite back-end. > > It's probably already installed on your computer and Python has a > > nice interface to it in its standard library. > > Already installed? I thought the point of SQLite3 being in the > Python stdlib was that Python actually included the entire engine It's been a part of the stdlib since 2.5 (so those of us that maintain a bit of 2.4 code still in the wild had to add-on that module) -tkc From oscar.j.benjamin at gmail.com Sun Feb 9 09:30:55 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 9 Feb 2014 14:30:55 +0000 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: Please reply to the list rather than directly to me so that other people can see the answer to my question and offer you help. On 9 February 2014 14:04, Ni Wesley wrote: > 2014?2?9? ??9:41? "Oscar Benjamin" ??? > >> On 9 February 2014 12:13, Wesley wrote: >> > Hi guys, >> > Here is one question related to algorithm. >> > Details here: >> > >> > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx >> > always exist in pair. So, now, how to change the sequence to >> > a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). >> >> Do you mean that you have a list and you want to rearrange the >> elements in-place without creating a new list? > > Yes Okay so if you're going to do it with O(1) space then it's going to have to be done with a whole bunch of swaps. Have a think with pen and paper about how you could do a sequence of swaps that would rearrange the order to the one that you want (it's actually a harder problem than it looks at first glance). This is an example of what is known as "transposition" and much information is available about algorithms for doing this in-place: http://en.wikipedia.org/wiki/In-place_matrix_transposition Oscar From nispray at gmail.com Sun Feb 9 09:40:38 2014 From: nispray at gmail.com (Ni Wesley) Date: Sun, 9 Feb 2014 22:40:38 +0800 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: Yes, with no new list, otherwise, space won't to be O(1) Wesley 2014?2?9? ??10:31? "Oscar Benjamin" ??? > Please reply to the list rather than directly to me so that other > people can see the answer to my question and offer you help. > > On 9 February 2014 14:04, Ni Wesley wrote: > > 2014?2?9? ??9:41? "Oscar Benjamin" ??? > > > >> On 9 February 2014 12:13, Wesley wrote: > >> > Hi guys, > >> > Here is one question related to algorithm. > >> > Details here: > >> > > >> > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx > >> > always exist in pair. So, now, how to change the sequence to > >> > a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). > >> > >> Do you mean that you have a list and you want to rearrange the > >> elements in-place without creating a new list? > > > > Yes > > Okay so if you're going to do it with O(1) space then it's going to > have to be done with a whole bunch of swaps. Have a think with pen and > paper about how you could do a sequence of swaps that would rearrange > the order to the one that you want (it's actually a harder problem > than it looks at first glance). This is an example of what is known as > "transposition" and much information is available about algorithms for > doing this in-place: > http://en.wikipedia.org/wiki/In-place_matrix_transposition > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sun Feb 9 09:45:52 2014 From: roy at panix.com (Roy Smith) Date: Sun, 09 Feb 2014 09:45:52 -0500 Subject: system wide mutex References: Message-ID: In article , Skip Montanaro wrote: > > Which one is most recommended to use for mutex alike locking to > > achieve atomic access to single resource: > > > > - fcntl.lockf > > - os.open() with O_SHLOCK and O_EXLOCK > > - https://pypi.python.org/pypi/lockfile/0.9.1 > > - https://pypi.python.org/pypi/zc.lockfile/1.1.0 > > - any other ? > > As the author of lockfile, I can tell you it only implements advisory > locking. All programs needing to access the locked resources must > cooperate. This is true of all mutexes, no? We needed a mutex that worked across multiple machines, so we ended up implementing a mutex in memcache. We based ours on http://tinyurl.com/lybx2kl, but if you google for "memcache mutex python", you'll find a number of implementations. From roy at panix.com Sun Feb 9 10:05:02 2014 From: roy at panix.com (Roy Smith) Date: Sun, 09 Feb 2014 10:05:02 -0500 Subject: Sort one sequence by O(n) in time and O(1) in space References: Message-ID: In article , Wesley wrote: > Hi guys, > Here is one question related to algorithm. > Details here: > > here is input sequence like a1,a2,...,an,b1,b2,...,bn ???the ax and bx always > exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with > time complexity as O(n) and space as O(1). Is this a homework problem? It sounds like what you want to do is split the list into two halves, then shuffle them. Using itertools let's you do these operations without making copies of the data. Something like: -------------------------------------------------- from itertools import islice, izip def cut_and_shuffle(input): n = len(input) if n % 2: raise ValueError("input length must be even") split = n/2 print "split =", split first_half = islice(input, 0, split) second_half = islice(input, split, n) for a, b in izip(first_half, second_half): yield a yield b l = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4'] print list(cut_and_shuffle(l)) -------------------------------------------------- $ python shuffle.py split = 4 ['a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4'] From skip at pobox.com Sun Feb 9 10:40:00 2014 From: skip at pobox.com (Skip Montanaro) Date: Sun, 9 Feb 2014 09:40:00 -0600 Subject: system wide mutex In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 8:45 AM, Roy Smith wrote: > This is true of all mutexes, no? Hmmm... You might well be right. I thought that use of the O_EXLOCK flag in the open(2) system call would prevent other processes from opening the file, but (at least on my Mac) it just blocks until the first process closes the file. Perhaps there are some other flags you can use to cause the second open(2) call to error out. Skip From oscar.j.benjamin at gmail.com Sun Feb 9 10:48:17 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 9 Feb 2014 15:48:17 +0000 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: Please don't top-post. On Feb 9, 2014 2:40 PM, "Ni Wesley" wrote: > > Yes, with no new list, otherwise, space won't to be O(1) Did you read the link I posted: >> http://en.wikipedia.org/wiki/In-place_matrix_transposition Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Feb 9 10:49:23 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Feb 2014 15:49:23 +0000 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> Message-ID: On 09/02/2014 10:47, wxjmfauth at gmail.com wrote: > Le dimanche 9 f?vrier 2014 06:17:03 UTC+1, Skybuck Flying a ?crit : >> " >> >> >> >> >> However there is more... Python may lack some technical language elements >> >> like, call by reference, and perhaps other low level codes, like 8 bit, 16 >> >> bit, 32 bit integers which play a roll with interfacing with hardware. >> >> >> > > Or, pure software, interfacing with the unicode transformation units! > > jmf > You missed this :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Sun Feb 9 11:08:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Feb 2014 16:08:20 +0000 Subject: Help! In-Reply-To: References: <60e4d561-135e-41e4-a69d-e6114fe9a034@googlegroups.com> <3ad7e7ec-2b27-4417-84a3-342c29df5dab@googlegroups.com> Message-ID: On 09/02/2014 13:52, Moz wrote: > On Sunday, February 9, 2014 5:54:16 PM UTC+5, Asaf Las wrote: >> On Sunday, February 9, 2014 2:25:16 PM UTC+2, Moz wrote: >> >>> I want to make something that can aid me financially. If you have >> >>> done something like this please can you provide me with the resources >> >>> and the libraries so that i may study even further. >> >>> >> >>> Thanks You! >> >> >> >> you can try similar to this : >> >> >> >> http://www.rent-acoder.com >> >> >> >> find the task you can't do but can figure out and gain in knowledge >> >> i never used such sites, only sporadic references from from whom i know. > > Thanks :) > I'm pleased to see that you have answers. In return would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing above, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From marko at pacujo.net Sun Feb 9 11:14:44 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 09 Feb 2014 18:14:44 +0200 Subject: system wide mutex References: Message-ID: <87ob2ggt57.fsf@elektro.pacujo.net> Asaf Las : > Which one is most recommended to use for mutex alike locking to > achieve atomic access to single resource: > > - fcntl.lockf I recommend fcntl.flock: ======================================================================== #!/usr/bin/python3 import sys, fcntl, time with open("test.lock", "w+") as lock: fcntl.flock(lock.fileno(), fcntl.LOCK_EX) # begin critical sys.stdout.write("hello\n") time.sleep(3) sys.stdout.write("world\n") # end critical ======================================================================== Marko From roy at panix.com Sun Feb 9 11:52:15 2014 From: roy at panix.com (Roy Smith) Date: Sun, 09 Feb 2014 11:52:15 -0500 Subject: imperative mood in docstrings References: Message-ID: In article , bagrat lazaryan wrote: > pep 257 -- docstring conventions, as well as a myriad of books and other > resources, recommend documenting a function's or method's effect as a command > ("do this", "return that"), not as a description ("does this", "returns > that"). what's the logic behind this recommendation? > > bagratte Methods are verbs, and should be described as such. If I had: class Sheep: def fly(self): "Plummet to the ground." I'm defining the action the verb performs. If, on the other hand, I had: class Sheep: def fly(self): "Plummets to the ground" I'm no longer describing the action of flying, I'm describing what the sheep does when it attempts to perform that action. From breamoreboy at yahoo.co.uk Sun Feb 9 12:15:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 09 Feb 2014 17:15:46 +0000 Subject: imperative mood in docstrings In-Reply-To: References: Message-ID: On 09/02/2014 12:05, bagrat lazaryan wrote: > pep 257 -- docstring conventions, as well as a myriad of books and other resources, recommend documenting a function's or method's effect as a command ("do this", "return that"), not as a description ("does this", "returns that"). what's the logic behind this recommendation? > > bagratte > I can't really answer your question as I don't understand why docstrings should get moody, or did you mean mode? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From jpiitula at ling.helsinki.fi Sun Feb 9 12:21:47 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 09 Feb 2014 19:21:47 +0200 Subject: imperative mood in docstrings References: Message-ID: Mark Lawrence writes: > On 09/02/2014 12:05, bagrat lazaryan wrote: > > > pep 257 -- docstring conventions, as well as a myriad of books and > > other resources, recommend documenting a function's or method's > > effect as a command ("do this", "return that"), not as a > > description ("does this", "returns that"). what's the logic behind > > this recommendation? > > I can't really answer your question as I don't understand why > docstrings should get moody, or did you mean mode? :) From roegltd at gmail.com Sun Feb 9 12:39:15 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 09:39:15 -0800 (PST) Subject: system wide mutex In-Reply-To: <87ob2ggt57.fsf@elektro.pacujo.net> References: <87ob2ggt57.fsf@elektro.pacujo.net> Message-ID: Hi Thanks for replies. It would be good to have blocking implementation. I have to check fcntl if it works in blocking mdoe on CentOS. Meanwhile there is Posix Semaphore made for Python: http://semanchuk.com/philip/posix_ipc/ will try it as well. /Asaf From kwpolska at gmail.com Sun Feb 9 12:46:33 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 9 Feb 2014 18:46:33 +0100 Subject: imperative mood in docstrings In-Reply-To: References: Message-ID: On Sun, Feb 9, 2014 at 5:52 PM, Roy Smith wrote: > In article , > bagrat lazaryan wrote: > >> pep 257 -- docstring conventions, as well as a myriad of books and other >> resources, recommend documenting a function's or method's effect as a command >> ("do this", "return that"), not as a description ("does this", "returns >> that"). what's the logic behind this recommendation? >> >> bagratte > > Methods are verbs, and should be described as such. If I had: > > class Sheep: > def fly(self): > "Plummet to the ground." > > I'm defining the action the verb performs. If, on the other hand, I had: > > class Sheep: > def fly(self): > "Plummets to the ground" > > I'm no longer describing the action of flying, I'm describing what the > sheep does when it attempts to perform that action. This can also be seen with a (monolingual) dictionary. For example: https://www.google.com/search?q=define+fly (that?s actually from the New Oxford American Dictionary): fly, verb: 1. move through the air under control. 2. move or be hurled quickly through the air. Those could be valid docstrings (if sheep could fly, of course?) ? so, in other words, act as if you were writing a dictionary and not Python code. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From ethan at stoneleaf.us Sun Feb 9 12:53:27 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 09 Feb 2014 09:53:27 -0800 Subject: imperative mood in docstrings In-Reply-To: References: Message-ID: <52F7C097.7050407@stoneleaf.us> On 02/09/2014 08:52 AM, Roy Smith wrote: > In article , > bagrat lazaryan wrote: > >> pep 257 -- docstring conventions, as well as a myriad of books and other >> resources, recommend documenting a function's or method's effect as a command >> ("do this", "return that"), not as a description ("does this", "returns >> that"). what's the logic behind this recommendation? >> >> bagratte > > Methods are verbs, and should be described as such. If I had: > > class Sheep: > def fly(self): > "Plummet to the ground." > > I'm defining the action the verb performs. If, on the other hand, I had: Shouldn't that be: class Pig: def fly(self): "Soar gracefully through the air if a hot place is very cold." if hell is frozen: self.sprout_wings() self.altitude += 10 self.velocity += 25 else: self.splat() ;) -- ~Ethan~ From tjreedy at udel.edu Sun Feb 9 15:46:05 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 09 Feb 2014 15:46:05 -0500 Subject: imperative mood in docstrings In-Reply-To: References: Message-ID: On 2/9/2014 7:05 AM, bagrat lazaryan wrote: > pep 257 -- docstring conventions, as well as a myriad of books and other resources, recommend documenting a function's or method's effect as a command ("do this", "return that"), not as a description ("does this", "returns that"). what's the logic behind this recommendation? The imperative is directed at the Python interpreter. It says what a call instructs the interpreter to do. -- Terry Jan Reedy From nicholas.cole at gmail.com Sun Feb 9 16:05:58 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sun, 9 Feb 2014 21:05:58 +0000 Subject: Python (?) webserver for WSGI Message-ID: Dear List, What is the latest "best-practice" for deploying a python wsgi application into production? For development, I've been using CherryPyWSGIServer which has been working very well (and the code is small enough to actually ship with my application). But I would like some way of deploying a server listening on port 80 (and then dropping root privileges). I have looked at using gunicorn + ngnix, but that gives me 3 layers that I need to set up: - my own application - gunicorn - ngnix Compared to using something like CherryPyWSGIServer (where a single line of code starts my application!) that seems like overkill and rather complicated for a small application. I'm not expecting 1000s of users (or even dozens!), but this is an application that will be accessible to "the internet" and so server security is a concern (which is why I don't want to use anything that labels itself as a "development" webserver). As far as I can tell, this is something of a fast-moving target. What advice do people have? I'm using python 3, in case it makes a difference. Best wishes, N. From jsf80238 at gmail.com Sun Feb 9 16:25:13 2014 From: jsf80238 at gmail.com (Jason Friedman) Date: Sun, 9 Feb 2014 14:25:13 -0700 Subject: Google API and Python 2 Message-ID: I started Python programming in the last few years and so I started with version 3 and 99% of my code is in version 3. Much of Google API Python code seems to be Python 2. I can convert the occasional file to version 3 with 2to3, but for an entire 3rd-party library, could it be as simple as using the find command (recursive) and iterating over the *py files in the download? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Feb 9 16:31:31 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Feb 2014 21:31:31 GMT Subject: Sort one sequence by O(n) in time and O(1) in space References: Message-ID: <52f7f3b3$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sun, 09 Feb 2014 04:13:50 -0800, Wesley wrote: > Hi guys, > Here is one question related to algorithm. > Details here: > > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx > always exist in pair. So, now, how to change the sequence to > a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). Time complexity O(n) implies that you can iterate over the list at most a constant number of times. Space complexity O(1) implies that you can only use a small, constant amount of extra space, which means that you have to modify the input sequence in place. This is a kind of shuffle. Imagine you pull out all the spades ? and hearts ? from a deck of cards, and sort them individually: cards = ['A?', '2?', '3?', '4?', ... 'K?', 'A?', '2?', '3?', '4?', ... 'K?'] You want to move the cards so that you end up with the spades and hearts interleaved: cards = ['A?', 'A?', '2?', '2?', '3?', '3?', '4?', '4?', ... 'K?', 'K?'] This is called a "riffle shuffle" or "Faro shuffle", and there are two kinds, an in-shuffle and an out-shuffle, which differ in which card ends up on top. The obvious way to do it is to split the deck down the middle into two sets of cards, then riffle them together, one card from the left hand following by one card from the right (or visa versa): left = cards[:len(cards)//2] right = cards[len(cards)//2:] cards = [] for l, r in zip(left, right): cards.append(l) cards.append(r) but this doesn't use constant space, since it uses extra space proportional to N. Since this sounds like homework, I'm not going to tell you how to do this using only constant space, but it may help if you actually sit down with a set of cards, lay them out in order, and see how you might do it by hand. -- Steven From roegltd at gmail.com Sun Feb 9 16:33:16 2014 From: roegltd at gmail.com (Asaf Las) Date: Sun, 9 Feb 2014 13:33:16 -0800 (PST) Subject: Python (?) webserver for WSGI In-Reply-To: References: Message-ID: <35c48ba6-6d1a-4e3b-a9a5-0b47f6c9ae83@googlegroups.com> On Sunday, February 9, 2014 11:05:58 PM UTC+2, Nicholas wrote: > Dear List, > > > > What is the latest "best-practice" for deploying a python wsgi > application into production? > > For development, I've been using CherryPyWSGIServer which has been > working very well (and the code is small enough to actually ship with > my application). But I would like some way of deploying a server > listening on port 80 (and then dropping root privileges). > > I have looked at using gunicorn + ngnix, but that gives me 3 layers > that I need to set up: > > - my own application > - gunicorn > - ngnix Yes, but are you after simplicity of setup or reliability? If security is your concern - eventually you have to dive into routines of verifying settings auditing etc and spend week(s) if you have no solid prior experience in that field and even after that there is still a lot to learn. the interesting side of nginx is load balancing toward back end so you can distribute your back ends over multiple machines and have scalability for least effort, though seems you don't need due to low expected load. there is another popular choice nginx + uwsgi From rosuav at gmail.com Sun Feb 9 17:03:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 09:03:46 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: <5e6ff9tu3ih5c080so22ubsgbh4674ifto@4ax.com> References: <5e6ff9tu3ih5c080so22ubsgbh4674ifto@4ax.com> Message-ID: On Mon, Feb 10, 2014 at 2:40 AM, Dennis Lee Bieber wrote: > Any opinion on Firebird? Just curiosity given how often the advice > seems to be "start with SQLite, avoid MySQL, end with PostgreSQL" No, because I've never used it. Has anyone here? What are its strengths and weaknesses? ChrisA From rosuav at gmail.com Sun Feb 9 17:09:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 09:09:18 +1100 Subject: system wide mutex In-Reply-To: References: Message-ID: On Mon, Feb 10, 2014 at 1:45 AM, Roy Smith wrote: > In article , > Skip Montanaro wrote: > >> As the author of lockfile, I can tell you it only implements advisory >> locking. All programs needing to access the locked resources must >> cooperate. > > This is true of all mutexes, no? > Not quite all; mandatory locks actually prevent other access. But they require support from whatever makes the resource available - most commonly, the file system - where cooperative locking doesn't. I've written a number of cooperative locking systems in the past (eg to protect a network resource, when the mounted file system didn't offer the sort of locking I needed), and they're usually the way to go when there's anything complicated going on. What, all mutexes? Yes, all mutexes! What, all? Well.... nearly all! -- with apologies to WS Gilbert, HMS Pinafore, and the Pirates of Penzance ChrisA From rosuav at gmail.com Sun Feb 9 17:12:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 09:12:45 +1100 Subject: imperative mood in docstrings In-Reply-To: <52F7C097.7050407@stoneleaf.us> References: <52F7C097.7050407@stoneleaf.us> Message-ID: On Mon, Feb 10, 2014 at 4:53 AM, Ethan Furman wrote: > Shouldn't that be: > > class Pig: > def fly(self): > "Soar gracefully through the air if a hot place is very cold." > if hell is frozen: > self.sprout_wings() > self.altitude += 10 > self.velocity += 25 > else: > self.splat() > > ;) The Python 'is' operator does not do what you think it does. If it did, 'hell is frozen' would mean that one could say 'war is frozen', which makes no sense. No, I think this calls for a LISP-style predicate: if frozenp(hell): ChrisA From nicholas.cole at gmail.com Sun Feb 9 17:29:33 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sun, 9 Feb 2014 22:29:33 +0000 Subject: Python (?) webserver for WSGI In-Reply-To: <35c48ba6-6d1a-4e3b-a9a5-0b47f6c9ae83@googlegroups.com> References: <35c48ba6-6d1a-4e3b-a9a5-0b47f6c9ae83@googlegroups.com> Message-ID: On Sunday, 9 February 2014, Asaf Las > wrote: > On Sunday, February 9, 2014 11:05:58 PM UTC+2, Nicholas wrote: > > Dear List, > > > > > > > > What is the latest "best-practice" for deploying a python wsgi > > application into production? > > > > For development, I've been using CherryPyWSGIServer which has been > > working very well (and the code is small enough to actually ship with > > my application). But I would like some way of deploying a server > > listening on port 80 (and then dropping root privileges). > > > > I have looked at using gunicorn + ngnix, but that gives me 3 layers > > that I need to set up: > > > > - my own application > > - gunicorn > > - ngnix > > Yes, but are you after simplicity of setup or reliability? > If security is your concern - eventually you have to dive into > routines of verifying settings auditing etc and spend > week(s) if you have no solid prior experience in that field and even > after that there is still a lot to learn. > [snip] Yes, I managed a large apache installation for some years. I suppose that my hope was that in 2014 there might be some better, simpler way to run smaller web applications, especially with the tulip async stuff becoming part of the language. I don't think running a WSGI application to serve basic requests should NEED a lot of special setting up -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Feb 9 18:01:37 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Feb 2014 23:01:37 GMT Subject: imperative mood in docstrings References: Message-ID: <52f808d1$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sun, 09 Feb 2014 16:05:59 +0400, bagrat lazaryan wrote: > pep 257 -- docstring conventions, as well as a myriad of books and other > resources, recommend documenting a function's or method's effect as a > command ("do this", "return that"), not as a description ("does this", > "returns that"). what's the logic behind this recommendation? Consider a class with a procedural method, that is, a method that does something: class Duck: def swim(self): """Flap feet in a rhythmic manner so as to gracefully move through water. """ Here, we naturally write as if giving instructions to the duck, that is, using the imperative mood. "Duck, swim." >From there, it isn't a big step to using the same mood for functions: def count(haystack, needle): """Return the number of needles in haystack.""" Here we are figuratively instructing the function, telling it what to do: "Function, return the number of needles found in this haystack." -- Steven From steve+comp.lang.python at pearwood.info Sun Feb 9 18:14:18 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 09 Feb 2014 23:14:18 GMT Subject: Sort one sequence by O(n) in time and O(1) in space References: Message-ID: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sun, 09 Feb 2014 10:05:02 -0500, Roy Smith wrote: > Is this a homework problem? and then (paraphrasing): > working code that solves the problem /headdesk -- Steven From eliasbylarsen at gmail.com Sun Feb 9 18:48:57 2014 From: eliasbylarsen at gmail.com (eliasbylarsen at gmail.com) Date: Sun, 9 Feb 2014 15:48:57 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project Message-ID: I am fully ready to invest in the Google Cloud Platform, and bring with me my very own idea: Glass Solver (Sometimes called GlaSolver). Long story short, this application for Google Glass will connect to the Cloud to retrieve God's Algorithm for the cube sitting in front of you by doing a series of scans of the cube. But, that (specifically) is not what I came here for. In order to have all these algorithms, I have to make them first. One important detail that is probably worth mentioning is the fact that this application will support no only 3x3s. It will also support 2x2s,4x4s,and 5x5s. The last 2 mentioned have not been done before. God's Number has never been found for the 4x4 or 5x5 cube. But thanks to Google and their Compute Platform, it is possible. I myself am relatively new to Python. My experience is in Java primarily. Again, long story even shorter, I am asking for a Python (2.7 please!) script for each cube. Thanks for reading this and possibly for your script! From roy at panix.com Sun Feb 9 19:15:38 2014 From: roy at panix.com (Roy Smith) Date: Sun, 09 Feb 2014 19:15:38 -0500 Subject: Sort one sequence by O(n) in time and O(1) in space References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <52f80bca$0$29972$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Sun, 09 Feb 2014 10:05:02 -0500, Roy Smith wrote: > > > Is this a homework problem? > > and then (paraphrasing): > > > working code that solves the problem > > /headdesk I gave him the benefit of the doubt. Also, as I look at my solution, I realize it doesn't really meet the O(1) space requirement. Understanding why is left as an exercise for the reader :-) From rymg19 at gmail.com Sun Feb 9 17:42:30 2014 From: rymg19 at gmail.com (Ryan Gonzalez) Date: Sun, 9 Feb 2014 16:42:30 -0600 Subject: [ANN] PyExt 0.6 Released! Message-ID: PyExt is a set of nifty(and sometimes either overly hackish, overly dangerous, or overly both) extensions to Python. It has things like a switch statement, runtime module creation, function overloading(does NOT work with class methods...yet), and more! Links: PyPI: https://pypi.python.org/pypi/pyext GitHub: https://github.com/kirbyfan64/pyext -- Ryan If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated." -------------- next part -------------- An HTML attachment was scrubbed... URL: From nispray at gmail.com Sun Feb 9 21:07:41 2014 From: nispray at gmail.com (Wesley) Date: Sun, 9 Feb 2014 18:07:41 -0800 (PST) Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: ? 2014?2?9????UTC+8??11?48?17??Oscar Benjamin??? > Please don't top-post. > > On Feb 9, 2014 2:40 PM, "Ni Wesley" wrote: > > > > > > Yes, with no new list, otherwise, space won't to be O(1) > > Did you read the link I posted: > > >> http://en.wikipedia.org/wiki/In-place_matrix_transposition > > > Oscar Sorry getting a network problem these two days. I am reading :-) From nispray at gmail.com Sun Feb 9 21:09:47 2014 From: nispray at gmail.com (Wesley) Date: Sun, 9 Feb 2014 18:09:47 -0800 (PST) Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: Message-ID: <76182aa9-75bc-446d-87ea-9545fe7e2a8f@googlegroups.com> > > here is input sequence like a1,a2,...,an,b1,b2,...,bn ?the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). > > > > The two halves of the list are already sorted, yes? [Wesley] No, not sorted yet.. From eliasbylarsen at gmail.com Sun Feb 9 21:16:16 2014 From: eliasbylarsen at gmail.com (eliasbylarsen at gmail.com) Date: Sun, 9 Feb 2014 18:16:16 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: Message-ID: <81d9cfbd-4087-4b4d-9fec-94d68349d941@googlegroups.com> Also I should mention that I will credit whomever writes the scripts. I have contacted Google on their Compute Engine which would execute these scripts. I am await a reply! From nispray at gmail.com Sun Feb 9 21:26:56 2014 From: nispray at gmail.com (Wesley) Date: Sun, 9 Feb 2014 18:26:56 -0800 (PST) Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> [Wesley] This is not homework:-) And actually I am new to algorithm, so you guys can feel free to say anything you want From davea at davea.name Sun Feb 9 21:57:42 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 21:57:42 -0500 (EST) Subject: Google Cloud Platform and GlassSolver Project References: <81d9cfbd-4087-4b4d-9fec-94d68349d941@googlegroups.com> Message-ID: eliasbylarsen at gmail.com Wrote in message: > Also I should mention that I will credit whomever writes the scripts. I have contacted Google on their Compute Engine which would execute these scripts. I am await a reply! > It might help if you mention that you're talking about the Rubic cube, and supply an example of what you want in such a script. -- DaveA From davea at davea.name Sun Feb 9 22:00:56 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 22:00:56 -0500 (EST) Subject: Sort one sequence by O(n) in time and O(1) in space References: <76182aa9-75bc-446d-87ea-9545fe7e2a8f@googlegroups.com> Message-ID: Wesley Wrote in message: > >> > here is input sequence like a1,a2,...,an,b1,b2,...,bn ???the ax and bx always exist in pair. So, now, how to change the sequence to a1,b1,...,an,bn, with time complexity as O(n) and space as O(1). >> >> >> >> The two halves of the list are already sorted, yes? > > [Wesley] No, not sorted yet.. > -- > https://mail.python.org/mailman/listinfo/python-list > Then supply some example lists and show the result you want. So far, your description is thoroughly ambiguous. -- DaveA From swdunning at cox.net Sun Feb 9 23:17:52 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 9 Feb 2014 21:17:52 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: <972E1362-8C9D-47BC-BAD7-A0CA754C8D84@cox.net> On Feb 8, 2014, at 11:30 PM, Chris Angelico wrote: I have one more question on this if you don?t mind. I?m a bit confused on how it works this way without it being in seconds? I?ll answer below each step of how it seems to work to me. > How to do it from the small end up: > > time = int(raw_input("Enter number of seconds: ")) > seconds = time % 60 So here it takes say 1000000 and divides it by 60 to put in seconds and spits out the remainder? 1000000 / 60 is approximately 16666 with a remainder of about 40, which would be the correct amount for seconds. From there I get a little lost. > time /= 60 Then we take the remainder (40) from above and divide that by 60? Already it?s confusing me. > minutes = time % 60 Are we still using the new number from above for time and dividing that by 60 and using the remainder for minutes? > time /= 60 Then taking the remainder from the line above and so on and so on?? > hours = time % 24 > time /= 24 > days = time % 7 > time /= 7 > weeks = time > # Alternative way to format for display: > print("%d weeks, %d days, %02d:%02d:%02d"%(weeks,days,hours,minutes,seconds)) > Also, would it work the same way with smaller divisors the other way around (from weeks - seconds)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sun Feb 9 23:30:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 15:30:55 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <972E1362-8C9D-47BC-BAD7-A0CA754C8D84@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> <972E1362-8C9D-47BC-BAD7-A0CA754C8D84@cox.net> Message-ID: On Mon, Feb 10, 2014 at 3:17 PM, Scott W Dunning wrote: > How to do it from the small end up: > > time = int(raw_input("Enter number of seconds: ")) > seconds = time % 60 > > So here it takes say 1000000 and divides it by 60 to put in seconds and > spits out the remainder? 1000000 / 60 is approximately 16666 with a > remainder of about 40, which would be the correct amount for seconds. From > there I get a little lost. > > time /= 60 > > Then we take the remainder (40) from above and divide that by 60? Already > it?s confusing me. The first part just spits out the remainder, without changing the base. It'll set seconds to 40 (exactly, not about), but time is still 1000000. Then in the next line, we divide time by 60, which sets it to that quotient (16666). This is why it's probably clearer to use divmod, which does both halves (quotient and remainder) at once. ChrisA From swdunning at cox.net Sun Feb 9 23:31:03 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 9 Feb 2014 21:31:03 -0700 Subject: Python 2.7.6 help with modules In-Reply-To: References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> Message-ID: <4D2A950B-E797-4005-B0AB-0E3EA0B3389E@cox.net> On Feb 8, 2014, at 11:30 PM, Chris Angelico wrote: OH, I think I figured it out. > time = int(raw_input("Enter number of seconds: ?)) 1000000 > seconds = time % 60 Remainder of 40 <- for seconds. > time /= 60 Here you take 1000000/60 = 16666 (which = time for the next line). > minutes = time % 60 16666/60 with a remainder of 46 <- minutes > time /= 60 Then take 16666/60 = 277 (which = time for the line below to use). > hours = time % 24 Then we use 277/24 with a remainder of 13 <- hours > time /= 24 Then it use 277/24??.. > days = time % 7 > time /= 7 > weeks = time I guess I answered my own question and it looks like it wouldn?t matter if you did it opposite from weeks to seconds. Thanks again for all your help everyone! Scott From rosuav at gmail.com Sun Feb 9 23:36:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 15:36:22 +1100 Subject: Python 2.7.6 help with modules In-Reply-To: <4D2A950B-E797-4005-B0AB-0E3EA0B3389E@cox.net> References: <032F2E23-6983-4710-B087-C1771B66C3EF@cox.net> <635C857D-1F7A-4F95-B3A7-F1A3C69BF137@cox.net> <1DA52F3B-CE00-4E47-BE84-C07482966FD7@cox.net> <4D2A950B-E797-4005-B0AB-0E3EA0B3389E@cox.net> Message-ID: On Mon, Feb 10, 2014 at 3:31 PM, Scott W Dunning wrote: > I guess I answered my own question and it looks like it wouldn?t matter if you did it opposite from weeks to seconds. Yep, you've got it! Remember, you can always try things out in the interactive interpreter to see what's happening. Helps *hugely*. ChrisA From duncan.booth at invalid.invalid Mon Feb 10 04:12:40 2014 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Feb 2014 09:12:40 GMT Subject: Google Cloud Platform and GlassSolver Project References: Message-ID: eliasbylarsen at gmail.com wrote: > I am fully ready to invest in the Google Cloud Platform, and bring > with me my very own idea: Glass Solver (Sometimes called GlaSolver). One thing you will have to do is find another name for your project. https://developers.google.com/glass/design/branding-guidelines says: > Glass is never part of the name of your business, Glassware, other > products. Instead, use "for Glass." If you use "for Glass" in > conjunction with a logo, "for Glass" must be a smaller size than the > rest of the logo. > > Correct: "Cat Facts for Glass" > > Incorrect: "Glass Cat Facts", "Glassy Cat Photos" -- Duncan Booth http://kupuguy.blogspot.com From as at sci.fi Mon Feb 10 05:10:09 2014 From: as at sci.fi (Anssi Saari) Date: Mon, 10 Feb 2014 12:10:09 +0200 Subject: What are the kinds of software that are not advisable to be developed using Python? References: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> <4fb34e9b-d2f0-432b-852e-55177a38167c@googlegroups.com> Message-ID: Asaf Las writes: > btw, Python could be language of choice for embedded systems if small footprint > vm could be developed. had seen similar for java having 10-20 KB byte sized > interpreter with very limited set of functions. Well, there's the newish Micro python project. Its footprint is apparently about 60 kB at a minimum (Thumb2 code on ARM). Their kickstarter is at https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers and source at https://github.com/micropython/micropython The kickstarter was for funding development and a small board with ST's Cortex-M4 on it. The source code includes Windows and Unix targets so it's easy to experiment with without a board too. From sturla.molden at gmail.com Mon Feb 10 05:20:33 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Mon, 10 Feb 2014 10:20:33 +0000 (UTC) Subject: Sort one sequence by O(n) in time and O(1) in space References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> Message-ID: <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> Wesley wrote: > [Wesley] This is not homework:-) > And actually I am new to algorithm, so you guys can feel free to say anything you want In general, we cannot sort a sequence in O(n) time. O(n log n) is the lower bound on the complexity. From jeanmichel at sequans.com Mon Feb 10 05:06:31 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 Feb 2014 11:06:31 +0100 (CET) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: Message-ID: <208618256.3515651.1392026791840.JavaMail.root@sequans.com> Thank you all for you insights. I'll probably go with virtualenv, I'll be able to distribute it among the team. There's still one point worrying me though: We're doing a lot a remote execution. We're using "execnet" http://codespeak.net/execnet/, and I'm not sure it can be compatible with virtualenv. execnet working at the "python level" I don't see how I can execute shell stuff before. I had a look at fabric http://docs.fabfile.org/en/1.8/, and it looks like it can handle virtual env (anyone confirm?). Has someone already successfully remotely activated a venv then execute a python scripts within that env, getting back the stdout/stderr ? I'm afraid right now that switching to venv would mean switching from execnet to fabric as well (I hate redoing stuff that works :-/ ). JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From rosuav at gmail.com Mon Feb 10 05:37:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 10 Feb 2014 21:37:59 +1100 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> Message-ID: On Mon, Feb 10, 2014 at 9:20 PM, Sturla Molden wrote: > Wesley wrote: >> [Wesley] This is not homework:-) >> And actually I am new to algorithm, so you guys can feel free to say anything you want > > In general, we cannot sort a sequence in O(n) time. O(n log n) is the lower > bound on the complexity. That's assuming it really is a sort operation. The problem description isn't entirely clear on this point, but if it's actually a zip, then it can definitely be done in O(n). ChrisA From duncan.booth at invalid.invalid Mon Feb 10 05:50:52 2014 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Feb 2014 10:50:52 GMT Subject: Vedr: What does """ means in python? References: <72a7dd52-7619-4520-991e-20db7ce55ba3@googlegroups.com> Message-ID: Gisle Vanem wrote: > Regrading handy uses of ''', you learned me one trick when using Python? > code in a Windows .bat file: > > rem = ''' > @echo off > echo This is batch > \python32\python %0 > echo All done > exit /b > rem ''' > import sys > print("This is Python") > for i,p in enumerate(sys.path): > print('sys.path[%2d]: %s' % (i, p)) > print("Python done") > You'll have a variable in Python called 'rem' which contains all > your > batch code :) It exploits the fact that 'rem' makes a > one-line > comment, but the triple quotes go across multiple lines. > A better trick would be to use a Powershell script instead of a batch file: ------------------------------------------- filter python() { $_ | c:\Python33\python.exe ($args -replace'(\\*)"','$1$1\"') } Write-Host "This is the powershell script" dir cert: | convertto-json | python -c @" import json, sys stores = json.loads(sys.stdin.read()) print("This is Python") for store in stores: print("{}: {}".format(store['PSChildName'], ', '.join(store['StoreNames']))) print("Python done") "@ Write-Host "All done" ------------------------------------------- C:\scripts> . .\Pythoncerts.ps1 This is the powershell script This is Python CurrentUser: Root, UserDS, Disallowed, Trust, My, TrustedPublisher, SmartCardRoot, TrustedPeople, ADDRESSBOOK, AuthRoot, McAfee Trust, CA, REQUEST, ACRS LocalMachine: Disallowed, Trust, CA, TrustedPublisher, SmartCardRoot, My, TrustedPeople, AuthRoot, TrustedDevices, Root Python done All done C:\scripts> Notes on the above: Powershell messes up arguments when running legacy programs. The filter ensures that all arguments pass through Windows command line processing unscathed (except they can't contain null characters). You don't actually have to use the filter if you are careful about how you write quotes in the code, but it makes life simpler. Python scripts up to just over 32,000 characters can be written on the command line this way. You can also assign the script to a variable and keep the Python command a bit cleaner: $script = @" print("Python here!") "@ python -c $script Or without the filter it is best to avoid the double quotes: $script = @" print('Python here!') "@ c:\python33\python.exe -c $script To run from a traditional cmd.exe prompt you have to explicitly use Powershell. The default file associations for .ps1 files will run notepad instead. If your system execution policy is Restricted (the default) use: powershell -executionpolicy RemoteSigned .\Pythoncerts.ps1 Otherwise set the execution policy to something more lenient (at a Powershell prompt running as administrator enter "Set-ExecutionPolicy RemoteSigned") and you can just do: powershell .\Pythoncerts.ps1 I also use Powershell interactively so I have the filters defined in my startup ($Home\Documents\WindowsPowerShell\profile.ps1): filter py() { $_ | py.exe ($args -replace'(\\*)"','$1$1\"') } filter python() { $_ | c:\Python33\python.exe ($args -replace'(\\*)"','$1$1\"') } -- Duncan Booth From eliasbylarsen at gmail.com Mon Feb 10 06:09:25 2014 From: eliasbylarsen at gmail.com (EliasL) Date: Mon, 10 Feb 2014 03:09:25 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: Message-ID: On Monday, February 10, 2014 4:12:40 AM UTC-5, Duncan Booth wrote: > EliasL wrote: > > > > > I am fully ready to invest in the Google Cloud Platform, and bring > > > with me my very own idea: Glass Solver (Sometimes called GlaSolver). > > > > One thing you will have to do is find another name for your project. > > https://developers.google.com/glass/design/branding-guidelines says: > > > > > Glass is never part of the name of your business, Glassware, other > > > products. Instead, use "for Glass." If you use "for Glass" in > > > conjunction with a logo, "for Glass" must be a smaller size than the > > > rest of the logo. > > > > > > Correct: "Cat Facts for Glass" > > > > > > Incorrect: "Glass Cat Facts", "Glassy Cat Photos" > > > > > > > > -- > > Duncan Booth http://kupuguy.blogspot.com Thanks! This name is rather temporary to begin with. I won't necessarily keep that name in the future. As for now, that is my first name and for now I will be keeping it (until it is released) From eliasbylarsen at gmail.com Mon Feb 10 06:12:07 2014 From: eliasbylarsen at gmail.com (EliasL) Date: Mon, 10 Feb 2014 03:12:07 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: <81d9cfbd-4087-4b4d-9fec-94d68349d941@googlegroups.com> Message-ID: <6bf7c738-0742-40b3-8e3e-0766253bd034@googlegroups.com> On Sunday, February 9, 2014 9:57:42 PM UTC-5, Dave Angel wrote: > EliasL Wrote in message: > > > Also I should mention that I will credit whomever writes the scripts. I have contacted Google on their Compute Engine which would execute these scripts. I am await a reply! > > > > > > > It might help if you mention that you're talking about the Rubic > > cube, and supply an example of what you want in such a script. > > > > > > -- > > DaveA I came here because I don't know what the script needs to be. I will edit my post anyway to add some details. I didn't once say Rubik's Cube? :O From eliasbylarsen at gmail.com Mon Feb 10 06:17:07 2014 From: eliasbylarsen at gmail.com (EliasL) Date: Mon, 10 Feb 2014 03:17:07 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: Message-ID: <73a421ff-7635-48be-9a7b-c6cec836a8cb@googlegroups.com> Boy am I glad that this is still alive! What do I mean? Click: http://www.speedsolving.com/forum/showthread.php?46268-Introducing-GlassSolver-back-and-better-than-ever!&p=951473 From thomas.lehmann at adtech.com Mon Feb 10 06:39:06 2014 From: thomas.lehmann at adtech.com (thomas.lehmann at adtech.com) Date: Mon, 10 Feb 2014 03:39:06 -0800 (PST) Subject: Pylint across Python versions Message-ID: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> Hi, somebody who can tell me about pylint experiences across different Python version. Example: I'm using a construct like this: if sys.version.startswith("3."): unicode = str The reason is that Python 3 does not have this function anymore but pylint yells for Python < 3 about redefinition also it does not happen. How to get forward with this? Regards, Thomas From breamoreboy at yahoo.co.uk Mon Feb 10 07:53:45 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Feb 2014 12:53:45 +0000 Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: Message-ID: On 10/02/2014 11:09, EliasL wrote: [all double line spaced stuff snipped] Would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing that you are sending, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Mon Feb 10 08:03:36 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Feb 2014 13:03:36 +0000 Subject: Pylint across Python versions In-Reply-To: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> References: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> Message-ID: On 10/02/2014 11:39, thomas.lehmann at adtech.com wrote: > Hi, > > somebody who can tell me about pylint experiences across > different Python version. > > Example: > I'm using a construct like this: > > if sys.version.startswith("3."): > unicode = str > > The reason is that Python 3 does not have this > function anymore but pylint yells for Python < 3 > about redefinition also it does not happen. I've no idea what the above is saying but see below anyway. > > How to get forward with this? > > Regards, > Thomas > >>> import sys >>> sys.version '3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 16:23:43) [MSC v.1600 32 bit (Intel)]' >>> sys.version.startswith('3.') True >>> -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rosuav at gmail.com Mon Feb 10 08:59:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 00:59:36 +1100 Subject: Pylint across Python versions In-Reply-To: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> References: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> Message-ID: On Mon, Feb 10, 2014 at 10:39 PM, wrote: > Example: > I'm using a construct like this: > > if sys.version.startswith("3."): > unicode = str > > The reason is that Python 3 does not have this > function anymore but pylint yells for Python < 3 > about redefinition also it does not happen. > > How to get forward with this? It's more common to spell that with a try/except. Does pylint complain if you use this instead? try: unicode except NameError: unicode = str Although it would be better to write your code for Python 3, and have compatibility code at the top for Python 2. That would mean using 'str' everywhere, and then having this at the top: try: str = unicode except NameError: pass That way, when you're ready to drop support for Python 2, you simply delete the compat code and everything works. Otherwise, you have to maintain messy code indefinitely. Alternatively, to avoid redefinition at all, you could use your own name everywhere: try: unicode_string = unicode except NameError: unicode_string = str Use something less unwieldy if you prefer, but this avoids any chance of collision :) ChrisA From wxjmfauth at gmail.com Mon Feb 10 09:07:14 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 10 Feb 2014 06:07:14 -0800 (PST) Subject: Finding size of Variable In-Reply-To: <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: Le samedi 8 f?vrier 2014 03:48:12 UTC+1, Steven D'Aprano a ?crit : > > > We consider it A GOOD THING that Python spends memory for programmer > > convenience and safety. Python looks for memory optimizations when it can > > save large amounts of memory, not utterly trivial amounts. So in a Python > > wide build, a ten-thousand block character string requires a little bit > > more than 40KB. In Python 3.3, that can be reduced to only 10KB for a > > purely Latin-1 string, or 20K for a string without any astral characters. > > That's the sort of memory savings that are worthwhile, reducing memory > > usage by 75%. > > > In its attempt to save memory, Python only succeeds to do worse than any utf* coding schemes. --- Python does not save memory at all. A str (unicode string) uses less memory only - and only - because and when one uses explicitly characters which are consuming less memory. Not only the memory gain is zero, Python falls back to the worse case. >>> sys.getsizeof('a' * 1000000) 1000025 >>> sys.getsizeof('a' * 1000000 + 'oe') 2000040 >>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') 4000048 The opposite of what the utf8/utf16 do! >>> sys.getsizeof(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-8')) 1000023 >>> sys.getsizeof(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-16')) 2000025 jmf From petef4+usenet at gmail.com Mon Feb 10 09:23:40 2014 From: petef4+usenet at gmail.com (Pete Forman) Date: Mon, 10 Feb 2014 14:23:40 +0000 Subject: Using virtualenv to bypass sudoer issues References: Message-ID: <86iosnujv7.fsf@gmail.com> Jean-Michel Pichavant writes: > Thank you all for you insights. > > I'll probably go with virtualenv, I'll be able to distribute it among > the team. > There's still one point worrying me though: > We're doing a lot a remote execution. We're using "execnet" > http://codespeak.net/execnet/, and I'm not sure it can be compatible > with virtualenv. execnet working at the "python level" I don't see how > I can execute shell stuff before. > > I had a look at fabric http://docs.fabfile.org/en/1.8/, and it looks > like it can handle virtual env (anyone confirm?). > > Has someone already successfully remotely activated a venv then > execute a python scripts within that env, getting back the > stdout/stderr ? > > I'm afraid right now that switching to venv would mean switching from > execnet to fabric as well (I hate redoing stuff that works :-/ ). Call the venv version of python and activation is handled. E.g. in a fabfile myenv/bin/python myscript.py -- Pete Forman From roegltd at gmail.com Mon Feb 10 09:25:16 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 06:25:16 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <56be2de0-ab95-4dc6-a7c2-571ae8bc0e26@googlegroups.com> On Monday, February 10, 2014 4:07:14 PM UTC+2, wxjm... at gmail.com wrote: Interesting > >>> sys.getsizeof('a' * 1000000) here you get string type > >>> sys.getsizeof(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-8')) and here bytes >>> type ('a' * 10000) >>> type(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-8')) >>> Why? From breamoreboy at yahoo.co.uk Mon Feb 10 09:39:30 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Feb 2014 14:39:30 +0000 Subject: Finding size of Variable In-Reply-To: <56be2de0-ab95-4dc6-a7c2-571ae8bc0e26@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <56be2de0-ab95-4dc6-a7c2-571ae8bc0e26@googlegroups.com> Message-ID: On 10/02/2014 14:25, Asaf Las wrote: > On Monday, February 10, 2014 4:07:14 PM UTC+2, wxjm... at gmail.com wrote: > Interesting > >>>>> sys.getsizeof('a' * 1000000) > here you get string type > >>>>> sys.getsizeof(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-8')) > and here bytes > >>>> type ('a' * 10000) > >>>> type(('a' * 1000000 + 'oe' + '\U00010000').encode('utf-8')) > >>>> > > Why? > Please don't feed this particular troll, he's spent 18 months driving us nuts with his nonsense. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From python.list at tim.thechases.com Mon Feb 10 09:43:08 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 10 Feb 2014 08:43:08 -0600 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20140210084308.7727c0fd@bigbox.christie.dr> On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: > Python does not save memory at all. A str (unicode string) > uses less memory only - and only - because and when one uses > explicitly characters which are consuming less memory. > > Not only the memory gain is zero, Python falls back to the > worse case. > > >>> sys.getsizeof('a' * 1000000) > 1000025 > >>> sys.getsizeof('a' * 1000000 + 'oe') > 2000040 > >>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') > 4000048 If Python used UTF-32 for EVERYTHING, then all three of those cases would be 4000048, so it clearly disproves your claim that "python does not save memory at all". > The opposite of what the utf8/utf16 do! > > >>> sys.getsizeof(('a' * 1000000 + 'oe' + > >>> '\U00010000').encode('utf-8')) > 1000023 > >>> sys.getsizeof(('a' * 1000000 + 'oe' + > >>> '\U00010000').encode('utf-16')) > 2000025 However, as pointed out repeatedly, string-indexing in fixed-width encodings are O(1) while indexing into variable-width encodings (e.g. UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing while saving space when a string doesn't need to use a full 32-bit width. -tkc From jeanmichel at sequans.com Mon Feb 10 09:46:31 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 10 Feb 2014 15:46:31 +0100 (CET) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: <86iosnujv7.fsf@gmail.com> Message-ID: <201346723.3545451.1392043591632.JavaMail.root@sequans.com> > Call the venv version of python and activation is handled. > E.g. in a fabfile > > myenv/bin/python myscript.py > > -- > Pete Forman > -- > https://mail.python.org/mailman/listinfo/python-list wow, the solution is so nice and simple. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From ned at nedbatchelder.com Mon Feb 10 10:02:50 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 10 Feb 2014 10:02:50 -0500 Subject: Finding size of Variable In-Reply-To: <20140210084308.7727c0fd@bigbox.christie.dr> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <20140210084308.7727c0fd@bigbox.christie.dr> Message-ID: On 2/10/14 9:43 AM, Tim Chase wrote: > On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: >> Python does not save memory at all. A str (unicode string) >> uses less memory only - and only - because and when one uses >> explicitly characters which are consuming less memory. >> >> Not only the memory gain is zero, Python falls back to the >> worse case. >> >>>>> sys.getsizeof('a' * 1000000) >> 1000025 >>>>> sys.getsizeof('a' * 1000000 + 'oe') >> 2000040 >>>>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') >> 4000048 > > If Python used UTF-32 for EVERYTHING, then all three of those cases > would be 4000048, so it clearly disproves your claim that "python > does not save memory at all". > >> The opposite of what the utf8/utf16 do! >> >>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >>>>> '\U00010000').encode('utf-8')) >> 1000023 >>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >>>>> '\U00010000').encode('utf-16')) >> 2000025 > > However, as pointed out repeatedly, string-indexing in fixed-width > encodings are O(1) while indexing into variable-width encodings (e.g. > UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing > while saving space when a string doesn't need to use a full 32-bit > width. > > -tkc > > > Please don't engage in this debate with JMF. His mind is made up, and he will not be swayed, no matter how persuasive and reasonable your arguments. Just ignore him. -- Ned Batchelder, http://nedbatchelder.com From sturla.molden at gmail.com Mon Feb 10 10:03:25 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Mon, 10 Feb 2014 15:03:25 +0000 (UTC) Subject: Sort one sequence by O(n) in time and O(1) in space References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> Message-ID: <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Chris Angelico wrote: > That's assuming it really is a sort operation. The problem description > isn't entirely clear on this point, but if it's actually a zip, then > it can definitely be done in O(n). Ah, I didn't read it carefully enough. :-) Granted, a zip can be done in O(n) time and O(1) memory using a generator, which by the way is what itertools.izip does. Sturla From mattbattista at gmail.com Mon Feb 10 10:06:09 2014 From: mattbattista at gmail.com (Matt Battista) Date: Mon, 10 Feb 2014 07:06:09 -0800 (PST) Subject: NYC-based Python Careers Message-ID: <0dbf6fda-05dd-445e-900f-7a21647233ec@googlegroups.com> Hey everyone! I am a Python developer recruiter based in NYC. I'm currently representing Fortune 500 companies as well as 5 person start ups that have needs for developers with basic to advanced Python skills. If you're looking for a career change in the area or want to experience NYC for the first time, feel free to reach out to me or pass my information along to someone who might want to utilize my services. I'm sure that many of the folks who frequent this group are experienced and have been contacted by recruiters before. Hopefully we haven't left a bad taste in your mouth as I am genuinely interested in helping you further your career or find your dream job. I look forward to working with any and all of you. Thanks, Matt Battista matthew.battista at workbridgeassociates.com From rosuav at gmail.com Mon Feb 10 10:23:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 02:23:08 +1100 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Message-ID: On Tue, Feb 11, 2014 at 2:03 AM, Sturla Molden wrote: > Chris Angelico wrote: > >> That's assuming it really is a sort operation. The problem description >> isn't entirely clear on this point, but if it's actually a zip, then >> it can definitely be done in O(n). > > Ah, I didn't read it carefully enough. :-) > > Granted, a zip can be done in O(n) time and O(1) memory using a generator, > which by the way is what itertools.izip does. Right. I poked around in itertools but nothing was quite what I was after, so I ended up writing my own generator. But it's still a zip operation, and as such, is just a variant form of iterating over the original list. All I do is follow a pattern other than the Red King's "Begin at the beginning, go on till you come to the end, then raise StopIteration" (or words to that effect). From rosuav at gmail.com Mon Feb 10 10:26:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 02:26:09 +1100 Subject: NYC-based Python Careers In-Reply-To: <0dbf6fda-05dd-445e-900f-7a21647233ec@googlegroups.com> References: <0dbf6fda-05dd-445e-900f-7a21647233ec@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 2:06 AM, Matt Battista wrote: > I am a Python developer recruiter based in NYC. I'm currently representing Fortune 500 companies as well as 5 person start ups that have needs for developers with basic to advanced Python skills. If you're looking for a career change in the area or want to experience NYC for the first time, feel free to reach out to me or pass my information along to someone who might want to utilize my services. > Hi! While some of us are indeed looking for jobs (myself included), the right place to discuss them is not the list itself, but the Python Job Board: http://www.python.org/community/jobs/ That's where people look. ChrisA From ned at nedbatchelder.com Mon Feb 10 10:36:50 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 10 Feb 2014 10:36:50 -0500 Subject: Pylint across Python versions In-Reply-To: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> References: <317fd2a4-186b-4b97-ad7f-084609d0a9a4@googlegroups.com> Message-ID: On 2/10/14 6:39 AM, thomas.lehmann at adtech.com wrote: > Hi, > > somebody who can tell me about pylint experiences across > different Python version. > > Example: > I'm using a construct like this: > > if sys.version.startswith("3."): > unicode = str > > The reason is that Python 3 does not have this > function anymore but pylint yells for Python < 3 > about redefinition also it does not happen. > > How to get forward with this? > > Regards, > Thomas > Pylint may have a difficult time understanding what you are doing here. You can use pylint comments to tell it to shut up when you know better. But also, you might find it easier to use the "six" module from PyPI to handle these sorts of differences. It's easier than doing it ad-hoc with your own logic. -- Ned Batchelder, http://nedbatchelder.com From oscar.j.benjamin at gmail.com Mon Feb 10 10:45:08 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 10 Feb 2014 15:45:08 +0000 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Message-ID: On 10 February 2014 15:03, Sturla Molden wrote: > Chris Angelico wrote: > >> That's assuming it really is a sort operation. The problem description >> isn't entirely clear on this point, but if it's actually a zip, then >> it can definitely be done in O(n). > > Ah, I didn't read it carefully enough. :-) > > Granted, a zip can be done in O(n) time and O(1) memory using a generator, > which by the way is what itertools.izip does. Yes but turning the generator into a list takes O(N) storage (for the new list!). The OP wants to rearrange a list in-place. Something like mylist[:] = reorder_generator(mylist) won't work because the generator would need to access the data non-sequentially (it would need to read elements after they were overwritten). The way to do this is to find the cycles of data movement i.e. the sets of indices for which a permutation occurs. If you know the size of the input then you can find these once and hard-code them. Otherwise you need an algorithm that finds each cycle exactly once using O(1) storage which is definitely not trivial. You can see the top-level code that fftw uses for this here (I think this code is very hard to follow without prior experience of their code base - I certainly don't understand it): https://github.com/FFTW/fftw3/blob/master/rdft/vrank3-transpose.c#L159 I'm not even sure if that really is O(1) storage though: it may be something like O(MN/gcd(M, N)). This page describes the general problem http://en.wikipedia.org/wiki/In-place_matrix_transposition and mentions the existence of "more complicated" algorithms that can use O(N+M) or O(log(MN)) storage. So I don't think an O(1) storage O(N) operations solution exists for the general M*N case although it may be possible for the specialisation to 2*M. (I haven't tried this but if you're interested see what cycles come up for different input sizes and whether there's a pattern that can be predicted using O(1) storage). Oscar From rosuav at gmail.com Mon Feb 10 10:52:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 02:52:08 +1100 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Message-ID: On Tue, Feb 11, 2014 at 2:45 AM, Oscar Benjamin wrote: > Something like > > mylist[:] = reorder_generator(mylist) > > won't work because the generator would need to access the data > non-sequentially (it would need to read elements after they were > overwritten). This would have O(1) space and O(n) time. It's absolutely perfect... except that you now don't technically have a list any more: mylist = reorder_generator(mylist) You can iterate over it, but can't index it. But hey, it complies with the space/time requirements! ChrisA From roegltd at gmail.com Mon Feb 10 11:01:17 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 08:01:17 -0800 (PST) Subject: Using virtualenv to bypass sudoer issues In-Reply-To: References: <86iosnujv7.fsf@gmail.com> Message-ID: On Monday, February 10, 2014 4:46:31 PM UTC+2, Jean-Michel Pichavant wrote: > > Call the venv version of python and activation is handled. > > E.g. in a fabfile > > > > myenv/bin/python myscript.py > > > > -- > > Pete Forman > > -- > > https://mail.python.org/mailman/listinfo/python-list > > wow, the solution is so nice and simple. > > JM > venv activation (venv/bin/activate bash script) adds venv/bin directory in venv into PATH variable in front of PATH's current value. if you plan to use pip or any other executable in venv/bin directory without running bin/activate, they have to be also addressed via absolute path too. It also defines deactivate bash function and if i am not wrong one environment variable to flag activation /Asaf From wkhughey at gmail.com Mon Feb 10 11:10:22 2014 From: wkhughey at gmail.com (Walter Hughey) Date: Mon, 10 Feb 2014 11:10:22 -0500 (EST) Subject: Fwd: Newcomer Help In-Reply-To: <936508254.6549591.1391795689236.JavaMail.root@okbu.edu> Message-ID: <675340207.6922848.1392048622415.JavaMail.root@okbu.edu> I am new to Python programming, actually new to any programming language. I sent the email below to the "pythonmac-sig at python.org a few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am supposed to be a member. I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac list because I am trying to run Python 3.3 on a Mac computer. Thank you, Walter ----- Original Message ----- From: "Walter Hughey" To: pythonmac-sig at python.org Sent: Friday, February 7, 2014 11:54:49 AM Subject: Newcomer Help Greetings, I am new at Python programming, technically a newbie at writing programming code. I have been involved in the maintenance of computers for several years and have decided to increase my knowledge and experience. I am taking a course that - although not a programming course - does require writing of code. I am trying to use Python to write the code. I use a Mac computer and the first issue is getting working with Python. The computer I currently use is running Mac OS X 10.6.8, Intel Core i5 Processor, with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have added Python 3.3, the version our Professor recommended. I have checked out the Python installed by Apple and can enter in code and it works, but I need to create a file, run it, and then provide it for the Professor to grade and I don't know how with the Apple installed version. While reading about Python, I saw comments about the note concerning outdated software: If you are using Python from a python.org 64-bit/32-bit Python installer for Mac OS X 10.6 and later , you should only use IDLE or tkinter with an updated third-party Tcl/Tk 8.5, like ActiveTcl 8.5 installed. I located, downloaded and installed the recommended version of ActiveTcl 8.5.15.0. When I open Idle, I see a warning that "The version of Tcl/Tk (8.5.7) in use may be unstable." I received this warning both before and after installing the software above. I open Idle, choose "New File" then most often the computer will freeze, Idle does nothing, cannot enter text into the text box, cannot close the application either with the red circle or by selecting Idle>Close Idle. As often as that, Idle freezes as soon as I open new file, and I cannot close without resorting to Force Quit. I have removed and re-installed Python after downloading and installing the Tcl/Tk software and it does not help. I have seen this work fine on a Mac running Mac OS X 10.8.3. I really just need to get this working on the older version. A am not only new to Python, I am new on this list and hope I have started my stay here in the correct manner! Thank you, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 10 11:41:33 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 10 Feb 2014 16:41:33 +0000 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Message-ID: On 10 February 2014 15:52, Chris Angelico wrote: > On Tue, Feb 11, 2014 at 2:45 AM, Oscar Benjamin > wrote: >> Something like >> >> mylist[:] = reorder_generator(mylist) >> >> won't work because the generator would need to access the data >> non-sequentially (it would need to read elements after they were >> overwritten). > > This would have O(1) space and O(n) time. It's absolutely perfect... > except that you now don't technically have a list any more: > > mylist = reorder_generator(mylist) > > You can iterate over it, but can't index it. But hey, it complies with > the space/time requirements! That is very likely a practical solution for many problems involving transposition. Doing this in Python is pretty artificial since a new list object will likely use a lot less memory than the elements it contains. The practical use for such algorithms is in something like C and even then it's often better to simply iterate in a different order. The advantage of physically transposing the data is to improve memory locality but this only makes sense if your transpose algorithm itself has a good memory access pattern (which is likely impossible with O(1) storage). Oscar From invalid at invalid.invalid Mon Feb 10 11:54:10 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Feb 2014 16:54:10 +0000 (UTC) Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: On 2014-02-09, Chris Angelico wrote: > Heavy computation might be unideal in Python, but if you can grunge > it into NumPy operations, that won't be a problem. While one might thing Python is not suitable for heavy number crunching, it actually gets used for that a lot due to the wide variety of hard-core number-crunching libraries[1] available (BLAS, LINPACK, LAPACK, and the sort of thing usually associated with boffins writin FORTRAN programs). If you're interestedin that sort of stuff, check out Scientific Python, SciPy, et al. http://www.scipy.org/ http://en.wikipedia.org/wiki/ScientificPython/ https://wiki.python.org/moin/NumericAndScientific For extra geek-points you run them on the Fermilab/CERN "Scientific Linux" distro: https://www.scientificlinux.org/ You can also get a Python distribution with all the extra geekyness already baked in: https://www.enthought.com/products/epd/ [1] Some of those libraries are in FORTRAN because I guess there are some sorts of numerical hocus-pocus that still writes easier and runs faster in FORTRAN than in C. -- Grant Edwards grant.b.edwards Yow! I'm ZIPPY the PINHEAD at and I'm totally committed gmail.com to the festive mode. From invalid at invalid.invalid Mon Feb 10 12:00:15 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Feb 2014 17:00:15 +0000 (UTC) Subject: system wide mutex References: Message-ID: On 2014-02-09, Asaf Las wrote: > Hi > > Which one is most recommended to use for mutex alike locking to > achieve atomic access to single resource: > > - fcntl.lockf > - os.open() with O_SHLOCK and O_EXLOCK > - https://pypi.python.org/pypi/lockfile/0.9.1 > - https://pypi.python.org/pypi/zc.lockfile/1.1.0 > - any other ? Posix "pthread" mutexes shared memory. -- Grant Edwards grant.b.edwards Yow! Give them RADAR-GUIDED at SKEE-BALL LANES and gmail.com VELVEETA BURRITOS!! From rustompmody at gmail.com Mon Feb 10 12:07:14 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 10 Feb 2014 09:07:14 -0800 (PST) Subject: Newcomer Help In-Reply-To: References: <936508254.6549591.1391795689236.JavaMail.root@okbu.edu> Message-ID: <8e09e652-4998-4fd9-becb-e7b2158ef987@googlegroups.com> On Monday, February 10, 2014 9:40:22 PM UTC+5:30, Walter Hughey wrote: > I am new to Python programming, actually new to any programming language. I sent the email below to the "python... at python.org a few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am supposed to be a member. > > > I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac list because I am trying to run Python 3.3 on a Mac computer. > > > Thank you, > > > Walter > > From: "Walter Hughey" > To: python... at python.org > Sent: Friday, February 7, 2014 11:54:49 AM > Subject: Newcomer Help > > > Greetings, > I am new at Python programming, technically a newbie at writing programming code. I have been involved in the maintenance of computers for several years and have decided to increase my knowledge and experience. I am taking a course that - although not a programming course - does require writing of code. I am trying to use Python to write the code. > > I use a Mac computer and the first issue is getting working with Python. The computer I currently use is running Mac OS X 10.6.8, Intel Core i5 Processor, with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have added Python 3.3, the version our Professor recommended. I have checked out the Python installed by Apple and can enter in code and it works, but I need to create a file, run it, and then provide it for the Professor to grade and I don't know how with the Apple installed version. > > While reading about Python, I saw comments about the note concerning outdated software: ?If you are using Python from a python.org > 64-bit/32-bit Python installer for Mac OS X 10.6 and later, > you should only use IDLE or tkinter with an updated > third-party Tcl/Tk 8.5, like > ActiveTcl 8.5 > installed. > > I located, downloaded and installed the recommended version of ActiveTcl 8.5.15.0. When I open Idle, I see a warning that "The version of Tcl/Tk (8.5.7) in use may be unstable." ?I received this warning both before and after installing the software above. I open Idle, choose "New File" then most often the computer will freeze, Idle does nothing, cannot enter text into the text box, cannot close the application either with the red circle or by selecting Idle>Close Idle. As often as that, Idle freezes as soon as I open new file, and I cannot close without resorting to Force Quit.? > > I have removed and?re-installed?Python after downloading and?installing?the Tcl/Tk software and it does not help. I have seen this work fine on a Mac running Mac OS X 10.8.3. I really just need to get this working on the older version. > > A am not only new to Python, I am new on this list and hope I have started my stay here in the correct manner! > Hi! You have started on a clear note and are welcome here. I dont know anything about macs so hopefully someone else will give you more specific answers. However can you check that python interpreter runs in a shell, and that after starting it if you type say: 2 + 3 RETURN you get 5 If that is the case you can still develop the way most python programmers develop, viz Write your code in a normal text editor Load it into the interpreter Check it Go back to the editor and continue writing/correcting the code From miki.tebeka at gmail.com Mon Feb 10 12:46:20 2014 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 10 Feb 2014 09:46:20 -0800 (PST) Subject: system wide mutex In-Reply-To: References: Message-ID: <6b667998-a04f-4ae8-a14a-567af99b072d@googlegroups.com> IIRC creating a directory is atomic in most environments. On Sunday, February 9, 2014 2:39:51 AM UTC-8, Asaf Las wrote: > Hi > > > > Which one is most recommended to use for mutex alike locking to > > achieve atomic access to single resource: > > > > - fcntl.lockf > > - os.open() with O_SHLOCK and O_EXLOCK > > - https://pypi.python.org/pypi/lockfile/0.9.1 > > - https://pypi.python.org/pypi/zc.lockfile/1.1.0 > > - any other ? > > > > Thanks > > > > /Asaf From rantingrickjohnson at gmail.com Mon Feb 10 13:45:40 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Mon, 10 Feb 2014 10:45:40 -0800 (PST) Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) Message-ID: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> ## START CODE ########################################### def foo(): # foo represents a patternless function # or method that returns a Boolean value # based on some internal test. # if 1==1: return True return False # # The fun begins when two tiny chars are forgotten, # however, since the code is legal, python will happily # give us the wrong answer. # if foo: # <- forgot parenthesis! print 'implicit conversion to bool bites!' else: # # This block will NEVER execute because foo is # ALWAYS True! # # # Some introspection to understand why this happened. # print 'foo =', foo print 'bool(foo) ->', bool(foo) # ## END CODE ############################################# It's obvious i did not follow the syntactical rules of Python, i understand that, however, there are three design flaws here that are contributing to this dilemma: 1. Implicit conversion to Boolean is evil 2. Conditionals should never accept parameter-less functions. If you want to check if a callable is True or False, then use "if bool(callable)". Any usage of a bare callable in conditionals should raise SyntaxError. 3. Implicit introspection is evil, i prefer all references to a callable's names to result in a CALL to that callable, not an introspection! Introspection should ALWAYS be explicit! For a long time i thought Python's idea of a returning the value of a callable-- who's name is unadorned with "(...)" --was a good idea, however, i am now wholly convinced that this design is folly, and the reason is two fold: 1. Parenthesis should not be required for parameter- less functions. I realize this is a bit more complicated in languages like Python where attributes are exposed to the public, but still, not reason enough to require such onerous typing. 2. Implicit introspection is evil. I would prefer an explicit method attached to all callables over a sugar for "callable.call". We should never consume syntactical sugars UNLESS they can greatly reduce the density of code (like math operators for instance!) From tn156 at scarletmail.rutgers.edu Mon Feb 10 13:57:02 2014 From: tn156 at scarletmail.rutgers.edu (tn156 at scarletmail.rutgers.edu) Date: Mon, 10 Feb 2014 10:57:02 -0800 (PST) Subject: Help with python functions? In-Reply-To: References: <5240489d$0$29992$c3e8da3$5496439d@news.astraweb.com> <66aa7d75-a819-4b21-9f1e-7ad265996150@googlegroups.com> Message-ID: <682c2ec7-e510-4525-b0c0-277fa3dc4bf8@googlegroups.com> On Monday, September 23, 2013 6:48:20 PM UTC-4, Terry Reedy wrote: > On 9/23/2013 6:32 PM, kjakupak at gmail.com wrote: > > > On Monday, September 23, 2013 9:56:45 AM UTC-4, Steven D'Aprano wrote: > > >> On Mon, 23 Sep 2013 05:57:34 -0700, kjakupak wrote: > > >> > > >> Now you're done! On to the next function... > > >> > > >> > > >> > > >> -- > > >> > > >> Steven > > > > > > def temp(T, from_unit, to_unit): > > > conversion_table = {('c', 'k'):lambda x: x + 273.15, > > > ('c', 'f'):lambda x: (x * (9.0/5)) + 32, > > > ('k', 'c'):lambda x: x - 273.15, > > > ('k', 'f'):lambda x: (x * (9.0/5)) - 459.67, > > > ('f', 'c'):lambda x: (x - 32) * (5.0/9), > > > ('f', 'k'):lambda x: (x + 459.67) * (5.0/9)} > > > f = conversion_table[(from_unit.lower(), to_unit.lower())] > > > return f(T) > > > > What happens if you run some tests? If you use unittest, you can use the > > assertAlmostEqualMethod, or just write something similar yourself. Be > > careful with values near 0.. > > > > At minimum, how many tests do you need, 6 or 9? > > > > > > -- > > Terry Jan Reedy can I use elif instead of lambda? From tn156 at scarletmail.rutgers.edu Mon Feb 10 14:01:54 2014 From: tn156 at scarletmail.rutgers.edu (tn156 at scarletmail.rutgers.edu) Date: Mon, 10 Feb 2014 11:01:54 -0800 (PST) Subject: Help with python functions? In-Reply-To: References: <5240489d$0$29992$c3e8da3$5496439d@news.astraweb.com> <66aa7d75-a819-4b21-9f1e-7ad265996150@googlegroups.com> Message-ID: <2c066932-e6dd-4cc6-84dd-2bc5a70bc082@googlegroups.com> On Monday, September 23, 2013 6:48:20 PM UTC-4, Terry Reedy wrote: > On 9/23/2013 6:32 PM, kjakupak at gmail.com wrote: > > > On Monday, September 23, 2013 9:56:45 AM UTC-4, Steven D'Aprano wrote: > > >> On Mon, 23 Sep 2013 05:57:34 -0700, kjakupak wrote: > > >> > > >> Now you're done! On to the next function... > > >> > > >> > > >> > > >> -- > > >> > > >> Steven > > > > > > def temp(T, from_unit, to_unit): > > > conversion_table = {('c', 'k'):lambda x: x + 273.15, > > > ('c', 'f'):lambda x: (x * (9.0/5)) + 32, > > > ('k', 'c'):lambda x: x - 273.15, > > > ('k', 'f'):lambda x: (x * (9.0/5)) - 459.67, > > > ('f', 'c'):lambda x: (x - 32) * (5.0/9), > > > ('f', 'k'):lambda x: (x + 459.67) * (5.0/9)} > > > f = conversion_table[(from_unit.lower(), to_unit.lower())] > > > return f(T) > > > > What happens if you run some tests? If you use unittest, you can use the > > assertAlmostEqualMethod, or just write something similar yourself. Be > > careful with values near 0.. > > > > At minimum, how many tests do you need, 6 or 9? > > > > > > -- > > Terry Jan Reedy can elif be used instead of lambda From breamoreboy at yahoo.co.uk Mon Feb 10 14:15:34 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Feb 2014 19:15:34 +0000 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On 10/02/2014 18:45, Rick Johnson wrote: > ## START CODE ########################################### > def foo(): > # foo represents a patternless function > # or method that returns a Boolean value > # based on some internal test. > # > if 1==1: > return True > return False > # > # The fun begins when two tiny chars are forgotten, > # however, since the code is legal, python will happily > # give us the wrong answer. > # > if foo: # <- forgot parenthesis! > print 'implicit conversion to bool bites!' > else: > # > # This block will NEVER execute because foo is > # ALWAYS True! > # > # > # Some introspection to understand why this happened. > # > print 'foo =', foo > print 'bool(foo) ->', bool(foo) > # > ## END CODE ############################################# > > It's obvious i did not follow the syntactical rules of > Python, i understand that, however, there are three design > flaws here that are contributing to this dilemma: > > 1. Implicit conversion to Boolean is evil > > 2. Conditionals should never accept parameter-less > functions. If you want to check if a callable is > True or False, then use "if bool(callable)". Any > usage of a bare callable in conditionals should > raise SyntaxError. > > 3. Implicit introspection is evil, i prefer all > references to a callable's names to result in a CALL > to that callable, not an introspection! > Introspection should ALWAYS be explicit! > > For a long time i thought Python's idea of a returning the > value of a callable-- who's name is unadorned with "(...)" > --was a good idea, however, i am now wholly convinced that > this design is folly, and the reason is two fold: > > 1. Parenthesis should not be required for parameter- > less functions. I realize this is a bit more > complicated in languages like Python where > attributes are exposed to the public, but still, not > reason enough to require such onerous typing. > > 2. Implicit introspection is evil. I would prefer an > explicit method attached to all callables over a > sugar for "callable.call". We should never consume > syntactical sugars UNLESS they can greatly reduce > the density of code (like math operators for > instance!) > This particular PyWart would immediately be caught if another PyWart, namely the unittest module, were to be used to catch this programming error. All of your preferences can be met by raising an issue on the bug tracker and providing a patch that changes code, docs and test suites as appropriate. Simples :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ned at nedbatchelder.com Mon Feb 10 14:17:33 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 10 Feb 2014 14:17:33 -0500 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On 2/10/14 1:45 PM, Rick Johnson wrote: > ## START CODE ########################################### > def foo(): > # foo represents a patternless function > # or method that returns a Boolean value > # based on some internal test. > # > if 1==1: > return True > return False > # > # The fun begins when two tiny chars are forgotten, > # however, since the code is legal, python will happily > # give us the wrong answer. > # > if foo: # <- forgot parenthesis! > print 'implicit conversion to bool bites!' > else: > # > # This block will NEVER execute because foo is > # ALWAYS True! > # > # > # Some introspection to understand why this happened. > # > print 'foo =', foo > print 'bool(foo) ->', bool(foo) > # > ## END CODE ############################################# > > It's obvious i did not follow the syntactical rules of > Python, i understand that, however, there are three design > flaws here that are contributing to this dilemma: > > 1. Implicit conversion to Boolean is evil > > 2. Conditionals should never accept parameter-less > functions. If you want to check if a callable is > True or False, then use "if bool(callable)". Any > usage of a bare callable in conditionals should > raise SyntaxError. > > 3. Implicit introspection is evil, i prefer all > references to a callable's names to result in a CALL > to that callable, not an introspection! > Introspection should ALWAYS be explicit! > > For a long time i thought Python's idea of a returning the > value of a callable-- who's name is unadorned with "(...)" > --was a good idea, however, i am now wholly convinced that > this design is folly, and the reason is two fold: > > 1. Parenthesis should not be required for parameter- > less functions. I realize this is a bit more > complicated in languages like Python where > attributes are exposed to the public, but still, not > reason enough to require such onerous typing. > > 2. Implicit introspection is evil. I would prefer an > explicit method attached to all callables over a > sugar for "callable.call". We should never consume > syntactical sugars UNLESS they can greatly reduce > the density of code (like math operators for > instance!) > It seems like you are only looking at how to improve the error you just stumbled over, and not how the full proposal would work out, or even if you would like it better. You haven't made the entire idea explicit yet. How would I pass the function foo to another function? The word "foo" now means, invoke foo. You mean an explicit method attached to callables, like "foo.as_callable" ? But why doesn't the word "foo" there invoke foo? Surely the word "as_callable" isn't special, so is it that "foo.anything" means direct attribute access on foo? So to perform attribute access on the result of foo I need "foo().something" ? In what cases does the word foo invoke the function, and when doesn't it? It's not possible to make a programming language error-proof. There will always be mistakes programmers can make. -- Ned Batchelder, http://nedbatchelder.com From wkhughey at gmail.com Mon Feb 10 15:19:40 2014 From: wkhughey at gmail.com (Walter Hughey) Date: Mon, 10 Feb 2014 15:19:40 -0500 (EST) Subject: Newcomer Help In-Reply-To: <8e09e652-4998-4fd9-becb-e7b2158ef987@googlegroups.com> Message-ID: <1471238627.7004721.1392063580008.JavaMail.root@okbu.edu> Thank you for your reply. One quick question, when I reply should it be replay to all or to the person who sent the emial? Apple does install a version of Python, normally a somewhat older version. My computer has 2.5 and 2.6 installed and I have opened it and inserted code that works. I do need a way to write the code, test it, and then save a copy to turn in for the assignment. I was not aware that a normal text editor would work. I shall definitely look at that later today. Walter ----- Original Message ----- From: "Rustom Mody" To: python-list at python.org Sent: Monday, February 10, 2014 11:07:14 AM Subject: Re: Newcomer Help On Monday, February 10, 2014 9:40:22 PM UTC+5:30, Walter Hughey wrote: > I am new to Python programming, actually new to any programming language. I sent the email below to the "python... at python.org a few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am supposed to be a member. > > > I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac list because I am trying to run Python 3.3 on a Mac computer. > > > Thank you, > > > Walter > > From: "Walter Hughey" > To: python... at python.org > Sent: Friday, February 7, 2014 11:54:49 AM > Subject: Newcomer Help > > > Greetings, > I am new at Python programming, technically a newbie at writing programming code. I have been involved in the maintenance of computers for several years and have decided to increase my knowledge and experience. I am taking a course that - although not a programming course - does require writing of code. I am trying to use Python to write the code. > > I use a Mac computer and the first issue is getting working with Python. The computer I currently use is running Mac OS X 10.6.8, Intel Core i5 Processor, with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have added Python 3.3, the version our Professor recommended. I have checked out the Python installed by Apple and can enter in code and it works, but I need to create a file, run it, and then provide it for the Professor to grade and I don't know how with the Apple installed version. > > While reading about Python, I saw comments about the note concerning outdated software: If you are using Python from a python.org > 64-bit/32-bit Python installer for Mac OS X 10.6 and later, > you should only use IDLE or tkinter with an updated > third-party Tcl/Tk 8.5, like > ActiveTcl 8.5 > installed. > > I located, downloaded and installed the recommended version of ActiveTcl 8.5.15.0. When I open Idle, I see a warning that "The version of Tcl/Tk (8.5.7) in use may be unstable." I received this warning both before and after installing the software above. I open Idle, choose "New File" then most often the computer will freeze, Idle does nothing, cannot enter text into the text box, cannot close the application either with the red circle or by selecting Idle>Close Idle. As often as that, Idle freezes as soon as I open new file, and I cannot close without resorting to Force Quit. > > I have removed and re-installed Python after downloading and installing the Tcl/Tk software and it does not help. I have seen this work fine on a Mac running Mac OS X 10.8.3. I really just need to get this working on the older version. > > A am not only new to Python, I am new on this list and hope I have started my stay here in the correct manner! > Hi! You have started on a clear note and are welcome here. I dont know anything about macs so hopefully someone else will give you more specific answers. However can you check that python interpreter runs in a shell, and that after starting it if you type say: 2 + 3 RETURN you get 5 If that is the case you can still develop the way most python programmers develop, viz Write your code in a normal text editor Load it into the interpreter Check it Go back to the editor and continue writing/correcting the code -- https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Mon Feb 10 15:47:45 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 10 Feb 2014 20:47:45 +0000 (UTC) Subject: Newcomer Help References: Message-ID: On 2014-02-10, Walter Hughey wrote: > Apple does install a version of Python, normally a somewhat older > version. My computer has 2.5 and 2.6 installed and I have opened it > and inserted code that works. I do need a way to write the code, test > it, and then save a copy to turn in for the assignment. I was not > aware that a normal text editor would work. I shall definitely look > at that later today. Can't you just use to edit a Python source file and then run it like you do on other Unix systems? $ emacs myprog.py or $ vi myprog.py or $ myprog.py then $ python myprog.py -- Grant Edwards grant.b.edwards Yow! The SAME WAVE keeps at coming in and COLLAPSING gmail.com like a rayon MUU-MUU ... From georg at python.org Mon Feb 10 15:55:40 2014 From: georg at python.org (Georg Brandl) Date: Mon, 10 Feb 2014 21:55:40 +0100 Subject: [RELEASED] Python 3.3.4 Message-ID: <52F93CCC.70304@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm very happy to announce the release of Python 3.3.4. Python 3.3.4 includes several security fixes and over 120 bug fixes compared to the Python 3.3.3 release. This release fully supports OS X 10.9 Mavericks. In particular, this release fixes an issue that could cause previous versions of Python to crash when typing in interactive mode on OS X 10.9. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.4 visit: http://www.python.org/download/releases/3.3.4/ This is a production release, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlL5PMwACgkQN9GcIYhpnLCv4wCePNVqwsOYCHdJBix2bKk4PNpK GBoAnRML2x6obCssnUJe5xwuUZYw8ZSY =+/Nz -----END PGP SIGNATURE----- From sg552 at hotmail.co.uk Mon Feb 10 16:12:23 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Mon, 10 Feb 2014 21:12:23 +0000 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On 10/02/2014 18:45, Rick Johnson wrote: > [...] > > 3. Implicit introspection is evil, i prefer all > references to a callable's names to result in a CALL > to that callable, not an introspection! So, for example, none of isinstance(x, myclass) map(myfunc, range(10)) x = property(x_get, x_set) would still work? From ned at nedbatchelder.com Mon Feb 10 17:00:14 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 10 Feb 2014 17:00:14 -0500 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On 2/10/14 4:12 PM, Rotwang wrote: > On 10/02/2014 18:45, Rick Johnson wrote: >> [...] >> >> 3. Implicit introspection is evil, i prefer all >> references to a callable's names to result in a CALL >> to that callable, not an introspection! > > So, for example, none of > > isinstance(x, myclass) > > map(myfunc, range(10)) > > x = property(x_get, x_set) > > would still work? I guess neither would: except ValueError: :( -- Ned Batchelder, http://nedbatchelder.com From gvanem at yahoo.no Mon Feb 10 17:13:44 2014 From: gvanem at yahoo.no (Gisle Vanem) Date: Mon, 10 Feb 2014 23:13:44 +0100 Subject: Newcomer Help References: <1471238627.7004721.1392063580008.JavaMail.root@okbu.edu> Message-ID: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> "Walter Hughey" wrote: > Thank you for your reply. One quick question, when > I reply should it be replay to all or to the person who sent the emial? When replying, the most important thing to remember is... order. A: Because it messes up the order in which people normally read text. Q: Why is it such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? Get the picture now newcomer? --gv ------ this crap came from you --------- > > > Apple does install a version of Python, normally a somewhat older version. My computer has 2.5 and 2.6 installed and I have opened > it and inserted code that works. I do need a way to write the code, test it, and then save a copy to turn in for the assignment. I > was not aware that a normal text editor would work. I shall definitely look at that later today. > > > Walter > ----- Original Message ----- > > From: "Rustom Mody" > To: python-list at python.org > Sent: Monday, February 10, 2014 11:07:14 AM > Subject: Re: Newcomer Help > > On Monday, February 10, 2014 9:40:22 PM UTC+5:30, Walter Hughey wrote: >> I am new to Python programming, actually new to any programming language. I sent the email below to the "python... at python.org a >> few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am >> supposed to be a member. >> >> >> I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would >> appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac >> list because I am trying to run Python 3.3 on a Mac computer. >> >> >> Thank you, >> >> >> Walter >> >> From: "Walter Hughey" >> To: python... at python.org >> Sent: Friday, February 7, 2014 11:54:49 AM >> Subject: Newcomer Help >> >> >> Greetings, >> I am new at Python programming, technically a newbie at writing programming code. I have been involved in the maintenance of >> computers for several years and have decided to increase my knowledge and experience. I am taking a course that - although not a >> programming course - does require writing of code. I am trying to use Python to write the code. >> >> I use a Mac computer and the first issue is getting working with Python. The computer I currently use is running Mac OS X 10.6.8, >> Intel Core i5 Processor, with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have added Python 3.3, the version >> our Professor recommended. I have checked out the Python installed by Apple and can enter in code and it works, but I need to >> create a file, run it, and then provide it for the Professor to grade and I don't know how with the Apple installed version. >> >> While reading about Python, I saw comments about the note concerning outdated software: If you are using Python from a python.org >> 64-bit/32-bit Python installer for Mac OS X 10.6 and later, >> you should only use IDLE or tkinter with an updated >> third-party Tcl/Tk 8.5, like >> ActiveTcl 8.5 >> installed. >> >> I located, downloaded and installed the recommended version of ActiveTcl 8.5.15.0. When I open Idle, I see a warning that "The >> version of Tcl/Tk (8.5.7) in use may be unstable." I received this warning both before and after installing the software above. I >> open Idle, choose "New File" then most often the computer will freeze, Idle does nothing, cannot enter text into the text box, >> cannot close the application either with the red circle or by selecting Idle>Close Idle. As often as that, Idle freezes as soon >> as I open new file, and I cannot close without resorting to Force Quit. >> >> I have removed and re-installed Python after downloading and installing the Tcl/Tk software and it does not help. I have seen >> this work fine on a Mac running Mac OS X 10.8.3. I really just need to get this working on the older version. >> >> A am not only new to Python, I am new on this list and hope I have started my stay here in the correct manner! >> > > Hi! You have started on a clear note and are welcome here. > I dont know anything about macs so hopefully someone else will give you > more specific answers. > > However can you check that python interpreter runs in a shell, and that > after starting it if you type say: > 2 + 3 RETURN > you get 5 > > If that is the case you can still develop the way most python programmers > develop, viz > Write your code in a normal text editor > Load it into the interpreter > Check it > Go back to the editor and continue writing/correcting the code > -- > https://mail.python.org/mailman/listinfo/python-list > > -------------------------------------------------------------------------------- > -- > https://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Mon Feb 10 17:30:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 09:30:09 +1100 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 5:45 AM, Rick Johnson wrote: > if foo: # <- forgot parenthesis! > print 'implicit conversion to bool bites!' You also forgot the parentheses on the second line, and that's nothing to do with boolification :) ChrisA From tjreedy at udel.edu Mon Feb 10 17:59:15 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Feb 2014 17:59:15 -0500 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: On 2/10/2014 4:12 PM, Rotwang wrote: > On 10/02/2014 18:45, Rick Johnson wrote: >> [...] >> >> 3. Implicit introspection is evil, i prefer all >> references to a callable's names to result in a CALL >> to that callable, not an introspection! > > So, for example, none of > isinstance(x, myclass) > map(myfunc, range(10)) > x = property(x_get, x_set) > would still work? No. That is what makes this a troll post, for fun, rather than a serious proposal. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Mon Feb 10 17:56:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 10 Feb 2014 22:56:16 GMT Subject: What are the kinds of software that are not advisable to be developed using Python? References: <4ffa1$52f70f30$5419b3e4$9454@cache1.tilbu1.nb.home.nl> Message-ID: <52f9590f$0$29972$c3e8da3$5496439d@news.astraweb.com> On Sun, 09 Feb 2014 06:17:03 +0100, Skybuck Flying wrote: > " > I got to know about Python a few months ago and today, I want to develop > only using Python because of its code readability. This is not a healthy > bias. To play my own devil's advocate, I have a question. What are the > kinds of software that are not advisable to be developed using Python? " > > Anything that needs to be super reliable. Obvious troll is obvious. Okay, I'll bite. What evidence do you have that programs written in Python are more bug-ridden or less reliable than programs written in other languages? Your own poorly written, buggy software doesn't count as evidence. Hypothetical arguments based on "it stands to reason" or "everybody knows" that static-typed compilers catch more bugs don't count either. Let's see some hard, reliable statistics. > My experience so far with Python versus Delphi has shown that Python > requires way more time to debug than Delphi. I'm sorry to hear that you aren't yet fluent at reading, writing and debugging Python code. While it's true that somebody can write hard-to- debug code in any language, in general Python's ease of us, dynamic but not too dynamic nature, and powerful introspection makes debugging quite easy. > The reason for this is the interpreter versus the compiler. Which interpreter is that? Do you understand that Python has a compiler? There's even a "compile" built-in function which compiles source code at runtime, ready to run it whenever you like. > Delphi's compiler will catch many bugs in branches that have not been > executed or tested. Only if you write many bugs. You can't catch bugs that aren't there *wink* But seriously, Delphi's compiler will catch a tiny subset of all possible bugs, namely, those which can be recognised by static type-checking. While that's useful, it doesn't happen for free. The cost is that Delphi, like Pascal, is a lot less flexible, and a lot more tightly constrained by the need to keep the compiler happy. Although Delphi does have type inference, it is apparently quite limited, which means you're writing a lot more boilerplate code declaring types compared to Python. > While Python's interpreter will mostly catch bugs in executed and tested > branches. > > Most of the code that has not been executed yet could contain bugs and > even syntax/typos/non declared variables and so forth. Deary deary me, you've just exposed yourself as somebody who doesn't actually know much about Python. Non-declared variables? Python doesn't require declarations for variables. Nor can syntax errors hide in code branches that haven't been run. (Well, technically they could, if you use eval or exec.) But for normal code, it is checked for syntax errors during the compilation phase, all at once. > Which means that the entire Python program will have to be re-executed > from the start to ultimately end up in branches that were not executed > the last time. That's certainly true. But the same applies to Delphi. Type errors and syntax errors are only a tiny subset of all the possible errors. You can have off-by-one errors, logic errors, out-of-bounds errors, network errors, database errors, file system errors... Delphi can't check for those at compile time. No matter how clever the programmer or the compiler, code that hasn't been run and tested cannot be trusted to be correct. As Donald Knuth said: Beware of bugs in the above code; I have only proved it correct, not tried it. > This way of debugging will require many many many many many many many > many runs of the same Python program before it's somewhat debugged. And if your Delphi code doesn't have just as many many many many many many many many runs, it won't be debugged either. > This is time lost in the debugging phase. > > Having said that... time is gained in the programming phase thanks to > it's shortened syntax. > > However there is more... Python may lack some technical language > elements like, call by reference, and perhaps other low level codes, > like 8 bit, 16 bit, 32 bit integers which play a roll with interfacing > with hardware. Call by reference is a means to an end, not an end to itself. Apart from that, all those things you say Python "may" lack, it actually has. > Types of software which would not go onto my python list: operating > systems, drivers, perhaps also virtual machines and even compilers, > python slow execution speed hampers that as well. Agree with the first three. Not so much the last one. Perhaps you have heard of PyPy? It's not just an optimizing Python compiler, but a more general compiler-building tool. -- Steven From geniusrko at gmail.com Mon Feb 10 18:44:28 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 15:44:28 -0800 (PST) Subject: Drawing polygons in python turtle Message-ID: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> Hi can anyone help finding the angle to draw different polygons shapes in this example import turtle wm = turtle.Screen() alex = turtle.Turtle() for i in range(5): alex.left(216) alex.forward(50) wm.exitonclick() Why do we use 216 From davea at davea.name Mon Feb 10 19:00:52 2014 From: davea at davea.name (Dave Angel) Date: Mon, 10 Feb 2014 19:00:52 -0500 (EST) Subject: Drawing polygons in python turtle References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> Message-ID: geniusrko at gmail.com Wrote in message: > Hi > can anyone help finding the angle to draw different polygons shapes > > in this example > > import turtle > wm = turtle.Screen() > alex = turtle.Turtle() > for i in range(5): > alex.left(216) > alex.forward(50) > wm.exitonclick() > > Why do we use 216 > 216 degrees doesn't seem to me that it would make a polygon, but rather a star. I can tell you what I remember about geometry, however. To make a regular polygon, you need to turn by a fixed amount and go a fixed distance each time. For an equilateral triangle, you turn 120 degrees. For a square, 90. For a pentagon, 108. 180 - (360/n) degrees. -- DaveA From greg.ewing at canterbury.ac.nz Mon Feb 10 19:19:09 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 11 Feb 2014 13:19:09 +1300 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <433934582413720306.205290sturla.molden-gmail.com@news.gmane.org> <2079199387413737237.368296sturla.molden-gmail.com@news.gmane.org> Message-ID: Chris Angelico wrote: > mylist = reorder_generator(mylist) > > You can iterate over it, but can't index it. But hey, it complies with > the space/time requirements! Rather than a generator, you could use a view object that rearranges the indices when you access an element. That would comply with the space/time requirements and be indexable as well. Actually it would do better than meet the requirements, since in a sense it would be O(1) in both space and time! -- Greg From roegltd at gmail.com Mon Feb 10 19:23:11 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 16:23:11 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> Message-ID: <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> On Tuesday, February 11, 2014 1:44:28 AM UTC+2, geni... at gmail.com wrote: > Hi > > can anyone help finding the angle to draw different polygons shapes > in this example > import turtle > wm = turtle.Screen() > alex = turtle.Turtle() > for i in range(5): > alex.left(216) > alex.forward(50) > wm.exitonclick() > Why do we use 216 because of every for every turn we need to make angle between edges equal to 36. If you will have a look to pentagon definition: http://en.wikipedia.org/wiki/Pentagon inner angle is equal to 108. from that you can easily calculate the angle between edges of star. there is no difference between these 2: alex.left(216) alex.right(144) change left() to right() and see. /Asaf From roegltd at gmail.com Mon Feb 10 19:34:19 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 16:34:19 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> Message-ID: On Tuesday, February 11, 2014 2:23:11 AM UTC+2, Asaf Las wrote: > On Tuesday, February 11, 2014 1:44:28 AM UTC+2, geni... at gmail.com wrote: > > Hi > > > > can anyone help finding the angle to draw different polygons shapes > > in this example > > import turtle > > wm = turtle.Screen() > > alex = turtle.Turtle() > > for i in range(5): > > alex.left(216) > > alex.forward(50) > > wm.exitonclick() > > > Why do we use 216 > because of every for every turn we need to make angle between edges > equal to 36. If you will have a look to pentagon definition: > http://en.wikipedia.org/wiki/Pentagon > inner angle is equal to 108. from that you can easily calculate > the angle between edges of star. > there is no difference between these 2: > alex.left(216) > alex.right(144) > > change left() to right() and see. > /Asaf just a bit add - confusing things here is the reference of 0 degree turtle takes to make turn from. i was also confused when so that (never tried turtle before). the 0 degree is the virtual line which is continuation of direction from point where forward(50) ends. so when left executes it should turn more than 180 to achieve 36 degrees and when right - less. p.s. i am not good in explaining things. From nad at acm.org Mon Feb 10 20:19:31 2014 From: nad at acm.org (Ned Deily) Date: Mon, 10 Feb 2014 17:19:31 -0800 Subject: Fwd: Newcomer Help References: <936508254.6549591.1391795689236.JavaMail.root@okbu.edu> <675340207.6922848.1392048622415.JavaMail.root@okbu.edu> Message-ID: In article <675340207.6922848.1392048622415.JavaMail.root at okbu.edu>, Walter Hughey wrote: > I am new to Python programming, actually new to any programming language. I > sent the email below to the "pythonmac-sig at python.org a few days ago. So far > I have not seen a reply, actually, I have not seen anything from pythonmac in > any emails although I am supposed to be a member. That's too bad! It may be that your email is being held for moderation on the list, especially if you haven't subscribed or are just subscribing. https://mail.python.org/mailman/listinfo/pythonmac-sig > I don't know if I am sending these to the correct place or if I am not > receiving emails from the pythonmac list. I would appreciate any assistance > either in how do I get to the pythonmac list or answers to the issue below. I > went to the pythonmac list because I am trying to run Python 3.3 on a Mac > computer. > > > Thank you, > > > Walter > ----- Original Message ----- > > From: "Walter Hughey" > To: pythonmac-sig at python.org > Sent: Friday, February 7, 2014 11:54:49 AM > Subject: Newcomer Help > > > Greetings, > I am new at Python programming, technically a newbie at writing programming > code. I have been involved in the maintenance of computers for several years > and have decided to increase my knowledge and experience. I am taking a > course that - although not a programming course - does require writing of > code. I am trying to use Python to write the code. > > > I use a Mac computer and the first issue is getting working with Python. The > computer I currently use is running Mac OS X 10.6.8, Intel Core i5 Processor, > with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have > added Python 3.3, the version our Professor recommended. I have checked out > the Python installed by Apple and can enter in code and it works, but I need > to create a file, run it, and then provide it for the Professor to grade and > I don't know how with the Apple installed version. > > > While reading about Python, I saw comments about the note concerning outdated > software: If you are using Python from a python.org 64-bit/32-bit Python > installer for Mac OS X 10.6 and later , you should only use IDLE or tkinter > with an updated third-party Tcl/Tk 8.5, like ActiveTcl 8.5 installed. > > > I located, downloaded and installed the recommended version of ActiveTcl > 8.5.15.0. When I open Idle, I see a warning that "The version of Tcl/Tk > (8.5.7) in use may be unstable." I received this warning both before and > after installing the software above. I open Idle, choose "New File" then most > often the computer will freeze, Idle does nothing, cannot enter text into the > text box, cannot close the application either with the red circle or by > selecting Idle>Close Idle. As often as that, Idle freezes as soon as I open > new file, and I cannot close without resorting to Force Quit. That should work. Just to be sure, here are the URLs for the current ActiveTcl and python.org 3.3 installers for OS X 10.6. http://downloads.activestate.com/ActiveTcl/releases/8.5.15.0/ActiveTcl8.5 .15.1.297588-macosx10.5-i386-x86_64-threaded.dmg http://www.python.org/ftp/python/3.3.4/python-3.3.4-macosx10.6.dmg Make sure you have quit IDLE before installing both. After installing, go to the /Applications/Python 3.3 folder and double-click on the IDLE icon. You should not see the "(8.5.7) may be unstable" message. As others have noted, though, you could use another editor and just run python3.3 from a Terminal window command line: /usr/local/bin/python3.3 your_filename_here.py Good luck! -- Ned Deily, nad at acm.org From geniusrko at gmail.com Mon Feb 10 21:13:16 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 18:13:16 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> Message-ID: <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> Well how about the star of david what are the angles From visiondoctor2020 at gmail.com Mon Feb 10 21:31:42 2014 From: visiondoctor2020 at gmail.com (pete suchsland) Date: Mon, 10 Feb 2014 18:31:42 -0800 (PST) Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: How about make it simple by using sorted(a.values()) ... >>> a = {} >>> a['first'] = datetime.datetime.now() >>> a['second'] = datetime.datetime.now() >>> a['third'] = datetime.datetime.now() >>> a['forth'] = datetime.datetime.now() >>> a['fifth'] = datetime.datetime.now() >>> sorted(a.values()) [datetime.datetime(2014, 2, 10, 19, 24, 35, 163585), datetime.datetime(2014, 2, 10, 19, 24, 53, 244532), datetime.datetime(2014, 2, 10, 19, 25, 9, 483683), datetime.datetime(2014, 2, 10, 19, 25, 25, 581743), datetime.datetime(2014, 2, 10, 19, 25, 37, 789907)] From hlauk.h.bogart at gmail.com Mon Feb 10 21:40:03 2014 From: hlauk.h.bogart at gmail.com (hlauk.h.bogart at gmail.com) Date: Mon, 10 Feb 2014 18:40:03 -0800 (PST) Subject: New to Py 3.3.3 having prob. with large integer div. float. Message-ID: I am coming off Python 2.6.6 32 bite platform and now in win 8.1 64 bite. I had no problems with gmpy in 2.6.6 and large integer floating points where you could control the length of the floating point by entering the bite size of the divisor(s) you are using. That would give the limit length of the float in the correct number of bites. In Python 3.3.3 and gmpy2 I have tried many things in the import mpfr module changing and trying all kinds of parameters in the gmpy2 set_context module and others. The best I can get without an error is the results of a large integer division is a/b = inf. or an integer rounded up or down. I can't seem to find the right settings for the limit of the remainders in the quotient. My old code in the first few lines of 2.6.6 worked great and looked like this - import gmpy BIG =(A large composite with 2048 bites) SML =(a smaller divisor with 1024 bites) Y= gmpy.mpz(1) A= gmpy.mpf(1) y=Y x=BIG z=SML a=A k=BIG j=BIG x=+ gmpy.next.prime(x) while y < 20: B = gmpy.mpf(x.1024) ## the above set the limit of z/b float (see below) to 1024 b=B a=z/b c=int(a) d=a-c if d = <.00000000000000000000000000000000001: proc. continues from here with desired results. gmpy2 seems a lot more complex but I am sure there is a work around. I am not interested in the mod function. My new conversion proc. is full of ## tags on the different things I tried that didn't work. TIA Dan From roegltd at gmail.com Mon Feb 10 21:49:05 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 18:49:05 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> Message-ID: On Tuesday, February 11, 2014 4:13:16 AM UTC+2, geni... at gmail.com wrote: > Well how about the star of david what are the angles hexagon is not constructed similar to your program for pentagon because crossing path can't jump from one triangle to another. you have 60 degrees turn after 2 turns edges will be concatenated. /Asaf From rosuav at gmail.com Mon Feb 10 21:51:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 13:51:17 +1100 Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: On Tue, Feb 11, 2014 at 1:31 PM, pete suchsland wrote: > How about make it simple by using sorted(a.values()) ... > >>>> a = {} >>>> a['first'] = datetime.datetime.now() >>>> a['second'] = datetime.datetime.now() >>>> a['third'] = datetime.datetime.now() >>>> a['forth'] = datetime.datetime.now() >>>> a['fifth'] = datetime.datetime.now() > >>>> sorted(a.values()) > [datetime.datetime(2014, 2, 10, 19, 24, 35, 163585), datetime.datetime(2014, 2, 10, 19, 24, 53, 244532), datetime.datetime(2014, 2, 10, 19, 25, 9, 483683), datetime.datetime(2014, 2, 10, 19, 25, 25, 581743), datetime.datetime(2014, 2, 10, 19, 25, 37, 789907)] Works nicely if you don't care about the keys. Otherwise, you need to somehow look them back up, which is at best going to add an extra O(n) step (creating a reverse dictionary), and at worst will require an O(n*n) search (if the objects aren't hashable). ChrisA From geniusrko at gmail.com Mon Feb 10 21:51:56 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 18:51:56 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> Message-ID: <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> so does that mean i have to draw two separate triangles From roegltd at gmail.com Mon Feb 10 21:56:46 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 18:56:46 -0800 (PST) Subject: Sorting dictionary by datetime value In-Reply-To: References: Message-ID: <577593ab-9ef3-4dad-a8c3-f0459baae34c@googlegroups.com> Why not use collections.OrderedDict ? There are nice examples in doc: http://docs.python.org/3.3/library/collections.html?highlight=ordered#ordereddict-examples-and-recipes From walterhurry at gmail.com Mon Feb 10 21:57:30 2014 From: walterhurry at gmail.com (Walter Hurry) Date: Tue, 11 Feb 2014 02:57:30 +0000 (UTC) Subject: What is the recommended python module for SQL database access? References: Message-ID: Chris Angelico wrote: > Broad recommendation: Single application, tiny workload, concurrency > not an issue, simplicity desired? Go SQLite. Big complex job, need > performance, lots of things reading and writing at once, want > networked access? Go PGSQL. And don't go MySQL if PG is an option. > > And definitely don't go for a non-free option (MS-SQL, DB2, etc) > unless you've looked into it really closely and you are absolutely > thoroughly *sure* that you need that system (which probably means you > need your app to integrate with someone else's, and that other app > demands one particular database). > I agree 100% with this. And speaking as an ex Oracle and DB2 DBA - not to mention MS-SQL (spit), with which I occasionally had to dabble, avoid them like the plague unless circumstances dictate. From roegltd at gmail.com Mon Feb 10 21:59:40 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 18:59:40 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> Message-ID: On Tuesday, February 11, 2014 4:51:56 AM UTC+2, geni... at gmail.com wrote: > so does that mean i have to draw two separate triangles If you need view of crossing triangles - yes, this is the simplest recipe. From geniusrko at gmail.com Mon Feb 10 22:01:33 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 19:01:33 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> Message-ID: Is there a better way of drawing such as another modules From roegltd at gmail.com Mon Feb 10 22:02:23 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 19:02:23 -0800 (PST) Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: <1faf45e1-e982-4a30-87c7-7b5940f12734@googlegroups.com> On Tuesday, February 11, 2014 4:57:30 AM UTC+2, Walter Hurry wrote: > Chris Angelico wrote: > > > > And definitely don't go for a non-free option (MS-SQL, DB2, etc) > > unless you've looked into it really closely and you are absolutely > > thoroughly *sure* that you need that system (which probably means you > > need your app to integrate with someone else's, and that other app > > demands one particular database). > > > > I agree 100% with this. And speaking as an ex Oracle and DB2 DBA - > not to mention MS-SQL (spit), with which I occasionally had to dabble, > avoid them like the plague unless circumstances dictate. What is about clustering? Do we have such option for free alternatives? Thanks From roegltd at gmail.com Mon Feb 10 22:03:43 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 19:03:43 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> Message-ID: <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> On Tuesday, February 11, 2014 5:01:33 AM UTC+2, geni... at gmail.com wrote: > Is there a better way of drawing such as another modules Could you please elaborate with question? What do you mean? From geniusrko at gmail.com Mon Feb 10 22:06:11 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 19:06:11 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> Message-ID: <97f0a5e2-4ac4-4810-921b-edcfc06feee1@googlegroups.com> A better way to draw stuff on screen From rosuav at gmail.com Mon Feb 10 22:18:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 14:18:53 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: References: Message-ID: On Tue, Feb 11, 2014 at 1:57 PM, Walter Hurry wrote: > Chris Angelico wrote: > >> Broad recommendation: Single application, tiny workload, concurrency >> not an issue, simplicity desired? Go SQLite. Big complex job, need >> performance, lots of things reading and writing at once, want >> networked access? Go PGSQL. And don't go MySQL if PG is an option. >> >> And definitely don't go for a non-free option (MS-SQL, DB2, etc) >> unless you've looked into it really closely and you are absolutely >> thoroughly *sure* that you need that system (which probably means you >> need your app to integrate with someone else's, and that other app >> demands one particular database). >> > I agree 100% with this. And speaking as an ex Oracle and DB2 DBA - not to mention MS-SQL (spit), with which I occasionally had to dabble, avoid them like the plague unless circumstances dictate. > I can't speak for Oracle as I've never used it, but DB2 is not at all a bad product. In fact, it's excellent. I'm not sorry to have spent a couple of decades using it; it's part of what taught me to assume transactions everywhere, for instance (you don't "BEGIN TRANSACTION", you simply are in one - after you COMMIT, another transaction is automatically opened (at next query, I think), so you have to explicitly COMMIT everything), and its networking support is excellent. (Also, back in the 1990s, PostgreSQL wasn't nearly as easy to use as it is now.) But it's non-free, and that makes a HUGE difference when you start deploying servers. You have to count up how many boxes you're using, and then factor in the number of test machines you have too. Licenses for your OS, database, etc, etc, all add up pretty quickly. When there are no license fees whatsoever, life's easy - I can create myself a Debian Linux VM image, install all our stuff on it, and then clone it a whole bunch of times to try different things; doing that with Windows or DB2 or anything pay-for is a lot less convenient (or even straight-up illegal, depending on the license terms). That's a pretty huge downside, and I've yet to use any pay-for database engine or operating system that outdoes that. ChrisA From roegltd at gmail.com Mon Feb 10 22:17:18 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 19:17:18 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: <97f0a5e2-4ac4-4810-921b-edcfc06feee1@googlegroups.com> References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> <97f0a5e2-4ac4-4810-921b-edcfc06feee1@googlegroups.com> Message-ID: On Tuesday, February 11, 2014 5:06:11 AM UTC+2, geni... at gmail.com wrote: > A better way to draw stuff on screen It depends on particular case/figure you wish to draw. Drawing is separate knowledge field with its own set of algorithms. Geometry is field of wonders. i never dealt with this stuff actually. From geniusrko at gmail.com Mon Feb 10 22:19:52 2014 From: geniusrko at gmail.com (geniusrko at gmail.com) Date: Mon, 10 Feb 2014 19:19:52 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> <97f0a5e2-4ac4-4810-921b-edcfc06feee1@googlegroups.com> Message-ID: Going off-topic Which resource do you recommend for learning this wonderful language From roegltd at gmail.com Mon Feb 10 22:23:12 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 19:23:12 -0800 (PST) Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> <4f29e644-f63a-4b78-9d81-eabb1554dc44@googlegroups.com> <97f0a5e2-4ac4-4810-921b-edcfc06feee1@googlegroups.com> Message-ID: On Tuesday, February 11, 2014 5:19:52 AM UTC+2, geni... at gmail.com wrote: > Going off-topic Which resource do you recommend for learning this > wonderful language My advice won't be good as mentioned before i never dealt with it. You have chance to discover that country yourself or wait for advice of others or do both at same time. From rosuav at gmail.com Mon Feb 10 22:31:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 14:31:35 +1100 Subject: What is the recommended python module for SQL database access? In-Reply-To: <1faf45e1-e982-4a30-87c7-7b5940f12734@googlegroups.com> References: <1faf45e1-e982-4a30-87c7-7b5940f12734@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 2:02 PM, Asaf Las wrote: > On Tuesday, February 11, 2014 4:57:30 AM UTC+2, Walter Hurry wrote: >> Chris Angelico wrote: >> > >> > And definitely don't go for a non-free option (MS-SQL, DB2, etc) >> > unless you've looked into it really closely and you are absolutely >> > thoroughly *sure* that you need that system (which probably means you >> > need your app to integrate with someone else's, and that other app >> > demands one particular database). >> > >> >> I agree 100% with this. And speaking as an ex Oracle and DB2 DBA - >> not to mention MS-SQL (spit), with which I occasionally had to dabble, >> avoid them like the plague unless circumstances dictate. > > What is about clustering? Do we have such option for free alternatives? > > Thanks PostgreSQL has replication in-built now, which will do most forms of clustering. With some third-party software like Slony (also free), you can do even more (including replicating between different PostgreSQL versions, so you can upgrade progressively without any downtime; PG's internal replication has tight restrictions on that). I've used PG's streaming replication to fairly good effect. You do need some kind of system to decide when to promote a slave to master, though - my boss had this weird idea that each node had to be a perfect peer with no external authority [1], which led to unsolvable problems, but if you have an external system that declares which of several slaves should be promoted, it's pretty easy to do. I could whip you up a proof-of-concept in an hour, probably; just needs a heartbeat script and some way of signalling them to fail over to the new master. Clustering for performance, as opposed to reliability, is a bit trickier. You can do read-only queries on slaves (so if you have a many-readers-few-writers model, this can work nicely), but otherwise, you probably need some third-party middleware. I haven't looked into that side of things. Ultimately your biggest bottleneck is going to be locking, which fundamentally has to be done in one place... or else you have to deal with merge conflicts (the bane of true multi-master replication). So, it all depends on what you need to accomplish, and how much work you're willing to do. Postgres offers a particular set of primitives (including replication, promotion of a slave to master, etc), and lets you trigger things from scripts (execute "pg_ctl promote" to make this node become master). Advanced logic can be done by writing a Python script that edits config files, runs programs, sends Unix signals, whatever. There are pay-for Postgres support companies, too, if you need that sort of thing. tl;dr: Yeah, you can do that too. :) ChrisA [1] He had a weird issue with the concept of authority, actually. I think his dislike of any form of government polluted his thinking so he wouldn't accept even the IT sense of the word "authority". Never mind that that's the best way to solve a lot of problems. But I digress. From roegltd at gmail.com Mon Feb 10 22:45:44 2014 From: roegltd at gmail.com (Asaf Las) Date: Mon, 10 Feb 2014 19:45:44 -0800 (PST) Subject: What is the recommended python module for SQL database access? In-Reply-To: References: <1faf45e1-e982-4a30-87c7-7b5940f12734@googlegroups.com> Message-ID: <34721440-2065-42d5-a2db-c15788708c5c@googlegroups.com> On Tuesday, February 11, 2014 5:31:35 AM UTC+2, Chris Angelico wrote: > On Tue, Feb 11, 2014 at 2:02 PM, Asaf Las wrote: > > > On Tuesday, February 11, 2014 4:57:30 AM UTC+2, Walter Hurry wrote: > >> Chris Angelico wrote: > >> > > >> > And definitely don't go for a non-free option (MS-SQL, DB2, etc) > >> > unless you've looked into it really closely and you are absolutely > >> > thoroughly *sure* that you need that system (which probably means you > >> > need your app to integrate with someone else's, and that other app > >> > demands one particular database). > >> > > >> > >> I agree 100% with this. And speaking as an ex Oracle and DB2 DBA - > >> not to mention MS-SQL (spit), with which I occasionally had to dabble, > >> avoid them like the plague unless circumstances dictate. > > > > What is about clustering? Do we have such option for free alternatives? > > > > Thanks > > PostgreSQL has replication in-built now, which will do most forms of > clustering. With some third-party software like Slony (also free), you > can do even more (including replicating between different PostgreSQL > versions, so you can upgrade progressively without any downtime; PG's > internal replication has tight restrictions on that). I've used PG's > streaming replication to fairly good effect. You do need some kind of > system to decide when to promote a slave to master, though - my boss > had this weird idea that each node had to be a perfect peer with no > external authority [1], which led to unsolvable problems, but if you > have an external system that declares which of several slaves should > be promoted, it's pretty easy to do. I could whip you up a > proof-of-concept in an hour, probably; just needs a heartbeat script > and some way of signalling them to fail over to the new master. > > Clustering for performance, as opposed to reliability, is a bit > trickier. You can do read-only queries on slaves (so if you have a > many-readers-few-writers model, this can work nicely), but otherwise, > you probably need some third-party middleware. I haven't looked into > that side of things. Ultimately your biggest bottleneck is going to be > locking, which fundamentally has to be done in one place... or else > you have to deal with merge conflicts (the bane of true multi-master > replication). > > So, it all depends on what you need to accomplish, and how much work > you're willing to do. Postgres offers a particular set of primitives > (including replication, promotion of a slave to master, etc), and lets > you trigger things from scripts (execute "pg_ctl promote" to make this > node become master). Advanced logic can be done by writing a Python > script that edits config files, runs programs, sends Unix signals, > whatever. There are pay-for Postgres support companies, too, if you > need that sort of thing. > > tl;dr: Yeah, you can do that too. :) > > ChrisA > > [1] He had a weird issue with the concept of authority, actually. I > think his dislike of any form of government polluted his thinking so > he wouldn't accept even the IT sense of the word "authority". Never > mind that that's the best way to solve a lot of problems. But I > digress. Chris, Thank You very much for your detailed answer Regards /Asaf From patil.jay2009 at gmail.com Mon Feb 10 23:07:23 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 10 Feb 2014 20:07:23 -0800 (PST) Subject: Error getting while running python function Message-ID: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> I have defined one function as below. def InfoDir(msg): msg1 = wx.MessageDialog(msg) msg1.ShowModal() msg1.Destroy() InfoDir("Testing") It gives below error. msg1 = wx.MessageDialog(msg) File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2922, in __init__ _windows_.MessageDialog_swiginit(self,_windows_.new_MessageDialog(*args, **kwargs)) TypeError: Required argument 'message' (pos 2) not found Process finished with exit code 1 Please give me solution for this. From rosuav at gmail.com Mon Feb 10 23:12:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 15:12:35 +1100 Subject: Error getting while running python function In-Reply-To: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> References: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 3:07 PM, Jaydeep Patil wrote: > I have defined one function as below. > > def InfoDir(msg): > msg1 = wx.MessageDialog(msg) > msg1.ShowModal() > msg1.Destroy() > > InfoDir("Testing") > > > It gives below error. > msg1 = wx.MessageDialog(msg) > File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2922, in __init__ > _windows_.MessageDialog_swiginit(self,_windows_.new_MessageDialog(*args, **kwargs)) > TypeError: Required argument 'message' (pos 2) not found > > Process finished with exit code 1 It looks like you're missing a required argument :) http://www.wxpython.org/docs/api/wx.MessageDialog-class.html#__init__ Try passing it a parent window as well as the message. ChrisA From wrw at mac.com Mon Feb 10 22:14:19 2014 From: wrw at mac.com (William Ray Wing) Date: Mon, 10 Feb 2014 22:14:19 -0500 Subject: Newcomer Help In-Reply-To: <675340207.6922848.1392048622415.JavaMail.root@okbu.edu> References: <675340207.6922848.1392048622415.JavaMail.root@okbu.edu> Message-ID: On Feb 10, 2014, at 11:10 AM, Walter Hughey wrote: > I am new to Python programming, actually new to any programming language. I sent the email below to the "pythonmac-sig at python.org a few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am supposed to be a member. > > I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac list because I am trying to run Python 3.3 on a Mac computer. > > Thank you, > > Walter Walter, I'm one of the (relatively few) people on this list who develops using Macs and therefore also subscribes to pythonmac-sig. I don't know what may have happened to your e-mail, but I can assure you that if you didn't get answers from the pythonmac list it wasn't because people were ignoring you. I've looked back through the last six months of pythonmac and saw nothing with your name in it. I assume you signed up here: https://mail.python.org/mailman/listinfo/pythonmac-sig if not, that would explain things. I see others are providing the help you need, so I won't attempt any other comments. -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmpython at gmail.com Mon Feb 10 23:21:11 2014 From: cmpython at gmail.com (CM) Date: Mon, 10 Feb 2014 20:21:11 -0800 (PST) Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Saturday, February 8, 2014 10:43:47 PM UTC-5, Steven D'Aprano wrote: > PyPy can generate code which is comparable to compiled C in speed. > Perhaps you mean, "if execution speed is the most important thing, using > a naive Python interpreter may not be fast enough". Given that the OP seems to be new enough to Python to not know what it is not as good for, my guess is that PyPy may not yet be "ready enough" to serve some/most of his needs. For example, if he wanted to write a GUI app, AFAIK he is, for now, limited to Tkinter and a constrained section of wxPython, and wxPython is dicey. I tend to see things through a desktop GUI application lens, so maybe this is just my bias. And I hope I am wrong. I am in no way trying to slight the PyPy efforts. Maybe he could somehow write the GUI part with CPython and the speed-critical parts with PyPy but I don't know if that is possible. (Is it?) From patil.jay2009 at gmail.com Mon Feb 10 23:26:54 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 10 Feb 2014 20:26:54 -0800 (PST) Subject: Error getting while running python function In-Reply-To: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> References: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> Message-ID: On Tuesday, 11 February 2014 09:37:23 UTC+5:30, Jaydeep Patil wrote: > I have defined one function as below. > > > > def InfoDir(msg): > > msg1 = wx.MessageDialog(msg) > > msg1.ShowModal() > > msg1.Destroy() > > > > InfoDir("Testing") > > > > > > It gives below error. > > msg1 = wx.MessageDialog(msg) > > File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2922, in __init__ > > _windows_.MessageDialog_swiginit(self,_windows_.new_MessageDialog(*args, **kwargs)) > > TypeError: Required argument 'message' (pos 2) not found > > > > Process finished with exit code 1 > > > > > > > > Please give me solution for this. Is anybody answer my query? Regards Jay From patil.jay2009 at gmail.com Mon Feb 10 23:34:48 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 10 Feb 2014 20:34:48 -0800 (PST) Subject: Error getting while running python function In-Reply-To: References: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> Message-ID: <4e284506-52f5-4bb5-bb21-caf21b7742b3@googlegroups.com> On Tuesday, 11 February 2014 09:42:35 UTC+5:30, Chris Angelico wrote: > On Tue, Feb 11, 2014 at 3:07 PM, Jaydeep Patil wrote: > > > I have defined one function as below. > > > > > > def InfoDir(msg): > > > msg1 = wx.MessageDialog(msg) > > > msg1.ShowModal() > > > msg1.Destroy() > > > > > > InfoDir("Testing") > > > > > > > > > It gives below error. > > > msg1 = wx.MessageDialog(msg) > > > File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2922, in __init__ > > > _windows_.MessageDialog_swiginit(self,_windows_.new_MessageDialog(*args, **kwargs)) > > > TypeError: Required argument 'message' (pos 2) not found > > > > > > Process finished with exit code 1 > > > > It looks like you're missing a required argument :) > > > > http://www.wxpython.org/docs/api/wx.MessageDialog-class.html#__init__ > > > > Try passing it a parent window as well as the message. > > > > ChrisA @ Chris: There is not parent window such. I just write a simple function to define. There is no class. Is it possible to work like the way i am doing? Regards Jay From tundra at tundraware.com Mon Feb 10 23:40:48 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 10 Feb 2014 22:40:48 -0600 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: Message-ID: On 02/08/2014 05:54 PM, Sam wrote: > I got to know about Python a few months ago and today, I want to develop only using Python because of its code readability. This is not a healthy bias. To play my own devil's advocate, I have a question. What are the kinds of software that are not advisable to be developed using Python? > Anything requiring strict time determinism - interrupt handlers, hard realtime, etc. Embedded software (stuff going into ROM). Virtual memory managers or any other core part of a OS that manipulates hardware. It can be done with a minimal lower language shim to the hardware, but it likely would be slooooowwwww. Life-critical (life support, weapons control, etc.) unless you're willing to strictly avoid the runtime dynamism of the language. When life and limb are at stake you want a very static language with strong type enforcement and lots of assertion checks. In principle, you can certainly do this in Python, but the language naturally encourages dynamic typing, introspection, and other, similar runtime behaviors. Applications where storage for programs is at a premium such as Atmel and PIC microcontrollers with onboard flash. Applications in which you do not want the casual reader to be able to derive the meaning of the source code. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From rosuav at gmail.com Mon Feb 10 23:59:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 15:59:40 +1100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: <52f6f973$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Feb 11, 2014 at 3:21 PM, CM wrote: > On Saturday, February 8, 2014 10:43:47 PM UTC-5, Steven D'Aprano wrote: > >> PyPy can generate code which is comparable to compiled C in speed. >> Perhaps you mean, "if execution speed is the most important thing, using >> a naive Python interpreter may not be fast enough". > > Given that the OP seems to be new enough to Python to not know what it is > not as good for, my guess is that PyPy may not yet be "ready enough" to > serve some/most of his needs. For example, if he wanted to write a GUI > app, AFAIK he is, for now, limited to Tkinter and a constrained section of > wxPython, and wxPython is dicey. I tend to see things through a desktop GUI > application lens, so maybe this is just my bias. And I hope I am wrong. I > am in no way trying to slight the PyPy efforts. > > Maybe he could somehow write the GUI part with CPython and the speed-critical > parts with PyPy but I don't know if that is possible. (Is it?) More likely, he can write the whole thing in Python, and then run it in CPython. Then see if its speed is good enough. Sometimes "good enough" means "finishes executing in less than 100ms after user interaction". Sometimes it's even more generous. Other times it's "can handle at least X requests per second on a single CPU core", where X is defined based on the number of requests that the network can handle. If it meets that requirement, there's no reason to go to any sort of effort to improve performance. And that's how it is for huge HUGE numbers of Python scripts. Of course, if performance _is_ a problem, then the next step is to measure and find out exactly what's the slow bit. It's seldom what you first think of. ChrisA From rosuav at gmail.com Tue Feb 11 00:01:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Feb 2014 16:01:16 +1100 Subject: Error getting while running python function In-Reply-To: <4e284506-52f5-4bb5-bb21-caf21b7742b3@googlegroups.com> References: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> <4e284506-52f5-4bb5-bb21-caf21b7742b3@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 3:34 PM, Jaydeep Patil wrote: > There is not parent window such. I just write a simple function to define. > There is no class. > Is it possible to work like the way i am doing? You could try reading the docs; there might be a way to say "no parent window" (maybe pass it None), but you can't simply omit parameters. Start with the docs. They're friendly. ChrisA From steve at pearwood.info Tue Feb 11 00:20:28 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 11 Feb 2014 05:20:28 GMT Subject: Sort one sequence by O(n) in time and O(1) in space References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> Message-ID: <52f9b31c$0$11128$c3e8da3@news.astraweb.com> On Mon, 10 Feb 2014 10:20:33 +0000, Sturla Molden wrote: > Wesley wrote: >> [Wesley] This is not homework:-) >> And actually I am new to algorithm, so you guys can feel free to say >> anything you want > > In general, we cannot sort a sequence in O(n) time. O(n log n) is the > lower bound on the complexity. Firstly, you're talking about average complexity, not best-case complexity. The base-case can be O(N) for a sequence which is already sorted. Worst case can be much greater, e.g. O(N**2) for Quicksort, or unbounded for Bogosort. (That is, Bogosort is not guaranteed to sort a sequence even after infinite time!) Secondly, O(N*log N) applies to *comparison sorts*. Non-comparison sorts such as radix-, counting- and bucket-sort have average case complexity of O(N). See, for example: http://algorithmstwo.soc.srcf.net/resources/asides/noncomparison/ http://en.wikipedia.org/wiki/Bead_sort http://en.wikipedia.org/wiki/Radix_sort http://en.wikipedia.org/wiki/Spaghetti_sort etc. -- Steven From tundra at tundraware.com Tue Feb 11 00:37:26 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 10 Feb 2014 23:37:26 -0600 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> Message-ID: <52F9B716.2060404@tundraware.com> On 02/10/2014 04:20 AM, Sturla Molden wrote: > In general, we cannot sort a sequence in O(n) time. O(n log n) is the lower > bound on the complexity. Only true for sorting that involve comparison. However, sorts that use the values of the inputs as positional keys have a lower bound complexity (omega) of O(n) and a worst case complexity of O(n) and are thus asymptotically optimal. For example, given a range of integers guaranteed to be within the range of j to k (lower to higher), one can created a bit field to represent all possible values of j to k. Then, as values are read in, the corresponding but is set true. You have to process the list of n elements once to read it in, and then a second time to read them out in order. This is a 2n operation which is O(n). For very large ranges of j to k, this is impractical and we resort to things like hashing functions which can perform better than n log n sorting algorithms. But there are lots of real world applications where inputs-as-keys works just fine, such as short dispatch tables in operating systems where the value to be sorted represents a process priority, for example. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From steve at pearwood.info Tue Feb 11 00:35:44 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 11 Feb 2014 05:35:44 GMT Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: <52f9b6af$0$11128$c3e8da3@news.astraweb.com> On Mon, 10 Feb 2014 22:40:48 -0600, Tim Daneliuk wrote: > On 02/08/2014 05:54 PM, Sam wrote: >> I got to know about Python a few months ago and today, I want to >> develop only using Python because of its code readability. This is not >> a healthy bias. To play my own devil's advocate, I have a question. >> What are the kinds of software that are not advisable to be developed >> using Python? [snip a bunch of good examples] > Applications in which you do not want the casual reader to be able to > derive the meaning of the source code. That's a bad example. Do you think that the casual reader will be able to understand the meaning of .pyc files? -- Steven From ikorot01 at gmail.com Tue Feb 11 00:42:16 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Mon, 10 Feb 2014 21:42:16 -0800 Subject: Get a datetime with nanoseconds Message-ID: Hi, ALL, I am woking on an application for digital forensic. In this application I am getting this 2 pieces of information: atime - long representing the time stamp atime_nano - long representing the nanoseconds. What I'd like to do is to have a python datetime object which will be a representation of those 2 values. I can get a datetime object out of atime timestamp, but I don't know how to do it for atime_nano. I did a little research. It looks like people on SO are saying that I will not be able to get this kind of precision, but I'd be grateful if I can at least get the best possible precision (millioseconds?) it would be great. Thank you for any pointers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tundra at tundraware.com Tue Feb 11 00:37:26 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 10 Feb 2014 23:37:26 -0600 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> Message-ID: <52F9B716.2060404@tundraware.com> On 02/10/2014 04:20 AM, Sturla Molden wrote: > In general, we cannot sort a sequence in O(n) time. O(n log n) is the lower > bound on the complexity. Only true for sorting that involve comparison. However, sorts that use the values of the inputs as positional keys have a lower bound complexity (omega) of O(n) and a worst case complexity of O(n) and are thus asymptotically optimal. For example, given a range of integers guaranteed to be within the range of j to k (lower to higher), one can created a bit field to represent all possible values of j to k. Then, as values are read in, the corresponding but is set true. You have to process the list of n elements once to read it in, and then a second time to read them out in order. This is a 2n operation which is O(n). For very large ranges of j to k, this is impractical and we resort to things like hashing functions which can perform better than n log n sorting algorithms. But there are lots of real world applications where inputs-as-keys works just fine, such as short dispatch tables in operating systems where the value to be sorted represents a process priority, for example. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From tundra at tundraware.com Tue Feb 11 00:50:01 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 10 Feb 2014 23:50:01 -0600 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: <52f9b6af$0$11128$c3e8da3@news.astraweb.com> References: <52f9b6af$0$11128$c3e8da3@news.astraweb.com> Message-ID: <52F9BA09.5060303@tundraware.com> On 02/10/2014 11:35 PM, Steven D'Aprano wrote: > On Mon, 10 Feb 2014 22:40:48 -0600, Tim Daneliuk wrote: > >> On 02/08/2014 05:54 PM, Sam wrote: >>> I got to know about Python a few months ago and today, I want to >>> develop only using Python because of its code readability. This is not >>> a healthy bias. To play my own devil's advocate, I have a question. >>> What are the kinds of software that are not advisable to be developed >>> using Python? > > [snip a bunch of good examples] > >> Applications in which you do not want the casual reader to be able to >> derive the meaning of the source code. > > That's a bad example. Do you think that the casual reader will be able to > understand the meaning of .pyc files? > > Point taken :) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From boedy.bios at gmail.com Tue Feb 11 00:55:03 2014 From: boedy.bios at gmail.com (Setia Budi) Date: Mon, 10 Feb 2014 21:55:03 -0800 (PST) Subject: Send commands to USB device in Python Message-ID: <74d95ce4-cd83-43d4-aa09-c0cb417a3431@googlegroups.com> Hi fellows, I am facing difficulties in order to send USB commands to an RFID reader. This is the command reference of the device: https://github.com/mti-rfid/RFID_Explorer I am working with the MTI RU-824 model. The manufacturer of the device only provide a driver for Windows (using .Net), but we need to run the device on Linux. That's why I need to write few lines of code in Python as a new "driver". I am using PyUSB for accessing the device, and this is few lines of my code: ============================================================================ import usb.core import usb.util import sys VENDOR_ID = 0x24e9 PRODUCT_ID = 0x0824 device = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID) if device is None: sys.exit("Could not find Id System Barcode Reader.") else: print 'Device detected' device.set_configuration() cfg = device.get_active_configuration() interface_number = cfg[(0, 0)].bInterfaceNumber alternate_setting = usb.control.get_interface(device, interface_number) usb_interface = usb.util.find_descriptor( cfg, bInterfaceNumber=interface_number, bAlternateSetting=alternate_setting ) endpoint_out = usb.util.find_descriptor( usb_interface, # match the first OUT endpoint custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT ) endpoint_in = usb.util.find_descriptor( usb_interface, # match the first IN endpoint custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN ) endpoint_out.write('0x01') print endpoint_in.read(len('0x01'), 1000) ============================================================================= My question is on the last 2 lines. I am using endpoint_out to send a command and endpoint_in to read data from the reader. Am I correct? The problem is, when I run the code, there is an error message like this: usb.core.USBError: [Errno 110] Operation timed out Anyone can give a clue? Thank you. From steve at pearwood.info Tue Feb 11 01:30:43 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 11 Feb 2014 06:30:43 GMT Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> Message-ID: <52f9c392$0$11128$c3e8da3@news.astraweb.com> On Mon, 10 Feb 2014 10:45:40 -0800, Rick Johnson wrote: > ## START CODE ########################################### > def foo(): > # foo represents a patternless function Patternless? I have never heard that term before in this context. Do you mean a parameter-less or argument-less function? > # or method that returns a Boolean value > # based on some internal test. > # > if 1==1: > return True > return False This always returns True, since 1 always equals 1. > # The fun begins when two tiny chars are forgotten, > # however, since the code is legal, python will happily > # give us the wrong answer. > # > if foo: # <- forgot parenthesis! > print 'implicit conversion to bool bites!' No it doesn't. It rocks. You have found one tiny little disadvantage, about the size of a mote of dust floating: if you write functions that take no arguments (already a code-smell) and forget the brackets (mistakes will happen...) and have no tests to ensure that both branches of the `if` are tested (what, are you careless and negligent?), then you might be bitten by a bug of your own creation. Compared to that mote, the usefulness and convenience of duck-typing bools is about the size of Mt Everest. > else: > # > # This block will NEVER execute because foo is > # ALWAYS True! Correct. And since foo() is also always True, there is no difference. [...] > It's obvious i did not follow the syntactical rules of Python, i > understand that, No you don't understand that. You *did* follow the syntactical rules of Python. `if foo` is perfectly correct syntax, if it were not, you would have got a SyntaxError exception at compile-time. You need to understand the difference between syntax and semantics. This is invalid English syntax: "Cat mat on sat the." This is valid syntax, but semantically wrong: "The mat sat on the cat." This is both syntactically and semantically correct: "The cat sat on the mat." > however, there are three design flaws here that are > contributing to this dilemma: > > 1. Implicit conversion to Boolean is evil It's not implicit conversion. You're not understanding what is going on. foo is not converted to a bool, foo remains a function object. Rather, it's duck-typing truthiness, which is no different from any other duck- typing. If it swims like a bool and quacks like a bool, it might as well be a bool. Duck-typing is a design feature, not a flaw. > 2. Conditionals should never accept parameter-less functions. How is the conditional supposed to know that its term is a function? What's so special about parameter-less functions? You can forget to call functions with any number of parameters, especially if they take default values. Let's suppose that you get your way. Which of the following if-tests should be prohibited, and when should they be prohibited? At compile time? if random.random() > 0.5: spam = lambda x=23: x eggs = 42 else: spam = 42 eggs = lambda x=23: x if spam: print "spam is a truthy value" if eggs: print "eggs is a truthy value" > If you > want to check if a callable is True or False, then use "if > bool(callable)". Ewww. That's horrible. bool() should only be used to get a canonical bool object, e.g. for writing to a database or something. It should never be used just because you are scared of Python's power. > Any usage of a bare callable in conditionals should > raise SyntaxError. Ah, so it should happen at compile-time, not run-time? I'm afraid you're not as clear about how Python operates as you perhaps think you are. > 3. Implicit introspection is evil, i prefer all references to a > callable's names to result in a CALL to that callable, not an > introspection! Introspection should ALWAYS be explicit! Again, this is a complete misunderstanding of Python's execution model. It is true that callables have names, but they are only used for displaying error messages in tracebacks. Otherwise, callables are no different from any other object: they can have zero, one or many names bound to them, and referring to the name gives you access to the object itself. spam = spam # this is a reference to the object Introspection has nothing to do with this. > For a long time i thought Python's idea of a returning the value of a > callable-- who's name is unadorned with "(...)" --was a good idea, > however, i am now wholly convinced that this design is folly, Oh well, not everyone has the sense to recognise good design. You should do more Python programming, and less ranting, you might learn something. > and the > reason is two fold: > > 1. Parenthesis should not be required for parameter- less functions. Of course they should. Firstly, parameter-less functions are a code- smell, and ought to be discouraged. Secondly, even if you have a good reason for using one -- for example, random.random -- then the difference between referring to the object and calling the object should be clear. With Python's correct design, we have: spam # always, without exception, refers to the object spam() # always, without exception, calls the object With your suggested design, we would have: spam # sometimes refers to the object, sometimes calls the object spam() # always calls the object Ruby makes this mistake, and is a lessor language for it. > I realize this is a bit more complicated in languages like Python > where attributes are exposed to the public, but still, not reason > enough to require such onerous typing. What does the presence or absence of attributes have to do with this? > 2. Implicit introspection is evil. I would prefer an explicit method > attached to all callables over a sugar for "callable.call". We > should never consume syntactical sugars UNLESS they can greatly > reduce the density of code (like math operators for instance!) I do not understand what you are trying to say here. -- Steven From casevh at gmail.com Tue Feb 11 02:24:01 2014 From: casevh at gmail.com (casevh at gmail.com) Date: Mon, 10 Feb 2014 23:24:01 -0800 (PST) Subject: New to Py 3.3.3 having prob. with large integer div. float. In-Reply-To: References: Message-ID: On Monday, February 10, 2014 6:40:03 PM UTC-8, hlauk.h... at gmail.com wrote: > I am coming off Python 2.6.6 32 bite platform and now in win 8.1 64 bite. > I had no problems with gmpy in 2.6.6 and large integer floating points where > you could control the length of the floating point by entering the bite size > of the divisor(s) you are using. That would give the limit length of the float > in the correct number of bites. > > In Python 3.3.3 and gmpy2 I have tried many things in the import mpfr module > changing and trying all kinds of parameters in the gmpy2 set_context module > and others. > > The best I can get without an error is the results of a large integer > division is a/b = inf. or an integer rounded up or down. > I can't seem to find the right settings for the limit of the remainders in the > quotient. > > My old code in the first few lines of 2.6.6 worked great and looked like this - > > import gmpy > > BIG =(A large composite with 2048 bites) > SML =(a smaller divisor with 1024 bites) > > Y= gmpy.mpz(1) > A= gmpy.mpf(1) > > y=Y > > x=BIG > z=SML > a=A > k=BIG > j=BIG > x=+ gmpy.next.prime(x) > > while y < 20: > B = gmpy.mpf(x.1024) > ## the above set the limit of z/b float (see below) to 1024 > b=B > a=z/b > c=int(a) > d=a-c > if d = <.00000000000000000000000000000000001: > proc. continues from here with desired results. > > gmpy2 seems a lot more complex but I am sure there is a work around. > I am not interested in the mod function. > > My new conversion proc. is full of ## tags on the different things > I tried that didn't work. > > TIA > Dan The following example will divide two integers with a result precision of 1024 bits: import gmpy2 # Set mpfr precision to 1024 gmpy2.get_context().precision=1024 # Omitting code.... a = gmpy2.mpz(SML)/gmpy2.mpz(x) Python 3.x performs true division by default. When integer division involves an mpz, the result will be an mpfr with the precision of the current context. Does this help? casevh From larry at hastings.org Tue Feb 11 02:43:15 2014 From: larry at hastings.org (Larry Hastings) Date: Mon, 10 Feb 2014 23:43:15 -0800 Subject: [RELEASED] Python 3.4.0 release candidate 1 Message-ID: <52F9D493.6090100@hastings.org> On behalf of the Python development team, I'm delighted to announce the first release candidate of Python 3.4. This is a preview release, and its use is not recommended for production settings. Python 3.4 includes a range of improvements of the 3.x series, including hundreds of small improvements and bug fixes. Major new features and changes in the 3.4 release series include: * PEP 428, a "pathlib" module providing object-oriented filesystem paths * PEP 435, a standardized "enum" module * PEP 436, a build enhancement that will help generate introspection information for builtins * PEP 442, improved semantics for object finalization * PEP 443, adding single-dispatch generic functions to the standard library * PEP 445, a new C API for implementing custom memory allocators * PEP 446, changing file descriptors to not be inherited by default in subprocesses * PEP 450, a new "statistics" module * PEP 451, standardizing module metadata for Python's module import system * PEP 453, a bundled installer for the *pip* package manager * PEP 454, a new "tracemalloc" module for tracing Python memory allocations * PEP 456, a new hash algorithm for Python strings and binary data * PEP 3154, a new and improved protocol for pickled objects * PEP 3156, a new "asyncio" module, a new framework for asynchronous I/O Python 3.4 is now in "feature freeze", meaning that no new features will be added. The final release is projected for mid-March 2014. To download Python 3.4.0rc1 visit: http://www.python.org/download/releases/3.4.0/ Please consider trying Python 3.4.0rc1 with your code and reporting any new issues you notice to: http://bugs.python.org/ Enjoy! -- Larry Hastings, Release Manager larry at hastings.org (on behalf of the entire python-dev team and 3.4's contributors) From pconnell at gmail.com Tue Feb 11 03:12:08 2014 From: pconnell at gmail.com (Phil Connell) Date: Tue, 11 Feb 2014 08:12:08 +0000 Subject: Using asyncio for serial port In-Reply-To: References: Message-ID: On 8 Feb 2014 23:45, wrote: > > > Hiya > > I'm looking at using asyncio for creating an socket <-> serial protocol bridge, but looking at the current implementation of asyncio it looks to be quite socket specific. > > I can't see any way to get it to support a simple serial device. > > Any advice on where to proceed would be very much appreciated! You might have more luck on the python-tulip list/group. Asyncio is still very new for most people :) Cheers, Phil > > Thanks! > > James > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Feb 11 04:35:50 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 04:35:50 -0500 Subject: Drawing polygons in python turtle In-Reply-To: References: <4fa08222-582c-4585-b945-e67468c66f6d@googlegroups.com> <0c7e98b6-b3db-472e-ac6b-73a8010a7892@googlegroups.com> <97ec9cf6-ec3c-4bdc-9b9b-23e4a0025eb0@googlegroups.com> <9ada3f87-6e4f-4b4e-8dc0-b954af46284e@googlegroups.com> Message-ID: On 2/10/2014 10:01 PM, geniusrko at gmail.com wrote: > Is there a better way of drawing such as another modules Logo is a drawing language designed for kids who do not know geometry but can imagine walking around on a dirt field and occasionally turning while dragging a stick or dripping paint. Part of the charm is discovering the patterns that emerge when simple actions are repeated. The Python version, turtle, is built on top of tkinter and its Canvas widget. Since I *do* know coordinate geometry and don't care about the moving animal metaphor, I find it easier to use Canvas directly. This avoids the bugs and limitations (including speed) introduced by the turtle module. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Tue Feb 11 04:59:55 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 09:59:55 +0000 Subject: Error getting while running python function In-Reply-To: References: <6e857925-8571-438b-84a6-bf53a3488037@googlegroups.com> Message-ID: On 11/02/2014 04:26, Jaydeep Patil wrote: > On Tuesday, 11 February 2014 09:37:23 UTC+5:30, Jaydeep Patil wrote: >> I have defined one function as below. >> >> >> >> def InfoDir(msg): >> >> msg1 = wx.MessageDialog(msg) >> >> msg1.ShowModal() >> >> msg1.Destroy() >> >> >> >> InfoDir("Testing") >> >> >> >> >> >> It gives below error. >> >> msg1 = wx.MessageDialog(msg) >> >> File "C:\Python27\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2922, in __init__ >> >> _windows_.MessageDialog_swiginit(self,_windows_.new_MessageDialog(*args, **kwargs)) >> >> TypeError: Required argument 'message' (pos 2) not found >> >> >> >> Process finished with exit code 1 >> >> >> >> >> >> >> >> Please give me solution for this. > > > > Is anybody answer my query? > > Regards > Jay > Come on you lot, pull your bloody fingers out, I've been waiting for NINETEEN minutes!!! Would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing above, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From tjreedy at udel.edu Tue Feb 11 05:13:14 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 05:13:14 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: <52F9D493.6090100@hastings.org> References: <52F9D493.6090100@hastings.org> Message-ID: On 2/11/2014 2:43 AM, Larry Hastings wrote: > > On behalf of the Python development team, I'm delighted to announce > the first release candidate of Python 3.4. > To download Python 3.4.0rc1 visit: > > http://www.python.org/download/releases/3.4.0/ I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in repair mode and again, no problem. With 64 bit 3.4.0, I get "There is a problem with this Windows Installer package. A program required for the install to complete could not be run." No, the generic message does not bother to say *which* program :-(. 34 bit 3.4.0 installed fine. I redownloaded 64bit 3.4.0 and install gives the same message. Can someone verify that this is not some bizarre glitch on my machine? If it is not, Windows users should download the 32 bit binary for now. Someone should remove the link to the installer that does not work. A followup should be posted when it is replaced. -- Terry Jan Reedy From victor.stinner at gmail.com Tue Feb 11 05:16:29 2014 From: victor.stinner at gmail.com (Victor Stinner) Date: Tue, 11 Feb 2014 11:16:29 +0100 Subject: [Python-Dev] [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: <52F9D493.6090100@hastings.org> References: <52F9D493.6090100@hastings.org> Message-ID: Hi, It would be nice to give also the link to the whole changelog in your emails and on the website: http://docs.python.org/3.4/whatsnew/changelog.html Congrats for your RC1 release :-) It's always hard to make developers stop addings "new minor" changes before the final version :-) Victor 2014-02-11 8:43 GMT+01:00 Larry Hastings : > > On behalf of the Python development team, I'm delighted to announce > the first release candidate of Python 3.4. > > This is a preview release, and its use is not recommended for > production settings. > > Python 3.4 includes a range of improvements of the 3.x series, including > hundreds of small improvements and bug fixes. Major new features and > changes in the 3.4 release series include: > > * PEP 428, a "pathlib" module providing object-oriented filesystem paths > * PEP 435, a standardized "enum" module > * PEP 436, a build enhancement that will help generate introspection > information for builtins > * PEP 442, improved semantics for object finalization > * PEP 443, adding single-dispatch generic functions to the standard library > * PEP 445, a new C API for implementing custom memory allocators > * PEP 446, changing file descriptors to not be inherited by default > in subprocesses > * PEP 450, a new "statistics" module > * PEP 451, standardizing module metadata for Python's module import system > * PEP 453, a bundled installer for the *pip* package manager > * PEP 454, a new "tracemalloc" module for tracing Python memory allocations > * PEP 456, a new hash algorithm for Python strings and binary data > * PEP 3154, a new and improved protocol for pickled objects > * PEP 3156, a new "asyncio" module, a new framework for asynchronous I/O > > Python 3.4 is now in "feature freeze", meaning that no new features will be > added. The final release is projected for mid-March 2014. > > > To download Python 3.4.0rc1 visit: > > http://www.python.org/download/releases/3.4.0/ > > > Please consider trying Python 3.4.0rc1 with your code and reporting any > new issues you notice to: > > http://bugs.python.org/ > > > Enjoy! > > -- > Larry Hastings, Release Manager > larry at hastings.org > (on behalf of the entire python-dev team and 3.4's contributors) > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > https://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > https://mail.python.org/mailman/options/python-dev/victor.stinner%40gmail.com From tjreedy at udel.edu Tue Feb 11 05:45:04 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 05:45:04 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: On 2/11/2014 5:13 AM, Terry Reedy wrote: > On 2/11/2014 2:43 AM, Larry Hastings wrote: >> >> On behalf of the Python development team, I'm delighted to announce >> the first release candidate of Python 3.4. > >> To download Python 3.4.0rc1 visit: >> >> http://www.python.org/download/releases/3.4.0/ > > I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in > repair mode and again, no problem. > > With 64 bit 3.4.0, I get > "There is a problem with this Windows Installer package. A program > required for the install to complete could not be run." > > No, the generic message does not bother to say *which* program :-(. > > 34 bit 3.4.0 installed fine. I wrote too soon. Python 3.4.0rc1 (v3.4.0rc1:5e088cea8660, Feb 11 2014, 05:54:25) [MSC >>> import tkinter Traceback ... import _tkinter ImportError: DLL load failed: %1 is not a valid Win32 application. So tkinter, Idle, turtle fail and the corresponding tests get skipped. -- Terry Jan Reedy From vlastimil.brom at gmail.com Tue Feb 11 06:11:06 2014 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 11 Feb 2014 12:11:06 +0100 Subject: Get a datetime with nanoseconds In-Reply-To: References: Message-ID: 2014-02-11 6:42 GMT+01:00 Igor Korot : > Hi, ALL, > I am woking on an application for digital forensic. > In this application I am getting this 2 pieces of information: > > atime - long representing the time stamp > atime_nano - long representing the nanoseconds. > > What I'd like to do is to have a python datetime object which will be a > representation of those 2 values. > I can get a datetime object out of atime timestamp, but I don't know how to > do it for atime_nano. > > I did a little research. It looks like people on SO are saying that I will > not be able to get this kind of precision, but I'd be grateful if I can at > least get the best possible precision (millioseconds?) it would be great. > > Thank you for any pointers. > > -- > https://mail.python.org/mailman/listinfo/python-list > Hi, it seems, datetime has support for microseconds datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) http://docs.python.org/3.3/library/datetime.html#datetime.datetime I haven't done anything using this precision, but I guess, microseconds could be used out of the box; for some higher precision, you'd probably need to code your own datatype. hth, vbr From davea at davea.name Tue Feb 11 06:36:20 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Feb 2014 06:36:20 -0500 (EST) Subject: Get a datetime with nanoseconds References: Message-ID: Igor Korot Wrote in message: > Construct a datetime. timedelta object, and add it to your datetime. mytime += datetime. timedelta (microseconds=nano//1000) -- DaveA From roegltd at gmail.com Tue Feb 11 06:57:17 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 11 Feb 2014 03:57:17 -0800 (PST) Subject: Get a datetime with nanoseconds In-Reply-To: References: Message-ID: On Tuesday, February 11, 2014 7:42:16 AM UTC+2, Igor Korot wrote: > Hi, ALL, > > I am woking on an application for digital forensic. > > In this application I am getting this 2 pieces of information: > > ? > > atime - long representing the time stamp > > atime_nano - long representing the nanoseconds. > > ? > > What I'd like to do is to have a python datetime object which will be a representation of those 2 values. > > I can get a datetime object out of atime timestamp, but I don't know > how to do it for atime_nano. > > I did a little research. It looks like people on SO are saying > that I will not be able to get this kind of precision, but I'd > be grateful if I can at least get the best possible precision > (millioseconds?) it would be great. > > Thank you for any pointers. i think you mix 2 issues here: - get date time for specific point in time from system with nanosecond precision. If i am wrong then to what "SO are saying that I will not be able to get this kind of precision" is related? - and how to have datetime to support nanosecond. That should be straightforward and isn't hard. You should implement class having datetime class instance stored and another member for nanosecond portion. Yet implement datetime operators and members to mimic all of that in original class. /Asaf From drobinow at gmail.com Tue Feb 11 08:06:53 2014 From: drobinow at gmail.com (David Robinow) Date: Tue, 11 Feb 2014 08:06:53 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: On Tue, Feb 11, 2014 at 5:45 AM, Terry Reedy wrote: > On 2/11/2014 5:13 AM, Terry Reedy wrote: >> ... >> I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in >> repair mode and again, no problem. >> >> With 64 bit 3.4.0, I get >> "There is a problem with this Windows Installer package. A program >> required for the install to complete could not be run." >> >> No, the generic message does not bother to say *which* program :-(. >> >> 34 bit 3.4.0 installed fine. > > > I wrote too soon. > > Python 3.4.0rc1 (v3.4.0rc1:5e088cea8660, Feb 11 2014, 05:54:25) [MSC >>>> import tkinter > Traceback ... > import _tkinter > ImportError: DLL load failed: %1 is not a valid Win32 application. > > So tkinter, Idle, turtle fail and the corresponding tests get skipped. 32 bit and 64 bit both work for me. Windows 7. From python at mrabarnett.plus.com Tue Feb 11 08:18:27 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 11 Feb 2014 13:18:27 +0000 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: <52FA2323.8060404@mrabarnett.plus.com> On 2014-02-11 13:06, David Robinow wrote: > On Tue, Feb 11, 2014 at 5:45 AM, Terry Reedy wrote: >> On 2/11/2014 5:13 AM, Terry Reedy wrote: >>> ... >>> I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in >>> repair mode and again, no problem. >>> >>> With 64 bit 3.4.0, I get >>> "There is a problem with this Windows Installer package. A program >>> required for the install to complete could not be run." >>> >>> No, the generic message does not bother to say *which* program :-(. >>> >>> 34 bit 3.4.0 installed fine. >> >> >> I wrote too soon. >> >> Python 3.4.0rc1 (v3.4.0rc1:5e088cea8660, Feb 11 2014, 05:54:25) [MSC >>>>> import tkinter >> Traceback ... >> import _tkinter >> ImportError: DLL load failed: %1 is not a valid Win32 application. >> >> So tkinter, Idle, turtle fail and the corresponding tests get skipped. > 32 bit and 64 bit both work for me. Windows 7. > Also works for me. Windows 8.1 64-bit. From breamoreboy at yahoo.co.uk Tue Feb 11 09:10:32 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 14:10:32 +0000 Subject: pip3.x error using LIST instead of list Message-ID: As the subject line says, details below. c:\Python34\Scripts>pip3.4 LIST Traceback (most recent call last): File "C:\Python34\lib\runpy.py", line 189, in _run_module_as_main "__main__", mod_spec) File "C:\Python34\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "c:\Python34\Scripts\pip3.4.exe\__main__.py", line 9, in File "C:\Python34\lib\site-packages\pip\__init__.py", line 177, in main cmd_name, cmd_args = parseopts(initial_args) File "C:\Python34\lib\site-packages\pip\__init__.py", line 156, in parseopts cmd_args.remove(args_else[0].lower()) ValueError: list.remove(x): x not in list Is this a known problem, should I raise a bug against pip, what is the best course of action? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rosuav at gmail.com Tue Feb 11 09:22:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 01:22:29 +1100 Subject: pip3.x error using LIST instead of list In-Reply-To: References: Message-ID: On Wed, Feb 12, 2014 at 1:10 AM, Mark Lawrence wrote: > File "C:\Python34\lib\site-packages\pip\__init__.py", line 156, in > parseopts > cmd_args.remove(args_else[0].lower()) > ValueError: list.remove(x): x not in list > > Is this a known problem, should I raise a bug against pip, what is the best > course of action? Hmm, yep. I'd confirm that as a bug. Inspection of the surrounding code suggests that it shouldn't be lowercasing there (a couple of lines above, it fetches out args_else[0].lower(), but to remove it from cmd_args, it should use original case). Search the tracker for it, to see if it already exists; if not, create it. You have the file name and line number, so you could probably even make a patch :) ChrisA From roy at panix.com Tue Feb 11 09:24:05 2014 From: roy at panix.com (Roy Smith) Date: Tue, 11 Feb 2014 09:24:05 -0500 Subject: What are the kinds of software that are not advisable to be developed using Python? References: <52f9b6af$0$11128$c3e8da3@news.astraweb.com> Message-ID: In article <52f9b6af$0$11128$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Mon, 10 Feb 2014 22:40:48 -0600, Tim Daneliuk wrote: > > > On 02/08/2014 05:54 PM, Sam wrote: > >> I got to know about Python a few months ago and today, I want to > >> develop only using Python because of its code readability. This is not > >> a healthy bias. To play my own devil's advocate, I have a question. > >> What are the kinds of software that are not advisable to be developed > >> using Python? > > [snip a bunch of good examples] > > > Applications in which you do not want the casual reader to be able to > > derive the meaning of the source code. > > That's a bad example. Do you think that the casual reader will be able to > understand the meaning of .pyc files? No, but anybody with script-kiddie level sophistication can download a pyc decompiler and get back a pretty good representation of what the source was. Whether I mind shipping my source, or you mind shipping your source isn't really what matters here. What matters is that there *are* people/companies who don't want to expose their source. Perhaps for reasons we don't agree with. For those people, Python is not a good choice. From mailman at hanez.org Tue Feb 11 09:27:30 2014 From: mailman at hanez.org (Johannes Findeisen) Date: Tue, 11 Feb 2014 15:27:30 +0100 Subject: pip3.x error using LIST instead of list In-Reply-To: References: Message-ID: <20140211152730.3b99d350@hanez.org> On Tue, 11 Feb 2014 14:10:32 +0000 Mark Lawrence wrote: > As the subject line says, details below. > > c:\Python34\Scripts>pip3.4 LIST > Traceback (most recent call last): > File "C:\Python34\lib\runpy.py", line 189, in _run_module_as_main > "__main__", mod_spec) > File "C:\Python34\lib\runpy.py", line 87, in _run_code > exec(code, run_globals) > File "c:\Python34\Scripts\pip3.4.exe\__main__.py", line 9, in > File "C:\Python34\lib\site-packages\pip\__init__.py", line 177, in main > cmd_name, cmd_args = parseopts(initial_args) > File "C:\Python34\lib\site-packages\pip\__init__.py", line 156, in > parseopts > cmd_args.remove(args_else[0].lower()) > ValueError: list.remove(x): x not in list > > Is this a known problem, should I raise a bug against pip, what is the > best course of action? Hi, I get the same error with an older release of pip. But, I get that error regardless which uppercase argument I am passing to pip. Look below: hanez at phantom ~ % pip LIST Traceback (most recent call last): File "/usr/lib/python-exec/python2.7/pip", line 9, in load_entry_point('pip==1.5.2', 'console_scripts', 'pip')() File "/usr/lib64/python2.7/site-packages/pip/__init__.py", line 177, in main cmd_name, cmd_args = parseopts(initial_args) File "/usr/lib64/python2.7/site-packages/pip/__init__.py", line 156, in parseopts cmd_args.remove(args_else[0].lower()) ValueError: list.remove(x): x not in list hanez at phantom ~ % pip FOO Traceback (most recent call last): File "/usr/lib/python-exec/python2.7/pip", line 9, in load_entry_point('pip==1.5.2', 'console_scripts', 'pip')() File "/usr/lib64/python2.7/site-packages/pip/__init__.py", line 177, in main cmd_name, cmd_args = parseopts(initial_args) File "/usr/lib64/python2.7/site-packages/pip/__init__.py", line 156, in parseopts cmd_args.remove(args_else[0].lower()) ValueError: list.remove(x): x not in list hanez at phantom ~ % pip foo ERROR: unknown command "foo" hanez at phantom ~ % pip --version pip 1.5.2 from /usr/lib64/python2.7/site-packages (python 2.7) hanez at phantom ~ % From neilc at norwich.edu Tue Feb 11 09:29:22 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Tue, 11 Feb 2014 14:29:22 +0000 (UTC) Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <20140210084308.7727c0fd@bigbox.christie.dr> Message-ID: On 2014-02-10, Ned Batchelder wrote: > On 2/10/14 9:43 AM, Tim Chase wrote: >>> The opposite of what the utf8/utf16 do! >>> >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >>>>>> '\U00010000').encode('utf-8')) >>> 1000023 >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >>>>>> '\U00010000').encode('utf-16')) >>> 2000025 >> >> However, as pointed out repeatedly, string-indexing in >> fixed-width encodings are O(1) while indexing into >> variable-width encodings (e.g. UTF8/UTF16) are O(N). The FSR >> gives the benefits of O(1) indexing while saving space when a >> string doesn't need to use a full 32-bit width. > > Please don't engage in this debate with JMF. His mind is made > up, and he will not be swayed, no matter how persuasive and > reasonable your arguments. Just ignore him. I think reasonable criticisms should be contested no matter who posts them. I agree jmf shouldn't be singled out for abuse, summoned, insulted, or have his few controversial opinions brought into other topics. Tim's post was responding to a specific, well-presented criticism of Python's string implementation. Left unchallenged, it might linger unhappily in the air, like a symphony ended on a dominant 7th chord. -- Neil Cerutti From rosuav at gmail.com Tue Feb 11 09:37:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 01:37:36 +1100 Subject: What are the kinds of software that are not advisable to be developed using Python? In-Reply-To: References: <52f9b6af$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Wed, Feb 12, 2014 at 1:24 AM, Roy Smith wrote: > Whether I mind shipping my source, or you mind shipping your source > isn't really what matters here. What matters is that there *are* > people/companies who don't want to expose their source. Perhaps for > reasons we don't agree with. For those people, Python is not a good > choice. But if it comes to that, there's really nothing that's all that great a choice. After all, a small amount of introspection will identify the external references in something (even C code has that, unless every single call is statically linked; and even then, I've used gdb usefully on other people's optimized binaries), so while someone might not be able to figure out how your code works, they can at least figure out what it's doing, and call on it directly. The only difference between a .pyc file and a binary executable is that the pyc bytecode is written for a virtual machine rather than a physical CPU. It's not a matter of "this is good, that is bad", but a spectrum of difficulties - optimized C code with everything statically linked is about as close to one extreme as you'll get without consciously obfuscating your code, and well-commented source is the opposite extreme. A minified source file, a .pyc file, or a dynamically linked .so, all are just someplace along that range. It's just a question of how much time and effort it takes to figure out the internals of the code. Considering that there are big companies spending lots of money devising DRM schemes, and their code often gets decompiled or reverse engineered within a day of release, I'd have to say that even obfuscated code is no real barrier. The *only* way to expose nothing is to publish nothing - which, these days, usually means running your software on a server and distributing a fairly dumb client... a model that MUDs have been using to great effect for decades, and are even today able to be run commercially. ChrisA From rosuav at gmail.com Tue Feb 11 09:41:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 01:41:15 +1100 Subject: pip3.x error using LIST instead of list In-Reply-To: <20140211152730.3b99d350@hanez.org> References: <20140211152730.3b99d350@hanez.org> Message-ID: On Wed, Feb 12, 2014 at 1:27 AM, Johannes Findeisen wrote: > Hi, I get the same error with an older release of pip. But, I get that > error regardless which uppercase argument I am passing to pip. Look > below: > Correct. The exception is thrown before it's looked at what the subcommand is; it happens any time the argument != argument.lower(). Simple work-around: always type subcommands in lower-case :) Much easier work-around than for some bugs I've seen. Like, printing from Win-OS/2 requires holding the print queue, printing your document, adding a second job from a smarter print client, then releasing the print queue so both jobs go through in succession. This one, the work-around is just "do what you'd normally do anyway". ChrisA From breamoreboy at yahoo.co.uk Tue Feb 11 09:50:28 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 14:50:28 +0000 Subject: pip3.x error using LIST instead of list In-Reply-To: References: <20140211152730.3b99d350@hanez.org> Message-ID: On 11/02/2014 14:41, Chris Angelico wrote: > On Wed, Feb 12, 2014 at 1:27 AM, Johannes Findeisen wrote: >> Hi, I get the same error with an older release of pip. But, I get that >> error regardless which uppercase argument I am passing to pip. Look >> below: >> > > Correct. The exception is thrown before it's looked at what the > subcommand is; it happens any time the argument != argument.lower(). > Simple work-around: always type subcommands in lower-case :) > No matter what I try I can't get the subcommands in lower-case when I have caps lock on, is there a simple work-around for this as well? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From hlauk.h.bogart at gmail.com Tue Feb 11 09:50:28 2014 From: hlauk.h.bogart at gmail.com (hlauk.h.bogart at gmail.com) Date: Tue, 11 Feb 2014 06:50:28 -0800 (PST) Subject: New to Py 3.3.3 having prob. with large integer div. float. In-Reply-To: References: Message-ID: On Tuesday, February 11, 2014 2:24:01 AM UTC-5, cas... at gmail.com wrote: > On Monday, February 10, 2014 6:40:03 PM UTC-8, hlauk.h... at gmail.com wrote: > > > I am coming off Python 2.6.6 32 bite platform and now in win 8.1 64 bite. > > > I had no problems with gmpy in 2.6.6 and large integer floating points where > > > you could control the length of the floating point by entering the bite size > > > of the divisor(s) you are using. That would give the limit length of the float > > > in the correct number of bites. > > > > > > In Python 3.3.3 and gmpy2 I have tried many things in the import mpfr module > > > changing and trying all kinds of parameters in the gmpy2 set_context module > > > and others. > > > > > > The best I can get without an error is the results of a large integer > > > division is a/b = inf. or an integer rounded up or down. > > > I can't seem to find the right settings for the limit of the remainders in the > > > quotient. > > > > > > My old code in the first few lines of 2.6.6 worked great and looked like this - > > > > > > import gmpy > > > > > > BIG =(A large composite with 2048 bites) > > > SML =(a smaller divisor with 1024 bites) > > > > > > Y= gmpy.mpz(1) > > > A= gmpy.mpf(1) > > > > > > y=Y > > > > > > x=BIG > > > z=SML > > > a=A > > > k=BIG > > > j=BIG > > > x=+ gmpy.next.prime(x) > > > > > > while y < 20: > > > B = gmpy.mpf(x.1024) > > > ## the above set the limit of z/b float (see below) to 1024 > > > b=B > > > a=z/b > > > c=int(a) > > > d=a-c > > > if d = <.00000000000000000000000000000000001: > > > proc. continues from here with desired results. > > > > > > gmpy2 seems a lot more complex but I am sure there is a work around. > > > I am not interested in the mod function. > > > > > > My new conversion proc. is full of ## tags on the different things > > > I tried that didn't work. > > > > > > TIA > > > Dan > > > > The following example will divide two integers with a result precision > > of 1024 bits: > > > > import gmpy2 > > > > # Set mpfr precision to 1024 > > gmpy2.get_context().precision=1024 > > > > # Omitting code.... > > > > a = gmpy2.mpz(SML)/gmpy2.mpz(x) > > > > Python 3.x performs true division by default. When integer division involves > > an mpz, the result will be an mpfr with the precision of the current context. > > > > Does this help? > > > > casevh Thanks a lot, I will give it a go. Dan From rosuav at gmail.com Tue Feb 11 09:58:38 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 01:58:38 +1100 Subject: pip3.x error using LIST instead of list In-Reply-To: References: <20140211152730.3b99d350@hanez.org> Message-ID: On Wed, Feb 12, 2014 at 1:50 AM, Mark Lawrence wrote: > On 11/02/2014 14:41, Chris Angelico wrote: >> >> On Wed, Feb 12, 2014 at 1:27 AM, Johannes Findeisen >> wrote: >>> >>> Hi, I get the same error with an older release of pip. But, I get that >>> error regardless which uppercase argument I am passing to pip. Look >>> below: >>> >> >> Correct. The exception is thrown before it's looked at what the >> subcommand is; it happens any time the argument != argument.lower(). >> Simple work-around: always type subcommands in lower-case :) >> > > No matter what I try I can't get the subcommands in lower-case when I have > caps lock on, is there a simple work-around for this as well? :) Hold Shift :) ChrisA From breamoreboy at yahoo.co.uk Tue Feb 11 10:05:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 15:05:01 +0000 Subject: New to Py 3.3.3 having prob. with large integer div. float. In-Reply-To: References: Message-ID: On 11/02/2014 14:50, hlauk.h.bogart at gmail.com wrote: > > Thanks a lot, I will give it a go. > > Dan > I'm pleased to see that you have answers. In return would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing that I've snipped as there's so much of it, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From python.list at tim.thechases.com Tue Feb 11 10:26:46 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Feb 2014 09:26:46 -0600 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <52f9c392$0$11128$c3e8da3@news.astraweb.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> Message-ID: <20140211092646.56834ec0@bigbox.christie.dr> On 2014-02-11 06:30, Steven D'Aprano wrote: > You need to understand the difference between syntax and semantics. > This is invalid English syntax: > > "Cat mat on sat the." > > This is valid syntax, but semantically wrong: > > "The mat sat on the cat." > > This is both syntactically and semantically correct: > > "The cat sat on the mat." And there are times you *do* want to do unconventional things with the language, and Python allows that: http://www.catster.com/files/600px-cat-hiding-under-rug.jpg because in that particular use case, it *is* semantically correct. > With Python's correct design, we have: > > spam # always, without exception, refers to the object > spam() # always, without exception, calls the object > > With your suggested design, we would have: > > spam # sometimes refers to the object, sometimes calls the object > spam() # always calls the object > > Ruby makes this mistake, and is a lessor language for it. One of the (many) reasons Ruby drives me nuts. -tkc From roegltd at gmail.com Tue Feb 11 10:25:42 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 11 Feb 2014 07:25:42 -0800 (PST) Subject: pip3.x error using LIST instead of list In-Reply-To: References: Message-ID: <3dfac1b7-3a38-4a59-8979-53f524d5accc@googlegroups.com> On Tuesday, February 11, 2014 4:10:32 PM UTC+2, Mark Lawrence wrote: > As the subject line says, details below. > c:\Python34\Scripts>pip3.4 LIST > Traceback (most recent call last): > File "C:\Python34\lib\runpy.py", line 189, in _run_module_as_main > "__main__", mod_spec) > File "C:\Python34\lib\runpy.py", line 87, in _run_code > exec(code, run_globals) > File "c:\Python34\Scripts\pip3.4.exe\__main__.py", line 9, in > File "C:\Python34\lib\site-packages\pip\__init__.py", line 177, in main > cmd_name, cmd_args = parseopts(initial_args) > File "C:\Python34\lib\site-packages\pip\__init__.py", line 156, in > parseopts > cmd_args.remove(args_else[0].lower()) > ValueError: list.remove(x): x not in list > > Is this a known problem, should I raise a bug against pip, what is the > best course of action? > > Mark Lawrence Python 3.3.3 pip 1.4.1 no problem: (app1)app1#pip LIST ecdsa (0.10) gevent (1.0) greenlet (0.4.2) hiredis (0.1.2) json-rpc (1.2) lockfile (0.9.1) lxml (3.2.5) mysql-connector-python (1.1.5) paramiko (1.12.1) pip (1.4.1) pycrypto (2.6.1) redis (2.9.0) requests (2.2.0) setuptools (0.9.8) tinyrpc (0.5) uWSGI (2.0) WebOb (1.3.1) Werkzeug (0.9.4) python 3.3.3 pip 1.5.2 - problem (mnp_venv3)mnp_venv3#pip LIST Traceback (most recent call last): File "/opt/smsc/mnp/mnp_venv3/bin/pip", line 11, in sys.exit(main()) File "/opt/smsc/mnp/mnp_venv3/lib/python3.3/site-packages/pip/__init__.py", line 177, in main cmd_name, cmd_args = parseopts(initial_args) File "/opt/smsc/mnp/mnp_venv3/lib/python3.3/site-packages/pip/__init__.py", line 156, in parseopts cmd_args.remove(args_else[0].lower()) ValueError: list.remove(x): x not in list imho there are ongoing changes in pip due to new features. It could be due to that. imho, at line 156 .lower() should be removed, because of cmd_args holds original argument list (copied at line 155) got as argument to function parseopts() /Asaf From travisgriggs at gmail.com Tue Feb 11 10:36:34 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Tue, 11 Feb 2014 07:36:34 -0800 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <52f9c392$0$11128$c3e8da3@news.astraweb.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> Message-ID: <4E8B29DC-F3A3-44A4-B912-9438CE56B3F2@gmail.com> On Feb 10, 2014, at 10:30 PM, Steven D'Aprano wrote: >> >> 1. Parenthesis should not be required for parameter- less functions. > > Of course they should. Firstly, parameter-less functions are a code- > smell, and ought to be discouraged. Secondly, even if you have a good > reason for using one -- for example, random.random -- then the difference > between referring to the object and calling the object should be clear. Interesting. Can you clarify or provide some links to the "parameter-less functions are a code-smell? bit? I agree with your points about consistency. I disagree with the original poster that niladic functions should have a different syntax than the others. I empathize with him, I?ve made the same mistake before (being an ardent Smalltalker in the past, it?s an easy habit to have bite you). But the consistency is more important. And in python, things ?happen? when parentheses appear. I just accept that. OTOH, I?m not sure I?ve heard the parameters-less functions are a code one? Is it just loose functions that you?re referring to? As opposed to methods (which are just bound functions)? I could maybe accept that. But methods with fewer arguments, and even none, are a desirable thing. There are code smells that are the opposite in fact, methods with long parameter lists are generally seen as code smell (?passing a paragraph?). Anyway, I?d love to understand better what you see as the code smell and why. From duncan.booth at invalid.invalid Tue Feb 11 10:42:16 2014 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Feb 2014 15:42:16 GMT Subject: [RELEASED] Python 3.4.0 release candidate 1 References: <52F9D493.6090100@hastings.org> Message-ID: Terry Reedy wrote: > On 2/11/2014 2:43 AM, Larry Hastings wrote: >> >> On behalf of the Python development team, I'm delighted to announce >> the first release candidate of Python 3.4. > >> To download Python 3.4.0rc1 visit: >> >> http://www.python.org/download/releases/3.4.0/ > > I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in > repair mode and again, no problem. > > With 64 bit 3.4.0, I get > "There is a problem with this Windows Installer package. A program > required for the install to complete could not be run." > > No, the generic message does not bother to say *which* program :-(. > > 34 bit 3.4.0 installed fine. I redownloaded 64bit 3.4.0 and install > gives the same message. > > Can someone verify that this is not some bizarre glitch on my machine? > I downloaded and installed it without problems on a 64bit Windows 7 system. Maybe it is a bizarre glitch on your system, or perhaps it assumes something is present which is there on my system and missing on yours. I see that part way through the install it downloads setuptools/pip from pypi. Did your system have network access? What happens if you enable the installer log by running: msiexec /i python-3.4.0rc1.amd64.msi /L*v logfile.txt Does it put any useful messages in logfile.txt? -- Duncan Booth From rosuav at gmail.com Tue Feb 11 10:52:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 02:52:29 +1100 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <4E8B29DC-F3A3-44A4-B912-9438CE56B3F2@gmail.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <4E8B29DC-F3A3-44A4-B912-9438CE56B3F2@gmail.com> Message-ID: On Wed, Feb 12, 2014 at 2:36 AM, Travis Griggs wrote: > OTOH, I?m not sure I?ve heard the parameters-less functions are a code one? Is it just loose functions that you?re referring to? As opposed to methods (which are just bound functions)? I could maybe accept that. But methods with fewer arguments, and even none, are a desirable thing. There are code smells that are the opposite in fact, methods with long parameter lists are generally seen as code smell (?passing a paragraph?). > 'self' is, imo, a parameter. When you call a parameter-less method on an object, it's usually an imperative with a direct object (or sometimes a subject): some_file.close() # "Close some_file" some_list.shuffle() # "Shuffle some_list" some_file.readline() # "Some_file, read in a line" There are times when, for convenience, the object is implicit. print("some text", file=some_file) # Print that text print(file=some_file) # Print a blank line print("some text") # Print that text to sys.stdout print() # Print a blank line to sys.stdout So in that situation, the no-args call does make sense. Of course, this is a call to a function that does take args, but it's accepting all the defaults and providing no additional content. It's quite different to actually define a function that mandates exactly zero arguments, and isn't making use of some form of implicit state (eg a closure, or maybe a module-level function that manipulates module-level state - random.random() would be an example of the latter). Syntactically, Python can't tell the difference between "print()" and "foo()" where foo can never take args. I'd say that a function taking no args is code smell, unless it's obviously taking its state from somewhere else (callbacks, for instance - maybe you pass a bound method, or maybe a closure, but in either case it has implicit state that's not described by function args); but _calling_ with no args isn't as smelly. It's certainly less common than using args, but there are plenty of times when a type is called without args, for instance[1]. ChrisA [1] Okay, that was a really abysmal pun. From jpiitula at ling.helsinki.fi Tue Feb 11 11:07:06 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 11 Feb 2014 18:07:06 +0200 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> Message-ID: Travis Griggs writes: > in fact, methods with long parameter lists are generally seen as "If you have a predicate with ten arguments, you probably forgot some" (heard long time ago over in the Prolog world). From rosuav at gmail.com Tue Feb 11 11:14:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 03:14:40 +1100 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Wed, Feb 12, 2014 at 3:07 AM, Jussi Piitulainen wrote: > Travis Griggs writes: > >> in fact, methods with long parameter lists are generally seen as > > "If you have a predicate with ten arguments, you probably forgot some" > (heard long time ago over in the Prolog world). Conversely: "Thirteen pushes for each call! Whew. But now we have our files open." (from an assembly language programming tutorial, on the DosOpen API in OS/2) ChrisA From mal at python.org Tue Feb 11 11:18:58 2014 From: mal at python.org (M.-A. Lemburg) Date: Tue, 11 Feb 2014 17:18:58 +0100 Subject: ANN: PSF Python Marketing Brochure - Last call for Ad Sponsors Message-ID: <52FA4D72.8020607@python.org> [Please help spread the word by forwarding to other relevant mailing lists, user groups, etc. world-wide; thanks :-)] ________________________________________________________________________ ANNOUNCING PSF Python Marketing Brochure - Last call for Ad Sponsors Please support the PSF in providing the Python community with free high quality marketing material to promote Python ________________________________________________________________________ INTRODUCTION Over the last few years, the Python brochure team has worked on and created a high-quality brochure to help user groups, conferences and companies using Python to promote and spread the word about Python. The brochure will be printed in a first edition of 10,000 copies which the PSF will then distribute to user groups, Python conferences and educational institutions on request and free of charge. With the Python brochure, we hope to reach out to an audience which is not easy to address and convince using electronic and mostly developer oriented media. ________________________________________________________________________ PREVIEW Please take a look at our preview PDF version of the brochure to see for yourself: http://brochure.getpython.info/preview.pdf ________________________________________________________________________ SEEKING YOUR HELP The team set out to create and print the brochure without introducing extra costs for the PSF. Our aim is to fully finance the brochure production, printing and shipment to interested parties using money from sponsors. To make this happen, we are seeking your help ! => We have already signed up sponsors for 6 half page ads, but still need another *5 half page ad sponsors* to sign up. => There are also *6 smaller reference entry sponsorships* left to be sold. If you are affiliated with or know a company investing into Python and looking for ways to reach out to a large audience of interested Python users, students, developers - and people in key decision making positions, please reach out to us and help make the project a success. The deadline for ad and reference entry signups is *Feb 28* - in just under three weeks. You can find all the details about the available sponsorship options on this page: http://brochure.getpython.info/sponsorship Orders can be placed directly with the production company, Evenios Publishing on the website. All sponsors will receive a box of about 120 free copies of the brochure as Thank You gift. ________________________________________________________________________ ORDERING EXTRA COPIES Companies who are interested in receiving extra copies can pre-order additional boxes which will then be printed in addition to the initial 10.000 copy batch: http://brochure.getpython.info/mediadata/subscription-order-procedure It is also possible to donate such extra boxes to educational institutions: http://brochure.getpython.info/mediadata/education-sponsorship If you have special requirements, please contact the team at brochure at getpython.info for more information. We're very flexible in addressing your needs. ________________________________________________________________________ MORE INFORMATION More information on the brochure, the idea behind it, media data and ordering links are available on our project page: http://brochure.getpython.info/ Thanks for your help, -- Marc-Andre Lemburg Director Python Software Foundation http://www.python.org/psf/ From travisgriggs at gmail.com Tue Feb 11 11:19:24 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Tue, 11 Feb 2014 08:19:24 -0800 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <4E8B29DC-F3A3-44A4-B912-9438CE56B3F2@gmail.com> Message-ID: <0FBEAFE1-409D-4FFA-B332-34DBE81072C8@gmail.com> On Feb 11, 2014, at 7:52 AM, Chris Angelico wrote: > On Wed, Feb 12, 2014 at 2:36 AM, Travis Griggs wrote: >> OTOH, I?m not sure I?ve heard the parameters-less functions are a code one? Is it just loose functions that you?re referring to? As opposed to methods (which are just bound functions)? I could maybe accept that. But methods with fewer arguments, and even none, are a desirable thing. There are code smells that are the opposite in fact, methods with long parameter lists are generally seen as code smell (?passing a paragraph?). >> > > 'self' is, imo, a parameter. When you call a parameter-less method on > an object, it's usually an imperative with a direct object (or > sometimes a subject): > > some_file.close() # "Close some_file" > some_list.shuffle() # "Shuffle some_list" > some_file.readline() # "Some_file, read in a line" > > There are times when, for convenience, the object is implicit. > > print("some text", file=some_file) # Print that text > print(file=some_file) # Print a blank line > print("some text") # Print that text to sys.stdout > print() # Print a blank line to sys.stdout > > So in that situation, the no-args call does make sense. Of course, > this is a call to a function that does take args, but it's accepting > all the defaults and providing no additional content. It's quite > different to actually define a function that mandates exactly zero > arguments, and isn't making use of some form of implicit state (eg a > closure, or maybe a module-level function that manipulates > module-level state - random.random() would be an example of the > latter). Syntactically, Python can't tell the difference between > "print()" and "foo()" where foo can never take args. So at this point, what I?m reading is that actually making a ?no arg function? is difficult, if we widen the semantics. The ?arguments? of a function may be bound to its implicit self parameter, or tied to module state. > > I'd say that a function taking no args is code smell, unless it's > obviously taking its state from somewhere else (callbacks, for > instance - maybe you pass a bound method, or maybe a closure, but in > either case it has implicit state that's not described by function > args); but _calling_ with no args isn't as smelly. It's certainly less > common than using args, but there are plenty of times when a type is > called without args, for instance[1]. Which leaves me wondering, how would I get my code to smell this way then? What IS an example of a no arg function that doesn?t have an implicit object, that smells? It seems I can escape the smell clause, as long as I find some data that I reason is attached to my function. This all aside, I don?t think these are what the OP had in mind. A code inspection algorithm is not going to be able to discern when an explicitly parameterless function has implicit parameters. It?s just going to see something like print vs print() or aPoint.transpose vs aPoint.transpose() From tjreedy at udel.edu Tue Feb 11 11:21:15 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 11:21:15 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: On 2/11/2014 8:06 AM, David Robinow wrote: > On Tue, Feb 11, 2014 at 5:45 AM, Terry Reedy wrote: >> On 2/11/2014 5:13 AM, Terry Reedy wrote: >>> ... >>> I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in >>> repair mode and again, no problem. >>> >>> With 64 bit 3.4.0, I get >>> "There is a problem with this Windows Installer package. A program >>> required for the install to complete could not be run." >>> >>> No, the generic message does not bother to say *which* program :-(. >>> >>> 34 bit 3.4.0 installed fine. >> >> >> I wrote too soon. >> >> Python 3.4.0rc1 (v3.4.0rc1:5e088cea8660, Feb 11 2014, 05:54:25) [MSC >>>>> import tkinter >> Traceback ... >> import _tkinter >> ImportError: DLL load failed: %1 is not a valid Win32 application. >> >> So tkinter, Idle, turtle fail and the corresponding tests get skipped. > 32 bit and 64 bit both work for me. Windows 7. The failed 64-bit installs somehow messed up the 32-bit install. With 3.4 completely removed, including the residual directories, the 32-bit install works but the 64-bit install still gives me the same message. -- Terry Jan Reedy From davea at davea.name Tue Feb 11 11:42:21 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Feb 2014 11:42:21 -0500 (EST) Subject: pip3.x error using LIST instead of list References: <20140211152730.3b99d350@hanez.org> Message-ID: Mark Lawrence Wrote in message: > > > No matter what I try I can't get the subcommands in lower-case when I > have caps lock on, is there a simple work-around for this as well? :) > You could do what I've done for my own DOS, Windows, and Linux computers for years: disable the caps-lock key -- DaveA From marko at pacujo.net Tue Feb 11 11:42:45 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 11 Feb 2014 18:42:45 +0200 Subject: Using asyncio for serial port References: Message-ID: <87d2itd2ii.fsf@elektro.pacujo.net> james.time4tea at gmail.com: > I'm looking at using asyncio for creating an socket <-> serial > protocol bridge, but looking at the current implementation of asyncio > it looks to be quite socket specific. > > I can't see any way to get it to support a simple serial device. Never tried it, but if you can open the serial device and get its file descriptor, you should be able to use http://docs.python.org/3.4/library/asyncio-eventloop.html#watch-file-descriptors BTW, the specification doesn't indicate if the reader/writer callbacks are level-triggered or edge-triggered. I'm afraid they are level-triggered. At any rate, asyncio looks like a real positive development in Pythonland. Marko From wkhughey at gmail.com Tue Feb 11 11:49:53 2014 From: wkhughey at gmail.com (Walter Hughey) Date: Tue, 11 Feb 2014 11:49:53 -0500 (EST) Subject: Newcomer Help In-Reply-To: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: <1276685405.7199506.1392137393610.JavaMail.root@okbu.edu> No, Gisle Vanem - I do NOT get the picture. First of all you did NOT answer my question. And this is the way I always have - and the people I typically respond to - respond to emails. Check the end - if that is where you expect me to enter any additional info. ----- Original Message ----- From: "Gisle Vanem" To: "Walter Hughey" Cc: python-list at python.org Sent: Monday, February 10, 2014 4:13:44 PM Subject: Re: Newcomer Help "Walter Hughey" wrote: > Thank you for your reply. One quick question, when > I reply should it be replay to all or to the person who sent the emial? When replying, the most important thing to remember is... order. A: Because it messes up the order in which people normally read text. Q: Why is it such a bad thing? A: Top-posting. Q: What is the most annoying thing in e-mail? Get the picture now newcomer? --gv ------ this crap came from you --------- > > > Apple does install a version of Python, normally a somewhat older version. My computer has 2.5 and 2.6 installed and I have opened > it and inserted code that works. I do need a way to write the code, test it, and then save a copy to turn in for the assignment. I > was not aware that a normal text editor would work. I shall definitely look at that later today. > > > Walter > ----- Original Message ----- > > From: "Rustom Mody" > To: python-list at python.org > Sent: Monday, February 10, 2014 11:07:14 AM > Subject: Re: Newcomer Help > > On Monday, February 10, 2014 9:40:22 PM UTC+5:30, Walter Hughey wrote: >> I am new to Python programming, actually new to any programming language. I sent the email below to the "python... at python.org a >> few days ago. So far I have not seen a reply, actually, I have not seen anything from pythonmac in any emails although I am >> supposed to be a member. >> >> >> I don't know if I am sending these to the correct place or if I am not receiving emails from the pythonmac list. I would >> appreciate any assistance either in how do I get to the pythonmac list or answers to the issue below. I went to the pythonmac >> list because I am trying to run Python 3.3 on a Mac computer. >> >> >> Thank you, >> >> >> Walter >> >> From: "Walter Hughey" >> To: python... at python.org >> Sent: Friday, February 7, 2014 11:54:49 AM >> Subject: Newcomer Help >> >> >> Greetings, >> I am new at Python programming, technically a newbie at writing programming code. I have been involved in the maintenance of >> computers for several years and have decided to increase my knowledge and experience. I am taking a course that - although not a >> programming course - does require writing of code. I am trying to use Python to write the code. >> >> I use a Mac computer and the first issue is getting working with Python. The computer I currently use is running Mac OS X 10.6.8, >> Intel Core i5 Processor, with 4GB RAM. It has Python 2.3, 2.5, and 2.6 installed by Apple. I have added Python 3.3, the version >> our Professor recommended. I have checked out the Python installed by Apple and can enter in code and it works, but I need to >> create a file, run it, and then provide it for the Professor to grade and I don't know how with the Apple installed version. >> >> While reading about Python, I saw comments about the note concerning outdated software: If you are using Python from a python.org >> 64-bit/32-bit Python installer for Mac OS X 10.6 and later, >> you should only use IDLE or tkinter with an updated >> third-party Tcl/Tk 8.5, like >> ActiveTcl 8.5 >> installed. >> >> I located, downloaded and installed the recommended version of ActiveTcl 8.5.15.0. When I open Idle, I see a warning that "The >> version of Tcl/Tk (8.5.7) in use may be unstable." I received this warning both before and after installing the software above. I >> open Idle, choose "New File" then most often the computer will freeze, Idle does nothing, cannot enter text into the text box, >> cannot close the application either with the red circle or by selecting Idle>Close Idle. As often as that, Idle freezes as soon >> as I open new file, and I cannot close without resorting to Force Quit. >> >> I have removed and re-installed Python after downloading and installing the Tcl/Tk software and it does not help. I have seen >> this work fine on a Mac running Mac OS X 10.8.3. I really just need to get this working on the older version. >> >> A am not only new to Python, I am new on this list and hope I have started my stay here in the correct manner! >> > > Hi! You have started on a clear note and are welcome here. > I dont know anything about macs so hopefully someone else will give you > more specific answers. > > However can you check that python interpreter runs in a shell, and that > after starting it if you type say: > 2 + 3 RETURN > you get 5 > > If that is the case you can still develop the way most python programmers > develop, viz > Write your code in a normal text editor > Load it into the interpreter > Check it > Go back to the editor and continue writing/correcting the code > -- > https://mail.python.org/mailman/listinfo/python-list > > I suppose what you mean by "top posting" is replying to an email by entering a reply at the top when according to your policies and procedures - a person should reply at the bottom of the email - like this. IF/WHEN I am on this site, I shall do my utmost best to change the way I and the people I normally work with to reply at the bottom, Assuming Gisle Vanem this is what you mean and what you want. This "newcomer" apologizes for ------ this crap came from you ---------. I hope I have not totally destroyed all of everybody's systems with my inappropriate and thoughtless disregard for the sanctity of this site. May be it be best I not reply/ask for help/or in any way be involved in this site. -------------------------------------------------------------------------------- > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Feb 11 12:11:49 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 12:11:49 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: On 2/11/2014 10:42 AM, Duncan Booth wrote: > Terry Reedy wrote: > >> On 2/11/2014 2:43 AM, Larry Hastings wrote: >>> >>> On behalf of the Python development team, I'm delighted to announce >>> the first release candidate of Python 3.4. >> >>> To download Python 3.4.0rc1 visit: >>> >>> http://www.python.org/download/releases/3.4.0/ >> >> I installed 64 bit 3.3.4 yesterday with no problem. I reran it today in >> repair mode and again, no problem. >> >> With 64 bit 3.4.0, I get >> "There is a problem with this Windows Installer package. A program >> required for the install to complete could not be run." >> >> No, the generic message does not bother to say *which* program :-(. >> >> 34 bit 3.4.0 installed fine. I redownloaded 64bit 3.4.0 and install >> gives the same message. >> >> Can someone verify that this is not some bizarre glitch on my machine? >> > I downloaded and installed it without problems on a 64bit Windows 7 system. > Maybe it is a bizarre glitch on your system, or perhaps it assumes > something is present which is there on my system and missing on yours. As I noted in response to David, starting completely clean allows 32 bit version to install, but not 64 bit version. > I see that part way through the install it downloads setuptools/pip from > pypi. Did your system have network access? Enough to post the original message ;-). And yes, A box came up asking about that and I said yes. > What happens if you enable the installer log by running: > > msiexec /i python-3.4.0rc1.amd64.msi /L*v logfile.txt A megabyte file with nearly 7000 lines > Does it put any useful messages in logfile.txt? 'error' occurs on 40. most are like the following MSI (s) (40:08) [11:57:25:973]: Package to be registered: 'python-3.4.0rc1.amd64.msi' MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: Error 3: -2147287038 MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: AdminProperties 3: -2147287038 Here is the one for the boxed message: Action 11:57:26: RemovePip. Action start 11:57:26: RemovePip. MSI (s) (40:0C) [11:57:26:426]: Note: 1: 1721 2: RemovePip 3: C:\Programs\Python34\python.exe 4: -m ensurepip._uninstall MSI (s) (40:0C) [11:57:26:426]: Note: 1: 2262 2: Error 3: -2147287038 Error 1721. There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor. Action: RemovePip, location: C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall MSI (s) (40:0C) [11:57:28:874]: Note: 1: 2262 2: Error 3: -2147287038 MSI (s) (40:0C) [11:57:28:874]: Product: Python 3.4.0b2 (64-bit) -- Error 1721. There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor. Action: RemovePip, location: C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall MSI (c) (98:EC) [11:57:30:204]: PROPERTY CHANGE: Deleting SECONDSEQUENCE property. Its current value is '1'. Action ended 11:57:30: ExecuteAction. Return value 3. MSI (c) (98:EC) [11:57:30:204]: Doing action: FatalError A Can you make anything of these? -- Terry Jan Reedy From luke.geelen at gmail.com Tue Feb 11 12:29:22 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 09:29:22 -0800 (PST) Subject: Flag control variable Message-ID: hello, i'd like to know how to set up a flag to change a variable, for example, i want a simple script to combine 2 numbers, sum = num + another_num print "Now the sum of the numbers equals : ", sum how could i make it so that if i type python ./script.py 21 41 that i get the sum of 21 and 41 ? luke From larry.martell at gmail.com Tue Feb 11 12:44:09 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Feb 2014 12:44:09 -0500 Subject: Flag control variable In-Reply-To: References: Message-ID: On Tuesday, February 11, 2014, wrote: > hello, > i'd like to know how to set up a flag to change a variable, > for example, i want a simple script to combine 2 numbers, > > > sum = num + another_num > print "Now the sum of the numbers equals : ", sum > > how could i make it so that if i type python ./script.py 21 41 > that i get the sum of 21 and 41 ? > > Google for python command line arguments. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 11 12:46:40 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 18:46:40 +0100 Subject: Flag control variable References: Message-ID: luke.geelen at gmail.com wrote: > i'd like to know how to set up a flag to change a variable, > for example, i want a simple script to combine 2 numbers, > > > sum = num + another_num > print "Now the sum of the numbers equals : ", sum > > how could i make it so that if i type python ./script.py 21 41 > that i get the sum of 21 and 41 ? You seem to be looking for sys.argv which contains the script name and the command-line arguments. $ cat script.py import sys a = int(sys.argv[1]) b = int(sys.argv[2]) print a, "+", b, "=", a + b $ python script.py 21 41 21 + 41 = 62 The conversion to int (or float etc.) is necessary because in python >>> "21" + "41" '2141' From tjreedy at udel.edu Tue Feb 11 12:57:24 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Feb 2014 12:57:24 -0500 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <0FBEAFE1-409D-4FFA-B332-34DBE81072C8@gmail.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <4E8B29DC-F3A3-44A4-B912-9438CE56B3F2@gmail.com> <0FBEAFE1-409D-4FFA-B332-34DBE81072C8@gmail.com> Message-ID: On 2/11/2014 11:19 AM, Travis Griggs wrote: > > On Feb 11, 2014, at 7:52 AM, Chris Angelico wrote: > >> So in that situation, the no-args call does make sense. Of course, >> this is a call to a function that does take args, but it's accepting >> all the defaults and providing no additional content. It's quite >> different to actually define a function that mandates exactly zero >> arguments, and isn't making use of some form of implicit state (eg a >> closure, or maybe a module-level function that manipulates >> module-level state - random.random() would be an example of the >> latter). Syntactically, Python can't tell the difference between >> "print()" and "foo()" where foo can never take args. > > So at this point, what I?m reading is that actually making a ?no arg function? is difficult, if we widen the semantics. It is quite easy. def f(): return 3 # or any other constant. Chris said that useful functions in Python are (mostly) not really niladic, which is equivalent to saying that niladic functions in Python are (mostly) not really useful. They are a mainly a device in pure function theory to have constants (True, False, 0, 1, ...) while also having everything be a function (the 'pure' part). Pure set theory uses its own tricks to make the same constants (and functions) be sets ;-). -- Terry Jan Reedy From luke.geelen at gmail.com Tue Feb 11 13:00:48 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 10:00:48 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: <4f701123-2d03-4ed4-8ef0-05e9e273e196@googlegroups.com> Thanks a lot From travisgriggs at gmail.com Tue Feb 11 13:13:31 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Tue, 11 Feb 2014 10:13:31 -0800 Subject: Metaprogramming question Message-ID: The discussion about niladic functions, made me want to follow a segue and do some reflection/introspective programming in Python. I?ve not done a lot of that yet, and it seemed like an educational (well, at least entertaining) goose chase. If I run the following code: import datetime datetime.datetime.now(13, 42) I will get an error (expected). The error I will get is: Traceback (most recent call last): File "", line 1, in TypeError: now() takes at most 1 argument (2 given) So, at some point, there?s some metadata in the system attached to the builtin datetime.datetime.now method, that indicates 1 argument, tops. So here?s my basic question. Is there anyway to programatically query that information in python code? inspect.signature(datetime.datetime.now) just gives a ValueError. inspect must only be good for the python code that I write, in python. Is there another way to dig out what the interpreter knows there? From luke.geelen at gmail.com Tue Feb 11 13:16:20 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 10:16:20 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: <0938f7a5-702f-48f7-a8ef-cd0a2fb198df@googlegroups.com> when expandig the script to multiple calcs i got a problem >>> a = 32 >>> c = 51 >>> sign = * File "", line 1 sign = * ^ SyntaxError: invalid syntax is there a way of adding * without quoting marks, because if you do it just soms the arguments From zachary.ware+pylist at gmail.com Tue Feb 11 13:25:47 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 11 Feb 2014 12:25:47 -0600 Subject: Metaprogramming question In-Reply-To: References: Message-ID: On Tue, Feb 11, 2014 at 12:13 PM, Travis Griggs wrote: > So here?s my basic question. Is there anyway to programatically query that information in python code? > > inspect.signature(datetime.datetime.now) > > just gives a ValueError. inspect must only be good for the python code that I write, in python. Is there another way to dig out what the interpreter knows there? Fixing that issue is in the works. Argument Clinic[1][2] has been added for Python 3.4 which, once all C functions have been converted, will provide signature information for all builtins (functions written in C). If you try out the Python 3.4 RC1[3], you can try inspect.signature(datetime.datetime.now) again and get the information you expect: that's one of the (unfortunately relatively few) builtins that is already converted. Aside from the Argument Clinic effort, builtin functions are pretty much black boxes to Python--hence why we're trying to fix it! -- Zach [1] http://docs.python.org/3.4/howto/clinic.html [2] http://hg.python.org/cpython/file/default/Tools/clinic/clinic.py [3] http://python.org/download/releases/3.4.0/ From python.list at tim.thechases.com Tue Feb 11 13:32:54 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Feb 2014 12:32:54 -0600 Subject: Flag control variable In-Reply-To: <0938f7a5-702f-48f7-a8ef-cd0a2fb198df@googlegroups.com> References: <0938f7a5-702f-48f7-a8ef-cd0a2fb198df@googlegroups.com> Message-ID: <20140211123254.407e2f07@bigbox.christie.dr> On 2014-02-11 10:16, luke.geelen at gmail.com wrote: > when expandig the script to multiple calcs i got a problem > >>> a = 32 > >>> c = 51 > >>> sign = * > > File "", line 1 > sign = * > ^ > SyntaxError: invalid syntax > > is there a way of adding * without quoting marks, because if you do > it just soms the arguments -- You want to store the actual operation. The "operator" module makes this fairly easy, so you can do something like import operator as o operations = { "*": o.mul, "+": o.add, "/": o.div, "-": o.sub, } a = 32 c = 51 operation = operations["*"] print(operation(a,c)) -tkc From luke.geelen at gmail.com Tue Feb 11 13:37:45 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 10:37:45 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> well i'm trying something else but no luck : #!bin/bash/python import sys import os a = int(sys.argv[1]) sign = (sys.argv[2]) b = int(sys.argv[3]) if sign == '+': sum = a + b print a, sign, b, "=", a + b command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" % (a, b, sum) os.system (command1) elif sign == "*": sum = a * b print a, sign, b, "=", a * b command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" % (a, b, sum) when using * i get Traceback (most recent call last): File "./math+.py", line 6, in b = int(sys.argv[3]) ValueError: invalid literal for int() with base 10: 'Adafruit-Raspberry-Pi-Python-Code' i don't understand why b is a problem, it works fine with + From python.list at tim.thechases.com Tue Feb 11 13:51:14 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Feb 2014 12:51:14 -0600 Subject: Flag control variable In-Reply-To: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: <20140211125114.4c093ab7@bigbox.christie.dr> On 2014-02-11 10:37, luke.geelen at gmail.com wrote: > command1 = "sudo mpg321 > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" > % (a, b, sum) > > when using * i get > > Traceback (most recent call last): > File "./math+.py", line 6, in > b = int(sys.argv[3]) > ValueError: invalid literal for int() with base 10: > 'Adafruit-Raspberry-Pi-Python-Code' > > i don't understand why b is a problem, it works fine with + This is the fault of your shell (bash perhaps)? Try this: bash$ echo + + bash$ echo * (a list of files in your current directory here) which occurs because of file-globbing. You have a couple options that occur to me: 1) quote the asterisk: bash$ ./mycode.py 3 "*" 2 which will let Python see it without the shell expanding it 2) use a different character/string such as "3 times 2" 3) pass the whole thing as a quoted string and then let Python do the splitting: bash$ ./mycode.py "3 * 2" a, operator, b = argv[1:].split() print(a,b,c) -tkc From __peter__ at web.de Tue Feb 11 13:51:40 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 19:51:40 +0100 Subject: Flag control variable References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: luke.geelen at gmail.com wrote: > well i'm trying something else but no luck : > > #!bin/bash/python Hm. > import sys > import os For debugging purposes put the line print sys.argv here to see what arguments are passed to the script. When you type $ python script.py 2 * 2 in the shell the "*" sign is replaced with all items in the current directory. To avoid that you have to escape, i. e. prepend a backslash: $ python script.py 2 \* 2 To illustrate: $ touch one two three $ ls one three two $ python -c 'import sys; print sys.argv' 2 + 2 ['-c', '2', '+', '2'] $ python -c 'import sys; print sys.argv' 2 * 2 ['-c', '2', 'one', 'three', 'two', '2'] $ python -c 'import sys; print sys.argv' 2 \* 2 ['-c', '2', '*', '2'] > a = int(sys.argv[1]) > sign = (sys.argv[2]) > b = int(sys.argv[3]) > > if sign == '+': > sum = a + b > print a, sign, b, "=", a + b > command1 = "sudo mpg321 > 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" > % (a, b, sum) os.system (command1) > > elif sign == "*": > sum = a * b > print a, sign, b, "=", a * b > command1 = "sudo mpg321 > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" > % (a, b, sum) > > when using * i get > > Traceback (most recent call last): > File "./math+.py", line 6, in > b = int(sys.argv[3]) > ValueError: invalid literal for int() with base 10: > 'Adafruit-Raspberry-Pi-Python-Code' > > i don't understand why b is a problem, it works fine with + From roegltd at gmail.com Tue Feb 11 13:53:47 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 11 Feb 2014 10:53:47 -0800 (PST) Subject: pip3.x error using LIST instead of list In-Reply-To: References: <20140211152730.3b99d350@hanez.org> Message-ID: <5ec37c35-9267-4b6c-9c65-487992d352d0@googlegroups.com> https://groups.google.com/forum/#!topic/python-virtualenv/8wzQfjQW2i8 From wxjmfauth at gmail.com Tue Feb 11 13:53:53 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 11 Feb 2014 10:53:53 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> Le lundi 10 f?vrier 2014 15:43:08 UTC+1, Tim Chase a ?crit?: > On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: > > > Python does not save memory at all. A str (unicode string) > > > uses less memory only - and only - because and when one uses > > > explicitly characters which are consuming less memory. > > > > > > Not only the memory gain is zero, Python falls back to the > > > worse case. > > > > > > >>> sys.getsizeof('a' * 1000000) > > > 1000025 > > > >>> sys.getsizeof('a' * 1000000 + 'oe') > > > 2000040 > > > >>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') > > > 4000048 > > > > If Python used UTF-32 for EVERYTHING, then all three of those cases > > would be 4000048, so it clearly disproves your claim that "python > > does not save memory at all". > > > > > The opposite of what the utf8/utf16 do! > > > > > > >>> sys.getsizeof(('a' * 1000000 + 'oe' + > > > >>> '\U00010000').encode('utf-8')) > > > 1000023 > > > >>> sys.getsizeof(('a' * 1000000 + 'oe' + > > > >>> '\U00010000').encode('utf-16')) > > > 2000025 > > > > However, as pointed out repeatedly, string-indexing in fixed-width > > encodings are O(1) while indexing into variable-width encodings (e.g. > > UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing > > while saving space when a string doesn't need to use a full 32-bit > > width. > > A utf optimizes the memory and the performance at the same time. It behaves like a mathematical operator, a unique operator for a unique set of elements. Unbeatable. The FSR is an exclusive or mechanism. I you wish to same memory, you have to encode, and if you are encoding, maybe because you have to, one loses performance. Paradoxal. Your O(1) indexing works only and only because and when you are working explicitly with a "static" unicode string you never touch. It's a little bit the the "corresponding" performance case of the memory case. jmf From gary.herron at islandtraining.com Tue Feb 11 13:55:59 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 10:55:59 -0800 Subject: Flag control variable In-Reply-To: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: <52FA723F.6010006@islandtraining.com> On 02/11/2014 10:37 AM, luke.geelen at gmail.com wrote: > well i'm trying something else but no luck : > > #!bin/bash/python > import sys > import os > a = int(sys.argv[1]) > sign = (sys.argv[2]) > b = int(sys.argv[3]) > > if sign == '+': > sum = a + b > print a, sign, b, "=", a + b > command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" % (a, b, sum) > os.system (command1) > > elif sign == "*": > sum = a * b > print a, sign, b, "=", a * b > command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" % (a, b, sum) > > when using * i get > > Traceback (most recent call last): > File "./math+.py", line 6, in > b = int(sys.argv[3]) > ValueError: invalid literal for int() with base 10: 'Adafruit-Raspberry-Pi-Python-Code' > > i don't understand why b is a problem, it works fine with + Look at the error message. Carefully! It says, quite clearly, the call to int is being passed a string "Adafruit-Raspberry-Pi-Python-Code", which of course can't be converted to an integer. Now the question is how you ran the program in such a manner that sys.argv[3] has such an odd value. What does your command line look like? You didn't tell us, but that's where the trouble is. Gary Herron From luke.geelen at gmail.com Tue Feb 11 13:59:46 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 10:59:46 -0800 (PST) Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: Op dinsdag 11 februari 2014 19:55:59 UTC+1 schreef Gary Herron: > On 02/11/2014 10:37 AM, luke.geelen at gmail.com wrote: > > > well i'm trying something else but no luck : > > > > > > #!bin/bash/python > > > import sys > > > import os > > > a = int(sys.argv[1]) > > > sign = (sys.argv[2]) > > > b = int(sys.argv[3]) > > > > > > if sign == '+': > > > sum = a + b > > > print a, sign, b, "=", a + b > > > command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" % (a, b, sum) > > > os.system (command1) > > > > > > elif sign == "*": > > > sum = a * b > > > print a, sign, b, "=", a * b > > > command1 = "sudo mpg321 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" % (a, b, sum) > > > > > > when using * i get > > > > > > Traceback (most recent call last): > > > File "./math+.py", line 6, in > > > b = int(sys.argv[3]) > > > ValueError: invalid literal for int() with base 10: 'Adafruit-Raspberry-Pi-Python-Code' > > > > > > i don't understand why b is a problem, it works fine with + > > > > Look at the error message. Carefully! It says, quite clearly, the call > > to int is being passed a string "Adafruit-Raspberry-Pi-Python-Code", > > which of course can't be converted to an integer. > > > > Now the question is how you ran the program in such a manner that > > sys.argv[3] has such an odd value. > > What does your command line look like? You didn't tell us, but that's > > where the trouble is. > > > > Gary Herron how do you meen "what does your command line look like?" From breamoreboy at yahoo.co.uk Tue Feb 11 14:04:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 19:04:02 +0000 Subject: Finding size of Variable In-Reply-To: <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> Message-ID: On 11/02/2014 18:53, wxjmfauth at gmail.com wrote: > Le lundi 10 f?vrier 2014 15:43:08 UTC+1, Tim Chase a ?crit : >> On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: >> >>> Python does not save memory at all. A str (unicode string) >> >>> uses less memory only - and only - because and when one uses >> >>> explicitly characters which are consuming less memory. >> >>> >> >>> Not only the memory gain is zero, Python falls back to the >> >>> worse case. >> >>> >> >>>>>> sys.getsizeof('a' * 1000000) >> >>> 1000025 >> >>>>>> sys.getsizeof('a' * 1000000 + 'oe') >> >>> 2000040 >> >>>>>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') >> >>> 4000048 >> >> >> >> If Python used UTF-32 for EVERYTHING, then all three of those cases >> >> would be 4000048, so it clearly disproves your claim that "python >> >> does not save memory at all". >> >> >> >>> The opposite of what the utf8/utf16 do! >> >>> >> >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >> >>>>>> '\U00010000').encode('utf-8')) >> >>> 1000023 >> >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >> >>>>>> '\U00010000').encode('utf-16')) >> >>> 2000025 >> >> >> >> However, as pointed out repeatedly, string-indexing in fixed-width >> >> encodings are O(1) while indexing into variable-width encodings (e.g. >> >> UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing >> >> while saving space when a string doesn't need to use a full 32-bit >> >> width. >> >> > > A utf optimizes the memory and the performance at the same time. > It behaves like a mathematical operator, a unique operator for > a unique set of elements. Unbeatable. > > The FSR is an exclusive or mechanism. I you wish to > same memory, you have to encode, and if you are encoding, > maybe because you have to, one loses performance. Paradoxal. > > Your O(1) indexing works only and only because and > when you are working explicitly with a "static" unicode > string you never touch. > It's a little bit the the "corresponding" performance > case of the memory case. > > jmf > Why are you so rude as to continually post your nonsense here that not a single person believes, and at the same time still quite deliberately use gg to post it with double line spacing. If you lack the courtesy to stop the former, please have the courtesy to stop the latter. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From luke.geelen at gmail.com Tue Feb 11 14:01:05 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 11:01:05 -0800 (PST) Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: Op dinsdag 11 februari 2014 19:51:40 UTC+1 schreef Peter Otten: > luke.geelen at gmail.com wrote: > > > > > well i'm trying something else but no luck : > > > > > > #!bin/bash/python > > > > Hm. > > > > > import sys > > > import os > > > > For debugging purposes put the line > > > > print sys.argv > > > > here to see what arguments are passed to the script. When you type > > > > $ python script.py 2 * 2 > > > > in the shell the "*" sign is replaced with all items in the current > > directory. To avoid that you have to escape, i. e. prepend a backslash: > > > > $ python script.py 2 \* 2 > > > > To illustrate: > > > > $ touch one two three > > $ ls > > one three two > > $ python -c 'import sys; print sys.argv' 2 + 2 > > ['-c', '2', '+', '2'] > > $ python -c 'import sys; print sys.argv' 2 * 2 > > ['-c', '2', 'one', 'three', 'two', '2'] > > $ python -c 'import sys; print sys.argv' 2 \* 2 > > ['-c', '2', '*', '2'] > > > > > a = int(sys.argv[1]) > > > sign = (sys.argv[2]) > > > b = int(sys.argv[3]) > > > > > > if sign == '+': > > > sum = a + b > > > print a, sign, b, "=", a + b > > > command1 = "sudo mpg321 > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" > > > % (a, b, sum) os.system (command1) > > > > > > elif sign == "*": > > > sum = a * b > > > print a, sign, b, "=", a * b > > > command1 = "sudo mpg321 > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" > > > % (a, b, sum) > > > > > > when using * i get > > > > > > Traceback (most recent call last): > > > File "./math+.py", line 6, in > > > b = int(sys.argv[3]) > > > ValueError: invalid literal for int() with base 10: > > > 'Adafruit-Raspberry-Pi-Python-Code' > > > > > > i don't understand why b is a problem, it works fine with + when using python script.py 2 \* 2 i get Traceback (most recent call last): File "math2.py", line 5, in sign = int(sys.argv[2]) ValueError: invalid literal for int() with base 10: '*' From gary.herron at islandtraining.com Tue Feb 11 14:09:22 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 11:09:22 -0800 Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: <52FA7562.9090800@islandtraining.com> On 02/11/2014 10:59 AM, luke.geelen at gmail.com wrote: > > > Look at the error message. Carefully! It says, quite clearly, the call > > to int is being passed a string "Adafruit-Raspberry-Pi-Python-Code", > > which of course can't be converted to an integer. > > > > Now the question is how you ran the program in such a manner that > > sys.argv[3] has such an odd value. > > What does your command line look like? You didn't tell us, but that's > > where the trouble is. > > > > Gary Herron > how do you meen "what does your command line look like?" When you run this python script, *how* do you do so? Perhaps you type something like: python script.py 21 '*' 42 If not, then how do you supply values for the script's sys.argv? If it is like that, then I see the most likely potential problem. The asterisk character (on Linux at least) is considered a wild-card character -- it is replaced by a list of local files so your command becomes python script.py 21 somefile1 somefile2 somefile3 <...and so on.> 42 If you put it in quotes, then it won't be expanded (at least in the usual Linux shells -- you system may vary) and you'll end up with the asterisk in sys.argv[2] and the number in sys.argv[3]. Gary Herron From luke.geelen at gmail.com Tue Feb 11 14:06:42 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 11:06:42 -0800 (PST) Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> Op dinsdag 11 februari 2014 20:01:05 UTC+1 schreef luke.... at gmail.com: > Op dinsdag 11 februari 2014 19:51:40 UTC+1 schreef Peter Otten: > > > luke.geelen at gmail.com wrote: > > > > > > > > > > > > > well i'm trying something else but no luck : > > > > > > > > > > > > > > #!bin/bash/python > > > > > > > > > > > > Hm. > > > > > > > > > > > > > import sys > > > > > > > import os > > > > > > > > > > > > For debugging purposes put the line > > > > > > > > > > > > print sys.argv > > > > > > > > > > > > here to see what arguments are passed to the script. When you type > > > > > > > > > > > > $ python script.py 2 * 2 > > > > > > > > > > > > in the shell the "*" sign is replaced with all items in the current > > > > > > directory. To avoid that you have to escape, i. e. prepend a backslash: > > > > > > > > > > > > $ python script.py 2 \* 2 > > > > > > > > > > > > To illustrate: > > > > > > > > > > > > $ touch one two three > > > > > > $ ls > > > > > > one three two > > > > > > $ python -c 'import sys; print sys.argv' 2 + 2 > > > > > > ['-c', '2', '+', '2'] > > > > > > $ python -c 'import sys; print sys.argv' 2 * 2 > > > > > > ['-c', '2', 'one', 'three', 'two', '2'] > > > > > > $ python -c 'import sys; print sys.argv' 2 \* 2 > > > > > > ['-c', '2', '*', '2'] > > > > > > > > > > > > > a = int(sys.argv[1]) > > > > > > > sign = (sys.argv[2]) > > > > > > > b = int(sys.argv[3]) > > > > > > > > > > > > > > if sign == '+': > > > > > > > sum = a + b > > > > > > > print a, sign, b, "=", a + b > > > > > > > command1 = "sudo mpg321 > > > > > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_plus%s_equals%s'" > > > > > > > % (a, b, sum) os.system (command1) > > > > > > > > > > > > > > elif sign == "*": > > > > > > > sum = a * b > > > > > > > print a, sign, b, "=", a * b > > > > > > > command1 = "sudo mpg321 > > > > > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" > > > > > > > % (a, b, sum) > > > > > > > > > > > > > > when using * i get > > > > > > > > > > > > > > Traceback (most recent call last): > > > > > > > File "./math+.py", line 6, in > > > > > > > b = int(sys.argv[3]) > > > > > > > ValueError: invalid literal for int() with base 10: > > > > > > > 'Adafruit-Raspberry-Pi-Python-Code' > > > > > > > > > > > > > > i don't understand why b is a problem, it works fine with + > > > > when using python script.py 2 \* 2 > > i get > > > > Traceback (most recent call last): > > File "math2.py", line 5, in > > sign = int(sys.argv[2]) > > ValueError: invalid literal for int() with base 10: '*' i found it int(sys.argv[2]) should be sys.argv[2] is there a way i can do python ./script.py 3 * 3 instead of python ./script 3 \* 3 ? From breamoreboy at yahoo.co.uk Tue Feb 11 14:08:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 19:08:20 +0000 Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: On 11/02/2014 18:59, luke.geelen at gmail.com wrote: Would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spaced text that I've snipped, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From jpiitula at ling.helsinki.fi Tue Feb 11 14:14:05 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 11 Feb 2014 21:14:05 +0200 Subject: Flag control variable References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: luke.geelen at gmail.com writes: > when using python script.py 2 \* 2 > i get > > Traceback (most recent call last): > File "math2.py", line 5, in > sign = int(sys.argv[2]) > ValueError: invalid literal for int() with base 10: '*' You've mis-spelt sigh. This is not the code that you posted. You misunderestimate that error message. It tells everything. From gary.herron at islandtraining.com Tue Feb 11 14:20:27 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 11:20:27 -0800 Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> Message-ID: <52FA77FB.1030302@islandtraining.com> On 02/11/2014 11:01 AM, luke.geelen at gmail.com wrote: > when using python script.py 2 \* 2 i get Traceback (most recent call > last): File "math2.py", line 5, in sign = int(sys.argv[2]) > ValueError: invalid literal for int() with base 10: '*' Stop trying to guess what is going on. Print out sys.argv, and *see* what values are there. Then read the error message. You wrote your script expecting sys.argv[2] to contain an int, but in fact (according to the error) it contains a '*' -- which can't be converted to an integer obviously. Your error is in running the script incorrectly, *OR* in your understanding of how the command line arguments get placed in sys.argv. In either case you best bet is to examine sys.argv by printing it (or examining it within a debugger) and *see* what values it contains. Then adjust your script (or the running of it) accordingly. These are very beginner level debugging suggestions. If you develop the skill to read and understand the error messages, and the skill to print (or otherwise examine) the values your program is dealing with, you progress will by 100's of times faster then this slow wait for someone to respond to on this list. Gary Herron From gary.herron at islandtraining.com Tue Feb 11 14:26:06 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 11:26:06 -0800 Subject: Flag control variable In-Reply-To: <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> Message-ID: <52FA794E.6040804@islandtraining.com> On 02/11/2014 11:06 AM, luke.geelen at gmail.com wrote: > > i found it int(sys.argv[2]) should be sys.argv[2] > > is there a way i can do python ./script.py 3 * 3 instead of python ./script 3 \* 3 ? That's not really a Python question. The shell (as it's called) which interprets your typed command and runs Python with the rest of the command line arguments is in control of this. If you can find a way to tell your shell to not expand '*' characters, or find a shell that does not do so, then yes, you can dispense with the back-slash. Gary Herron From python.list at tim.thechases.com Tue Feb 11 14:28:44 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Feb 2014 13:28:44 -0600 Subject: Flag control variable In-Reply-To: <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> Message-ID: <20140211132844.76f1b1b2@bigbox.christie.dr> On 2014-02-11 11:06, luke.geelen at gmail.com wrote: > > > > command1 = "sudo mpg321 > > > > > > > > > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" 1) PLEASE either stop using Google Groups or take the time to remove the superfluous white-space you keep adding to your posts/replies 2) you shouldn't need to use "sudo" to play sounds. That's just a bad practice waiting for trouble. -tkc From jurko.gospodnetic at pke.hr Tue Feb 11 14:42:19 2014 From: jurko.gospodnetic at pke.hr (=?UTF-8?B?SnVya28gR29zcG9kbmV0acSH?=) Date: Tue, 11 Feb 2014 20:42:19 +0100 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: References: <52F9D493.6090100@hastings.org> Message-ID: Hi. On 11.2.2014. 17:21, Terry Reedy wrote: > The failed 64-bit installs somehow messed up the 32-bit install. With > 3.4 completely removed, including the residual directories, the 32-bit > install works but the 64-bit install still gives me the same message. I had a similar problem with the beta 3 release where x64 failed to install on my computer. Not sure if the underlying issue is the same as yours but my issue was resolved after uninstalling the Visual Studio C++ runtime, rebooting and doing a clean install. I wanted to report the issue then, but since I could not reproduce it, I had nothing exact to say other than 'did not work for me, now it does, don't know if it was me or you'. :-) Hope this helps. Best regards, Jurko Gospodneti? From luke.geelen at gmail.com Tue Feb 11 14:54:06 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 11:54:06 -0800 (PST) Subject: Flag control variable In-Reply-To: References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> Message-ID: <30df1873-45fd-4960-9407-86b0da73f41d@googlegroups.com> Op dinsdag 11 februari 2014 20:28:44 UTC+1 schreef Tim Chase: > On 2014-02-11 11:06, luke.geelen at gmail.com wrote: > > > > > > command1 = "sudo mpg321 > > > > > > > > > > > > > > > > > > > 'http://translate.google.com/translate_tts?tl=en&q=%s_times%s_equals%s'" > > > > > > 1) PLEASE either stop using Google Groups or take the time to remove > > the superfluous white-space you keep adding to your posts/replies > > > > 2) you shouldn't need to use "sudo" to play sounds. That's just a > > bad practice waiting for trouble. > > > > -tkc its one rule in the original (at least on my computer) From luke.geelen at gmail.com Tue Feb 11 14:55:33 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 11:55:33 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: hey, i got another problem now, if i use the imterpreter to do 3 * 4 it gives twelve the script gives 3333? any tips From breamoreboy at yahoo.co.uk Tue Feb 11 15:02:26 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 11 Feb 2014 20:02:26 +0000 Subject: Flag control variable In-Reply-To: <30df1873-45fd-4960-9407-86b0da73f41d@googlegroups.com> References: <5019eb5d-ebda-4417-ab2d-9a58afcdd186@googlegroups.com> <9881c34f-20f4-43ea-9f9c-e1bd7fec8400@googlegroups.com> <30df1873-45fd-4960-9407-86b0da73f41d@googlegroups.com> Message-ID: On 11/02/2014 19:54, luke.geelen at gmail.com wrote: > Op dinsdag 11 februari 2014 20:28:44 UTC+1 schreef Tim Chase: >> >> 1) PLEASE either stop using Google Groups or take the time to remove >> the superfluous white-space you keep adding to your posts/replies >> For the THIRD time, would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing which I've AGAIN snipped, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From gary.herron at islandtraining.com Tue Feb 11 15:19:06 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 12:19:06 -0800 Subject: Flag control variable In-Reply-To: References: Message-ID: <52FA85BA.3080708@islandtraining.com> On 02/11/2014 11:55 AM, luke.geelen at gmail.com wrote: > hey, i got another problem now, > if i use the imterpreter to do 3 * 4 it gives twelve > the script gives 3333? > any tips >>> 3*4 12 >>> "3"*4 '3333' Multiplying two integers produces the result you expect. Multiplying a *string* by an integer is what you are doing. (And it just repeats the string a number of times -- not what you want.) Your code used to have int(...) to convert the string supplied by sys.argv into integers. What happened to them? Gary Herron From luke.geelen at gmail.com Tue Feb 11 16:18:40 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 13:18:40 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: Would it be possible to make an int(sys.argv[1]) Not needed and set value 0 ( or in another script 1) For example a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) And I run Python ./script.py 2 3 It just set c automaticly to 0 or 1 Luke (PS thanks for the quick help) From greg.ewing at canterbury.ac.nz Tue Feb 11 17:56:57 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 12 Feb 2014 11:56:57 +1300 Subject: Sort one sequence by O(n) in time and O(1) in space In-Reply-To: <52f9b31c$0$11128$c3e8da3@news.astraweb.com> References: <52f80bca$0$29972$c3e8da3$5496439d@news.astraweb.com> <9671c418-cde8-4857-85ec-52380f8390eb@googlegroups.com> <52f9b31c$0$11128$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Secondly, O(N*log N) applies to *comparison sorts*. Non-comparison sorts > such as radix-, counting- and bucket-sort have average case complexity of > O(N). They require additional space, though. -- Greg From gary.herron at islandtraining.com Tue Feb 11 18:47:35 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Tue, 11 Feb 2014 15:47:35 -0800 Subject: Flag control variable In-Reply-To: References: Message-ID: <52FAB697.7070908@islandtraining.com> On 02/11/2014 01:18 PM, luke.geelen at gmail.com wrote: > Would it be possible to make an > int(sys.argv[1]) > Not needed and set value 0 ( or in another script 1) > For example > a = int(sys.argv[1]) > b = int(sys.argv[2]) > c = int(sys.argv[3]) > And I run > Python ./script.py 2 3 > > It just set c automaticly to 0 or 1 > > Luke > > (PS thanks for the quick help) That question does not make sense to me. Yes, you can set c=1 in your program, or zero if that's what you want, but this can't be the question you are really trying to ask. From emile at fenx.com Tue Feb 11 19:21:59 2014 From: emile at fenx.com (emile) Date: Tue, 11 Feb 2014 16:21:59 -0800 Subject: ANN: PSF Python Marketing Brochure - Last call for Ad Sponsors In-Reply-To: <52FA4D72.8020607@python.org> References: <52FA4D72.8020607@python.org> Message-ID: Under Subscription Sponsors in the listing of destinations, I'm going to guess from the grouping that NE should be NL. Emile On 02/11/2014 08:18 AM, M.-A. Lemburg wrote: > [Please help spread the word by forwarding to other relevant mailing lists, > user groups, etc. world-wide; thanks :-)] > > ________________________________________________________________________ > ANNOUNCING > > PSF Python Marketing Brochure - Last call for Ad Sponsors > > > Please support the PSF in providing the Python community with > free high quality marketing material > to promote Python > > ________________________________________________________________________ > INTRODUCTION > > Over the last few years, the Python brochure team has worked on and > created a high-quality brochure to help user groups, conferences and > companies using Python to promote and spread the word about Python. > > The brochure will be printed in a first edition of 10,000 copies > which the PSF will then distribute to user groups, Python conferences > and educational institutions on request and free of charge. > > With the Python brochure, we hope to reach out to an audience which > is not easy to address and convince using electronic and mostly > developer oriented media. > > ________________________________________________________________________ > PREVIEW > > Please take a look at our preview PDF version of the brochure to see > for yourself: > > http://brochure.getpython.info/preview.pdf > > ________________________________________________________________________ > SEEKING YOUR HELP > > The team set out to create and print the brochure without introducing > extra costs for the PSF. Our aim is to fully finance the brochure > production, printing and shipment to interested parties using money > from sponsors. > > To make this happen, we are seeking your help ! > > => We have already signed up sponsors for 6 half page ads, but still > need another *5 half page ad sponsors* to sign up. > > => There are also *6 smaller reference entry sponsorships* left to > be sold. > > If you are affiliated with or know a company investing into Python > and looking for ways to reach out to a large audience of interested > Python users, students, developers - and people in key decision making > positions, please reach out to us and help make the project > a success. > > The deadline for ad and reference entry signups is *Feb 28* - in just > under three weeks. > > You can find all the details about the available sponsorship > options on this page: > > http://brochure.getpython.info/sponsorship > > Orders can be placed directly with the production company, Evenios > Publishing on the website. All sponsors will receive a box of about > 120 free copies of the brochure as Thank You gift. > > ________________________________________________________________________ > ORDERING EXTRA COPIES > > Companies who are interested in receiving extra copies can pre-order > additional boxes which will then be printed in addition to the > initial 10.000 copy batch: > > http://brochure.getpython.info/mediadata/subscription-order-procedure > > It is also possible to donate such extra boxes to educational > institutions: > > http://brochure.getpython.info/mediadata/education-sponsorship > > If you have special requirements, please contact the team at > brochure at getpython.info for more information. We're very flexible > in addressing your needs. > > ________________________________________________________________________ > MORE INFORMATION > > More information on the brochure, the idea behind it, media data > and ordering links are available on our project page: > > http://brochure.getpython.info/ > > > Thanks for your help, > From ngangsia at gmail.com Tue Feb 11 19:21:29 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Tue, 11 Feb 2014 16:21:29 -0800 (PST) Subject: Python programming Message-ID: Please i have a silly question to ask. How long did it take you to learn how to write programs? What is the best way i can master thinker? I know the syntax but using it to write a program is a problem From ngangsia at gmail.com Tue Feb 11 19:21:47 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Tue, 11 Feb 2014 16:21:47 -0800 (PST) Subject: Python programming Message-ID: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Please i have a silly question to ask. How long did it take you to learn how to write programs? What is the best way i can master thinker? I know the syntax but using it to write a program is a problem From travisgriggs at gmail.com Tue Feb 11 19:34:03 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Tue, 11 Feb 2014 16:34:03 -0800 Subject: Fun with function argument counts Message-ID: <5A4B42E0-BE7F-415F-87D4-8A6B3A98D81D@gmail.com> After the recent discussion about the classic error: if self.isFooBar: return 42 Among many thing, the OPs contention was that the ability to have this kind of error was a Bad Thing (tm). Which led to me asking about code smells and parameterless functions/methods. So I got curious. Semantics of implicit objects aside, how often is it possible to write code like that. In short, how frequent are methods/functions that have zero explicit args (not implicit, because while fun, that?s not how we code them). It was a fun experiment, I?ve been doing python for a little over a year now, and I thought it would be enjoyable/educational to do a bit of metaprogramming. First the results though. Below is a histogram of function argument count: argCount x occurrences (% of total) -1 x 10426 ( 3.2%) # these are where I stuffed all of the routines I couldn?t extract the argspecs for 0 x 160763 (48.7%) 1 x 109028 (33.0%) 2 x 40473 (12.3%) 3 x 7059 ( 2.1%) 4 x 2383 ( 0.7%) 5 x 141 ( 0.0%) 6 x 46 ( 0.0%) 7 x 12 ( 0.0%) 10 x 1 ( 0.0%) 16 x 1 ( 0.0%) 19 x 2 ( 0.0%) Nearly half of the functions/methods I scanned were zero args (48.7). Which was more than I expected. I haven?t dug enough to see if there?s a flock of canaries in there or not. The code to produce that table is here: https://gist.github.com/anonymous/8947229. Yes, it?s hacky. Wasn?t trying to win any style/idiom awards with this one. To get this table, I used PyPy 3-2.1 beta for OSX. I basically attempted to parse all of the modules found in it?s lib-python directory. A subset of the modules wouldn?t load, I?m not sure whether to write that off as the work-in-progress nature of pypy or what. And I black listed some of them (such as idlelib.idle, ctypes.test.*, etc). But from the counts, I was able to get a pretty large corpus of them. I learned a number of fun things as part of the exercise: 1) I did not want to try load all modules at once into my environment. I suspect that would create problems. Using os.fork() to isolate the load/analysis of each module was a handy way to deal with that. The trick of using if pid: branch to split of the flow of execution was cool. Maybe it?s the wrong tool for the job and I missed an obvious one, but I thought it was kinda clever. 2) Using cpython, a lot of the core library can?t be reflected on. I tried to use the inspect module, and found that things like inspect.getmembers(datetime.datetime, inspect.ismethod) resulted in a big surprise. Especially if you leave off the predicate, and see that there are a lot of things in there that claim they ARE methods). I finally stumbled into inspect.isroutine, but found that most of the results couldn?t be reified using inspect.signature anyway. The ?it?s all python, all the way down, well mostly? ideology of pypy ensured that a higher percentage opt the base libraries could be analyzed. 3) It?s easy to take 3.3.x for granted. I found right away that signature was introduced in 3.3, so I had to use inspect.getfullargspec() instead. 4) optional arguments were an interesting dillema. I chose to reduce the argument count of a signature by the number of default arguments. Since they are essentially optional. So the stats there have a bias to the ?minimal? call signature. 5) my method of scanning loadable modules is probably very naive/brute force/stupid. I would love it if there was a better way to do that. 6) Who writes a function with 19 mandatory arguments anyway???? subprocess._execute_child() and distutils.cygwincompiler._execute_child() 7) I?m not entirely sure, given #6, that I?m not seeing inherited methods for all classes, so getting an overinflated count from them. Can anyone answer that? From breamoreboy at yahoo.co.uk Tue Feb 11 19:54:21 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 00:54:21 +0000 Subject: Python programming In-Reply-To: <26217118-437d-464b-bc32-151795880030@googlegroups.com> References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: On 12/02/2014 00:21, ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? > > What is the best way i can master thinker? > I know the syntax but using it to write a program is a problem > You *NEVER* stop learning. To become a master thinker take a degree in philosophy. On the other hand to master tkinter search for a tutorial that you can follow. Or if you're feeling brave help out with tkinter or IDLE issues on the bug tracker at bugs.python.org :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rosuav at gmail.com Tue Feb 11 20:05:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 12:05:49 +1100 Subject: Fun with function argument counts In-Reply-To: <5A4B42E0-BE7F-415F-87D4-8A6B3A98D81D@gmail.com> References: <5A4B42E0-BE7F-415F-87D4-8A6B3A98D81D@gmail.com> Message-ID: On Wed, Feb 12, 2014 at 11:34 AM, Travis Griggs wrote: > 1) I did not want to try load all modules at once into my environment. I suspect that would create problems. Using os.fork() to isolate the load/analysis of each module was a handy way to deal with that. The trick of using if pid: branch to split of the flow of execution was cool. Maybe it?s the wrong tool for the job and I missed an obvious one, but I thought it was kinda clever. > That's the normal way to use fork() in any environment. The standard C idiom is to call fork(), and then test for *three* possibilities: 0 means you're in the child, >0 means you're in the parent, and <0 means you're still in the parent, and forking failed. Python simplifies that a bit by raising an error if something goes wrong, so you can simply: if os.fork(): # Parent continues else: # Child process > 2) Using cpython, a lot of the core library can?t be reflected on That's being improved as of 3.4, thanks to Argument Clinic. Though the whole stdlib might not be converted, so you might have to wait for 3.5. > 4) optional arguments were an interesting dillema. I chose to reduce the argument count of a signature by the number of default arguments. Since they are essentially optional. So the stats there have a bias to the ?minimal? call signature. > That's one way to look at it. That tells you what can be called with no args. But it's not always a fair look at the function's usefulness; maybe with no arguments, it always returns a constant value: >>> bool() False The bool function (really the type/constructor) is much more useful with an argument, but it's technically callable without. > 6) Who writes a function with 19 mandatory arguments anyway???? subprocess._execute_child() and distutils.cygwincompiler._execute_child() Hmm. Those are internal functions (leading underscore). Might be fairer to remove those from consideration. ChrisA From swdunning at cox.net Tue Feb 11 20:06:17 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Feb 2014 18:06:17 -0700 Subject: Simple % question Message-ID: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> I just have a simple question. I don?t understand why 1%10 = 1? From davea at davea.name Tue Feb 11 20:11:39 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Feb 2014 20:11:39 -0500 (EST) Subject: Python programming References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: ngangsia akumbo Wrote in message: > Please i have a silly question to ask. > No silly questions, just silly answers. > How long did it take you to learn how to write programs? > An hour, twenty years. It took an hour to learn how the keypunch worked, where the manuals were mounted, and how to submit unauthorized card decks to the college computer. Twenty years to find out that managing people was harder than managing computer languages. I did some of my best work before I learned that some of those problems were impossible. > What is the best way i can master thinker? Never heard of it. Is it a computer language? > I know the syntax but using it to write a program is a problem > -- DaveA From rosuav at gmail.com Tue Feb 11 20:17:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 12:17:36 +1100 Subject: Python programming In-Reply-To: References: Message-ID: On Wed, Feb 12, 2014 at 11:21 AM, ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? Well, let's see. I started programming a quarter of a century ago, and I'm a lot less than a quarter of the way to knowing everything about programming, so I'd say it'll take at least a hundred years :) Seriously, you will spend your whole life learning. Just as a program is never finished, but at some point you ship it, so also a programmer has never learned, but at some point you start writing things that are useful to other people. At what point does that happen? Varies enormously. Lots of teenagers go through a school or uni course on programming thinking, "I'm going to write a computer game!". That is, IMO, a bad start to programming - a truly fun game that can be written after taking a basic comp sci course is going to be a reimplementation of one that already exists (maybe Othello - that would be within a uni graduate's skill, I think), which isn't what most people think of when talking about "writing a computer game". So what's your goal? Automate some mundane task that you do every day/week/month? You could master that fairly readily. Win at Jeopardy using a supercomputer? Try assembling an IBM-level team of experts. :) > What is the best way i can master thinker? > I know the syntax but using it to write a program is a problem As Mark says, mastering tkinter means picking up a tutorial and working through it. More generally, I would recommend learning *any* skill (programming or not) by having a need, and chipping away at the problem until you've solved it to your own satisfaction. Don't learn tkinter just for the sake of learning tkinter; learn it because you want to make XYZ, for which you want/need a GUI. (Until you're an expert programmer already. Then you might learn a new skill just for the sake of learning it, but there's a difference, and you'll know it when you get to that point. Sometimes it's fun to create something under stupid restrictions that make absolutely no sense - that's part of the basis of code golf, for instance.) ChrisA From walterhurry at gmail.com Tue Feb 11 20:21:42 2014 From: walterhurry at gmail.com (Walter Hurry) Date: Wed, 12 Feb 2014 01:21:42 +0000 (UTC) Subject: Python programming References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: Dave Angel wrote: >> What is the best way i can master thinker? > > Never heard of it. Is it a computer language? > Socrates himself is particularly missed From rosuav at gmail.com Tue Feb 11 20:26:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 12:26:22 +1100 Subject: Python programming In-Reply-To: References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 12:11 PM, Dave Angel wrote: > I did some of my best work before I learned that some of those > problems were impossible. Sounds like something from the invention of Post-It Notes. I can't find an authoritative source, but it's all over the internet, attributed to Spencer Silver: "If I had thought about it, I wouldn't have done the experiment. The literature was full of examples that said you can't do this." Programming is often like this. Actually, computing generally. The literature was full of examples that said that "Alice: Madness Returns" required Windows 7, a hot video card, and so on. Turns out that Linux and Wine will do the job quite nicely. Never mind that the makers are completely uninterested in helping... I just did some leg-work and got my favourite recent game going under my favourite operating system :) ChrisA From larry.martell at gmail.com Tue Feb 11 20:26:44 2014 From: larry.martell at gmail.com (Larry Martell) Date: Tue, 11 Feb 2014 20:26:44 -0500 Subject: Python programming In-Reply-To: References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: On Tue, Feb 11, 2014 at 8:21 PM, Walter Hurry wrote: > Dave Angel wrote: > >>> What is the best way i can master thinker? >> >> Never heard of it. Is it a computer language? >> > Socrates himself is particularly missed A lovely little thinker, but a bugger when he's pissed. From ngangsia at gmail.com Tue Feb 11 20:29:13 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Tue, 11 Feb 2014 17:29:13 -0800 (PST) Subject: Python programming In-Reply-To: References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: On Wednesday, February 12, 2014 2:11:39 AM UTC+1, Dave Angel wrote: > ngangsia akumbo Wrote in message: python GUI Tkinter From ben+python at benfinney.id.au Tue Feb 11 20:31:22 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 12:31:22 +1100 Subject: Simple % question References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> Message-ID: <858uthce1h.fsf@benfinney.id.au> Scott W Dunning writes: > I just have a simple question. I don?t understand why 1%10 = 1? Have you read the documentation for that operator? The language reference is the place to look for official explanations of language features. -- \ ?I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators.? ?Steven Wright | _o__) | Ben Finney From ethan at stoneleaf.us Tue Feb 11 20:15:36 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 11 Feb 2014 17:15:36 -0800 Subject: Fun with function argument counts In-Reply-To: References: <5A4B42E0-BE7F-415F-87D4-8A6B3A98D81D@gmail.com> Message-ID: <52FACB38.2070106@stoneleaf.us> On 02/11/2014 05:05 PM, Chris Angelico wrote: > On Wed, Feb 12, 2014 at 11:34 AM, Travis Griggs wrote: > >> 6) Who writes a function with 19 mandatory arguments anyway???? >> subprocess._execute_child() and distutils.cygwincompiler._execute_child() > > Hmm. Those are internal functions (leading underscore). Might be > fairer to remove those from consideration. Not at all. Even private routines get used by somebody! ;) -- ~Ethan~ From rosuav at gmail.com Tue Feb 11 20:36:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 12:36:37 +1100 Subject: Simple % question In-Reply-To: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> Message-ID: On Wed, Feb 12, 2014 at 12:06 PM, Scott W Dunning wrote: > I just have a simple question. I don?t understand why 1%10 = 1? The real question is: What do you expect that symbol to mean? Its actual meaning is quite simple. In long division, dividing one number by another looks like this: 86528 ____________ 31415 ) 2718281828 251320 ------ 205081 188490 ------ 165918 157075 ------ 88432 62830 ----- 256028 251320 ------ 4708 (Monospaced font required here.) 2718281828 is the dividend; 31415 is the divisor. They're the numbers we started with. At the top, we get the quotient, 86528, and down the bottom, the remainder, 4708. Now let's ask Python about those numbers: >>> 2718281828 // 31415 86528 >>> 2718281828 % 31415 4708 That's all it is. The // operator, when given two integers, will give back an integer which is the quotient. The % operator (usually called "modulo"), given the same two integers, gives you back the remainder. With the dividend smaller than the divisor, your quotient is zero and your remainder is the whole rest of the number; so 1 % 10 is 1. In fact, 1 % anything greater than 1 will be 1. Does that help? ChrisA From cjwelborn at live.com Tue Feb 11 20:51:41 2014 From: cjwelborn at live.com (Christopher Welborn) Date: Tue, 11 Feb 2014 19:51:41 -0600 Subject: Simple % question In-Reply-To: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> Message-ID: On 02/11/2014 07:06 PM, Scott W Dunning wrote: > I just have a simple question. I don?t understand why 1%10 = 1? > > I think because 1 is evenly divisible by 10 exactly 0 times with a 1 remainder. I mean int(1 / 10) == 0, with a 1 remainder. The same is true for all numbers leading up to 10. for i in range(12): print('{} % 10 == {}'.format(i, i % 10)) 0 % 10 == 0 1 % 10 == 1 2 % 10 == 2 3 % 10 == 3 4 % 10 == 4 5 % 10 == 5 6 % 10 == 6 7 % 10 == 7 8 % 10 == 8 9 % 10 == 9 10 % 10 == 0 11 % 10 == 1 You can see that with the divmod() function also. -- \?\ /?/\ \ \/??\/ / / Christopher Welborn (cj) \__/\__/ / cjwelborn at live?com \__/\__/ http://welbornprod.com From rustompmody at gmail.com Tue Feb 11 21:16:45 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 11 Feb 2014 18:16:45 -0800 (PST) Subject: Simple % question In-Reply-To: References: Message-ID: On Wednesday, February 12, 2014 6:36:17 AM UTC+5:30, Scott W Dunning wrote: > I just have a simple question. I don't understand why 1%10 = 1? This is not really about python. See http://en.wikipedia.org/wiki/Euclidean_division Particularly the examples section and note that when you divide a by b you get a quotient -- q and remainder -- r. In your case a is 1 b is 10. Now see that wikipedia page From rustompmody at gmail.com Tue Feb 11 21:46:14 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 11 Feb 2014 18:46:14 -0800 (PST) Subject: Python programming In-Reply-To: References: Message-ID: On Wednesday, February 12, 2014 5:51:29 AM UTC+5:30, ngangsia akumbo wrote: > Please i have a silly question to ask. > > > How long did it take you to learn how to write programs? > > > What is the best way i can master thinker? > > I know the syntax but using it to write a program is a problem It takes 5 years to become a doctor It takes 10 years to become a musician At 3 years or thereabouts, (a typical computer science degree), programming is a bit easier. With some shaving off of fluff one could halve that 3 years. With even more aggressive shaving off, maybe one more halve. But thats it. And that implies: - You are working full (and over) time just to learn - You have a bunch of intelligent and dedicated teachers calibrating your progress and your learning-curve - You have at least normal intelligence - You dont suffer from excessive delusions [Just in case you think the last insulting, let me tell you about myself: When I was doing my first programming class, my 'goal' was to write an Ada compiler. This is called a delusion] It may help you to have a look at the area as seen for example here: http://ai.stanford.edu/users/sahami/CS2013/strawman-draft/cs2013-strawman.pdf From rustompmody at gmail.com Tue Feb 11 22:01:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 11 Feb 2014 19:01:13 -0800 (PST) Subject: Newcomer Help In-Reply-To: References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: On Tuesday, February 11, 2014 10:19:53 PM UTC+5:30, Walter Hughey wrote: > > This "newcomer" apologizes for?------ this crap came from you ---------. Firstly, on the behalf of the list, Apologies for uncalled for and unhelpful rudeness > I suppose what you mean by "top posting" is replying to an email by entering > a reply at the top when according to your policies and procedures - a person > should reply at the bottom of the email - like this. IF/WHEN I am on this > site, I shall do my utmost best to change the way I and the people I normally > work with to reply at the bottom, Assuming?Gisle Vanem this is what you mean > and what you want. See http://en.wikipedia.org/wiki/Posting_style Most people here prefer interleaved posting with significant trimming. In other contexts eg corporates, often the culture is the opposite: top-posting with strictly NO trimming. And one more suggestion: Use text mode for your posts not html > > > I hope I have not totally destroyed all of everybody's systems with my inappropriate and thoughtless disregard for the sanctity of this site. May be it be best I not reply/ask for help/or in any way be involved in this site. No you have done no such thing and I hope you wont generalize one instance to the whole community From roy at panix.com Tue Feb 11 22:02:20 2014 From: roy at panix.com (Roy Smith) Date: Tue, 11 Feb 2014 22:02:20 -0500 Subject: Python programming References: Message-ID: In article , ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? I've been working on it for 40 years. I'll let you know when I get there. From ameyer2 at yahoo.com Tue Feb 11 22:19:12 2014 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 11 Feb 2014 22:19:12 -0500 Subject: Python programming In-Reply-To: <26217118-437d-464b-bc32-151795880030@googlegroups.com> References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: <52FAE830.9080606@yahoo.com> On 2/11/2014 7:21 PM, ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? > > What is the best way i can master thinker? > I know the syntax but using it to write a program is a problem Here's one way to learn: Start with a manual (the online Python and Tkinter manuals are fine) and a computer. While (true): Write some code using skills that you have plus at least one new thing you've never done before that you will master and add to your skills. If you're not having fun: break To start, a total beginner might try things that take 10 minutes and 3 lines of code. Over time the skills he has will keep increasing and he'll find himself writing longer programs that take more time to write and produce more interesting outputs. The key is to have fun. If you find this work interesting and absorbing, you'll learn quickly and you'll enjoy all the time that you spend on it. You might get good enough in just a few months to try some very significant and useful programs. You won't be ready to write commercial software, but you'll be on your way. If you find it uninteresting, boring, or impossible to understand, then programming might not be the right thing for you. That doesn't mean you aren't smart. I've met some very smart people who don't like programming and aren't good at it. There are already too many programmers who don't really like programming and just learned it because they thought they could get good jobs. Most of them wind up with relatively bad jobs and are not respected by their colleagues. Don't join that crowd. Best of luck. Alan From asdrubalivan.listas at gmail.com Tue Feb 11 19:31:13 2014 From: asdrubalivan.listas at gmail.com (=?ISO-8859-1?Q?Asdr=FAbal_Iv=E1n_Su=E1rez?=) Date: Tue, 11 Feb 2014 20:01:13 -0430 Subject: Python programming In-Reply-To: References: Message-ID: Hello! Well, I got the knowledge at college, it took me a year to know the basics (But I guess it can take less if you work hard on it). I began with C, then C++ and right now I'm with Python (I use PHP too). That said, there are some interesting resources out there that you can use to learn. Codeacademy is a very good one[1]. Best of luck with your endeavor :) [1] http://www.codecademy.com 2014-02-11 19:51 GMT-04:30 ngangsia akumbo : > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? > > What is the best way i can master thinker? > I know the syntax but using it to write a program is a problem > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From asdrubalivan.listas at gmail.com Tue Feb 11 20:00:22 2014 From: asdrubalivan.listas at gmail.com (=?ISO-8859-1?Q?Asdr=FAbal_Iv=E1n_Su=E1rez?=) Date: Tue, 11 Feb 2014 20:30:22 -0430 Subject: Python programming In-Reply-To: References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: 2014-02-11 20:24 GMT-04:30 Mark Lawrence : > > > > > To become a master thinker take a degree in philosophy. > > On the other hand to master tkinter search for a tutorial that you can > follow. Or if you're feeling brave help out with tkinter or IDLE issues on > the bug tracker at bugs.python.org :) > > That's a good option too! Once you know the basics, try this book --> http://inventwithpython.com/ > -- > My fellow Pythonistas, ask not what our language can do for you, ask what > you can do for our language. > > Mark Lawrence > > --- > This email is free from viruses and malware because avast! Antivirus > protection is active. > http://www.avast.com > > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Tue Feb 11 22:38:21 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Feb 2014 20:38:21 -0700 Subject: Simple % question In-Reply-To: References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> Message-ID: <7F4A4207-585B-4F38-89ED-C26EBB780F23@cox.net> On Feb 11, 2014, at 6:51 PM, Christopher Welborn wrote: > I think because 1 is evenly divisible by 10 exactly 0 times with a 1 > remainder. I mean int(1 / 10) == 0, with a 1 remainder. > The same is true for all numbers leading up to 10. > Actually I think I get it now. I think I was not really looking at it as 1/10 more like the other way around. From rosuav at gmail.com Tue Feb 11 22:40:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 14:40:17 +1100 Subject: Simple % question In-Reply-To: <4ED77821-6237-484F-A6BF-5B970CC6560B@cox.net> References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> <4ED77821-6237-484F-A6BF-5B970CC6560B@cox.net> Message-ID: On Wed, Feb 12, 2014 at 2:30 PM, Scott W Dunning wrote: > On Feb 11, 2014, at 6:36 PM, Chris Angelico wrote: >> >> The real question is: What do you expect that symbol to mean? >> >> Its actual meaning is quite simple. In long division, dividing one >> number by another looks like this: > > Yeah I understand what the % means. It just confused me that 1%10 was 1. In my thought process it just didn?t work. 1/10= .1 and I just didn?t see where the remainder of 1 came in. > Ah, yes. When Python 2 -> Python 3 changed the meaning of / the meaning of % got tied instead to //. But if you think about it, with the floating-point result you're describing there, it simply makes no sense to even ask what the remainder is. So, if you're going to use %, use //, and then it all makes sense. ChrisA From ben+python at benfinney.id.au Tue Feb 11 23:09:50 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 15:09:50 +1100 Subject: Python programming References: Message-ID: <854n45c6pd.fsf@benfinney.id.au> ngangsia akumbo writes: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? Please clarify what you mean by ?how to write programs?. I could write programs perhaps ten minutes after beginning to learn; but learning how to write programs *well* is a learning journey which continues thirty years later. So, what are you asking? What level of skill do you want to attain, how would you describe the goal? -- \ ?In general my children refuse to eat anything that hasn't | `\ danced on television.? ?Erma Bombeck | _o__) | Ben Finney From ben+python at benfinney.id.au Tue Feb 11 23:14:20 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 15:14:20 +1100 Subject: Newcomer Help References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: <85zjlxarxf.fsf@benfinney.id.au> Rustom Mody writes: > On Tuesday, February 11, 2014 10:19:53 PM UTC+5:30, Walter Hughey wrote: > > I suppose what you mean by "top posting" is replying to an email by > > entering a reply at the top That's right. Top-posting is wasteful of the reader's time while it also omits a lot of contextual information. > See http://en.wikipedia.org/wiki/Posting_style > > Most people here prefer interleaved posting with significant trimming. It's worth pointing out that you will likely find the ?interleaved posting with trimmed quotations? to be *acceptable* virtually everywhere on the internet. So it's a good practice to adopt for all such forums. > In other contexts eg corporates, often the culture is the opposite: > top-posting with strictly NO trimming. I've never found a corporation that objects to the sensible conversation-style, minimal-quotes-for-context interleaved posting style. > And one more suggestion: > Use text mode for your posts not html Yes, especially for technical forums where you'll need to frequently show *exactly* what text you mean, without unexpected rendering differences. -- \ ?Generally speaking, the errors in religion are dangerous; | `\ those in philosophy only ridiculous.? ?David Hume, _A Treatise | _o__) of Human Nature_, 1739 | Ben Finney From swdunning at cox.net Tue Feb 11 22:30:23 2014 From: swdunning at cox.net (Scott W Dunning) Date: Tue, 11 Feb 2014 20:30:23 -0700 Subject: Simple % question In-Reply-To: References: <63EBCBF1-6C1B-4B8B-9D4A-0567CBDA978A@cox.net> Message-ID: <4ED77821-6237-484F-A6BF-5B970CC6560B@cox.net> On Feb 11, 2014, at 6:36 PM, Chris Angelico wrote: > > The real question is: What do you expect that symbol to mean? > > Its actual meaning is quite simple. In long division, dividing one > number by another looks like this: Yeah I understand what the % means. It just confused me that 1%10 was 1. In my thought process it just didn?t work. 1/10= .1 and I just didn?t see where the remainder of 1 came in. From roegltd at gmail.com Tue Feb 11 23:34:37 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 11 Feb 2014 20:34:37 -0800 (PST) Subject: singleton ... again Message-ID: playing a bit with subject. pros and cons of this approach? did i create bicycle again? :-) class myclass(object): class_instance = None def __new__(cls, *args, **kwargs): if myclass.class_instance == None: return object.__new__(cls) return myclass.class_instance def __init__(self, some): if self.__class__.class_instance == None: # init blocker self.__class__.class_instance = self self.member = some def __del__(self): self.__class__.class_instance = None one_class = myclass(1) print(id(one_class), one_class.member ) two_class = myclass(2) print(id(two_class), two_class.member) From luke.geelen at gmail.com Wed Feb 12 00:09:02 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Tue, 11 Feb 2014 21:09:02 -0800 (PST) Subject: Flag control variable In-Reply-To: References: Message-ID: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> Can I make it that if C = int(sys.argv[3]) But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 From davea at davea.name Wed Feb 12 00:23:14 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 00:23:14 -0500 (EST) Subject: Flag control variable References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> Message-ID: luke.geelen at gmail.com Wrote in message: > Can I make it that if > C = int(sys.argv[3]) > But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 > Why do you ask for 'automatically'? You're the programmer, write the test in the code. if len (sys.argv) == 3: sys.argv. append ("0") But of course there are lots of other things you need to check, so consider all of them at the same time. -- DaveA From roegltd at gmail.com Wed Feb 12 00:15:35 2014 From: roegltd at gmail.com (Asaf Las) Date: Tue, 11 Feb 2014 21:15:35 -0800 (PST) Subject: singleton ... again In-Reply-To: References: Message-ID: there is error should assign weakref to class static member otherwise __del__ will never be called. From davea at davea.name Wed Feb 12 00:48:51 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 00:48:51 -0500 (EST) Subject: singleton ... again References: Message-ID: Asaf Las Wrote in message: > playing a bit with subject. > > pros and cons of this approach? did i create bicycle again? :-) > > class myclass(object): > class_instance = None > > def __new__(cls, *args, **kwargs): > if myclass.class_instance == None: > return object.__new__(cls) > return myclass.class_instance > > def __init__(self, some): > if self.__class__.class_instance == None: # init blocker > self.__class__.class_instance = self > self.member = some > > def __del__(self): > self.__class__.class_instance = None > > one_class = myclass(1) > print(id(one_class), one_class.member ) > > two_class = myclass(2) > print(id(two_class), two_class.member) > > Perhaps if you would state your actual goal, we could judge whether this code is an effective way to accomplish it. -- DaveA From roy at panix.com Wed Feb 12 00:55:59 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 00:55:59 -0500 Subject: singleton ... again References: Message-ID: In article , Dave Angel wrote: > Asaf Las Wrote in message: > > playing a bit with subject. > > > > pros and cons of this approach? did i create bicycle again? :-) > > > > class myclass(object): > > class_instance = None > > > > def __new__(cls, *args, **kwargs): > > if myclass.class_instance == None: > > return object.__new__(cls) > > return myclass.class_instance > > > > def __init__(self, some): > > if self.__class__.class_instance == None: # init blocker > > self.__class__.class_instance = self > > self.member = some > > > > def __del__(self): > > self.__class__.class_instance = None > > > > one_class = myclass(1) > > print(id(one_class), one_class.member ) > > > > two_class = myclass(2) > > print(id(two_class), two_class.member) > > > > > > Perhaps if you would state your actual goal, we could judge > whether this code is an effective way to accomplish > it. It looks to me like he's trying to implement a classic Gang of Four singleton pattern. From pydev at allsup.co Wed Feb 12 02:05:11 2014 From: pydev at allsup.co (John Allsup) Date: Wed, 12 Feb 2014 07:05:11 +0000 Subject: Top down Python Message-ID: <52FB1D27.8090009@allsup.co> What is needed for proper learning is near-absolute simplicity. Even one toy too many to play with is an intolerable distraction, but one too few massively hampers learning and induces boredom. I want to be able to say: 1. Put a nice picture on the background. 2. Put a terminal window with, say, 64x20 lines, dead centre. 3. Run a simple REPL program written in Python or Ruby within it. I do not really want to write any more lines of code than I need to. Why do we not have langauges and libraries that can do the above with only five lines of code (line 0 == setup, line 4 == cleanup). Programming should be that efficient if we learn to make things beautiful and not tolerate wastes of lines and characters, on a global scale as well as locally to our projects. Consider ==== #!/usr/bin/env python3 from myappfw import app from myapp1 import repl app.background = "Moutains1" t = app.terminal.open(title="Typing commands One Oh One",position="centre", width="80%",height="72%",rows="20",columns="64") exit(t.run(repl)) ==== What Python would I need to write, as concise but readable as practically possible, so that the above program works as desired (for any repl that obeys the basic input-process-output behaviour of a repl)? This is top-down design done right IMO (as described in Thinking Forth, by the way). From rosuav at gmail.com Wed Feb 12 02:42:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 18:42:11 +1100 Subject: Top down Python In-Reply-To: <52FB1D27.8090009@allsup.co> References: <52FB1D27.8090009@allsup.co> Message-ID: On Wed, Feb 12, 2014 at 6:05 PM, John Allsup wrote: > 1. Put a nice picture on the background. > 2. Put a terminal window with, say, 64x20 lines, dead centre. > 3. Run a simple REPL program written in Python or Ruby within it. > I do not really want to write any more lines of code than I need to. > Why do we not have langauges and libraries that can do the above > with only five lines of code (line 0 == setup, line 4 == cleanup). #!/bin/sh xfce4-terminal --geometry=64x20 -x python3 There you are, two lines. :) Seriously though, what you're asking is deceptively simple yet incredibly difficult. You're trying to recreate the entire structure of a terminal emulator or telnet client. I can show you the code for a MUD client, which does a lot of what you're looking for; in fact, this one has a REPL inbuilt (not Python or Ruby though): https://github.com/Rosuav/Gypsum/ That's roughly how much code it takes to make a reasonably usable replicant of a terminal window. (Some of that is specific to networking and MUDding, but at very least, window.pike is basically all about the visuals.) You'll do far better to make use of someone else's terminal renderer, and just put a desktop background to make your fancy image. Otherwise, you have to recreate everything - console output (complete with color, presumably), scrolling, input history (you can get most of your editing keys easily enough, but you will need command history), clipboard operations, and somewhere along the way, performance. Save yourself a whole mess of trouble and just use your OS-provided terminal program :) Actually, for what you're looking at, IDLE is probably close to what you want. You could have a look at how much code it takes to power IDLE, and/or just use it as is. It's pretty handy; I use it as my primary interactive Python on Windows. ChrisA From gordon at panix.com Wed Feb 12 02:40:53 2014 From: gordon at panix.com (John Gordon) Date: Wed, 12 Feb 2014 07:40:53 +0000 (UTC) Subject: Top down Python References: Message-ID: In John Allsup writes: > I want to be able to say: > 1. Put a nice picture on the background. > 2. Put a terminal window with, say, 64x20 lines, dead centre. > 3. Run a simple REPL program written in Python or Ruby within it. > I do not really want to write any more lines of code than I need to. > Why do we not have langauges and libraries that can do the above > with only five lines of code (line 0 == setup, line 4 == cleanup). You're asking for prepackaged libraries with extremely specific behavior. Forgive me for making an analogy on the Internet, but your request is akin to asking for a hammer that will automatically pound six-penny nails through half-inch drywall, while facing south, on Tuesdays. Such a hammer is great if those are your specific requirements, but worthless otherwise. It's much better to sell a generic hammer. Sure, it's a little more work for the user, but it will pound any type of nail though a variety of surfaces. I.e., it's reusable. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From wxjmfauth at gmail.com Wed Feb 12 02:49:51 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 11 Feb 2014 23:49:51 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> Message-ID: <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Le mardi 11 f?vrier 2014 20:04:02 UTC+1, Mark Lawrence a ?crit?: > On 11/02/2014 18:53, wxjmfauth at gmail.com wrote: > > > Le lundi 10 f?vrier 2014 15:43:08 UTC+1, Tim Chase a ?crit : > > >> On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: > > >> > > >>> Python does not save memory at all. A str (unicode string) > > >> > > >>> uses less memory only - and only - because and when one uses > > >> > > >>> explicitly characters which are consuming less memory. > > >> > > >>> > > >> > > >>> Not only the memory gain is zero, Python falls back to the > > >> > > >>> worse case. > > >> > > >>> > > >> > > >>>>>> sys.getsizeof('a' * 1000000) > > >> > > >>> 1000025 > > >> > > >>>>>> sys.getsizeof('a' * 1000000 + 'oe') > > >> > > >>> 2000040 > > >> > > >>>>>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') > > >> > > >>> 4000048 > > >> > > >> > > >> > > >> If Python used UTF-32 for EVERYTHING, then all three of those cases > > >> > > >> would be 4000048, so it clearly disproves your claim that "python > > >> > > >> does not save memory at all". > > >> > > >> > > >> > > >>> The opposite of what the utf8/utf16 do! > > >> > > >>> > > >> > > >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + > > >> > > >>>>>> '\U00010000').encode('utf-8')) > > >> > > >>> 1000023 > > >> > > >>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + > > >> > > >>>>>> '\U00010000').encode('utf-16')) > > >> > > >>> 2000025 > > >> > > >> > > >> > > >> However, as pointed out repeatedly, string-indexing in fixed-width > > >> > > >> encodings are O(1) while indexing into variable-width encodings (e.g. > > >> > > >> UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing > > >> > > >> while saving space when a string doesn't need to use a full 32-bit > > >> > > >> width. > > >> > > >> > > > > > > A utf optimizes the memory and the performance at the same time. > > > It behaves like a mathematical operator, a unique operator for > > > a unique set of elements. Unbeatable. > > > > > > The FSR is an exclusive or mechanism. I you wish to > > > same memory, you have to encode, and if you are encoding, > > > maybe because you have to, one loses performance. Paradoxal. > > > > > > Your O(1) indexing works only and only because and > > > when you are working explicitly with a "static" unicode > > > string you never touch. > > > It's a little bit the the "corresponding" performance > > > case of the memory case. > > > > > > jmf > > > > > > > Why are you so rude as to continually post your nonsense here that not a > > single person believes, and at the same time still quite deliberately > > use gg to post it with double line spacing. If you lack the courtesy to > > stop the former, please have the courtesy to stop the latter. > > > > -- > > My fellow Pythonistas, ask not what our language can do for you, ask > > what you can do for our language. > > Nonsense? >>> sys.getsizeof('') - sys.getsizeof('a') -1 The day you find an operator working on the set of reals (R) and it is somehow "optimized" for N (the subset of natural numbers), let me know. A conflict is quickly appearing. Either the operator is not correctly defined or the choice of the set is wrong. You can replace the "operator" with an "encoding" and the "set" with a "repertoire of characters". It's the main reason, why we have to live today with all these coding schemes. Even in more sophisticated cases like, CID-fonts or "char boxes" in a pdf (with the hope you understand how it works). jmf From rosuav at gmail.com Wed Feb 12 02:50:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 18:50:32 +1100 Subject: Top down Python In-Reply-To: References: Message-ID: On Wed, Feb 12, 2014 at 6:40 PM, John Gordon wrote: > In John Allsup writes: > >> I want to be able to say: >> 1. Put a nice picture on the background. >> 2. Put a terminal window with, say, 64x20 lines, dead centre. >> 3. Run a simple REPL program written in Python or Ruby within it. >> I do not really want to write any more lines of code than I need to. >> Why do we not have langauges and libraries that can do the above >> with only five lines of code (line 0 == setup, line 4 == cleanup). > > You're asking for prepackaged libraries with extremely specific behavior. > Forgive me for making an analogy on the Internet, but your request is akin > to asking for a hammer that will automatically pound six-penny nails > through half-inch drywall, while facing south, on Tuesdays. > > Such a hammer is great if those are your specific requirements, but > worthless otherwise. It's much better to sell a generic hammer. Sure, > it's a little more work for the user, but it will pound any type of nail > though a variety of surfaces. I.e., it's reusable. There is a reusable component to this: a "terminal window" GUI object. If one existed, then this would be a matter of: 1) Create window 2) Put picture as background 3) Create terminal window with size 64x20 (which, IMO, is tiny) 4) Call on subprocess to handle REPL Depending on how compact the code is, it might take 6-10 lines rather than five, but it would be fairly short. However, it depends on being able to simply "create terminal window" the way you "create button" or "create entry field". As far as I know, this doesn't exist *anywhere*, which is why I've written a number of MUD clients whose primary purpose is to do exactly that. ChrisA From rosuav at gmail.com Wed Feb 12 03:06:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 19:06:30 +1100 Subject: Finding size of Variable In-Reply-To: <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 6:49 PM, wrote: > The day you find an operator working on the set of > reals (R) and it is somehow "optimized" for N > (the subset of natural numbers), let me know. I have yet to find any computer that works with the set of real numbers in any way. Never mind optimization, they simply cannot work with real numbers. As to operations that are optimized for integers (usually not for naturals - supporting zero and negatives isn't hard), they are legion. In Python, integers have arbitrary precision, but floats, Fractions, and Decimals, don't. Nearly any operation on arbitrarily large numbers will be either more accurate or more efficient (maybe both) with integers than with any of the other types. Letting you know, that's all. ChrisA From ben+python at benfinney.id.au Wed Feb 12 03:09:14 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 19:09:14 +1100 Subject: Top down Python References: <52FB1D27.8090009@allsup.co> Message-ID: <85vbwkbvmd.fsf@benfinney.id.au> John Allsup writes: > What is needed for proper learning is near-absolute simplicity. I think that's too simplistic :-) but I'll take it as merely a preference on your part for simplicity at this time. > I want to be able to say: > 1. Put a nice picture on the background. > 2. Put a terminal window with, say, 64x20 lines, dead centre. Those are deeply dependent on exactly what operating system and desktop environment and window manager your computer is running. What exact values for those variables do you want the simple program to assume? No cross-platform standard library (such as the Python standard library) will be able to reliably do those things without making a huge amount of assumption of the operating environment, much of which will be wrong for a large number of users. If you can fix each of those things precisely so that you can ignore all other possible values, then you can probably come up with a simple program to do them. > 3. Run a simple REPL program written in Python or Ruby within it. Python has its own REPL, of course; you get it when you run ?python? from a command line. Simple! If, on the other hand, you want a REPL that plugs into something *other than* Python, what do you want it to plug into? You have a Python REPL already, so if you want something else you'll need to be specific. > I do not really want to write any more lines of code than I need to. For what goal? Python optimises your lines of code for *communicating with other programmers*, which in my view is pretty close to the most important variable to be optimising. -- \ ?I went camping and borrowed a circus tent by mistake. I didn't | `\ notice until I got it set up. People complained because they | _o__) couldn't see the lake.? ?Steven Wright | Ben Finney From ben+python at benfinney.id.au Wed Feb 12 03:17:06 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 19:17:06 +1100 Subject: Working with the set of real numbers (was: Finding size of Variable) References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: <85r478bv99.fsf_-_@benfinney.id.au> Chris Angelico writes: > I have yet to find any computer that works with the set of real > numbers in any way. Never mind optimization, they simply cannot work > with real numbers. Not *any* computer? Not in *any* way? The Python built-in ?float? type ?works with the set of real numbers?, in a way. The ABC defines behaviours for types implementing the set of real numbers. What specific behaviour would, for you, qualify as ?works with the set of real numbers in any way?? -- \ ?The fact that I have no remedy for all the sorrows of the | `\ world is no reason for my accepting yours. It simply supports | _o__) the strong probability that yours is a fake.? ?Henry L. Mencken | Ben Finney From wxjmfauth at gmail.com Wed Feb 12 03:35:38 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 12 Feb 2014 00:35:38 -0800 (PST) Subject: Working with the set of real numbers (was: Finding size of Variable) In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: Integers are integers. (1) Characters are characters. (2) (1) is a unique "natural" set. (2) is an artificial construct working with 3 sets (unicode). jmf From rosuav at gmail.com Wed Feb 12 03:47:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 19:47:55 +1100 Subject: Working with the set of real numbers (was: Finding size of Variable) In-Reply-To: <85r478bv99.fsf_-_@benfinney.id.au> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> Message-ID: On Wed, Feb 12, 2014 at 7:17 PM, Ben Finney wrote: > Chris Angelico writes: > >> I have yet to find any computer that works with the set of real >> numbers in any way. Never mind optimization, they simply cannot work >> with real numbers. > > Not *any* computer? Not in *any* way? The Python built-in ?float? type > ?works with the set of real numbers?, in a way. No, the Python built-in float type works with a subset of real numbers: >>> float("pi") Traceback (most recent call last): File "", line 1, in float("pi") ValueError: could not convert string to float: 'pi' >>> float("?") Traceback (most recent call last): File "", line 1, in float("?") ValueError: could not convert string to float: '?' Same goes for fractions.Fraction and [c]decimal.Decimal. All of them are restricted to some subset of rational numbers, not all reals. > The ABC > defines behaviours for types implementing the set of real numbers. > > What specific behaviour would, for you, qualify as ?works with the set > of real numbers in any way?? Being able to represent surds, pi, e, etc, for a start. It'd theoretically be possible with an algebraic notation (eg by carrying through some representation like "2*pi" rather than 6.28....), but otherwise, irrationals can't be represented with finite storage and a digit-based system. ChrisA From wxjmfauth at gmail.com Wed Feb 12 03:46:47 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 12 Feb 2014 00:46:47 -0800 (PST) Subject: Working with the set of real numbers (was: Finding size of Variable) In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: Le mercredi 12 f?vrier 2014 09:35:38 UTC+1, wxjm... at gmail.com a ?crit?: > Integers are integers. (1) > > Characters are characters. (2) > > > > (1) is a unique "natural" set. > > > > (2) is an artificial construct working > > with 3 sets (unicode). > > > > jmf Addendum: One should not confuse unicode and the implementation of unicode. jmf From benjaminabramowitz at gmail.com Tue Feb 11 23:04:59 2014 From: benjaminabramowitz at gmail.com (Ben Abramowitz) Date: Tue, 11 Feb 2014 20:04:59 -0800 Subject: Python programming In-Reply-To: <26217118-437d-464b-bc32-151795880030@googlegroups.com> References: <26217118-437d-464b-bc32-151795880030@googlegroups.com> Message-ID: I started learning python 3.3 for 13 days (including today) ago, using this book, with no programming experience: http://openbookproject.net/thinkcs/python/english3e/index.html the fact that the author uses the python turtle to teach readers object orientated programming, has been ALL the difference. by chapter 4, you are writing basic void and fruitful functions. it is awesome. it has exercises at the end of every chapter, that if you grind out, you learn a truckload from. and progress. If you put in the time, and glue your butt to a seat for as long as you can, as many days in a row, the results are very satisfying. the book is free. I highly recommend it. On Tue, Feb 11, 2014 at 4:21 PM, ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? > > What is the best way i can master thinker? > I know the syntax but using it to write a program is a problem > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gheskett at wdtv.com Tue Feb 11 23:14:42 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Tue, 11 Feb 2014 23:14:42 -0500 Subject: Python programming In-Reply-To: References: Message-ID: <201402112314.42370.gheskett@wdtv.com> On Tuesday 11 February 2014 23:13:33 Roy Smith did opine: > In article , > > ngangsia akumbo wrote: > > Please i have a silly question to ask. > > > > How long did it take you to learn how to write programs? > > I've been working on it for 40 years. I'll let you know when I get > there. I started, on an RCA 1802 board in '79. I'm damned sure not there yet. 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) Genes Web page NOTICE: Will pay 100 USD for an HP-4815A defective but complete probe assembly. From ben+python at benfinney.id.au Wed Feb 12 03:52:51 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 19:52:51 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: <85mwhwbtlo.fsf@benfinney.id.au> wxjmfauth at gmail.com writes: > (2) is an artificial construct working > with 3 sets (unicode). jmf, you are being exceedingly disruptive: attempting to derail unrelated discussions for your favourite hobby-horse topic. Please stop. Everyone else: Please don't engage these attempts; instead, avoid engaging with this trollish behaviour. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney From jpiitula at ling.helsinki.fi Wed Feb 12 03:57:50 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 12 Feb 2014 10:57:50 +0200 Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: Chris Angelico writes: > On Wed, Feb 12, 2014 at 6:49 PM, wrote: > > The day you find an operator working on the set of > > reals (R) and it is somehow "optimized" for N > > (the subset of natural numbers), let me know. ... > In Python, integers have arbitrary precision, but floats, Fractions, > and Decimals, don't. Nearly any operation on arbitrarily large > numbers will be either more accurate or more efficient (maybe both) > with integers than with any of the other types. Is that true about Fractions? From ben+python at benfinney.id.au Wed Feb 12 03:56:29 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 19:56:29 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> Message-ID: <85ioskbtfm.fsf@benfinney.id.au> Chris Angelico writes: > On Wed, Feb 12, 2014 at 7:17 PM, Ben Finney wrote: > > Chris Angelico writes: > > > >> I have yet to find any computer that works with the set of real > >> numbers in any way. Never mind optimization, they simply cannot > >> work with real numbers. > > > > Not *any* computer? Not in *any* way? The Python built-in ?float? > > type ?works with the set of real numbers?, in a way. > > No, the Python built-in float type works with a subset of real numbers So, ?works with a subset of real numbers? is not satisfactory, then. Okay. > Same goes for fractions.Fraction and [c]decimal.Decimal. All of them > are restricted to some subset of rational numbers, not all reals. > > > What specific behaviour would, for you, qualify as ?works with the > > set of real numbers in any way?? > > Being able to represent surds, pi, e, etc, for a start. So, if I understand you right, you want to say that you've not found a computer that works with the *complete* set of real numbers. Yes? -- \ ?To have the choice between proprietary software packages, is | `\ being able to choose your master. Freedom means not having a | _o__) master.? ?Richard M. Stallman, 2007-05-16 | Ben Finney From rosuav at gmail.com Wed Feb 12 04:16:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 20:16:36 +1100 Subject: Working with the set of real numbers In-Reply-To: <85ioskbtfm.fsf@benfinney.id.au> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> Message-ID: On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: > So, if I understand you right, you want to say that you've not found a > computer that works with the *complete* set of real numbers. Yes? Correct. When jmf referred to real numbers, he implied that there are no optimizations done for natural numbers, that everything's just as efficient for any real number as for any other. My point is that computers *do not* work with real numbers, but only ever with some subset thereof, and that certain subsets (integers usually) are optimized for in ways that other subsets aren't. A true "real number" type might be useful in a few extremely narrow situations, but for the most part, I'd much rather have the optimized implementation that works with a subset thereof, and actually runs within reasonable time/space complexity. (Though, that said, I think a lot of programmers could do with some education on exactly _what_ subset of real numbers they're working with. The classic IEEE double-precision floating point type is good enough with low numbers that lots of people seem to think it stores reals, which it doesn't.) ChrisA From rosuav at gmail.com Wed Feb 12 04:24:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 20:24:09 +1100 Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 7:57 PM, Jussi Piitulainen wrote: >> In Python, integers have arbitrary precision, but floats, Fractions, >> and Decimals, don't. Nearly any operation on arbitrarily large >> numbers will be either more accurate or more efficient (maybe both) >> with integers than with any of the other types. > > Is that true about Fractions? I'm not 100% sure if fraction.Fraction and decimal.Decimal ever limit the size or precision of their data, but certainly if they don't, it'll be at horrendous expense of performance. (Decimal can add and subtract in reasonable time complexity, but multiplication and division will get slow when you have huge numbers of digits. Fraction can multiply and divide efficiently, but will get crazily slow on addition and subtraction.) Integers are an optimized case in many ways. I can do accurate arbitrary-precision integer arithmetic without worrying about simple operations suddenly saturating the CPU. I can't do that with non-integers in any way. It's not optimized for natural numbers (nonnegative integers), as negatives are just as cheap as positives, but it's certainly an optimization for integers. ChrisA From jpiitula at ling.helsinki.fi Wed Feb 12 04:23:21 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 12 Feb 2014 11:23:21 +0200 Subject: Working with the set of real numbers (was: Finding size of Variable) References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> Message-ID: Chris Angelico writes: > On Wed, Feb 12, 2014 at 7:17 PM, Ben Finney wrote: > > What specific behaviour would, for you, qualify as ?works with the > > set of real numbers in any way?? > > Being able to represent surds, pi, e, etc, for a start. It'd > theoretically be possible with an algebraic notation (eg by carrying > through some representation like "2*pi" rather than 6.28....), but > otherwise, irrationals can't be represented with finite storage and > a digit-based system. I've seen papers on exact computable reals that would, in effect, generate more precision when needed for some operation. It wasn't symbolic like 2pi, more like 6.28... with a promise to delve into the ellipsis, and some notable operations not supported. Equality testing was missing, I think, and I think it could not be known in general whether such a number is positive, zero or negative, so even approximate printing in the usual digit notation would not be possible. (Interval arithmetic, I hear, has a similar problem about not knowing the sign of a number.) In stark contrast, exact rationals work nicely, up to efficiency considerations. From info at egenix.com Wed Feb 12 04:28:12 2014 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Wed, 12 Feb 2014 10:28:12 +0100 Subject: ANN: eGenix mxODBC Connect 2.0.4 - Python ODBC Database Interface Message-ID: <52FB3EAC.3070408@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Connect Python ODBC Database Interface Version 2.0.4 mxODBC Connect is our commercially supported client-server product for connecting Python applications to relational databases in a truly platform independent way. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-2.0.4-GA.html ________________________________________________________________________ INTRODUCTION The mxODBC Connect Database Interface for Python allows users to easily connect Python applications to all major databases on the market today in a highly portable, convenient and secure way. Python Database Connectivity the Easy Way ----------------------------------------- Unlike our mxODBC Python extension, mxODBC Connect is designed as client-server application, so you no longer need to find production quality ODBC drivers for all the platforms you target with your Python application. Instead you use an easy to install royalty-free Python client library which connects directly to the mxODBC Connect database server over the network. This makes mxODBC Connect a great basis for writing cross-platform multi-tier database applications and utilities in Python, especially if you run applications that need to communicate with databases such as MS SQL Server and MS Access, Oracle Database, IBM DB2 and Informix, Sybase ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more, that run on Windows or Linux machines. Ideal for Database Driven Client Applications --------------------------------------------- By removing the need to install and configure ODBC drivers on the client side and dealing with complicated network setups for each set of drivers, mxODBC Connect greatly simplifies deployment of database driven client applications, while at the same time making the network communication between client and database server more efficient and more secure. For more information, please have a look at the mxODBC Connect product page, in particular, the full list of available features. For more information, please see the product page: http://www.egenix.com/products/python/mxODBCConnect/ ________________________________________________________________________ NEWS The 2.0.4 release of mxODBC Connect includes the following enhancements and fixes: Security Enhancements --------------------- * Upgraded client and server to the most recent eGenix pyOpenSSL Distribution 0.13.3.1.0.1.6. See http://egenix.com/go52 for details. * Authentication errors are now reported with the SYSTEM_ERROR log level, making them visible using the default server side log level setting. Server Enhancements ------------------- * Updated the server to use eGenix mxODBC 3.2.3 for database connectivity. See http://egenix.com/go45 for details. * Added new server connection configuration setting connection_cursortype which allows modifying the default cursor type (using the new connection.cursortype attribute value; see http://egenix.com/go42) without having to modify the client side applications. The setting can be applied on a per connection basis for enhanced flexibility. * The mxODBC DataDirect subpackage is now built against the current DataDirect ODBC manager version 7.1.2. Client Enhancements ------------------- * Fixed a problem with the .warningformat attribute not working as expected on cursors and connections. Performance Enhancements ------------------------ * MS SQL Server performance can be much enhanced, and increased to levels beyond that of mxODBC Connect 2.0.2 and previous releases, by adjusting the default cursor type to forward-only cursors instead of static cursors. mxODBC Connect 2.0.4 makes this possible without having to change client side applications by modifying the server-config.ini file as follows: [Connection_Example] ... # Use the faster forward-only cursors on this connection connection_cursortype = SQL.CURSOR_FORWARD_ONLY The performance increase compared to mxODBC Connect 2.0.2 is enormous: from 2-3x faster executes/fetches for average queries, up to 300x faster for simple cases. In mxODBC Connect 2.1, we will switch to using forward-only cursors per default for all database backends. * IBM DB2 can benefit from the same performance enhancements using forward-only cursors. The effect is a lot smaller, but still noticeable: up to 2x faster executes/fetches with forward-only cursors, compared to mxODBC Connect 2.0.2. For the full set of changes, please check the mxODBC Connect change log: http://www.egenix.com/products/python/mxODBCConnect/changelog.html mxODBC Connect 2.0 Highlights ----------------------------- mxODBC Connect 2.0 was released on 2012-08-20. These are the most important highlights: * mxODBC Connect Server now uses mxODBC 3.2 internally and makes its API available in the mxODBC Connect Client. This is a major step forward from the mxODBC 3.0 version used in mxODBC Connect Server 1.0. * We've added native Windows x64 builds. * mxODBC Connect Client now integrates directly with gevent, allowing client applications to run asynchronous tasks while performing remote database queries. Please see the release announcement for full details: http://www.egenix.com/company/news/eGenix-mxODBC-Connect-2.0.0-GA.html ________________________________________________________________________ UPGRADING You are encouraged to upgrade to this latest mxODBC Connect release. When upgrading, please always upgrade both the server and the client installations to the same version - even for patch level releases. Customers who have purchased mxODBC Connect 2.0 licenses can continue to use their licenses with this patch level release. Customers who have purchased mxODBC Connect 1.x licenses can request 20% discount coupons for upgrade purchases. Please contact the eGenix.com Sales Team (sales at egenix.com) with your existing license serials for details. Users of our stand-alone mxODBC product will have to purchase new licenses from our online shop in order to use mxODBC Connect. You can request 30-day evaluation licenses by visiting our web-site or writing to sales at egenix.com, stating your name (or the name of the company) and the number of eval licenses that you need. http://www.egenix.com/products/python/mxODBCConnect/#Evaluation ________________________________________________________________________ DOWNLOADS The download archives as well as instructions for installation and configuration of the product can be found on the product page: http://www.egenix.com/products/python/mxODBCConnect/ If you want to try the package, jump straight to the download instructions: https://cms.egenix.com/products/python/mxODBCConnect/#Download Fully functional evaluation licenses for the mxODBC Connect Server are available free of charge: http://www.egenix.com/products/python/mxODBCConnect/#Evaluation mxODBC Connect Client is always free of charge. _______________________________________________________________________ SUPPORT Commercial support for this product is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. _______________________________________________________________________ INFORMATION About Python (http://www.python.org/): Python is an object-oriented Open Source programming language which runs on all modern platforms. By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for today's IT challenges. About eGenix (http://www.egenix.com/): eGenix is a software project, consulting and product company focusing on expert project services and professional quality products for companies, Python users and developers. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 12 2014) >>> Python Projects, Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope/Plone.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::::: Try our 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 jpiitula at ling.helsinki.fi Wed Feb 12 04:35:22 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 12 Feb 2014 11:35:22 +0200 Subject: Finding size of Variable References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: Chris Angelico writes: > On Wed, Feb 12, 2014 at 7:57 PM, Jussi Piitulainen wrote: > >> In Python, integers have arbitrary precision, but floats, Fractions, > >> and Decimals, don't. Nearly any operation on arbitrarily large > >> numbers will be either more accurate or more efficient (maybe both) > >> with integers than with any of the other types. > > > > Is that true about Fractions? > > I'm not 100% sure if fraction.Fraction and decimal.Decimal ever limit > the size or precision of their data, but certainly if they don't, > it'll be at horrendous expense of performance. (Decimal can add and > subtract in reasonable time complexity, but multiplication and > division will get slow when you have huge numbers of digits. Fraction > can multiply and divide efficiently, but will get crazily slow on > addition and subtraction.) Integers are an optimized case in many > ways. I can do accurate arbitrary-precision integer arithmetic without > worrying about simple operations suddenly saturating the CPU. I can't > do that with non-integers in any way. > > It's not optimized for natural numbers (nonnegative integers), as > negatives are just as cheap as positives, but it's certainly an > optimization for integers. Right. I don't know about Decimal, but I don't think there are any precision restrictions in Fraction, other than running out of heap (or possibly integer precision). In my (quite limited) experience, the most expensive operation on both exact rationals and exact integers has been the printing, in decimal, of several screenfuls of digits. The actual calculations have taken a couple of seconds and then I have wished that I could interrupt the printing of a single number :) From greg.ewing at canterbury.ac.nz Wed Feb 12 05:04:32 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 12 Feb 2014 23:04:32 +1300 Subject: singleton ... again In-Reply-To: References: Message-ID: Roy Smith wrote: > It looks to me like he's trying to implement a classic Gang of Four > singleton pattern. Which I've never really seen the point of in Python, or any other language for that matter. Just create one instance of the class during initialisation, put it in a global somewhere, and use it thereafter. If you really want to make sure nobody creates another instance by accident, delete the class out of the namespace after instantiating it. -- Greg From ben+python at benfinney.id.au Wed Feb 12 05:07:04 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 21:07:04 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> Message-ID: <85eh38bq5z.fsf@benfinney.id.au> Chris Angelico writes: > On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: > > So, if I understand you right, you want to say that you've not found > > a computer that works with the *complete* set of real numbers. Yes? > > Correct. [?] My point is that computers *do not* work with real > numbers, but only ever with some subset thereof [?] You've done it again: by saying that ?computers *do not* work with real numbers?, that if I find a real number ? e.g. the number 4 ? your position is that, since it's a real number, computers don't work with that number. That's why I think you need to be clear that your point isn't ?computers don't work with real numbers?, but rather ?computers work only with a limited subset of real numbers?. -- \ ?We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech.? ?David Brin | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Feb 12 05:09:25 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 21:09:25 +1100 Subject: singleton ... again References: Message-ID: <85a9dwbq22.fsf@benfinney.id.au> Gregory Ewing writes: > Roy Smith wrote: > > It looks to me like he's trying to implement a classic Gang of Four > > singleton pattern. > > Which I've never really seen the point of in Python, or any other > language for that matter. Just create one instance of the class during > initialisation, put it in a global somewhere, and use it thereafter. Make that ?somewhere? a module namespace, and you effectively have a Singleton for all practical purposes. So yes, I see the point of it; but we already have it built in :-) -- \ ?To save the world requires faith and courage: faith in reason, | `\ and courage to proclaim what reason shows to be true.? | _o__) ?Bertrand Russell | Ben Finney From rosuav at gmail.com Wed Feb 12 05:20:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 21:20:19 +1100 Subject: Working with the set of real numbers In-Reply-To: <85eh38bq5z.fsf@benfinney.id.au> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: On Wed, Feb 12, 2014 at 9:07 PM, Ben Finney wrote: > Chris Angelico writes: > >> On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: >> > So, if I understand you right, you want to say that you've not found >> > a computer that works with the *complete* set of real numbers. Yes? >> >> Correct. [?] My point is that computers *do not* work with real >> numbers, but only ever with some subset thereof [?] > > You've done it again: by saying that ?computers *do not* work with real > numbers?, that if I find a real number ? e.g. the number 4 ? your > position is that, since it's a real number, computers don't work with > that number. > > That's why I think you need to be clear that your point isn't ?computers > don't work with real numbers?, but rather ?computers work only with a > limited subset of real numbers?. Hmm, I'm not sure that my statement is false. If a computer can work with "real numbers", then I would expect it to be able to work with any real number. In C, I can declare an 'int' variable, which can hold the real number 4 - does that mean that that variable stores real numbers? No, and it's not useful to say that it does. It doesn't store rationals either, even though 4 is a rational. The fact that computers can work with some subset of real numbers does not disprove my statement that computers don't work with "real numbers" as a class. Program X works with text files, but it fails if the file contains U+003C; can I feed it this thing, which is a text file? No, I can't, because it works only with a subset of text files. ChrisA From xstgavin124 at gmail.com Wed Feb 12 05:27:44 2014 From: xstgavin124 at gmail.com (xstgavin124 at gmail.com) Date: Wed, 12 Feb 2014 02:27:44 -0800 (PST) Subject: PIL Image.fromarray( ... , mode="1" ) In-Reply-To: References: Message-ID: <8884bf70-8190-42b9-8e02-3f1da759be97@googlegroups.com> On Saturday, 31 October 2009 23:43:45 UTC+8, Hans Georg Schaathun wrote: > Does anyone know how to save two-tone images represented as > numpy arrays? I handle grayscale images by converting to > PIL Image objects (mode="L") and then use the PIL save method, > but I cannot make this work with mode="1". > > I have tried both boolean arrays and uint8 arrays (mod 2). > In both cases I get an image which is predominantly black, > with thin white stripes (possibly for every 8 pixels). > If, instead, multiply my (mod 2) image by 255, and then > convert with mode="L", I get the expected random-noise-looking > image. > > Does anyone have any ideas? What do I do wrong? What is the > right/best way to save/convert two-tone images? > I have not managed to find proper documentation for the > Image.fromarray() method; the docstring seems to be empty )-: > > TIA > :-- Hans Georg Possibly because you forget to convert the data type to unit8: " newtemp=np.uint8(TEMP*255) " I have encountered the same problem as you stated. After change the date type to uint8, problem solved. Hope it works. _ST From wxjmfauth at gmail.com Wed Feb 12 05:55:17 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 12 Feb 2014 02:55:17 -0800 (PST) Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: The fascinating aspect of this FSR lies in its mathematical absurdity. jmf From ben+python at benfinney.id.au Wed Feb 12 06:44:06 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Feb 2014 22:44:06 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: <854n44blo9.fsf@benfinney.id.au> Chris Angelico writes: > On Wed, Feb 12, 2014 at 9:07 PM, Ben Finney wrote: > > That's why I think you need to be clear that your point isn't > > ?computers don't work with real numbers?, but rather ?computers work > > only with a limited subset of real numbers?. > > Hmm, I'm not sure that my statement is false. If a computer can work > with "real numbers", then I would expect it to be able to work with > any real number. Likewise, if you claim that a computer *does not* work with real numbers, then I would expect that for any real number, the computer would fail to work with that number. Which is why neither of those is a good statement of your position, IMO, and you're better off saying the *limitations* you're describing. -- \ ?An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.? ?Niels Bohr | _o__) | Ben Finney From ned at nedbatchelder.com Wed Feb 12 06:55:50 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 12 Feb 2014 06:55:50 -0500 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: On 2/12/14 5:55 AM, wxjmfauth at gmail.com wrote: > The fascinating aspect of this FSR lies > in its mathematical absurdity. > > jmf > Stop. -- Ned Batchelder, http://nedbatchelder.com From rosuav at gmail.com Wed Feb 12 06:58:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Feb 2014 22:58:51 +1100 Subject: Working with the set of real numbers In-Reply-To: <854n44blo9.fsf@benfinney.id.au> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <854n44blo9.fsf@benfinney.id.au> Message-ID: On Wed, Feb 12, 2014 at 10:44 PM, Ben Finney wrote: > Chris Angelico writes: > >> On Wed, Feb 12, 2014 at 9:07 PM, Ben Finney wrote: >> > That's why I think you need to be clear that your point isn't >> > ?computers don't work with real numbers?, but rather ?computers work >> > only with a limited subset of real numbers?. >> >> Hmm, I'm not sure that my statement is false. If a computer can work >> with "real numbers", then I would expect it to be able to work with >> any real number. > > Likewise, if you claim that a computer *does not* work with real > numbers, then I would expect that for any real number, the computer > would fail to work with that number. > > Which is why neither of those is a good statement of your position, IMO, > and you're better off saying the *limitations* you're describing. I think we're using different words to say the same thing here :) What I mean is that one cannot accurately say that a computer works with real numbers, because it cannot work with them all. Of course a computer can work with _some_ real numbers; but only some. (An awful lot of them, of course. A ridiculously huge number of numbers. More numbers than you could read in a lifetime! While the number is extremely large, it still falls pitifully short of infinity.[1]) And so we do have optimizations for some subset of reals: in approximate order of performance, an arbitrary-precision integer type, a limited precision floating point type, and two types that handle fractions (vulgar and decimal). They're all, in a sense, optimizations. In pure theory, we could have a single "real number" type and do everything with that; all the other types are approximations to that. [1] http://tools.ietf.org/search/rfc2795 From marko at pacujo.net Wed Feb 12 07:48:44 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Feb 2014 14:48:44 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: <8761okcx8z.fsf@elektro.pacujo.net> Chris Angelico : > Hmm, I'm not sure that my statement is false. If a computer can work > with "real numbers", then I would expect it to be able to work with > any real number. In C, I can declare an 'int' variable, which can hold > the real number 4 - does that mean that that variable stores real > numbers? No, and it's not useful to say that it does. It doesn't store > rationals either, even though 4 is a rational. The fact that computers > can work with some subset of real numbers does not disprove my > statement that computers don't work with "real numbers" as a class. > Program X works with text files, but it fails if the file contains > U+003C; can I feed it this thing, which is a text file? No, I can't, > because it works only with a subset of text files. According to your definition, there's no computer in the world that can work with integers or text files. Marko From rosuav at gmail.com Wed Feb 12 08:20:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 00:20:32 +1100 Subject: Working with the set of real numbers In-Reply-To: <8761okcx8z.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> Message-ID: On Wed, Feb 12, 2014 at 11:48 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> Hmm, I'm not sure that my statement is false. If a computer can work >> with "real numbers", then I would expect it to be able to work with >> any real number. In C, I can declare an 'int' variable, which can hold >> the real number 4 - does that mean that that variable stores real >> numbers? No, and it's not useful to say that it does. It doesn't store >> rationals either, even though 4 is a rational. The fact that computers >> can work with some subset of real numbers does not disprove my >> statement that computers don't work with "real numbers" as a class. >> Program X works with text files, but it fails if the file contains >> U+003C; can I feed it this thing, which is a text file? No, I can't, >> because it works only with a subset of text files. > > According to your definition, there's no computer in the world that can > work with integers or text files. Integers as far as RAM will allow, usually (which is the same caveat as is used when describing a programming language as "Turing complete" - strictly, that term is valid only if it has infinite memory available), but yes, technically that's a subset of integers. However, that subset is bounded by something other than the code, algorithms, or even hardware - it's theoretically possible to add two numbers larger than will fit in memory, by reading them in (even over the network), adding segments, and writing them out again. Text files. Since there's already no such thing as a "text file" unless you know what its encoding is, I don't see a problem with this. There's no such thing as an integer in memory, either, unless you know how it's encoded (those same bits could be a floating point number, or a pointer, or anything). If you know that the bytes in the file are, say, a UTF-8 stream, then the file is a text file, just as it could be a bash script, or an MS-DOS .COM file, if you've been told to decode it in that way. Once your encoding is declared (out of band), the file consists of a series of ASCII characters, or Unicode codepoints, or whatever else it is. A fully functional program should be able to process that file regardless of what sequence of codepoints it carries. Say you want to search a file for a particular string, for instance. You want to know whether or not "foobar" occurs in a file. (I'll leave aside the question of word boundaries and say you're looking for that string of six characters.) The program should be able to determine the presence or absence of "foobar" regardless of what other characters (or codepoints) are around it. Having U+001A shouldn't stop the search there; nor should U+0000 cause problems, nor U+003C, nor any other value. Doing otherwise would be a restriction: this program supports only a subset of text files (those not containing these "problem characters"). It might not be a bug, per se (maybe text inside is considered to be an XML tag and is deemed to be not what you're looking for), but it's still a restriction. An inability to represent the integer 9007199254740993 (but able to represent ...992 and ...994) is a restriction. Restrictions aren't necessarily bad, but they need to be acknowledged. ChrisA From breamoreboy at yahoo.co.uk Wed Feb 12 08:41:10 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 13:41:10 +0000 Subject: Python programming In-Reply-To: <201402112314.42370.gheskett@wdtv.com> References: <201402112314.42370.gheskett@wdtv.com> Message-ID: On 12/02/2014 04:14, Gene Heskett wrote: > On Tuesday 11 February 2014 23:13:33 Roy Smith did opine: > >> In article , >> >> ngangsia akumbo wrote: >>> Please i have a silly question to ask. >>> >>> How long did it take you to learn how to write programs? >> >> I've been working on it for 40 years. I'll let you know when I get >> there. > > I started, on an RCA 1802 board in '79. I'm damned sure not there yet. > > Cheers, Gene > Snap :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From roy at panix.com Wed Feb 12 08:40:30 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 08:40:30 -0500 Subject: singleton ... again References: Message-ID: In article , Ben Finney wrote: > Gregory Ewing writes: > > > Roy Smith wrote: > > > It looks to me like he's trying to implement a classic Gang of Four > > > singleton pattern. > > > > Which I've never really seen the point of in Python, or any other > > language for that matter. Just create one instance of the class during > > initialisation, put it in a global somewhere, and use it thereafter. > > Make that ???somewhere??? a module namespace, and you effectively have a > Singleton for all practical purposes. So yes, I see the point of it; but > we already have it built in :-) This is one of the big problems with the Gang of Four book (and most of the pattern literature). They present these patterns as universal to all OOPL's, when in reality, so much of them is "Things I need to do to appease the C++ compiler". From larry.martell at gmail.com Wed Feb 12 08:55:30 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 12 Feb 2014 08:55:30 -0500 Subject: Python programming In-Reply-To: References: Message-ID: On Tue, Feb 11, 2014 at 7:21 PM, ngangsia akumbo wrote: > Please i have a silly question to ask. > > How long did it take you to learn how to write programs? My entire life. I started in 1975 when I was 16 - taught myself BASIC and wrote a very crude downhill skiing game. I had dial in access to the mainframe at a local college (my HS math teacher got that for me). I could only access it off hours, so I wrote my program to yellow paper tape then uploaded it over a 110 baud connection. Then taught myself FORTRAN, then went to college at Rochester Institute of Technology majoring in Computer Engineering. First class was Pascal, then FORTRAN, which I tested out of. Then IBM 360 assembly language, then C. After college I taught myself SQL, shell programming, perl, C++, python, and PHP. And in just the last 2 years javascript, jQuery, HTML, and CSS. It never stops. From breamoreboy at yahoo.co.uk Wed Feb 12 09:04:42 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 14:04:42 +0000 Subject: Finding size of Variable In-Reply-To: <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: On 12/02/2014 07:49, wxjmfauth at gmail.com wrote: > Le mardi 11 f?vrier 2014 20:04:02 UTC+1, Mark Lawrence a ?crit : >> On 11/02/2014 18:53, wxjmfauth at gmail.com wrote: >> >>> Le lundi 10 f?vrier 2014 15:43:08 UTC+1, Tim Chase a ?crit : >> >>>> On 2014-02-10 06:07, wxjmfauth at gmail.com wrote: >> >>>> >> >>>>> Python does not save memory at all. A str (unicode string) >> >>>> >> >>>>> uses less memory only - and only - because and when one uses >> >>>> >> >>>>> explicitly characters which are consuming less memory. >> >>>> >> >>>>> >> >>>> >> >>>>> Not only the memory gain is zero, Python falls back to the >> >>>> >> >>>>> worse case. >> >>>> >> >>>>> >> >>>> >> >>>>>>>> sys.getsizeof('a' * 1000000) >> >>>> >> >>>>> 1000025 >> >>>> >> >>>>>>>> sys.getsizeof('a' * 1000000 + 'oe') >> >>>> >> >>>>> 2000040 >> >>>> >> >>>>>>>> sys.getsizeof('a' * 1000000 + 'oe' + '\U00010000') >> >>>> >> >>>>> 4000048 >> >>>> >> >>>> >> >>>> >> >>>> If Python used UTF-32 for EVERYTHING, then all three of those cases >> >>>> >> >>>> would be 4000048, so it clearly disproves your claim that "python >> >>>> >> >>>> does not save memory at all". >> >>>> >> >>>> >> >>>> >> >>>>> The opposite of what the utf8/utf16 do! >> >>>> >> >>>>> >> >>>> >> >>>>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >> >>>> >> >>>>>>>> '\U00010000').encode('utf-8')) >> >>>> >> >>>>> 1000023 >> >>>> >> >>>>>>>> sys.getsizeof(('a' * 1000000 + 'oe' + >> >>>> >> >>>>>>>> '\U00010000').encode('utf-16')) >> >>>> >> >>>>> 2000025 >> >>>> >> >>>> >> >>>> >> >>>> However, as pointed out repeatedly, string-indexing in fixed-width >> >>>> >> >>>> encodings are O(1) while indexing into variable-width encodings (e.g. >> >>>> >> >>>> UTF8/UTF16) are O(N). The FSR gives the benefits of O(1) indexing >> >>>> >> >>>> while saving space when a string doesn't need to use a full 32-bit >> >>>> >> >>>> width. >> >>>> >> >>>> >> >>> >> >>> A utf optimizes the memory and the performance at the same time. >> >>> It behaves like a mathematical operator, a unique operator for >> >>> a unique set of elements. Unbeatable. >> >>> >> >>> The FSR is an exclusive or mechanism. I you wish to >> >>> same memory, you have to encode, and if you are encoding, >> >>> maybe because you have to, one loses performance. Paradoxal. >> >>> >> >>> Your O(1) indexing works only and only because and >> >>> when you are working explicitly with a "static" unicode >> >>> string you never touch. >> >>> It's a little bit the the "corresponding" performance >> >>> case of the memory case. >> >>> >> >>> jmf >> >>> >> >> >> >> Why are you so rude as to continually post your nonsense here that not a >> >> single person believes, and at the same time still quite deliberately >> >> use gg to post it with double line spacing. If you lack the courtesy to >> >> stop the former, please have the courtesy to stop the latter. >> >> >> >> -- >> >> My fellow Pythonistas, ask not what our language can do for you, ask >> >> what you can do for our language. >> >> > > Nonsense? > >>>> sys.getsizeof('') - sys.getsizeof('a') > -1 > > > The day you find an operator working on the set of > reals (R) and it is somehow "optimized" for N > (the subset of natural numbers), let me know. > > A conflict is quickly appearing. Either the operator is > not correctly defined or the choice of the set is wrong. > > You can replace the "operator" with an "encoding" and > the "set" with a "repertoire of characters". > > It's the main reason, why we have to live today with > all these coding schemes. Even in more sophisticated > cases like, CID-fonts or "char boxes" in a pdf (with the > hope you understand how it works). > > jmf > I ask you, members of the jury, to find the accused, jmf, guilty of writing nonsense and deliberately using google groups to double line space. The evidence is directly above and quite clearly prooves, beyond a resonable doubt, that no verdict other than guilty can be recorded. I rest my case, m'lud. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rustompmody at gmail.com Wed Feb 12 09:11:37 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 12 Feb 2014 06:11:37 -0800 (PST) Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> Message-ID: <10afc311-f907-4eb8-859e-99180d1c07c0@googlegroups.com> On Wednesday, February 12, 2014 3:37:04 PM UTC+5:30, Ben Finney wrote: > Chris Angelico writes: > > On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: > > > So, if I understand you right, you want to say that you've not found > > > a computer that works with the *complete* set of real numbers. Yes? > > Correct. [...] My point is that computers *do not* work with real > > numbers, but only ever with some subset thereof [...] > You've done it again: by saying that "computers *do not* work with real > numbers", that if I find a real number - e.g. the number 4 - your > position is that, since it's a real number, computers don't work with > that number. There is a convention in logic called the implicit universal quantifier convention: when a bald unqualified reference is in a statement it means it is universally quantified. eg "A triangle is a polygon with 3 sides" really means "ALL polygons with 3 sides are triangles" ie the ALL is implied Now when for-all is inverted by de Morgan it becomes "for-some not..." So "computers work with real numbers" really means "computers work with all real numbers" and that is not true > That's why I think you need to be clear that your point isn't "computers > don't work with real numbers", but rather "computers work only with a > limited subset of real numbers". Yes both these statements are true by above. In fact computers cannot work with real numbers because the real number set is undecidable/uncomputable. In particular, trivial operations like equality on reals -- IN GENERAL -- is undecidable. From marko at pacujo.net Wed Feb 12 09:13:11 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 12 Feb 2014 16:13:11 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> Message-ID: <87txc4bers.fsf@elektro.pacujo.net> Chris Angelico : > On Wed, Feb 12, 2014 at 11:48 PM, Marko Rauhamaa wrote: >> According to your definition, there's no computer in the world that can >> work with integers or text files. > > Integers as far as RAM will allow, usually (which is the same caveat > as is used when describing a programming language as "Turing complete" > - strictly, that term is valid only if it has infinite memory > available), but yes, technically that's a subset of integers. However, > that subset is bounded by something other than the code, algorithms, > or even hardware - it's theoretically possible to add two numbers > larger than will fit in memory, by reading them in (even over the > network), adding segments, and writing them out again. > > Text files. Since there's already no such thing as a "text file" > unless you know what its encoding is, I don't see a problem with this. Text files suffer from the same caveat as integers: there's a limit to how much you can store on the physical computer. A similar caveat prevents computers from dealing with real numbers. In the case of integers, you have a finite subset of ??. In the case of reals, you have a finite subset of ??. Yes, integers are algorithmically much more tractable than reals. However, in practice integer math is often computationally much harder than real math. Take cryptography vs calculus as an example. Marko From roy at panix.com Wed Feb 12 09:13:52 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 09:13:52 -0500 Subject: Python programming References: Message-ID: In article , Larry Martell wrote: > On Tue, Feb 11, 2014 at 7:21 PM, ngangsia akumbo wrote: > > Please i have a silly question to ask. > > > > How long did it take you to learn how to write programs? > > My entire life. > > I started in 1975 when I was 16 - taught myself BASIC and wrote a very > crude downhill skiing game. I had dial in access to the mainframe at a > local college (my HS math teacher got that for me). Wow, sounds exactly like my experience. Probably one of these: https://en.wikipedia.org/wiki/HP_2000 Lunar lander. Hunt the wumpus. Space War. Actually, before I was allowed to get access to that, I got some time on one of these: http://www.oldcalculatormuseum.com/hp9810a.html From rustompmody at gmail.com Wed Feb 12 09:14:01 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 12 Feb 2014 06:14:01 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: <2ac510a9-69d3-49f5-afb9-8ef6a2463a01@googlegroups.com> On Wednesday, February 12, 2014 7:34:42 PM UTC+5:30, Mark Lawrence wrote: > I ask you, members of the jury, to find the accused, jmf, guilty of > writing nonsense and deliberately using google groups to double line > space. The evidence is directly above and quite clearly prooves, beyond > a resonable doubt, that no verdict other than guilty can be recorded. I > rest my case, m'lud. Is a proof more fool-proof because prove is spelt proove ? From breamoreboy at yahoo.co.uk Wed Feb 12 09:25:32 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 14:25:32 +0000 Subject: Finding size of Variable In-Reply-To: <2ac510a9-69d3-49f5-afb9-8ef6a2463a01@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <2ac510a9-69d3-49f5-afb9-8ef6a2463a01@googlegroups.com> Message-ID: On 12/02/2014 14:14, Rustom Mody wrote: > On Wednesday, February 12, 2014 7:34:42 PM UTC+5:30, Mark Lawrence wrote: > >> I ask you, members of the jury, to find the accused, jmf, guilty of >> writing nonsense and deliberately using google groups to double line >> space. The evidence is directly above and quite clearly prooves, beyond >> a resonable doubt, that no verdict other than guilty can be recorded. I >> rest my case, m'lud. > > Is a proof more fool-proof because prove is spelt proove ? > Fauultee keebored :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rustompmody at gmail.com Wed Feb 12 09:32:37 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 12 Feb 2014 06:32:37 -0800 (PST) Subject: Finding size of Variable In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <2ac510a9-69d3-49f5-afb9-8ef6a2463a01@googlegroups.com> Message-ID: <2bf8fc43-8555-4710-8273-e545ce115ac5@googlegroups.com> On Wednesday, February 12, 2014 7:55:32 PM UTC+5:30, Mark Lawrence wrote: > On 12/02/2014 14:14, Rustom Mody wrote: > > On Wednesday, February 12, 2014 7:34:42 PM UTC+5:30, Mark Lawrence wrote: > >> I ask you, members of the jury, to find the accused, jmf, guilty of > >> writing nonsense and deliberately using google groups to double line > >> space. The evidence is directly above and quite clearly prooves, beyond > >> a resonable doubt, that no verdict other than guilty can be recorded. I > >> rest my case, m'lud. > > Is a proof more fool-proof because prove is spelt proove ? > Fauultee keebored :) Very O(n)T considering the relation between Fawlty towers and Monty python :-) From invalid at invalid.invalid Wed Feb 12 10:17:01 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 12 Feb 2014 15:17:01 +0000 (UTC) Subject: Newcomer Help References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: On 2014-02-12, Ben Finney wrote: > >> In other contexts eg corporates, often the culture is the opposite: >> top-posting with strictly NO trimming. > > I've never found a corporation that objects to the sensible > conversation-style, minimal-quotes-for-context interleaved posting style. I've always worked in corporations where the email "culture" is the Microsoft-induced "lazy and stupid" style as you describe. And yet when I respond with editted quotes and interleaved repies like this I consitently get nothing favorable comments about it. Some people have even asked how I do it -- though they don't seem to adopt it. -- Grant Edwards grant.b.edwards Yow! FEELINGS are cascading at over me!!! gmail.com From kjakupak at gmail.com Wed Feb 12 10:20:32 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Wed, 12 Feb 2014 07:20:32 -0800 (PST) Subject: Combination Function Help Message-ID: So I need to write a function based off of nCr, which I have here: def choices(n, k): if n == k: return 1 if k == 1: return n if k == 0: return 1 return choices(n - 1, k) + choices(n - 1, k - 1) It works fine, but then I need to add in so that the user can have an input box for n and k. def choices(n, k): if k == 1: return n if n == k: return 1 if k == 0: return 1 return choices(n - 1, k) + choices(n - 1, k - 1) n_input = int(input("Number of courses you like: ")) k_input = int(input("Number of courses you can register for: ")) The above doesn't return any value at all. And then I need it to print the total number of ways of choosing k out of n courses, which I only have: print ("Total number of ways of choosing %d out of %d courses: " % (n_input, k_input)) So basically I need help figuring out why it won't return any value and how to print that final value. From invalid at invalid.invalid Wed Feb 12 10:24:45 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 12 Feb 2014 15:24:45 +0000 (UTC) Subject: Working with the set of real numbers (was: Finding size of Variable) References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: On 2014-02-12, Ben Finney wrote: > Chris Angelico writes: > >> I have yet to find any computer that works with the set of real >> numbers in any way. Never mind optimization, they simply cannot work >> with real numbers. > > Not *any* computer? Not in *any* way? The Python built-in "float" > type "works with the set of real numbers", in a way. The only people who think that are people who don't actualy _use_ floating point types on computers. > What specific behaviour would, for you, qualify as "works with the > set of real numbers in any way" There's a whole laundry list of things (some of them rather nasty and difficult) you have to worry about when using FP that simply don't apply to "real" numbers. -- Grant Edwards grant.b.edwards Yow! HUGH BEAUMONT died at in 1982!! gmail.com From luke.geelen at gmail.com Wed Feb 12 10:32:29 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Wed, 12 Feb 2014 07:32:29 -0800 (PST) Subject: Flag control variable In-Reply-To: References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> Message-ID: <9335871e-e4a5-4bdf-92de-72ac7f20a722@googlegroups.com> Op woensdag 12 februari 2014 06:23:14 UTC+1 schreef Dave Angel: > luke.geelen at gmail.com Wrote in message: > > > Can I make it that if > > > C = int(sys.argv[3]) > > > But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 > > > > > > > Why do you ask for 'automatically'? You're the programmer, write > > the test in the code. > > > > if len (sys.argv) == 3: > > sys.argv. append ("0") > > > > But of course there are lots of other things you need to check, > > so consider all of them at the same time. > > > > -- > > DaveA then i keep getting IndexError: list index out of range anyway to prevent it and just set the value to 0? From breamoreboy at yahoo.co.uk Wed Feb 12 10:40:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 15:40:48 +0000 Subject: Combination Function Help In-Reply-To: References: Message-ID: On 12/02/2014 15:20, kjakupak at gmail.com wrote: > So I need to write a function based off of nCr, which I have here: > > def choices(n, k): > if n == k: > return 1 > if k == 1: > return n > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > > It works fine, but then I need to add in so that the user can have an input box for n and k. > > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > > n_input = int(input("Number of courses you like: ")) > k_input = int(input("Number of courses you can register for: ")) > > The above doesn't return any value at all. And then I need it to print the total number of ways of choosing k out of n courses, which I only have: > > print ("Total number of ways of choosing %d out of %d courses: " % (n_input, k_input)) > > > So basically I need help figuring out why it won't return any value and how to print that final value. > Actually calling choices with n_input and k_input as inputs might help your cause. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Wed Feb 12 10:42:37 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 15:42:37 +0000 Subject: Flag control variable In-Reply-To: <9335871e-e4a5-4bdf-92de-72ac7f20a722@googlegroups.com> References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> <9335871e-e4a5-4bdf-92de-72ac7f20a722@googlegroups.com> Message-ID: On 12/02/2014 15:32, luke.geelen at gmail.com wrote: > Op woensdag 12 februari 2014 06:23:14 UTC+1 schreef Dave Angel: >> luke.geelen at gmail.com Wrote in message: >> >>> Can I make it that if >> >>> C = int(sys.argv[3]) >> >>> But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 >> >>> >> >> >> >> Why do you ask for 'automatically'? You're the programmer, write >> >> the test in the code. >> >> >> >> if len (sys.argv) == 3: >> >> sys.argv. append ("0") >> >> >> >> But of course there are lots of other things you need to check, >> >> so consider all of them at the same time. >> >> >> >> -- >> >> DaveA > > then i keep getting IndexError: list index out of range > anyway to prevent it and just set the value to 0? > Please find a semi-decent tool to use or always follow the instructions for how to remove the double line spacing when using gg, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From kjakupak at gmail.com Wed Feb 12 10:56:05 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Wed, 12 Feb 2014 07:56:05 -0800 (PST) Subject: Combination Function Help In-Reply-To: References: Message-ID: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> def choices(n, k): if k == 1: return n if n == k: return 1 if k == 0: return 1 return choices(n - 1, k) + choices(n - 1, k - 1) print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) n = int(input("Number of courses you like: ")) k = int(input("Number of courses you can register for: ")) choices(n, k) Changed it like you said, didn't work From alain at dpt-info.u-strasbg.fr Wed Feb 12 11:10:36 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Wed, 12 Feb 2014 17:10:36 +0100 Subject: Flag control variable References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> Message-ID: <878utg5n2b.fsf@dpt-info.u-strasbg.fr> luke.geelen at gmail.com writes: > Can I make it that if > C = int(sys.argv[3]) > But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 C = int(sys.argv[3]) if len(sys.argv) > 3 else 0 is one possibility. -- Alain. From joel.goldstick at gmail.com Wed Feb 12 11:21:26 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 12 Feb 2014 11:21:26 -0500 Subject: Combination Function Help In-Reply-To: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: Y On Feb 12, 2014 11:00 AM, wrote: > > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) Following line never runs > print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) > > n = int(input("Number of courses you like: ")) > k = int(input("Number of courses you can register for: ")) > choices(n, k) > > Changed it like you said, didn't work > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From gvanem at yahoo.no Wed Feb 12 11:23:40 2014 From: gvanem at yahoo.no (Gisle Vanem) Date: Wed, 12 Feb 2014 17:23:40 +0100 Subject: Working with the set of real numbers (was: Finding size of Variable) References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7e7d3200-a4ae-4842-ad8d-68b4435b9006@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> Message-ID: "Grant Edwards" wrote: >> Not *any* computer? Not in *any* way? The Python built-in "float" >> type "works with the set of real numbers", in a way. > > The only people who think that are people who don't actualy _use_ > floating point types on computers. FPU parsing the IEEE spec, or?. I didn't quite parse what *you* wrote. To paraphrase: #include "there are FP_NORMAL and FP_SUBNORMAL people in the world; those who understand IEEE 754 and those who don't." .. --gv From john_ladasky at sbcglobal.net Wed Feb 12 11:24:40 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 12 Feb 2014 08:24:40 -0800 (PST) Subject: Combination Function Help In-Reply-To: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: On Wednesday, February 12, 2014 7:56:05 AM UTC-8, kjak... at gmail.com wrote: [snip] > choices(n, k) > > Changed it like you said, didn't work What are you doing with the value returned by the function, choices()? Right now, you aren't doing anything with it. You are throwing it away. That's the beginning of your problem. In your own program, you have two other working examples of functions which return and use values. You should study these. The first, and easier function call for you to understand is the call to int(). You call it twice. The first time, you ASSIGN the name "n" to the value returned by int(). The second time, you assign the name "k" to the value returned by another run of int(). Assigning the names to the values returned by the function calls is what allows you to work with those values later, on other lines of your program. Without assigning n and k, attempting to call choices(n,k) would generate an error. If int() was written in Python (it probably isn't; most of the Python core is written in C) and you looked at int()'s source code, it would have a "return" statement in it, just like your choices() does. Does that help you to see how you should modify the last line of your program, and what you might do after that? There's a second function call in your program as well: you call input(). This function call would be harder for a beginner to understand, because it happens to be nested inside the int() function call. Let's take the simpler one first. From pydev at allsup.co Wed Feb 12 11:40:44 2014 From: pydev at allsup.co (John Allsup) Date: Wed, 12 Feb 2014 16:40:44 +0000 Subject: Top down Python In-Reply-To: <52FB1D27.8090009@allsup.co> References: <52FB1D27.8090009@allsup.co> Message-ID: <52FBA40C.3040806@allsup.co> I've realised that the best way to do this is to use a web browser for the graphical front end: high end graphics are simply not a necessity here, so one does not need to leave the confines of the browser. Thus we need a simple server script. I'm still minimalist, so I guess we want xmlrpc and a python server, with a bit of javascript in the browser to sort out the drawing end. This now seems way simpler than trying to play with Gtk or Qt. Basically the lesson is to use a web browser engine as a graphics engine unless you have performance issues. Hopefully in future html rendering engines will not be so strongly coupled to browsers, or even to the html format itself, but will be a general purpose user graphics engine (an ncurses for bitmapped displays). Can anybody suggest the quickest way to learn the bits of xmlrpc (in python) that I need to do this. Once it's working, I'll stick a source code download on my website. There will be only one version released: the one that works properly. Thus there is no need to github this. All the best, def my_sig(): print("--") print(signame(['n','o','h',uppercase('j')]).written_backwards) On 12/02/2014 07:05, John Allsup wrote: > What is needed for proper learning is near-absolute simplicity. > Even one toy too many to play with is an intolerable distraction, > but one too few massively hampers learning and induces boredom. > > I want to be able to say: > 1. Put a nice picture on the background. > 2. Put a terminal window with, say, 64x20 lines, dead centre. > 3. Run a simple REPL program written in Python or Ruby within it. > I do not really want to write any more lines of code than I need to. > Why do we not have langauges and libraries that can do the above > with only five lines of code (line 0 == setup, line 4 == cleanup). > > Programming should be that efficient if we learn to make things > beautiful and not tolerate wastes of lines and characters, on > a global scale as well as locally to our projects. > > Consider > ==== > #!/usr/bin/env python3 > > from myappfw import app > from myapp1 import repl > app.background = "Moutains1" > t = app.terminal.open(title="Typing commands One Oh One",position="centre", > width="80%",height="72%",rows="20",columns="64") > exit(t.run(repl)) > ==== > > What Python would I need to write, as concise but readable as > practically possible, so that the above program works as desired (for > any repl that obeys the basic input-process-output behaviour of a repl)? > > This is top-down design done right IMO (as described in Thinking Forth, > by the way). From larry.martell at gmail.com Wed Feb 12 11:43:09 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 12 Feb 2014 11:43:09 -0500 Subject: Python programming In-Reply-To: References: Message-ID: On Wed, Feb 12, 2014 at 9:13 AM, Roy Smith wrote: > In article , > Larry Martell wrote: > >> On Tue, Feb 11, 2014 at 7:21 PM, ngangsia akumbo wrote: >> > Please i have a silly question to ask. >> > >> > How long did it take you to learn how to write programs? >> >> My entire life. >> >> I started in 1975 when I was 16 - taught myself BASIC and wrote a very >> crude downhill skiing game. I had dial in access to the mainframe at a >> local college (my HS math teacher got that for me). > > Wow, sounds exactly like my experience. Probably one of these: > > https://en.wikipedia.org/wiki/HP_2000 I think it was a Xerox Sigma: http://en.wikipedia.org/wiki/SDS_Sigma_series From breamoreboy at yahoo.co.uk Wed Feb 12 11:55:10 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 16:55:10 +0000 Subject: Combination Function Help In-Reply-To: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: On 12/02/2014 15:56, kjakupak at gmail.com wrote: > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) > > n = int(input("Number of courses you like: ")) > k = int(input("Number of courses you can register for: ")) > choices(n, k) > > Changed it like you said, didn't work > Changed it like who said? I'm assuming myself, but with no context you can't always tell. Also, stating "didn't work" is often useless to us. What didn't work? Why didn't it work? Here it's obvious, you're throwing away the return value from your function call. Either save the return value and print it or add the function call directly to your original print call. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Wed Feb 12 11:56:34 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 16:56:34 +0000 Subject: Top down Python In-Reply-To: <52FBA40C.3040806@allsup.co> References: <52FB1D27.8090009@allsup.co> <52FBA40C.3040806@allsup.co> Message-ID: On 12/02/2014 16:40, John Allsup wrote: > I've realised that the best way to do this is to use a web browser for > the graphical front end: high end graphics are simply not a necessity > here, so one does not need to leave the confines of the browser. Thus > we need a simple server script. > > I'm still minimalist, so I guess we want xmlrpc and a python server, > with a bit of javascript in the browser to sort out the drawing end. > This now seems way simpler than trying to play with Gtk or Qt. > > Basically the lesson is to use a web browser engine as a graphics engine > unless you have performance issues. Hopefully in future html rendering > engines will not be so strongly coupled to browsers, or even to the html > format itself, but will be a general purpose user graphics engine (an > ncurses for bitmapped displays). > > Can anybody suggest the quickest way to learn the bits of xmlrpc (in > python) that I need to do this. Once it's working, I'll stick a source > code download on my website. There will be only one version released: > the one that works properly. Thus there is no need to github this. > > All the best, > > def my_sig(): > print("--") > print(signame(['n','o','h',uppercase('j')]).written_backwards) > > On 12/02/2014 07:05, John Allsup wrote: >> What is needed for proper learning is near-absolute simplicity. >> Even one toy too many to play with is an intolerable distraction, >> but one too few massively hampers learning and induces boredom. >> >> I want to be able to say: >> 1. Put a nice picture on the background. >> 2. Put a terminal window with, say, 64x20 lines, dead centre. >> 3. Run a simple REPL program written in Python or Ruby within it. >> I do not really want to write any more lines of code than I need to. >> Why do we not have langauges and libraries that can do the above >> with only five lines of code (line 0 == setup, line 4 == cleanup). >> >> Programming should be that efficient if we learn to make things >> beautiful and not tolerate wastes of lines and characters, on >> a global scale as well as locally to our projects. >> >> Consider >> ==== >> #!/usr/bin/env python3 >> >> from myappfw import app >> from myapp1 import repl >> app.background = "Moutains1" >> t = app.terminal.open(title="Typing commands One Oh >> One",position="centre", >> width="80%",height="72%",rows="20",columns="64") >> exit(t.run(repl)) >> ==== >> >> What Python would I need to write, as concise but readable as >> practically possible, so that the above program works as desired (for >> any repl that obeys the basic input-process-output behaviour of a repl)? >> >> This is top-down design done right IMO (as described in Thinking Forth, >> by the way). > Please don't top post on this list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From pydev at allsup.co Wed Feb 12 12:05:40 2014 From: pydev at allsup.co (John Allsup) Date: Wed, 12 Feb 2014 17:05:40 +0000 Subject: Top down Python In-Reply-To: <52FB74F2.4090002@allsup.co> References: <52FB74F2.4090002@allsup.co> Message-ID: <52FBA9E4.40707@allsup.co> Hi, Current software development methods make things way more complex than they need to be. I am trying to get an idea for how simple things can be from final product down to low level implementation, hoping to recover the code density miracles that the old school Forthers turned out ages ago. They outlined a philosophy that I wish to bring back to life. This is the beginning of my first attempt, and I wish to do this in the full gaze of fellow Pythoners so that any mistakes I make can be seen by others, and any lessons learned passed on as cheaply and efficiently (in terms of real world work and energy) as possible. Hope this starts to clarify the picture I have in my head. All the best, John On 12/02/2014 07:42, Chris Angelico wrote: > On Wed, Feb 12, 2014 at 6:05 PM, John Allsup wrote: >> 1. Put a nice picture on the background. >> 2. Put a terminal window with, say, 64x20 lines, dead centre. >> 3. Run a simple REPL program written in Python or Ruby within it. >> I do not really want to write any more lines of code than I need to. >> Why do we not have langauges and libraries that can do the above >> with only five lines of code (line 0 == setup, line 4 == cleanup). > > #!/bin/sh > xfce4-terminal --geometry=64x20 -x python3 > > There you are, two lines. :) > > Seriously though, what you're asking is deceptively simple yet > incredibly difficult. You're trying to recreate the entire structure > of a terminal emulator or telnet client. I can show you the code for a > MUD client, which does a lot of what you're looking for; in fact, this > one has a REPL inbuilt (not Python or Ruby though): > > https://github.com/Rosuav/Gypsum/ > > That's roughly how much code it takes to make a reasonably usable > replicant of a terminal window. (Some of that is specific to > networking and MUDding, but at very least, window.pike is basically > all about the visuals.) You'll do far better to make use of someone > else's terminal renderer, and just put a desktop background to make > your fancy image. Otherwise, you have to recreate everything - console > output (complete with color, presumably), scrolling, input history > (you can get most of your editing keys easily enough, but you will > need command history), clipboard operations, and somewhere along the > way, performance. Save yourself a whole mess of trouble and just use > your OS-provided terminal program :) > > Actually, for what you're looking at, IDLE is probably close to what > you want. You could have a look at how much code it takes to power > IDLE, and/or just use it as is. It's pretty handy; I use it as my > primary interactive Python on Windows. > > ChrisA > From pydev at allsup.co Wed Feb 12 12:06:16 2014 From: pydev at allsup.co (John Allsup) Date: Wed, 12 Feb 2014 17:06:16 +0000 Subject: Top down Python In-Reply-To: <52FB75E6.4030505@allsup.co> References: <52FB75E6.4030505@allsup.co> Message-ID: <52FBAA08.9090104@allsup.co> Hi, I'm trying to figure out where 'simpler' stops and 'too simplistic' begins. That's what I call 'absolute simplicity'. It is a necessity in some areas of learning where even a jot of inefficiency can be costly (consider a superconducting magnet just below the critical frequency with massive amps going through, and then it heats slightly, for a picture of how this 'blow up' happens in the real world). This is an exercise in trying to 'touch the wall'. When the possibilities are not infinite, merely an unimaginably large finite number, eventually a discrete 'wall' must exists and, thus, ought to be findable. John On 12/02/2014 08:09, Ben Finney wrote: > John Allsup writes: > >> What is needed for proper learning is near-absolute simplicity. > > I think that's too simplistic :-) but I'll take it as merely a > preference on your part for simplicity at this time. > >> I want to be able to say: >> 1. Put a nice picture on the background. >> 2. Put a terminal window with, say, 64x20 lines, dead centre. > > Those are deeply dependent on exactly what operating system and desktop > environment and window manager your computer is running. > > What exact values for those variables do you want > the simple program to assume? > > No cross-platform standard library (such as the Python standard library) > will be able to reliably do those things without making a huge amount of > assumption of the operating environment, much of which will be wrong for > a large number of users. > > If you can fix each of those things precisely so that you can ignore all > other possible values, then you can probably come up with a simple > program to do them. > >> 3. Run a simple REPL program written in Python or Ruby within it. > > Python has its own REPL, of course; you get it when you run ?python? > from a command line. Simple! > > If, on the other hand, you want a REPL that plugs into something *other > than* Python, what do you want it to plug into? You have a Python REPL > already, so if you want something else you'll need to be specific. > >> I do not really want to write any more lines of code than I need to. > > For what goal? Python optimises your lines of code for *communicating > with other programmers*, which in my view is pretty close to the most > important variable to be optimising. > From ben+python at benfinney.id.au Wed Feb 12 12:16:07 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Feb 2014 04:16:07 +1100 Subject: Top down Python References: <52FB75E6.4030505@allsup.co> <52FBAA08.9090104@allsup.co> Message-ID: <85wqh09rqg.fsf@benfinney.id.au> John Allsup writes: > Hi, (John, please don't top-post. Instead, retain only the quoted material you're responding to, and interleave your responses after the points like a conversation. See .) > I'm trying to figure out where 'simpler' stops and 'too simplistic' > begins. That's what I call 'absolute simplicity'. That is a rather misleading use of ?absolute?, since it is quite subjective and, since it's a point with further simplicity beyond, must by definition not be absolute simplicity. But again, I'll take this as a preference that you're looking for efficiency. > It is a necessity in some areas of learning where even a jot of > inefficiency can be costly (consider a superconducting magnet just > below the critical frequency with massive amps going through, and then > it heats slightly, for a picture of how this 'blow up' happens in the > real world). I have no idea what that analogy would mean for someone learning to program. Are you going to blow up? What is it you're trying to tell us? > This is an exercise in trying to 'touch the wall'. When the > possibilities are not infinite, merely an unimaginably large finite > number, eventually a discrete 'wall' must exists and, thus, ought to > be findable. Can you say more concretely what it is you're trying to learn, and where the teaching resources are not providing what you expect? What is it you expect? -- \ ?As soon as we abandon our own reason, and are content to rely | `\ upon authority, there is no end to our troubles.? ?Bertrand | _o__) Russell, _Unpopular Essays_, 1950 | Ben Finney From luke.geelen at gmail.com Wed Feb 12 12:15:49 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Wed, 12 Feb 2014 09:15:49 -0800 (PST) Subject: Flag control variable In-Reply-To: <878utg5n2b.fsf@dpt-info.u-strasbg.fr> References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> <878utg5n2b.fsf@dpt-info.u-strasbg.fr> Message-ID: <36d112ba-7e78-4514-a917-424afb270cac@googlegroups.com> Op woensdag 12 februari 2014 17:10:36 UTC+1 schreef Alain Ketterlin: > luke.geelen at gmail.com writes: > > > > > Can I make it that if > > > C = int(sys.argv[3]) > > > But when I only enter 2 argumentvariable it sets c automaticly to 0 or 1 > > > > C = int(sys.argv[3]) if len(sys.argv) > 3 else 0 > > > > is one possibility. > > > > -- Alain. thanks a lot From rosuav at gmail.com Wed Feb 12 12:52:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 04:52:31 +1100 Subject: Working with the set of real numbers In-Reply-To: <87txc4bers.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> <87txc4bers.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 13, 2014 at 1:13 AM, Marko Rauhamaa wrote: > Text files suffer from the same caveat as integers: there's a limit to > how much you can store on the physical computer. Sure, but nobody said the text file had to be _stored_ anywhere :) Computers are quite capable of working with streams of incoming data that are potentially infinite in size. But again, this is the same caveat as the Turing machine. If you wrote a Python interpreter for a Turing machine, it would be - without any changes to Python - capable of handling any integer and any text file. ChrisA From roegltd at gmail.com Wed Feb 12 12:50:47 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 09:50:47 -0800 (PST) Subject: singleton ... again In-Reply-To: References: Message-ID: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote: > > Perhaps if you would state your actual goal, we could judge > whether this code is an effective way to accomplish > it. > DaveA Thanks! There is no specific goal, i am in process of building pattern knowledge in python by doing some examples. From rosuav at gmail.com Wed Feb 12 12:56:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 04:56:57 +1100 Subject: Newcomer Help In-Reply-To: References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: On Thu, Feb 13, 2014 at 2:17 AM, Grant Edwards wrote: > On 2014-02-12, Ben Finney wrote: >> >>> In other contexts eg corporates, often the culture is the opposite: >>> top-posting with strictly NO trimming. >> >> I've never found a corporation that objects to the sensible >> conversation-style, minimal-quotes-for-context interleaved posting style. > > I've always worked in corporations where the email "culture" is the > Microsoft-induced "lazy and stupid" style as you describe. Lazy, stupid, and vulnerable to a major privacy breach. I haven't personally experienced this, but my Mum has on occasion: a (lengthy) private conversation between two people in an organization, then they come to a conclusion that should go public, and cc someone outside the organization (my Mum, in this case) on the final email...... complete with the entire history. Yup. ChrisA From torriem at gmail.com Wed Feb 12 12:57:57 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 12 Feb 2014 10:57:57 -0700 Subject: Top down Python In-Reply-To: <52FBA40C.3040806@allsup.co> References: <52FB1D27.8090009@allsup.co> <52FBA40C.3040806@allsup.co> Message-ID: <52FBB625.10906@gmail.com> On 02/12/2014 09:40 AM, John Allsup wrote: > I've realised that the best way to do this is to use a web browser for > the graphical front end: high end graphics are simply not a necessity > here, so one does not need to leave the confines of the browser. Thus > we need a simple server script. Maybe. Or how about a Python interpreter written in Javascript that runs in the browser? For example, http://www.skulpt.org/. Halfway down the main page is an interpreter running a REPL, that you can manipulate as an example. There are others I've seen over the years. One web site offered interactive versions of several languages in a web page. It's unclear of what you are really trying to do, though. Doing as you propose to have a python server communicating with a web front-end is going to be a lot harder than you think. You're going to have to deal with multiple languages and data processing types and paradigms. You're going to have Python, Javascript, HTML, CSS, JSON, at the very least. Plus you'll have to work with javascript libraries, at the very least jQuery, and on the server side you need a system for interacting with Python. Some kind of CGI system. Or roll your own with TCP/IP Sockets. If you're already familiar with all of these things, then yes it's simple; just a matter of plugging them together. But I fear it's several orders of magnitude more complicated than you think it's going to be. Could be a fun, though relatively pointless, exercise. From roegltd at gmail.com Wed Feb 12 12:56:33 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 09:56:33 -0800 (PST) Subject: singleton ... again In-Reply-To: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> There is another one. Once object passes through singletonizator there wont be any other object than first one. Then object constructor can freely be used in every place of code. Curious if there could be any impact and applicability of this to builtin types. p.s. learned today that object __init__ member function is bound to its class :-) class singletonizator(object): def __new__(cls, *args, **kwargs): def newnew(cls, *args, **kwargs): print("in new new", cls) return cls.__dict__['hidden_object'] def newinit(self, *args, **kwargv): print("in new init", self) pass if not 'hidden_object' in args[0].__class__.__dict__: setattr(args[0].__class__, 'hidden_object', args[0]) args[0].__class__.__new__ = newnew args[0].__class__.__init__ = newinit return args[0] class SomeClass: def __init__(self, num): print("in original init", self) self.mynum = num first_object = singletonizator(SomeClass(1)) print(first_object, first_object.mynum) second_object = singletonizator(SomeClass(2)) print(second_object, second_object.mynum) third_one = SomeClass(3) print(third_one, second_object.mynum) exit() in original init <__main__.SomeClass object at 0x0000000002F338D0> <__main__.SomeClass object at 0x0000000002F338D0> 1 in new new in new init <__main__.SomeClass object at 0x0000000002F338D0> <__main__.SomeClass object at 0x0000000002F338D0> 1 in new new in new init <__main__.SomeClass object at 0x0000000002F338D0> <__main__.SomeClass object at 0x0000000002F338D0> 1 From roegltd at gmail.com Wed Feb 12 12:58:49 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 09:58:49 -0800 (PST) Subject: singleton ... again In-Reply-To: <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> Message-ID: <45df2d21-3141-47ca-a78e-f45d458738ee@googlegroups.com> mistake, object constructor - to class constructor From rosuav at gmail.com Wed Feb 12 13:12:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 05:12:53 +1100 Subject: Top down Python In-Reply-To: <52FBB625.10906@gmail.com> References: <52FB1D27.8090009@allsup.co> <52FBA40C.3040806@allsup.co> <52FBB625.10906@gmail.com> Message-ID: On Thu, Feb 13, 2014 at 4:57 AM, Michael Torrie wrote: > It's unclear of what you are really trying to do, though. Doing as you > propose to have a python server communicating with a web front-end is > going to be a lot harder than you think. ... > Some kind of CGI system. Or roll your own with TCP/IP Sockets. ... There's a fundamentally tricky part to this, which is that the Python interpreter is stateful and HTTP is stateless. You can't usefully use the Python REPL as anything more than a calculator without maintaining a dedicated process for each connected client... and HTTP doesn't have a concept of "connected client". (Cookies will let you recognize a client as the same one who spoke to you earlier, but you'd need some kind of timeout system to flush out the ones who've gone away. Set the timeout too short and you annoy everyone until they don't use it; set it too long and you saturate your server with myriad processes that aren't needed any more.) So you may have to look into a non-HTTP way of communicating between the server and the client. At the moment, there aren't many ways you can do that; you can either plonk down a non-JS object (eg Flash or Java), or you can use HTML5 WebSockets (which aren't supported everywhere); either way, you have to worry about what clients will support it, how it traverses firewalls, etc, etc. Oh, and there's another tricky bit. Python isn't secure. Running it on your server means opening yourself up to all sorts of crazinesses - if nothing else, you need a way to kill the server process and restart it, when you get something stuck somewhere (trust me, you will - it doesn't require malice!). Using a web browser as a UI is fine for some things (I wrote a command/control system for movie players that works through a browser), but it's not automatically easy. ChrisA From neilc at norwich.edu Wed Feb 12 13:25:13 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Wed, 12 Feb 2014 18:25:13 +0000 (UTC) Subject: pip3.x error using LIST instead of list References: <20140211152730.3b99d350@hanez.org> Message-ID: On 2014-02-11, Dave Angel wrote: > Mark Lawrence Wrote in message: >> No matter what I try I can't get the subcommands in lower-case >> when I have caps lock on, is there a simple work-around for >> this as well? :) > > You could do what I've done for my own DOS, Windows, and Linux > computers for years: > > disable the caps-lock key I really liked rebinding it to Left-CTRL. I only stopped doing that because it screwed up my work flow when not at a keyboard I could remap. -- Neil Cerutti From davea at davea.name Wed Feb 12 13:38:15 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 13:38:15 -0500 (EST) Subject: Combination Function Help References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: kjakupak at gmail.com Wrote in message: > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) > > n = int(input("Number of courses you like: ")) > k = int(input("Number of courses you can register for: ")) > choices(n, k) > > Changed it like you said, didn't work > I see at least two problems with that code : The line with the print function will never get called, since it follows an unconditional return statement. You shouldn't print there anyway, just move it to top level, after the two calls to input. Don't forget to dedent it. You don't use or save the return value of choices. You should probably assign it to a name like combinations, then print it on the following line. The recursive function choices doesn't look right to me, but I'm not sure either way. I have not tested it. -- DaveA From davea at davea.name Wed Feb 12 13:51:43 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 13:51:43 -0500 (EST) Subject: Flag control variable References: <68f27949-e613-476b-9227-5a86e4f4df91@googlegroups.com> <9335871e-e4a5-4bdf-92de-72ac7f20a722@googlegroups.com> Message-ID: luke.geelen at gmail.com Wrote in message: > Deleting all the obnoxious doublespaced googlegroups nonsense. .. > > then i keep getting IndexError: list index out of range > anyway to prevent it and just set the value to 0? > My car makes a funny noise. What kind of coat should I wear to the dance to fix it? And do I turn left or back up at the corner? -- DaveA From petef4+usenet at gmail.com Wed Feb 12 13:45:29 2014 From: petef4+usenet at gmail.com (Pete Forman) Date: Wed, 12 Feb 2014 18:45:29 +0000 Subject: pip3.x error using LIST instead of list References: <20140211152730.3b99d350@hanez.org> Message-ID: <86k3d0yxti.fsf@gmail.com> Dave Angel writes: > Mark Lawrence Wrote in message: >> >> >> No matter what I try I can't get the subcommands in lower-case when I >> have caps lock on, is there a simple work-around for this as well? :) >> > > You could do what I've done for my own DOS, Windows, and Linux > computers for years: > > disable the caps-lock key My solution on Windows is to turn on Toggle Keys in the Accessibility options. That beeps when the Caps Lock (or Num or Scroll) is pressed. -- Pete Forman From breamoreboy at yahoo.co.uk Wed Feb 12 13:57:09 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 18:57:09 +0000 Subject: singleton ... again In-Reply-To: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: On 12/02/2014 17:50, Asaf Las wrote: > On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote: >> >> Perhaps if you would state your actual goal, we could judge >> whether this code is an effective way to accomplish >> it. >> DaveA > > Thanks! > > There is no specific goal, i am in process of building pattern knowledge > in python by doing some examples. > For more data on python patterns search for python+patterns+Alex+Martelli. He's forgotten more on the subject than many people on this list will ever know :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eneskristo at gmail.com Wed Feb 12 14:43:00 2014 From: eneskristo at gmail.com (eneskristo at gmail.com) Date: Wed, 12 Feb 2014 11:43:00 -0800 (PST) Subject: Wait... WHAT? Message-ID: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> http://postimg.org/image/rkm9lhj8n/ So, I was doing some cx freeze stuff. If you cant understand everything from the pic, I'll give extra info. Please help me. From ian.g.kelly at gmail.com Wed Feb 12 15:13:11 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Feb 2014 13:13:11 -0700 Subject: Wait... WHAT? In-Reply-To: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 12:43 PM, wrote: > http://postimg.org/image/rkm9lhj8n/ > > So, I was doing some cx freeze stuff. If you cant understand everything from the pic, I'll give extra info. Please help me. It would be preferable if you would please copy and paste the exception along with the code being run into your post, rather than linking to a (probably transient) image on some random hosting site. It appears that tkinter is trying to write an exception directly to stderr and failing because sys.stderr is None. This is probably because you're running the program in console-less mode, where sys.stderr (along with stdin and stdout) does not exist. You'll need to either run your program in console mode or set up a file-like object yourself in place of sys.stderr to capture these messages. It might also be considered a bug in tkinter that it attempts to write to stderr without first ensuring that stderr exists. From toby at tobiah.org Wed Feb 12 15:17:20 2014 From: toby at tobiah.org (Tobiah) Date: Wed, 12 Feb 2014 12:17:20 -0800 Subject: How does python know? Message-ID: I do this: a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' print print id(a) print id(b) And get this: True 140329184721376 140329184721376 This works for longer strings. Does python compare a new string to every other string I've made in order to determine whether it needs to create a new object? Thanks, Tobiah From eneskristo at gmail.com Wed Feb 12 15:21:25 2014 From: eneskristo at gmail.com (eneskristo at gmail.com) Date: Wed, 12 Feb 2014 12:21:25 -0800 (PST) Subject: Wait... WHAT? In-Reply-To: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: I think of it as a bit strange. Should I report it as a bug? I was trying to incorporate a save/load, and this happened. def save(): target = open ("save.swroc", 'w') target.write([counter, loop, number_of_competitors, competitors]) def load(): target = open("save.swroc", 'r') the_array = target counter = the_array[0] loop = the_array[1] number_of_competitors = the_array[2] competitors = the_array[3] Swroc is an nonexisting file format that i just made up, an acronym of the program From toby at tobiah.org Wed Feb 12 15:27:00 2014 From: toby at tobiah.org (Tobiah) Date: Wed, 12 Feb 2014 12:27:00 -0800 Subject: How does python know? In-Reply-To: References: Message-ID: On 02/12/2014 12:17 PM, Tobiah wrote: > I do this: > > a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > > print > print id(a) > print id(b) > > > And get this: > > True > 140329184721376 > 140329184721376 > > > This works for longer strings. Does python > compare a new string to every other string > I've made in order to determine whether it > needs to create a new object? > > Thanks, > > Tobiah Weird as well, is that in the interpreter, the introduction of punctuation appears to defeat the reuse of the object: >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b True >>> a = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> b = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b False >>> b = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b False >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b True Tobiah From rosuav at gmail.com Wed Feb 12 15:33:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 07:33:40 +1100 Subject: How does python know? In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 7:17 AM, Tobiah wrote: > This works for longer strings. Does python > compare a new string to every other string > I've made in order to determine whether it > needs to create a new object? No, it doesn't; but when you compile a module (including a simple script like that), Python checks for repeated literals. It's only good for literals, though. If you specifically need this behaviour, it's called 'interning'. You can ask Python to do this, or you can do it manually. But most of the time, you can just ignore id() and simply let two strings be equal based on their contents; the fact that constants are shared is a neat optimization, nothing more. ChrisA From breamoreboy at yahoo.co.uk Wed Feb 12 15:38:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 20:38:49 +0000 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: On 12/02/2014 20:21, eneskristo at gmail.com wrote: > I think of it as a bit strange. Should I report it as a bug? I was trying to incorporate a save/load, and this happened. > def save(): > target = open ("save.swroc", 'w') > target.write([counter, loop, number_of_competitors, competitors]) > def load(): > target = open("save.swroc", 'r') > the_array = target > counter = the_array[0] > loop = the_array[1] > number_of_competitors = the_array[2] > competitors = the_array[3] > Swroc is an nonexisting file format that i just made up, an acronym of the program > What is it, trying to write a Python list to a file or trying to access offsets into a file handle? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eneskristo at gmail.com Wed Feb 12 15:43:54 2014 From: eneskristo at gmail.com (eneskristo at gmail.com) Date: Wed, 12 Feb 2014 12:43:54 -0800 (PST) Subject: Wait... WHAT? In-Reply-To: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: One to write in the file, and one to read it. From ian.g.kelly at gmail.com Wed Feb 12 15:45:28 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Feb 2014 13:45:28 -0700 Subject: Working with the set of real numbers In-Reply-To: <10afc311-f907-4eb8-859e-99180d1c07c0@googlegroups.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <10afc311-f907-4eb8-859e-99180d1c07c0@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 7:11 AM, Rustom Mody wrote: > On Wednesday, February 12, 2014 3:37:04 PM UTC+5:30, Ben Finney wrote: >> Chris Angelico writes: > >> > On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: >> > > So, if I understand you right, you want to say that you've not found >> > > a computer that works with the *complete* set of real numbers. Yes? >> > Correct. [...] My point is that computers *do not* work with real >> > numbers, but only ever with some subset thereof [...] > >> You've done it again: by saying that "computers *do not* work with real >> numbers", that if I find a real number - e.g. the number 4 - your >> position is that, since it's a real number, computers don't work with >> that number. > > There is a convention in logic called the implicit universal quantifier > convention: when a bald unqualified reference is in a statement it means > it is universally quantified. eg > "A triangle is a polygon with 3 sides" > really means > "ALL polygons with 3 sides are triangles" ie the ALL is implied > > Now when for-all is inverted by de Morgan it becomes "for-some not..." > > So "computers work with real numbers" really means "computers work with > all real numbers" and that is not true I take exception whenever I see somebody trying to use predicate logic to determine the meaning of an English sentence. English does not follow the rules of predicate logic, and English sentences do not map consistently to logical sentences. To me, the meaning of "computers do not work with X" depends upon the domain of X. "Computers do not work with real numbers" implies that computers do not work with the set of real numbers (but implies nothing about subsets). "Computers do not work with keyboards" on the other hand would imply that no computer works with any keyboard (which of course is demonstrably false). From breamoreboy at yahoo.co.uk Wed Feb 12 15:56:10 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 20:56:10 +0000 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: On 12/02/2014 20:43, eneskristo at gmail.com wrote: > One to write in the file, and one to read it. > Nice to know, but please place this in context. Many people who partake in this group are smart, but we're not mind readers :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eneskristo at gmail.com Wed Feb 12 15:59:24 2014 From: eneskristo at gmail.com (eneskristo at gmail.com) Date: Wed, 12 Feb 2014 12:59:24 -0800 (PST) Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: <1c68d6f4-908b-475f-a46f-9c829b58ff8f@googlegroups.com> I am sorry then. So what's the problem, and if it is a bug, should I report it? From timothy.c.delaney at gmail.com Wed Feb 12 16:02:48 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Thu, 13 Feb 2014 08:02:48 +1100 Subject: Python programming In-Reply-To: References: Message-ID: On 13 February 2014 00:55, Larry Martell wrote: > On Tue, Feb 11, 2014 at 7:21 PM, ngangsia akumbo > wrote: > > Please i have a silly question to ask. > > > > How long did it take you to learn how to write programs? > > My entire life. > > I started in 1975 when I was 16 - taught myself BASIC and wrote a very > crude downhill skiing game. OK - it's degenerated into one of these threads - I'm going to participate. I received a copy of "The Beginners Computer Handbook: Understanding & programming the micro" (Judy Tatchell and Bill Bennet, edited by Lisa Watts - ISBN 0860206947) for Christmas of 1985 (I think - I would have been 11 years old). As you may be able to tell from that detail, I have it sitting in front of me right now - other books have come and gone, but I've kept that one with me. It appears to have been published elsewhere under a slightly different name with a very different (and much more boring) cover - I can't find any links to my edition. My school had a couple of Apple IIe and IIc machines, so I started by entering the programs in the book. Then I started modifying them. Then I started writing my own programs from scratch. A couple of years later my dad had been asked to teach a programming class and was trying to teach himself Pascal. We had a Mac 512K he was using. He'd been struggling with it for a few months and getting nowhere. One weekend I picked up his Pascal manual + a 68K assembler Mac ROM guide, combined the two and by the end of the weekend had a semi-working graphical paint program. A few years after that I went to university (comp sci); blitzed my computer-related classes; scraped by in my non-computer-related classes; did some programming work along the way; was recommended to a job by a lecturer half-way through my third year of uni; spent the next 4 years working while (slowly) finishing my degree; eventually found my way into an organisation which treated software development as a discipline and a craft, stayed there for 10 years learning how to be more than just a programmer; came out the other end a senior developer/technical lead and effective communicator. And that's how I learned to program. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From d2mp1a9 at newsguy.com Wed Feb 12 14:42:32 2014 From: d2mp1a9 at newsguy.com (Bob Hanson) Date: Wed, 12 Feb 2014 11:42:32 -0800 Subject: [RELEASED] Python 3.4.0 release candidate 1 References: <52F9D493.6090100@hastings.org> Message-ID: <3cinf99ja4k735tbokolk94dldub7shf9r@4ax.com> [32-bit Windows XP-SP2] On Tue, 11 Feb 2014 12:11:49 -0500, Terry Reedy wrote: > [problems installing rc1] > > On 2/11/2014 10:42 AM, Duncan Booth wrote: > > > Does it put any useful messages in logfile.txt? > > 'error' occurs on 40. most are like the following > > MSI (s) (40:08) [11:57:25:973]: Package to be registered: > 'python-3.4.0rc1.amd64.msi' > MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: Error 3: -2147287038 > MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: AdminProperties 3: > -2147287038 > > Here is the one for the boxed message: > > Action 11:57:26: RemovePip. > Action start 11:57:26: RemovePip. > MSI (s) (40:0C) [11:57:26:426]: Note: 1: 1721 2: RemovePip 3: > C:\Programs\Python34\python.exe 4: -m ensurepip._uninstall > MSI (s) (40:0C) [11:57:26:426]: Note: 1: 2262 2: Error 3: -2147287038 > Error 1721. There is a problem with this Windows Installer package. A > program required for this install to complete could not be run. Contact > your support personnel or package vendor. Action: RemovePip, location: > C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall > MSI (s) (40:0C) [11:57:28:874]: Note: 1: 2262 2: Error 3: -2147287038 > MSI (s) (40:0C) [11:57:28:874]: Product: Python 3.4.0b2 (64-bit) -- > Error 1721. There is a problem with this Windows Installer package. A > program required for this install to complete could not be run. Contact > your support personnel or package vendor. Action: RemovePip, location: > C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall > > MSI (c) (98:EC) [11:57:30:204]: PROPERTY CHANGE: Deleting SECONDSEQUENCE > property. Its current value is '1'. > Action ended 11:57:30: ExecuteAction. Return value 3. > MSI (c) (98:EC) [11:57:30:204]: Doing action: FatalError > A > > Can you make anything of these? Interesting. I just had problems trying to install the 32-bit rc1 (see thread in py-dev; I think it's now "solved"). Here's what Windows Event Viewer said: ''' Product: Python 3.4.0b3 -- Error 1721. There is a problem with this Windows Installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor. Action: RemovePip, location: C:\Python34\python.exe, command: -m ensurepip._uninstall ''' Not sure why the installers are complaining about 3.4.0b3...? Pip seems to be figuring into these glitches, somehow...? (Note that both Terry and I are longtime Windows users, so likely we're both using our own procedures which *have* worked for years.) Bob Hanson -- Confucius say, "Never, ever, make apps dependent on the Windows Registry." From timothy.c.delaney at gmail.com Wed Feb 12 16:07:36 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Thu, 13 Feb 2014 08:07:36 +1100 Subject: Newcomer Help In-Reply-To: References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: On 13 February 2014 02:17, Grant Edwards wrote: > On 2014-02-12, Ben Finney wrote: > > > >> In other contexts eg corporates, often the culture is the opposite: > >> top-posting with strictly NO trimming. > > > > I've never found a corporation that objects to the sensible > > conversation-style, minimal-quotes-for-context interleaved posting style. > > I've always worked in corporations where the email "culture" is the > Microsoft-induced "lazy and stupid" style as you describe. And yet > when I respond with editted quotes and interleaved repies like this I > consitently get nothing favorable comments about it. Some people have > even asked how I do it -- though they don't seem to adopt it. > Yep - the problem is that you usually have to fight against the tools to do it. It's worth the effort, but it can be really hard when you've got an already existing top-posted email thread with people using bizarre fonts and colours throughout. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary.herron at islandtraining.com Wed Feb 12 16:02:03 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Wed, 12 Feb 2014 13:02:03 -0800 Subject: How does python know? In-Reply-To: References: Message-ID: <52FBE14B.7030807@islandtraining.com> On 02/12/2014 12:17 PM, Tobiah wrote: > I do this: > > a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > > print > print id(a) > print id(b) > > > And get this: > > True > 140329184721376 > 140329184721376 > > > This works for longer strings. Does python > compare a new string to every other string > I've made in order to determine whether it > needs to create a new object? > > Thanks, > > Tobiah Yes. Kind of: It's a hash calculation not a direct comparison, and it's applied to strings of limited length. Details are implementation (and perhaps version) specific. The process is called "string interning". Google and wikipedia have lots to say about it. Gary Herron From rosuav at gmail.com Wed Feb 12 16:17:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 08:17:32 +1100 Subject: Wait... WHAT? In-Reply-To: <1c68d6f4-908b-475f-a46f-9c829b58ff8f@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <1c68d6f4-908b-475f-a46f-9c829b58ff8f@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 7:59 AM, wrote: > I am sorry then. So what's the problem, and if it is a bug, should I report it? As Mark said, we need a bit of context in your emails. This on its own carries no information. ChrisA From nirchernia at gmail.com Wed Feb 12 16:18:02 2014 From: nirchernia at gmail.com (Nir) Date: Wed, 12 Feb 2014 13:18:02 -0800 (PST) Subject: Simple Object assignment giving me errors Message-ID: This is from the book 'dive into python'. I am trying to define jeez as being an instance of FileInfo. class UserDict(object): def __init__(self, dict = None): self.data = {} if dict is not None: self.update(dict) class FileInfo(UserDict): def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename jeez = FileInfo("yo") I get a TypeError: 'FileInfo' object doesn't support item assignment . Am I missing something? From rosuav at gmail.com Wed Feb 12 16:22:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 08:22:57 +1100 Subject: Newcomer Help In-Reply-To: References: <22B9F56FF5BA4BC5B8260DE53F4709CC@dev.null> Message-ID: On Thu, Feb 13, 2014 at 8:07 AM, Tim Delaney wrote: > On 13 February 2014 02:17, Grant Edwards wrote: >> I've always worked in corporations where the email "culture" is the >> Microsoft-induced "lazy and stupid" style as you describe. And yet >> when I respond with editted quotes and interleaved repies like this I >> consitently get nothing favorable comments about it. Some people have >> even asked how I do it -- though they don't seem to adopt it. > > > Yep - the problem is that you usually have to fight against the tools to do > it. It's worth the effort, but it can be really hard when you've got an > already existing top-posted email thread with people using bizarre fonts and > colours throughout. Ugh, yes. I run a mailman list for a non-profit organization's committee... some of the people on that list know about standard netiquette, but others will quote the entire thread and add a "me too" with a multi-font, multi-color signature. When the latter sort get into conversation, it's possible for emails to trip the "messages over this many bytes go to the moderator" rule... I've given up trying to explain. :| ChrisA From breamoreboy at yahoo.co.uk Wed Feb 12 16:23:29 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 21:23:29 +0000 Subject: Wait... WHAT? In-Reply-To: <1c68d6f4-908b-475f-a46f-9c829b58ff8f@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <1c68d6f4-908b-475f-a46f-9c829b58ff8f@googlegroups.com> Message-ID: On 12/02/2014 20:59, eneskristo at gmail.com wrote: > I am sorry then. So what's the problem, and if it is a bug, should I report it? > Report what, you keep sending us one liners with no context? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rosuav at gmail.com Wed Feb 12 16:26:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 08:26:36 +1100 Subject: Simple Object assignment giving me errors In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 8:18 AM, Nir wrote: > class FileInfo(UserDict): > def __init__(self, filename=None): > UserDict.__init__(self) > self["name"] = filename > > I get a TypeError: 'FileInfo' object doesn't support item assignment . > > Am I missing something? You can't use square-brackets notation like that, unless you've written your class specifically to handle it. More likely, what you want is one of: self.name = filename self.dict["name"] = filename Also, the same problem will occur with the UserDict, which tries to update itself rather than its dict. Actually, a simpler solution might be to have UserDict inherit from dict. I'm not sure what you're trying to achieve here; more detail would help. But if UserDict really is a dict, then you can call self.update, and you can use square-brackets item assignment. I've no idea what you'd gain over just using a dict though. ChrisA From rosuav at gmail.com Wed Feb 12 16:34:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 08:34:00 +1100 Subject: Python programming In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 8:02 AM, Tim Delaney wrote: > I received a copy of "The Beginners Computer Handbook: Understanding & > programming the micro" (Judy Tatchell and Bill Bennet, edited by Lisa Watts > - ISBN 0860206947) for Christmas of 1985 (I think - I would have been 11 > years old). As you may be able to tell from that detail, I have it sitting > in front of me right now - other books have come and gone, but I've kept > that one with me. It appears to have been published elsewhere under a > slightly different name with a very different (and much more boring) cover - > I can't find any links to my edition. Heh. I wonder if I could still find back the copy of "Bible BASIC" that I learned from. And yes, I learned BASIC first. Moved on from there to 8086 assembly language, using DEBUG.EXE as my assembler, and proceeded through a variety of setups with crazy restrictions on them. Let's see... I wrote non-TSR interrupt handlers that executed a subprocess and cleaned up when that process finished; used BASIC with CALL ABSOLUTE to handle a mouse pointer; got onto OS/2 but didn't have a C compiler, ergo wrote OS/2 code in Pascal; wanted to write a device driver but lacked both C compiler and assembler, ergo wrote a two-pass assembler in REXX that piped everything through DEBUG.EXE running in a virtual 86 session; couldn't get hold of a copy of the no-longer-supported VX-REXX, and so wielded a demo version with a weird system of creating executables... you know, getting onto a Linux system with a real toolchain was quite the luxury. (Okay, okay, I did have some slightly more normal experiences in amongst the weird ones. But it sounds more insane to pretend that the above was how _all_ my programming went.) ChrisA From ned at nedbatchelder.com Wed Feb 12 16:34:34 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 12 Feb 2014 16:34:34 -0500 Subject: singleton ... again In-Reply-To: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: On 2/12/14 12:50 PM, Asaf Las wrote: > On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote: >> >> Perhaps if you would state your actual goal, we could judge >> whether this code is an effective way to accomplish >> it. >> DaveA > > Thanks! > > There is no specific goal, i am in process of building pattern knowledge > in python by doing some examples. > Not all patterns are useful. Just because it's been enshrined in the GoF patterns book doesn't mean that it's good for Python. I don't understand why you would like a class to pretend to make new instances, but actually lie and return the same instance over and over. It makes them impossible to test: your unit tests all act on the same object, there's no way to start over with a fresh object. If you only want one object, create just one, and use it everywhere. -- Ned Batchelder, http://nedbatchelder.com From ian.g.kelly at gmail.com Wed Feb 12 16:35:18 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Feb 2014 14:35:18 -0700 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 1:21 PM, wrote: > I think of it as a bit strange. Should I report it as a bug? I was trying to incorporate a save/load, and this happened. > def save(): > target = open ("save.swroc", 'w') > target.write([counter, loop, number_of_competitors, competitors]) > def load(): > target = open("save.swroc", 'r') > the_array = target > counter = the_array[0] > loop = the_array[1] > number_of_competitors = the_array[2] > competitors = the_array[3] > Swroc is an nonexisting file format that i just made up, an acronym of the program You can't write lists directly to files. You can only write strings to files. To write and read a list, you'll need to first serialize it and later deserialize it. Your needs appear simple enough that I suggest the json module for this. json.dump([counter, loop, number_of_competitors, competitors], target) [counter, loop, number_of_competitors, competitors] = json.load(target) It sounds like this may be the source of the exception that tkinter was trying unsuccessfully to report in your first post. You should still fix your sys.stderr so that tkinter can report exceptions. From davea at davea.name Wed Feb 12 16:41:29 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 16:41:29 -0500 (EST) Subject: Simple Object assignment giving me errors References: Message-ID: Nir Wrote in message: > This is from the book 'dive into python'. I am trying to define jeez as being an instance of FileInfo. > > class UserDict(object): > def __init__(self, dict = None): > self.data = {} > if dict is not None: self.update(dict) > > class FileInfo(UserDict): > def __init__(self, filename=None): > UserDict.__init__(self) > self["name"] = filename > > > jeez = FileInfo("yo") > > > > > I get a TypeError: 'FileInfo' object doesn't support item assignment . > > Am I missing something? > Yes, you're missing the rest of the error message. Show the whole thing, including the stack trace, and I'm sure it'll be clear that the error happened long before jeez was involved. I figure that the line in error is self["name"] = filename and that what you really need is self.data ["name"] = filename You also have a similar problem on the last line of the first class. -- DaveA From torriem at gmail.com Wed Feb 12 16:39:40 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 12 Feb 2014 14:39:40 -0700 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: <52FBEA1C.4080209@gmail.com> On 02/12/2014 01:21 PM, eneskristo at gmail.com wrote: > I think of it as a bit strange. Should I report it as a bug? I was trying to incorporate a save/load, and this happened. What happened? I'm not seeing any exception information. I do see code that doesn't quite make sense. > def save(): > target = open ("save.swroc", 'w') > target.write([counter, loop, number_of_competitors, competitors]) Do you know what actually gets written? IE do you know what the resulting text file looks like? > def load(): > target = open("save.swroc", 'r') > the_array = target > counter = the_array[0] > loop = the_array[1] > number_of_competitors = the_array[2] > competitors = the_array[3] This function isn't right. Question for you, what does open() return? And if you assign that to "the_array," what makes you think you can dereference open() as it it were an array? open() does not provide a __getitem__() dunder method. Python is pretty good at doing what you want usually, but you're missing a step. Python's not bug-free, but the first suspect in a case like this is your code. There's an outside chance you want to explore the "pickle" module. From nirchernia at gmail.com Wed Feb 12 16:42:28 2014 From: nirchernia at gmail.com (Nir) Date: Wed, 12 Feb 2014 13:42:28 -0800 (PST) Subject: Simple Object assignment giving me errors In-Reply-To: References: Message-ID: <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> Those two classes are from this code here(pasted below). Quite frankly, I don't understand this code. Also, UserDict is a built in module. I just typed it out so as to give reference or any clue as to why I cant instantiate jeez. ========================================================================== """Framework for getting filetype-specific metadata. Instantiate appropriate class with filename. Returned object acts like a dictionary, with key-value pairs for each piece of metadata. import fileinfo info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3") print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()]) Or use listDirectory function to get info on all files in a directory. for info in fileinfo.listDirectory("/music/ap/", [".mp3"]): ... Framework can be extended by adding classes for particular file types, e.g. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for parsing its files appropriately; see MP3FileInfo for example. This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark at diveintopython.org)" __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2001 Mark Pilgrim" __license__ = "Python" import os import sys from UserDict import UserDict def stripnulls(data): "strip whitespace and nulls" return data.replace("\00", " ").strip() class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)} def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == "name" and item: self.__parse(item) FileInfo.__setitem__(self, key, item) def listDirectory(directory, fileExtList): "get list of file info objects for files of particular extensions" fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [os.path.join(directory, f) for f in fileList \ if os.path.splitext(f)[1] in fileExtList] def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) and getattr(module, subclass) or FileInfo return [getFileInfoClass(f)(f) for f in fileList] if __name__ == "__main__": for info in listDirectory("/music/_singles/", [".mp3"]): print "\n".join(["%s=%s" % (k, v) for k, v in info.items()]) print ======================================================================== If this makes sense to you, great. I am trying to break it down so that I can make sense of it. As you mentioned self["name"] = filename doesn't work unless I built a class to handle it. I guess my question then, is how is the class handling it in this code? If you can show me by stripping it down to the bare minimum or write an example that would be awesome. From rosuav at gmail.com Wed Feb 12 16:48:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 08:48:31 +1100 Subject: Simple Object assignment giving me errors In-Reply-To: <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> References: <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 8:42 AM, Nir wrote: > Also, UserDict is a built in module. I just typed it out so as to give reference or any clue as to why I cant instantiate jeez. Recommendation for next time: Don't type it out, copy and paste it. Show the actual code you ran, and the actual error message. As a debugging/exploration technique, btw, copying in the definition of something from the standard library is often useful. You can then cut it down to the barest minimum that does what you want, and post that. But if you're using UserDict exactly as it is in the stdlib, you can simply show your import statement and we'll know what you mean. ChrisA From davea at davea.name Wed Feb 12 16:59:28 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 16:59:28 -0500 (EST) Subject: How does python know? References: Message-ID: Tobiah Wrote in message: > On 02/12/2014 12:17 PM, Tobiah wrote: >> I do this: >> >> a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' >> b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' >> >> print >> print id(a) >> print id(b) >> >> >> And get this: >> >> True >> 140329184721376 >> 140329184721376 >> >> >> This works for longer strings. Does python >> compare a new string to every other string >> I've made in order to determine whether it >> needs to create a new object? >> >> Thanks, >> >> Tobiah > > Weird as well, is that in the interpreter, > the introduction of punctuation appears to > defeat the reuse of the object: > > >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' > >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' > >>> a is b > True > >>> a = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' > >>> b = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' > >>> a is b > > As others have said, interning is implementation specific, so you should never rely on it. I think the current CPython algorithm is designed to save both memory and time in the storage and look up of symbol names. In a typical program, those are the most likely to be duplicated. So if your literal is of reasonable size and doesn???t invalid symbol characters (such as space, punctuation, etc) then it just might be added to the interned dictionary. -- DaveA From greg.ewing at canterbury.ac.nz Wed Feb 12 16:57:02 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Feb 2014 10:57:02 +1300 Subject: singleton ... again In-Reply-To: <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> Message-ID: Asaf Las wrote: > There is another one. > Once object passes through singletonizator > there wont be any other object than first one. > > Then object constructor can freely be used in every place > of code. You're still making things far more complicated than they need to be. *Why* do you want to be able to use the object constructor, instead of just using the prebuilt instance? If you want to hide the distinction between using call syntax and just accessing a global, then export a function that returns the global instance. That function can even lazily create the instance the first time it's called. That's a pattern that *is* useful, and I've often used in Python and other languages. E.g. _the_whatsit = None def get_whatsit(): if _the_whatsit is None: _the_whatsit = Whatsit() return _the_whatsit -- Greg From torriem at gmail.com Wed Feb 12 17:05:57 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 12 Feb 2014 15:05:57 -0700 Subject: singleton ... again In-Reply-To: References: Message-ID: <52FBF045.3060302@gmail.com> On 02/11/2014 09:34 PM, Asaf Las wrote: > playing a bit with subject. > > pros and cons of this approach? did i create bicycle again? :-) I always thought sticking an object in a module is the simplest form of singleton. From malaclypse2 at gmail.com Wed Feb 12 17:09:00 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 12 Feb 2014 17:09:00 -0500 Subject: Simple Object assignment giving me errors In-Reply-To: <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> References: <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> Message-ID: On Wed, Feb 12, 2014 at 4:42 PM, Nir wrote: > If this makes sense to you, great. I am trying to break it down so that I can make sense of it. As you mentioned self["name"] = filename doesn't work unless I built a class to handle it. I guess my question then, is how is the class handling it in this code? If you can show me by stripping it down to the bare minimum or write an example that would be awesome. This example works because the UserDict object being used in this code was built to handle it. The UserDict class in the standard library does a lot more than the little snippet you had in your original code. Your original code would work if you did the same thing, like this: from collections import UserDict class FileInfo(UserDict): def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename jeez = FileInfo("yo") (If you're using Python 2, then the first line should be "from UserDict import UserDict" instead). You can take a look at the source code for the userDict class here: http://hg.python.org/cpython/file/3.3/Lib/collections/__init__.py#l862 . In that class, the code responsible for handling the bracketed name lookup (i.e., self["name"]), is in the __getitem__ and __setitem__ methods (and peripherally in __delitem__, __len__ and __contains__) -- Jerry From greg.ewing at canterbury.ac.nz Wed Feb 12 17:09:57 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Feb 2014 11:09:57 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > That's why I think you need to be clear that your point isn't ?computers > don't work with real numbers?, but rather ?computers work only with a > limited subset of real numbers?. They actually work with a subset of *rational* numbers. All floats representable by a computer are rational. The rationals happen to be a subset of the reals, but that's kind of beside the point given that a float can't represent *any* real number that isn't also a rational. -- Greg From python.list at tim.thechases.com Wed Feb 12 17:14:27 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Feb 2014 16:14:27 -0600 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: <20140212161427.0a9843d5@bigbox.christie.dr> On 2014-02-12 14:35, Ian Kelly wrote: > You can't write lists directly to files. You can only write strings > to files. To write and read a list, you'll need to first serialize > it and later deserialize it. To be pedantic, you can only write *bytes* to files, so you need to serialize your lists (or other objects) to strings and then encode those to bytes; or skip the string and encode your list/object directly to bytes. Though unfortunately, I now have a tweaked version of that late-night commercial?: "PICKLE: SERIALIZE DIRECTLY TO BYTES! PICKLE: SERIALIZE DIRECTLY TO BYTES! PICKLE: SERIALIZE DIRECTLY TO BYTES!" -tkc ? http://www.youtube.com/watch?v=f_SwD7RveNE From greg.ewing at canterbury.ac.nz Wed Feb 12 17:24:51 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Feb 2014 11:24:51 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> <87txc4bers.fsf@elektro.pacujo.net> Message-ID: Chris Angelico wrote: > Sure, but nobody said the text file had to be _stored_ anywhere :) > Computers are quite capable of working with streams of incoming data > that are potentially infinite in size. However, they *can't* work with arbitrary real numbers in an exact way, even if they are represented by infinitely long digit streams, and you're willing to run the program for an infinitely long time to get the result. Consider adding two of these numbers, for example. You have to do it starting at the big end, because the small end is infinitely far away. And you only have a limited amount of buffer space, so you need to start writing out result digits before you've seen all the input digits. But you can't do that, because it's possible that some pair of input digits you haven't seen yet will cause a carry-over that ripples back and affects something you've already written out. This is where schemes such as computable reals get into trouble. Doing arithmetic with them gets extremely messy. -- Greg From nirchernia at gmail.com Wed Feb 12 17:25:19 2014 From: nirchernia at gmail.com (Nir) Date: Wed, 12 Feb 2014 14:25:19 -0800 (PST) Subject: Simple Object assignment giving me errors In-Reply-To: References: Message-ID: Thank you Jerry. And thank you to the rest of you. You all have been tremendously helpful. PS Chris, next time I will do just that. From greg.ewing at canterbury.ac.nz Wed Feb 12 17:32:39 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Feb 2014 11:32:39 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <854n44blo9.fsf@benfinney.id.au> Message-ID: Chris Angelico wrote: > Of course a > computer can work with _some_ real numbers; but only some. (An awful > lot of them, of course. A ridiculously huge number of numbers. More > numbers than you could read in a lifetime! While the number is > extremely large, it still falls pitifully short of infinity.[1]) The number of integers it can work with is also vanishingly small compared to the total number of integers. However, the number of reals is vastly greater than the number of integers, so the proportion of reals it can work with is even *more* vanishingly small. In some sense. -- Greg From davea at davea.name Wed Feb 12 17:56:53 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 17:56:53 -0500 (EST) Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> <87txc4bers.fsf@elektro.pacujo.net> Message-ID: Gregory Ewing Wrote in message: > Chris Angelico wrote: >> Sure, but nobody said the text file had to be _stored_ anywhere :) >> Computers are quite capable of working with streams of incoming data >> that are potentially infinite in size. > > However, they *can't* work with arbitrary real numbers in an > exact way, even if they are represented by infinitely long > digit streams, and you're willing to run the program for > an infinitely long time to get the result. > > Consider adding two of these numbers, for example. You have > to do it starting at the big end, because the small end is > infinitely far away. And you only have a limited amount of > buffer space, so you need to start writing out result > digits before you've seen all the input digits. > > But you can't do that, because it's possible that some > pair of input digits you haven't seen yet will cause a > carry-over that ripples back and affects something you've > already written out. > > Actually, the particular example you use can be done. When printing the infinite sum of two infinite decimal streams, you can simply hold back whenever you get one or more nines. Instead keep a count of how many nines you're holding, and emit them all only when you get something other than 9. I've done something analogous doing run length encoding of an rs232 stream. But you're right in general. -- DaveA From greg.ewing at canterbury.ac.nz Wed Feb 12 17:54:52 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 13 Feb 2014 11:54:52 +1300 Subject: Top down Python In-Reply-To: References: <52FB1D27.8090009@allsup.co> Message-ID: John Allsup wrote: > I'm still minimalist, so I guess we want xmlrpc and a python server, > with a bit of javascript in the browser to sort out the drawing end. > This now seems way simpler than trying to play with Gtk or Qt. Depends on what you mean by "simpler". You've just mentioned about 3 additional technologies to come to grips with, plus the complexity of splitting your application logic between a client and a server. Whether this is any easier depends on what you're already familiar with. -- Greg From timothy.c.delaney at gmail.com Wed Feb 12 17:57:43 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Thu, 13 Feb 2014 09:57:43 +1100 Subject: Python programming In-Reply-To: References: Message-ID: On 13 February 2014 08:02, Tim Delaney wrote: > I received a copy of "The Beginners Computer Handbook: Understanding & > programming the micro" (Judy Tatchell and Bill Bennet, edited by Lisa Watts > - ISBN 0860206947) > I should have noted that the examples were all BASIC (with details for how to modify for various BASIC implementations on various platforms). Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.martell at gmail.com Wed Feb 12 12:11:36 2014 From: larry.martell at gmail.com (Larry Martell) Date: Wed, 12 Feb 2014 12:11:36 -0500 Subject: Top posting and double spacing Message-ID: My personal rule is that I will give people 1 or 2 chances after they are asked. If they continue to top post or send double space posts, I simply ignore everything from them until they get with the program. If we all did that maybe they'd get the message (but probably not). From kjakupak at gmail.com Wed Feb 12 17:59:58 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Wed, 12 Feb 2014 14:59:58 -0800 (PST) Subject: Combination Function Help In-Reply-To: References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: def choices(n, k): if k == 1: return n if n == k: return 1 if k == 0: return 1 return choices(n - 1, k) + choices(n - 1, k - 1) comb = choices(n, k) print comb print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) n = int(input("Number of courses you like: ")) k = int(input("Number of courses you can register for: ")) Still isn't working though.. From timothy.c.delaney at gmail.com Wed Feb 12 18:08:07 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Thu, 13 Feb 2014 10:08:07 +1100 Subject: singleton ... again In-Reply-To: References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: On 13 February 2014 08:34, Ned Batchelder wrote: > On 2/12/14 12:50 PM, Asaf Las wrote: > >> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote: >> >>> >>> Perhaps if you would state your actual goal, we could judge >>> whether this code is an effective way to accomplish >>> it. >>> DaveA >>> >> >> Thanks! >> >> There is no specific goal, i am in process of building pattern knowledge >> in python by doing some examples. >> >> > Not all patterns are useful. Just because it's been enshrined in the GoF > patterns book doesn't mean that it's good for Python. > Speaking of which, my monitor is currently sitting on my copy of "Design Patterns". A lot of "Design Patterns" isn't directly relevant to Python, because Python either already has various patterns implemented, or obviates the need for them. For example, if you really need a singleton (answer - you don't) just use a module attribute. Functions as objects and iterators being so pervasive means that visitor and related patterns are just a normal style of programming, instead of having to be explicit. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Wed Feb 12 18:09:46 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 12 Feb 2014 23:09:46 +0000 (UTC) Subject: Wait... WHAT? References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> Message-ID: On 2014-02-12, eneskristo at gmail.com wrote: > One to write in the file, and one to read it. And one to bind them all! -- Grant Edwards grant.b.edwards Yow! I'm in direct contact at with many advanced fun gmail.com CONCEPTS. From breamoreboy at yahoo.co.uk Wed Feb 12 18:15:09 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 23:15:09 +0000 Subject: Combination Function Help In-Reply-To: References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: On 12/02/2014 22:59, kjakupak at gmail.com wrote: > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > > comb = choices(n, k) > print comb > > print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) > n = int(input("Number of courses you like: ")) > k = int(input("Number of courses you can register for: ")) > > Still isn't working though.. > Please be precise, "still isn't working" tells us nothing. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From davea at davea.name Wed Feb 12 18:22:07 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 18:22:07 -0500 (EST) Subject: Combination Function Help References: <11e9f551-f920-428c-895d-a5d19a4d7734@googlegroups.com> Message-ID: kjakupak at gmail.com Wrote in message: > def choices(n, k): > if k == 1: > return n > if n == k: > return 1 > if k == 0: > return 1 > return choices(n - 1, k) + choices(n - 1, k - 1) > > comb = choices(n, k) > print comb > > print ("Total number of ways of choosing %d out of %d courses: " % (n, k)) > n = int(input("Number of courses you like: ")) > k = int(input("Number of courses you can register for: ")) > > Still isn't working though.. > Still haven't figured how to post a traceback? The two lines defining and referencing comb need to be AFTER n and k are defined and given values. Also, what version of Python are you running? Version 3.x requires parentheses around the arguments to the print function. -- DaveA From invalid at invalid.invalid Wed Feb 12 18:23:21 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 12 Feb 2014 23:23:21 +0000 (UTC) Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <854n44blo9.fsf@benfinney.id.au> Message-ID: On 2014-02-12, Gregory Ewing wrote: > Chris Angelico wrote: > >> Of course a computer can work with _some_ real numbers; but only >> some. (An awful lot of them, of course. A ridiculously huge number of >> numbers. More numbers than you could read in a lifetime! While the >> number is extremely large, it still falls pitifully short of >> infinity.[1]) > > The number of integers it can work with is also vanishingly small > compared to the total number of integers. > > However, the number of reals is vastly greater than the number of > integers, so the proportion of reals it can work with is even *more* > vanishingly small. In some sense. More importantly, Computers can generally work with a subset of integers consisting of all integers between a min value and a max value. The min and max may be known and fixed at compile time (e.g. C "int" on a 32-bit machine), or it may depend on how much memory and time you have. But knowing that you can represent all values in some range makes life pretty easy. OTOH, no matter how small the magnitude of the range of real numbers you pick, computer FP can only represent a very tiny subset of the rational numbers which are an even tinier subset of the real numbers within whatever range you care to pick. If you pick your range and representation intelligently, you can still do some pretty useful stuff. But, if you pretend you're actually working with real numbers you will come a cropper. -- Grant Edwards grant.b.edwards Yow! Why is it that when at you DIE, you can't take gmail.com your HOME ENTERTAINMENT CENTER with you?? From breamoreboy at yahoo.co.uk Wed Feb 12 18:36:29 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Feb 2014 23:36:29 +0000 Subject: Wait... WHAT? In-Reply-To: <20140212161427.0a9843d5@bigbox.christie.dr> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> Message-ID: On 12/02/2014 22:14, Tim Chase wrote: > > To be pedantic, you can only write *bytes* to files, so you need to > serialize your lists (or other objects) to strings and then encode > those to bytes; or skip the string and encode your list/object > directly to bytes. > Really? >>> f = open('test.txt', 'w') >>> f.write('a string') 8 >>> f.close() >>> -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From tjreedy at udel.edu Wed Feb 12 18:48:15 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Feb 2014 18:48:15 -0500 Subject: [RELEASED] Python 3.4.0 release candidate 1 In-Reply-To: <3cinf99ja4k735tbokolk94dldub7shf9r@4ax.com> References: <52F9D493.6090100@hastings.org> <3cinf99ja4k735tbokolk94dldub7shf9r@4ax.com> Message-ID: On 2/12/2014 2:42 PM, Bob Hanson wrote: > [32-bit Windows XP-SP2] > > On Tue, 11 Feb 2014 12:11:49 -0500, Terry Reedy wrote: > >> [problems installing rc1] >> >> On 2/11/2014 10:42 AM, Duncan Booth wrote: >> >>> Does it put any useful messages in logfile.txt? >> >> 'error' occurs on 40. most are like the following >> >> MSI (s) (40:08) [11:57:25:973]: Package to be registered: >> 'python-3.4.0rc1.amd64.msi' >> MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: Error 3: -2147287038 >> MSI (s) (40:08) [11:57:25:973]: Note: 1: 2262 2: AdminProperties 3: >> -2147287038 >> >> Here is the one for the boxed message: >> >> Action 11:57:26: RemovePip. >> Action start 11:57:26: RemovePip. >> MSI (s) (40:0C) [11:57:26:426]: Note: 1: 1721 2: RemovePip 3: >> C:\Programs\Python34\python.exe 4: -m ensurepip._uninstall >> MSI (s) (40:0C) [11:57:26:426]: Note: 1: 2262 2: Error 3: -2147287038 >> Error 1721. There is a problem with this Windows Installer package. A >> program required for this install to complete could not be run. Contact >> your support personnel or package vendor. Action: RemovePip, location: >> C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall >> MSI (s) (40:0C) [11:57:28:874]: Note: 1: 2262 2: Error 3: -2147287038 >> MSI (s) (40:0C) [11:57:28:874]: Product: Python 3.4.0b2 (64-bit) -- >> Error 1721. There is a problem with this Windows Installer package. A >> program required for this install to complete could not be run. Contact >> your support personnel or package vendor. Action: RemovePip, location: >> C:\Programs\Python34\python.exe, command: -m ensurepip._uninstall >> >> MSI (c) (98:EC) [11:57:30:204]: PROPERTY CHANGE: Deleting SECONDSEQUENCE >> property. Its current value is '1'. >> Action ended 11:57:30: ExecuteAction. Return value 3. >> MSI (c) (98:EC) [11:57:30:204]: Doing action: FatalError >> A >> >> Can you make anything of these? > > Interesting. I just had problems trying to install the 32-bit rc1 > (see thread in py-dev; I think it's now "solved"). > > Here's what Windows Event Viewer said: > > ''' > Product: Python 3.4.0b3 -- Error 1721. There is a problem with > this Windows Installer package. A program required for this > install to complete could not be run. Contact your support > personnel or package vendor. Action: RemovePip, location: > C:\Python34\python.exe, command: -m ensurepip._uninstall > ''' > > Not sure why the installers are complaining about 3.4.0b3...? > > Pip seems to be figuring into these glitches, somehow...? > > (Note that both Terry and I are longtime Windows users, so likely > we're both using our own procedures which *have* worked for > years.) In my case, the problem appears to be that 3.4.0b3 did not completely uninstall and overwrite .0b2. Control Panel / Programs and Features (new name for Add/Remove) had entries for both .0b2 and .0b3, which it should not have. Trying to uninstall .0b2 gave same message. So I re-downloaded the .0b2 file from python.org/ftp/python/3.4.0, repaired .0b2, and then uninstalled it. The 64 bit .0c1 then seems to have installed Ok. -- Terry Jan Reedy From ian.g.kelly at gmail.com Wed Feb 12 19:01:13 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Feb 2014 17:01:13 -0700 Subject: Wait... WHAT? In-Reply-To: <20140212161427.0a9843d5@bigbox.christie.dr> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> Message-ID: On Wed, Feb 12, 2014 at 3:14 PM, Tim Chase wrote: > On 2014-02-12 14:35, Ian Kelly wrote: >> You can't write lists directly to files. You can only write strings >> to files. To write and read a list, you'll need to first serialize >> it and later deserialize it. > > To be pedantic, you can only write *bytes* to files, so you need to > serialize your lists (or other objects) to strings and then encode > those to bytes; or skip the string and encode your list/object > directly to bytes. The file was opened in text mode, not binary mode. Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('test.txt', 'w') >>> f.write(b'hello world') Traceback (most recent call last): File "", line 1, in TypeError: must be str, not bytes From cousinstanley at gmail.com Wed Feb 12 19:26:04 2014 From: cousinstanley at gmail.com (Cousin Stanley) Date: Wed, 12 Feb 2014 17:26:04 -0700 Subject: Top down Python References: Message-ID: > .... > 3) Create terminal window with size 64x20 > (which, IMO, is tiny) > .... Maybe .... 64 characters x 20 lines -- Stanley C. Kitching Human Being Phoenix, Arizona From python.list at tim.thechases.com Wed Feb 12 19:44:32 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Feb 2014 18:44:32 -0600 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> Message-ID: <20140212184432.1df9b491@bigbox.christie.dr> On 2014-02-12 23:36, Mark Lawrence wrote: > On 12/02/2014 22:14, Tim Chase wrote: > > > > To be pedantic, you can only write *bytes* to files, so you need > > to serialize your lists (or other objects) to strings and then > > encode those to bytes; or skip the string and encode your > > list/object directly to bytes. > > > > Really? > > >>> f = open('test.txt', 'w') > >>> f.write('a string') > 8 > >>> f.close() > >>> Yep: >>> s = "\u3141" # HANGUL LETTER MIEUM >>> f = open('test.txt', 'w') >>> f.write("\u3141") Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character '\u3141' in position 0: ordinal not in range(128) Just because the open() call hides the specification of how Python should do that encoding doesn't prevent the required encoding from happening. :-) -tkc From breamoreboy at yahoo.co.uk Wed Feb 12 19:59:16 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Feb 2014 00:59:16 +0000 Subject: Wait... WHAT? In-Reply-To: <20140212184432.1df9b491@bigbox.christie.dr> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> Message-ID: On 13/02/2014 00:44, Tim Chase wrote: > On 2014-02-12 23:36, Mark Lawrence wrote: >> On 12/02/2014 22:14, Tim Chase wrote: >>> >>> To be pedantic, you can only write *bytes* to files, so you need >>> to serialize your lists (or other objects) to strings and then >>> encode those to bytes; or skip the string and encode your >>> list/object directly to bytes. >>> >> >> Really? >> >> >>> f = open('test.txt', 'w') >> >>> f.write('a string') >> 8 >> >>> f.close() >> >>> > > Yep: > >>>> s = "\u3141" # HANGUL LETTER MIEUM >>>> f = open('test.txt', 'w') >>>> f.write("\u3141") > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character '\u3141' in > position 0: ordinal not in range(128) > > Just because the open() call hides the specification of how Python > should do that encoding doesn't prevent the required encoding from > happening. :-) > > -tkc > > Which clearly reinforces the fact that what you originally said is incorrect, I don't have to do anything, Python very kindly does things for me under the covers. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From roegltd at gmail.com Wed Feb 12 20:02:52 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 17:02:52 -0800 (PST) Subject: singleton ... again In-Reply-To: References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: On Wednesday, February 12, 2014 8:57:09 PM UTC+2, Mark Lawrence wrote: > > For more data on python patterns search for > python+patterns+Alex+Martelli. He's forgotten more on the subject than > many people on this list will ever know :) > > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > Oh, thanks, good information. From rosuav at gmail.com Wed Feb 12 20:06:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 12:06:12 +1100 Subject: Top down Python In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 11:26 AM, Cousin Stanley wrote: >> .... >> 3) Create terminal window with size 64x20 >> (which, IMO, is tiny) >> .... > > Maybe .... > > 64 characters x 20 lines Yes, but still tiny. Normal minimum would be 80x25 (maybe 80x24). I like to go a lot larger. When I'm compiling code, I generally maximize the window - on today's system, that's 190x51 - and for MUDding, I'll usually go for roughly 90x?, because I can. :) My current MUD window is 89x32 visible, 89x? stored. 64x20 means everything's going to wrap, and it won't take much to push text off the "screen". ChrisA From rosuav at gmail.com Wed Feb 12 20:10:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 12:10:22 +1100 Subject: Wait... WHAT? In-Reply-To: <20140212184432.1df9b491@bigbox.christie.dr> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> Message-ID: On Thu, Feb 13, 2014 at 11:44 AM, Tim Chase wrote: > Yep: > >>>> s = "\u3141" # HANGUL LETTER MIEUM >>>> f = open('test.txt', 'w') >>>> f.write("\u3141") > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character '\u3141' in > position 0: ordinal not in range(128) > > Just because the open() call hides the specification of how Python > should do that encoding doesn't prevent the required encoding from > happening. :-) > All it's hiding is what the default encoding is. Python 3.4.0rc1+ (default:2ba583191550, Feb 12 2014, 10:30:57) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> f = open('test.txt', 'w') >>> f.write("\u3141") 1 Python 3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 16:23:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> f = open('test.txt', 'w') >>> f.write("\u3141") Traceback (most recent call last): File "", line 1, in f.write("\u3141") File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u3141' in position 0: character maps to >>> f = open('test.txt', 'w', encoding='utf-8') >>> f.write("\u3141") 1 Be explicit, and you can store Unicode strings reliably. That said, though, you still can't store lists. ChrisA From roegltd at gmail.com Wed Feb 12 20:34:05 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 17:34:05 -0800 (PST) Subject: singleton ... again In-Reply-To: References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: <90b35309-2ffb-46b6-98bd-3696124e5935@googlegroups.com> On Wednesday, February 12, 2014 11:34:34 PM UTC+2, Ned Batchelder wrote: > Not all patterns are useful. Just because it's been enshrined in the > GoF patterns book doesn't mean that it's good for Python. Yes, i understand up to some extend usefulness of patterns. i did not read the GoF book. yet. > I don't understand why you would like a class to pretend to make new > instances, but actually lie and return the same instance over and over. > It makes them impossible to test: your unit tests all act on the same > object, there's no way to start over with a fresh object. > > If you only want one object, create just one, and use it everywhere. > > Ned Batchelder, http://nedbatchelder.com Actually it is not about singleton. Let say if i would like to make set of resources with controllable quantity and not for single class but for let say 10 or 20 classes , so i could read config file at time of program start and create them accordingly and only when needed. having unified attribute names within resource classes allows to do more more from one place, let say leaving resource recovery to background thread via proxy methods for failed resources, or scanning of objects in resource for timeouts or ticking clocks on them for delayed response. if there is no unified template - then for every particular class i have to put a list within module and count on number of objects created and then supervision and other things have to be handled separately. Though i do not defend current approach - it is a bit hack. same can be done via inheritance from base classes or with a bit more typing via static methods. Asaf From roegltd at gmail.com Wed Feb 12 20:38:55 2014 From: roegltd at gmail.com (Asaf Las) Date: Wed, 12 Feb 2014 17:38:55 -0800 (PST) Subject: singleton ... again In-Reply-To: References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> <9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com> Message-ID: On Wednesday, February 12, 2014 11:57:02 PM UTC+2, Gregory Ewing wrote: > > If you want to hide the distinction between using > call syntax and just accessing a global, then > export a function that returns the global instance. > > That function can even lazily create the instance > the first time it's called. That's a pattern that > *is* useful, and I've often used in Python and > other languages. > E.g. > _the_whatsit = None > def get_whatsit(): > if _the_whatsit is None: > _the_whatsit = Whatsit() > return _the_whatsit > Greg Gregory Ewing and Michael Torrie, yes you are both right, that is how things are done in standard Python library. But i am not restricting myself to that. Thanks /Asaf From rustompmody at gmail.com Wed Feb 12 20:47:19 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 12 Feb 2014 17:47:19 -0800 (PST) Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <10afc311-f907-4eb8-859e-99180d1c07c0@googlegroups.com> Message-ID: <4ee92a2b-41ec-4b8b-b1fe-bfea15166487@googlegroups.com> On Thursday, February 13, 2014 2:15:28 AM UTC+5:30, Ian wrote: > On Wed, Feb 12, 2014 at 7:11 AM, Rustom Mody wrote: > > On Wednesday, February 12, 2014 3:37:04 PM UTC+5:30, Ben Finney wrote: > >> Chris Angelico writes: > >> > On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: > >> > > So, if I understand you right, you want to say that you've not found > >> > > a computer that works with the *complete* set of real numbers. Yes? > >> > Correct. [...] My point is that computers *do not* work with real > >> > numbers, but only ever with some subset thereof [...] > >> You've done it again: by saying that "computers *do not* work with real > >> numbers", that if I find a real number - e.g. the number 4 - your > >> position is that, since it's a real number, computers don't work with > >> that number. > > There is a convention in logic called the implicit universal quantifier > > convention: when a bald unqualified reference is in a statement it means > > it is universally quantified. eg > > "A triangle is a polygon with 3 sides" > > really means > > "ALL polygons with 3 sides are triangles" ie the ALL is implied > > Now when for-all is inverted by de Morgan it becomes "for-some not..." > > So "computers work with real numbers" really means "computers work with > > all real numbers" and that is not true > I take exception whenever I see somebody trying to use predicate logic > to determine the meaning of an English sentence. Ok See below. > English does not follow the rules of predicate logic, Agreed > and English sentences do not map consistently to logical sentences. Agreed > To me, the meaning of "computers do not work with X" depends upon the > domain of X. Agreed > "Computers do not work with real numbers" implies that > computers do not work with the set of real numbers (but implies > nothing about subsets). How come? > "Computers do not work with keyboards" on the > other hand would imply that no computer works with any keyboard (which > of course is demonstrably false). The example is the other way. If one says: "Computers have keyboards" and then we have the demonstratation of say - a cloud server - a android phone which are computers that have no keyboards, then that demonstrates that "(ALL) computers have keyboards" is false" Two things therefore come into play here: 1. "All computers have keyboards" is falsified by predicate logic 2. Modelling the English "Computers have keyboards" to the above sentence needs: grammar, context, good-sense, good-will and a lot of other good (and soft) stuff. tl;dr Predicate logic can help to gain some clarity about where the implied but unstated quantifiers lie. From roy at panix.com Wed Feb 12 20:54:23 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 20:54:23 -0500 Subject: How does python know? References: Message-ID: In article , Tobiah wrote: > I do this: > > a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' > > print > print id(a) > print id(b) > > > And get this: > > True > 140329184721376 > 140329184721376 > > > This works for longer strings. Does python > compare a new string to every other string > I've made in order to determine whether it > needs to create a new object? Yes[*]. It's called interning. See https://en.wikipedia.org/wiki/Intern_(computer_science). [*] Well, nothing requires Python to do that. Some implementations do. Some don't. Some do it for certain types of strings. Your mileage may vary. From roy at panix.com Wed Feb 12 20:57:56 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 20:57:56 -0500 Subject: singleton ... again References: <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com> Message-ID: In article <9785668d-6bea-4382-8a0c-c1258f2e2693 at googlegroups.com>, Asaf Las wrote: > On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote: > > > > Perhaps if you would state your actual goal, we could judge > > whether this code is an effective way to accomplish > > it. > > DaveA > > Thanks! > > There is no specific goal, i am in process of building pattern knowledge > in python by doing some examples. That is a worthy goal. Patterns are interesting, and sometimes useful. Sometimes they're useful just as a vocabulary to help you think and talk about program structure. Just be aware that, like so many good things, a whole religion has grown up around them. Understanding the concept without getting sucked into the religion is a good goal. From roy at panix.com Wed Feb 12 21:01:35 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 21:01:35 -0500 Subject: Top posting and double spacing References: Message-ID: In article , Larry Martell wrote: > My personal rule is that I will give people 1 or 2 chances after they > are asked. If they continue to top post or send double space posts, I > simply ignore everything from them until they get with the program. If > we all did that maybe they'd get the message (but probably not). I have a somewhat more dynamic rule. If the subject looks interesting, I click on it. A window opens up with the article (speaking from a newsreader perspective here) in it. If the first screen contains nothing interesting, the odds of my scrolling down to see what might come later are approximately zero. From rustompmody at gmail.com Wed Feb 12 21:02:21 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 12 Feb 2014 18:02:21 -0800 (PST) Subject: Top posting and double spacing In-Reply-To: References: Message-ID: <09ed8720-8b68-4ad3-9a71-540713538e0d@googlegroups.com> On Wednesday, February 12, 2014 10:41:36 PM UTC+5:30, Larry.... at gmail.com wrote: > My personal rule is that I will give people 1 or 2 chances after they > are asked. If they continue to top post or send double space posts, I > simply ignore everything from them until they get with the program. If > we all did that maybe they'd get the message (but probably not). I think this is right. The only thing I will add is this: If the person answering the technical question also gently mentions the breach of etiquette, it would be more effective than some third party expressing bald irritation. What we need is something like the following self-policing rules: - First couple of answers, say nothing about etiquette/norms - Then start putting a gentle footnote indicating the issue along with the answer - If the problem is not attempted to be addressed, increase the severity of the warning and decrease the content of the answers - Stop answering content. Only 'tag' the mail 'top-posted' 'double-spaced' 'html-mail' whatever. No other technical response - Stop responding From invalid at invalid.invalid Wed Feb 12 21:57:34 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 13 Feb 2014 02:57:34 +0000 (UTC) Subject: Python programming References: <201402112314.42370.gheskett@wdtv.com> Message-ID: On 2014-02-13, Dennis Lee Bieber wrote: > An S-100 wire-wrap board. Yup, been there done that! I had a second-hand, off-the-shelf S-100 Z80 CPU board, a second-hand S-100 memory board with 4KB of DRAM (eight 4Kx1 chips) and 2KB of ROM (eight 256x8 Intel 1702A EPROMS), a home made backplace PCB with 5 or 6 slots, a home-made S-100 wire-wrapped board with two UARTs and some other miscellaneous stuff. I shoved it all into rack-mount Motorola Exorciser chassis I pulled out of a dumpster. > I hand assembled a monitor program with, as I recall, 0..F, High, > Low, Store, Go functions for the keyboard/display. I was living large: I had access to an Intel MDS-800 "blue box" system in one of the University's labs. It ran CPM with dual 8" floppies and an EPROM programmer. [I think it also may have run some proprietary Intel OS, but I was a CP/M man.] I typed in an assembly language monitor program out of some book or other, assembled it on the MDS-800, burned the ROMs, hooked up a borrowed Lear-Siegler ADM3A terminal to my wire-wrapped serial board, and it actually worked for a little while before something failed. Building reliable wire-wrap stuff is a real art -- unfortunately one I never learned. It also could have been the backplane that failed: the S-100 bus connecters never _quite_ lined up preciesly with the card cage's guides, so there were probably mechanical stress issues. -- Grant From steve at pearwood.info Wed Feb 12 21:58:46 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 13 Feb 2014 02:58:46 GMT Subject: singleton ... again References: Message-ID: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote: > Roy Smith wrote: >> It looks to me like he's trying to implement a classic Gang of Four >> singleton pattern. > > Which I've never really seen the point of in Python, or any other > language for that matter. Just create one instance of the class during > initialisation, put it in a global somewhere, and use it thereafter. > > If you really want to make sure nobody creates another instance by > accident, delete the class out of the namespace after instantiating it. That does not work. It is trivial to get the type from an instance: py> class Singleton: ... pass ... py> S = Singleton() py> del Singleton py> T = type(S)() py> S <__main__.Singleton object at 0xb71de9ec> py> T <__main__.Singleton object at 0xb71dea2c> This is not aimed at the original poster, just a general observation. The Singleton design pattern is overused because it is probably the only design pattern that most programmers really understand. -- Steven From roy at panix.com Wed Feb 12 22:04:19 2014 From: roy at panix.com (Roy Smith) Date: Wed, 12 Feb 2014 22:04:19 -0500 Subject: Python programming References: <201402112314.42370.gheskett@wdtv.com> Message-ID: In article , Grant Edwards wrote: > On 2014-02-13, Dennis Lee Bieber wrote: > > > An S-100 wire-wrap board. > > Yup, been there done that! Never did S-100, but I did do a custom Unibus card (wirewrap). You know you're working with a Real Computer (tm) when the +5V power supply can deliver as much current as an arc welder. From ben+python at benfinney.id.au Wed Feb 12 22:07:55 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Feb 2014 14:07:55 +1100 Subject: singleton ... again References: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> Message-ID: <85d2iraewk.fsf@benfinney.id.au> Steven D'Aprano writes: > On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote: > > If you really want to make sure nobody creates another instance by > > accident, delete the class out of the namespace after instantiating > > it. > > That does not work. It is trivial to get the type from an instance [by > calling ?type(foo)?]. Right, but surely you don't think people would do that ?by accident?, which is what Gregory was addressing. -- \ Hercules Grytpype-Thynne: ?Well, Neddie, I'm going to be | `\ frank.? Ned Seagoon: ?Right, I'll be Tom.? Count Moriarty: | _o__) ?I'll be Gladys.? *slap* ?The Goon Show, _World War I_ | Ben Finney From rosuav at gmail.com Wed Feb 12 22:13:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 14:13:02 +1100 Subject: Python programming In-Reply-To: References: <201402112314.42370.gheskett@wdtv.com> Message-ID: On Thu, Feb 13, 2014 at 2:04 PM, Roy Smith wrote: > You know you're working with a Real Computer (tm) when the +5V power > supply can deliver as much current as an arc welder. That'd run a reasonable number of devices..... ChrisA From python.list at tim.thechases.com Wed Feb 12 22:29:53 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Feb 2014 21:29:53 -0600 Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> Message-ID: <20140212212953.458b810a@bigbox.christie.dr> On 2014-02-13 00:59, Mark Lawrence wrote: > >>>> s = "\u3141" # HANGUL LETTER MIEUM > >>>> f = open('test.txt', 'w') > >>>> f.write("\u3141") > > Traceback (most recent call last): > > File "", line 1, in > > UnicodeEncodeError: 'ascii' codec can't encode character '\u3141' > > in position 0: ordinal not in range(128) > > > > Just because the open() call hides the specification of how Python > > should do that encoding doesn't prevent the required encoding from > > happening. :-) > > Which clearly reinforces the fact that what you originally said is > incorrect, I don't have to do anything, Python very kindly does > things for me under the covers. ...and when they break, you get to keep both pieces. :) If you don't know that encoding is being done, it's a lot harder to trust the assumption that you can directly write strings to files when exceptions like the above happen. My original point (though perhaps not conveyed as well as I'd intended) was that only bytes get written to the disk, and that some encoding must take place. It can be done implicitly using some defaults which may break (as demoed), whereas one would be better off doing it explicitly such as Chris shows: >>> f = open('test.txt', 'w', encoding='utf-8') >>> f.write("\u3141") 1 UTF-8'rs gonna 8. (or whatever memes the cool kids are riffing these days) -tkc From steve at pearwood.info Wed Feb 12 22:31:09 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 13 Feb 2014 03:31:09 GMT Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> Message-ID: <52fc3c7c$0$11128$c3e8da3@news.astraweb.com> On Wed, 12 Feb 2014 21:07:04 +1100, Ben Finney wrote: > Chris Angelico writes: > >> On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney >> wrote: >> > So, if I understand you right, you want to say that you've not found >> > a computer that works with the *complete* set of real numbers. Yes? >> >> Correct. [?] My point is that computers *do not* work with real >> numbers, but only ever with some subset thereof [?] > > You've done it again: by saying that ?computers *do not* work with real > numbers?, that if I find a real number ? e.g. the number 4 ? your > position is that, since it's a real number, computers don't work with > that number. That answer relies on the assumption that "computers do not work with X" implies: for each element x in X: it is true that "computers do not work with x" that is to say, a single counter-example of computers working with an element of X, even if it is a fluke, is enough to disprove the rule. To give a real-world, non-programming example: "The former South African apartheid government did not respect the Universal Human Rights of blacks." Under your strict interpretation, we would have to say that even a single example of the apartheid government respecting even a single human rights of a single black person would be sufficient to disprove the claim. But there's another interpretation available to us, one which is more suited to natural language statements as made by Chris: we interpret "computers do not work with X" as meaning: there is at least one element x, such that it is true that "computers do not work with x" In the case of real numbers, there is an *uncountably infinite* number of such elements x. In fact, we can pick any two distinct numbers, no matter how close together, say: 1 1.000000000001 and be sure that there are an uncountably infinite number of real numbers which computers do not work with between those two values. For the record, "uncountable infinite" is not just me emphasising that infinity is too big to count. It's a technical term from mathematics. In a nutshell it means that not only are there too many elements to count, but even in an infinite amount of time you couldn't count them all, not even if you counted infinitely fast. In fact, it isn't just that there are *specific* real numbers which computers cannot represent (say, irrationals like pi or e, really tiny numbers like 1/(googleplex**googleplex**googleplex), or really huge ones like Graham's Number), but that the fundamental mathematical laws of the reals are violated by computers. For example, it is not true that for every number x, 1/1(x)) == x. py> 1/(1/93.0) == 93.0 False Nor is it always true that a*(b+c) equals a*b + a*c, or that a+b+c is necessarily equal to b+c+a. So it isn't even that floats are merely a subset of reals. They're actually not reals at all, since the fundamental properties of real numbers do not always apply to floating point calculations. -- Steven From ben+python at benfinney.id.au Wed Feb 12 22:45:21 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Feb 2014 14:45:21 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <52fc3c7c$0$11128$c3e8da3@news.astraweb.com> Message-ID: <858utfad66.fsf@benfinney.id.au> Steven D'Aprano writes: > On Wed, 12 Feb 2014 21:07:04 +1100, Ben Finney wrote: > > > You've done it again: by saying that ?computers *do not* work with > > real numbers?, that if I find a real number ? e.g. the number 4 ? > > your position is that, since it's a real number, computers don't > > work with that number. > > That answer relies on the assumption that "computers do not work with X" > implies: > > for each element x in X: > it is true that "computers do not work with x" > > that is to say, a single counter-example of computers working with an > element of X, even if it is a fluke, is enough to disprove the rule. Right. I'm pointing out that this is a natural interpretation of ?computers do not work with X?. That is not the *only* natural interpretation, of course. But it is IMO a common enough interpretation that when trying to communicate clearly, one should re-phrase to avoid that false implication. -- \ ?I prayed for twenty years but received no answer until I | `\ prayed with my legs.? ?Frederick Douglass, escaped slave | _o__) | Ben Finney From rosuav at gmail.com Wed Feb 12 22:47:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 14:47:07 +1100 Subject: Wait... WHAT? In-Reply-To: <20140212212953.458b810a@bigbox.christie.dr> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> <20140212212953.458b810a@bigbox.christie.dr> Message-ID: On Thu, Feb 13, 2014 at 2:29 PM, Tim Chase wrote: > My original point (though > perhaps not conveyed as well as I'd intended) was that only bytes get > written to the disk, and that some encoding must take place. It can > be done implicitly using some defaults which may break (as demoed), > whereas one would be better off doing it explicitly such as Chris > shows And since the default encoding varies based on matters outside your script (most notably platform - I tried this on Windows and Linux, and got a default of UTF-8 on Linux and CP-1252 on Windows; but environment variables and such can interfere too), I would say that omitting the encoding= parameter should be done ONLY when you actually have no idea what the encoding is, only that it's "probably something from the rest of the system". And, well, if that's what you're looking at, you definitely can't trust to reading or writing non-ASCII (you can probably trust ASCII). When you create a file that you'll read back yourself, specify an encoding. ChrisA From wrw at mac.com Wed Feb 12 22:56:56 2014 From: wrw at mac.com (William Ray Wing) Date: Wed, 12 Feb 2014 22:56:56 -0500 Subject: Python programming In-Reply-To: References: <201402112314.42370.gheskett@wdtv.com> Message-ID: <82055DB9-758F-4B4C-9993-FE4DA60E3D50@mac.com> On Feb 12, 2014, at 10:04 PM, Roy Smith wrote: > In article , > Grant Edwards wrote: > >> On 2014-02-13, Dennis Lee Bieber wrote: >> >>> An S-100 wire-wrap board. >> >> Yup, been there done that! > > Never did S-100, but I did do a custom Unibus card (wirewrap). > > You know you're working with a Real Computer (tm) when the +5V power > supply can deliver as much current as an arc welder. > -- > https://mail.python.org/mailman/listinfo/python-list OK, and how many of you remember the original version of the tongue-in-cheek essay "Real Programmers Don't Use Pascal" from the back page of Datamation? -Bill From steve at pearwood.info Wed Feb 12 23:11:19 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 13 Feb 2014 04:11:19 GMT Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> Message-ID: <52fc45e6$0$11128$c3e8da3@news.astraweb.com> On Tue, 11 Feb 2014 07:36:34 -0800, Travis Griggs wrote: > On Feb 10, 2014, at 10:30 PM, Steven D'Aprano > wrote: > > >>> 1. Parenthesis should not be required for parameter- less >>> functions. >> >> Of course they should. Firstly, parameter-less functions are a code- >> smell, and ought to be discouraged. Secondly, even if you have a good >> reason for using one -- for example, random.random -- then the >> difference between referring to the object and calling the object >> should be clear. > > Interesting. Can you clarify or provide some links to the > "parameter-less functions are a code-smell? bit? Functions map a value to another value. They can be one-to-one, or many- to-one. (Mathematically, they cannot be one-to-many or many-to-many, that's called a relation.) What about zero-to-one? If the function always returns the same result, e.g.: def spam(): return "spam spam spam" why are you using a function? Just create a constant and use that. Calling a function which always returns the same value is a code smell. That's not to say it is always wrong, but it smells a bit off. How about zero-to-many functions? E.g. you have a situation where calling function() twice might return different values. Okay, here's an example: give_me_an_even_number() => returns 42 give_me_an_even_number() => returns 23 Hmmm. There's a bug in give_me_an_even_number(). How do I reproduce that bug? What arguments do I pass? Oh, the same no-arguments as for the working call. Clearly, the function must have *hidden state*. Hidden state (e.g. a global variable) makes it hard to reason about the function call, since you don't know what the hidden state is. So that's also a bit smelly. Hidden state is generally bad, because it makes it hard to reason about the function call, hard to reproduce results, hard to debug, hard to test. Think about the difference in difficulty in confirming that math.sin() of some value x returns the value 0.5, and confirming that random.random() of some hidden state returns a specific value: py> assert math.sin(0.5235987755982989) == 0.5 versus: py> state = random.getstate() py> random.seed(12345) py> assert random.random() == 0.41661987254534116 py> random.setstate(state) [...] > OTOH, I?m not sure I?ve heard the parameters-less functions are a code > one? Is it just loose functions that you?re referring to? As opposed to > methods (which are just bound functions)? I could maybe accept that. But > methods with fewer arguments, and even none, are a desirable thing. Methods that appear to take zero arguments actually take one argument, it is just that it is written in a different place: "some string".upper() is merely different syntax for: upper("some string") with the bonus that str.upper and MyClass.upper live in different namespaces and so can do different things. So I have no problem with zero- argument methods, or functions with default values. Remember that a code smell does not mean the code is bad. Only that it needs to be looked at a bit more carefully. Perhaps it is bad. Or perhaps, like durian fruit, it smells pretty awful but tastes really good. > There are code smells that are the opposite in fact, methods with long > parameter lists are generally seen as code smell (?passing a > paragraph?). Absolutely! You'll get no disagreement from me there. -- Steven From rosuav at gmail.com Wed Feb 12 23:17:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 15:17:36 +1100 Subject: Working with the set of real numbers In-Reply-To: <52fc3c7c$0$11128$c3e8da3@news.astraweb.com> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <52fc3c7c$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Thu, Feb 13, 2014 at 2:31 PM, Steven D'Aprano wrote: > "The former South African apartheid government did not respect the > Universal Human Rights of blacks." > > Under your strict interpretation, we would have to say that even a single > example of the apartheid government respecting even a single human rights > of a single black person would be sufficient to disprove the claim. Right. A common interpretation of that statement would be that, by and large, one can see a parallel between "people whose rights are not respected" and "people with black skin". The existence of a single black person whose rights are respected, or a single non-black person whose rights are not respected, doesn't change that; if there are X million black people whose rights are not respected, and Y million white people who are treated like people, and the converses are measured in thousands, then the statement would be considered valid. (That said, though, if there *were* a black person whose rights were respected, then it would be highly notable. I don't know if there had been such a case with .za, but there were - if you'll forgive me for Godwinning - a very VERY small number of Jews who held high position in Nazi Germany, and who were not harmed because they were of too great value to lose. It's notable because respecting a single person of a category of people considered "sub-human" effectively disproves the notion that "all X are less than people". (If one Jew is worth keeping around, how can you say that Jews are, by definition, subhuman? If one black woman can hold a highly respected position in a university, doesn't that prove that black people and women are just as intelligent as white males?) But, notable or not, it doesn't change the fact that Nazi Germany *as a whole* considered Jews *as a group* to be insignificant, and that the apartheid .za govt treated black-skinned people *as a group* to be insignificant.) So where does that leave computers and reals? Well, it comes down to descriptors. Suppose there were a place where all people are treated perfectly fairly, UNLESS a white-skinned person is male and aged between 13 and 20, in which case he is considered guilty until proven innocent. Does this place treat males and females equally? Not really. But it's also not really accurate to say that "men are mistreated by the law", any more than it's accurate to say that "IEEE floating point handles real numbers". I certainly would not say that an integer type "works with real numbers", simply because it's almost completely useless to say that - since it's such a tight subset of them. ChrisA From steve at pearwood.info Wed Feb 12 23:24:46 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 13 Feb 2014 04:24:46 GMT Subject: singleton ... again References: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> Message-ID: <52fc490d$0$11128$c3e8da3@news.astraweb.com> On Thu, 13 Feb 2014 14:07:55 +1100, Ben Finney wrote: > Steven D'Aprano writes: > >> On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote: >> > If you really want to make sure nobody creates another instance by >> > accident, delete the class out of the namespace after instantiating >> > it. >> >> That does not work. It is trivial to get the type from an instance [by >> calling ?type(foo)?]. > > Right, but surely you don't think people would do that ?by accident?, > which is what Gregory was addressing. Of course it can happen by accident. It's happened to me, where I've accidentally called NoneType() (which raises, rather than returning a new instance). The way it happened is I had a bunch of numeric values, all of the same type, and wanted to test that summing them with a custom sum function would give the same result whether I provided a start parameter or not: for data in list_of_datas: T = type(data[0]) zero = T() assert sum(data) == sum(data, zero) only somehow one of the data sets ends up containing None due to another bug. Now in *this* case, the error was obvious: NoneType() raises an exception. If the type happened to be bool(), I would have been okay too, because bool() returns the appropriate singleton True instance. Because I was testing a function with no side-effects, it wouldn't have mattered even if I had accidentally created a extra instance of something which nominally ought to have been a singleton. But if I were testing a function with side-effects, say one which modifies the internal state of the singleton, then I could have been in all sorts of strife. If you're going to have a singleton, you ought to do one of two things: * calling the constructor returns the same singleton each time; or * calling the constructor (apart from the very first time) raises an exception. I prefer the first case. -- Steven From rosuav at gmail.com Wed Feb 12 23:30:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 15:30:56 +1100 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <52fc45e6$0$11128$c3e8da3@news.astraweb.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Thu, Feb 13, 2014 at 3:11 PM, Steven D'Aprano wrote: > Think about the difference in difficulty in confirming that > math.sin() of some value x returns the value 0.5, and confirming that > random.random() of some hidden state returns a specific value: > > py> assert math.sin(0.5235987755982989) == 0.5 > > versus: > > py> state = random.getstate() > py> random.seed(12345) > py> assert random.random() == 0.41661987254534116 > py> random.setstate(state) Really, the assertion just requires the setting of the seed and the call to random.random(); the other two are to ensure that you don't fiddle with anything else that's using random.random(). And since random.random() is actually just a bound method of some module-level object, you can actually just create the exact same thing with explicit rather than implicit state: >>> random.Random(12345).random() 0.41661987254534116 Which doesn't tamper with the default object's state. Whether it's a module-level function, a bound method, a closure, or a callable object, a zero-arg function in Python always has some kind of implicit state. The question is, what is it doing with it? In the case of random number generation, maintained state is critical (and making it implicit is usually sufficient); similar with functions like input(), where the return value doesn't really depend on the argument at all [1], and of course anything that iterates over an object is going to need to change some kind of state (either a pointer, or the actual data, depending on whether you're looking at eg iter([1,2,3]).next or [1,2,3].pop). Do you know of any functions in Python that don't use any implicit state and don't take arguments? I can't think of any, but of course that proves nothing. ChrisA [1] input("Enter your name: ") vs input("What is one plus one? ") will probably return different values, but that's playing with humans rather than depending on the value of the argument... From rosuav at gmail.com Wed Feb 12 23:33:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 15:33:11 +1100 Subject: singleton ... again In-Reply-To: <52fc490d$0$11128$c3e8da3@news.astraweb.com> References: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> <52fc490d$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Thu, Feb 13, 2014 at 3:24 PM, Steven D'Aprano wrote: > Of course it can happen by accident. It's happened to me, where I've > accidentally called NoneType() (which raises, rather than returning a new > instance). It does in 2.7, yes, but not in 3.4: >>> type(None)() is None True Definitely prefer returning the singleton to raising. ChrisA From dan at tombstonezero.net Thu Feb 13 00:18:12 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 13 Feb 2014 05:18:12 +0000 (UTC) Subject: Python programming References: <201402112314.42370.gheskett@wdtv.com> Message-ID: On Wed, 12 Feb 2014 22:56:56 -0500, William Ray Wing wrote: > OK, and how many of you remember the original version of the > tongue-in-cheek essay "Real Programmers Don't Use Pascal" from the > back page of Datamation? And the April issue of Compubyte (or something like that) with a cover showing two white room technicians standing on a hard drive with a thirty three foot radius and an outer track whose speed exceeded the speed of light? From nsivaram.net at gmail.com Thu Feb 13 01:17:22 2014 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Thu, 13 Feb 2014 11:47:22 +0530 Subject: Top posting and double spacing References: <09ed8720-8b68-4ad3-9a71-540713538e0d@googlegroups.com> Message-ID: <87bnybwn7x.fsf@gmail.com> On Thu, Feb 13 2014,Rustom Mody wrote: [snipped 11 lines] > What we need is something like the following self-policing rules: > > - First couple of answers, say nothing about etiquette/norms > - Then start putting a gentle footnote indicating the issue along with the answer > - If the problem is not attempted to be addressed, increase the severity > of the warning and decrease the content of the answers > - Stop answering content. Only 'tag' the mail 'top-posted' 'double-spaced' > 'html-mail' whatever. No other technical response > - Stop responding This works for people willing to listen and adapt. And that pretty much answers your suggestions since the email netiquette posts appeared about a decade ago? sivaram -- From p.samir.p at gmail.com Thu Feb 13 01:55:20 2014 From: p.samir.p at gmail.com (ahmed) Date: Wed, 12 Feb 2014 22:55:20 -0800 (PST) Subject: Recursive problem Message-ID: <4c253ee6-e2d4-48ca-8a87-6b3c993195f4@googlegroups.com> So we had to do a project for our python class and we came across a recursive problem. The code we had to write was as follows: T(n) if n == 1 return 1 else for any number(k) between 1 and n - 1 2 * T(n-k) + 2^i - 1 from this we need to get the minimum number which would be produced depending on k. I don't know how to go about doing this. Any help would be appreciated. Thanks in advance. From jpiitula at ling.helsinki.fi Thu Feb 13 02:31:15 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 13 Feb 2014 09:31:15 +0200 Subject: Recursive problem References: <4c253ee6-e2d4-48ca-8a87-6b3c993195f4@googlegroups.com> Message-ID: ahmed writes: > So we had to do a project for our python class and we came across a > recursive problem. The code we had to write was as follows: > > T(n) > if n == 1 > return 1 > else > for any number(k) between 1 and n - 1 > 2 * T(n-k) + 2^i - 1 > > from this we need to get the minimum number which would be produced > depending on k. I don't know how to go about doing this. Any help > would be appreciated. A first step would be to put that pseudocode in a form that is closer to Python. I think it is meant as a definition of a function, T(n), where n is a positive integer. Indentation would help, and the else branch needs a return statement. Throw in the def T(n), too. The function min(T(n)) does not depend on k, but it depends on i. What's i? (Looks like the logarithm of a red herring to me.) The crucial question, however, is what to do with the choice of k in the else branch. You could pick a random integer in the range, making T a random function, and then do a number of rounds to get a possible minimum. Look up the module "random" for this, methods randint and randrange there. Or you could make T a generator function so that T(n) would generate all possible values. Look up the keyword "yield" for this. It goes in the place of "return". (This is the easiest change, and may well be what the instructor intends.) With a generator function, you can actually write min(T(n)), or "for m in T(n): print(m)", or "list(T(n)", and so on. As to recursion, you should be able to say why the function is guaranteed to terminate. Perhaps you've covered this in class. From larry.martell at gmail.com Thu Feb 13 03:30:39 2014 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 13 Feb 2014 03:30:39 -0500 Subject: Python programming In-Reply-To: <82055DB9-758F-4B4C-9993-FE4DA60E3D50@mac.com> References: <201402112314.42370.gheskett@wdtv.com> <82055DB9-758F-4B4C-9993-FE4DA60E3D50@mac.com> Message-ID: On Wed, Feb 12, 2014 at 10:56 PM, William Ray Wing wrote: > OK, and how many of you remember the original version of the tongue-in-cheek essay "Real Programmers Don't Use Pascal" from the back page of Datamation? I do remember it. http://www.webcitation.org/659yh1oSh From piet at vanoostrum.org Thu Feb 13 04:00:35 2014 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 13 Feb 2014 10:00:35 +0100 Subject: singleton ... again References: Message-ID: Ben Finney writes: > Gregory Ewing writes: > >> Roy Smith wrote: >> > It looks to me like he's trying to implement a classic Gang of Four >> > singleton pattern. >> >> Which I've never really seen the point of in Python, or any other >> language for that matter. Just create one instance of the class during >> initialisation, put it in a global somewhere, and use it thereafter. > > Make that ?somewhere? a module namespace, and you effectively have a > Singleton for all practical purposes. So yes, I see the point of it; but > we already have it built in :-) There is a use case for a singleton class: when creating the singleton object takes considerable resources and you don't need it always in your program. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From wilsonmonde at gmail.com Thu Feb 13 04:03:43 2014 From: wilsonmonde at gmail.com (wilsonmonde at gmail.com) Date: Thu, 13 Feb 2014 01:03:43 -0800 (PST) Subject: AttributeError: 'Or' object has no attribute 'as_independent' Message-ID: <512a3958-7f8e-4af0-a0d6-1c4dec4b1955@googlegroups.com> Traceback (most recent call last): File "testcsv.py", line 17, in print(sy.solve([x^2+x+1-t, x^3+x^2-t], x)) File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 902, in so lve solution = _solve_system(f, symbols, **flags) File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 1434, in _ solve_system i, d = _invert(g, *symbols) File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 2422, in _ invert indep, dep = lhs.as_independent(*symbols) AttributeError: 'Or' object has no attribute 'as_independent' Code: import csv as csv import os import numpy as np import sympy as sy #from sympy import solve, Poly, Eq, Function, exp from sympy import * from numpy import * from numpy.linalg import * from sympy.polys.polyfuncs import interpolate from sympy import Function, dsolve, Eq, Derivative, sin, cos from sympy.abc import x f = sy.Function('f') x = sy.Symbol("x") t = sy.Symbol("t") print(sy.solve([x^2+x+1-t, x^3+x^2-t], x)) print(sy.solve((x^2+x+1-t, x^3+x^2-t), x)) From patil.jay2009 at gmail.com Thu Feb 13 06:04:52 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Thu, 13 Feb 2014 03:04:52 -0800 (PST) Subject: AttributeError: '' object has no attribute 'SeriesCollection' Message-ID: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> I have created chart object. But unable to add series into chart. Look at below collection Code: chartObj = addNewChart(newws,-4169,350,600) >>> print chartObj; >>> chartObj.SeriesCollection().NewSeries() Traceback (most recent call last): File "", line 1, in chartObj.SeriesCollection().NewSeries() File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 465, in __getattr__ raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr)) AttributeError: '' object has no attribute 'SeriesCollection' >>> se = chartObj.SeriesCollection().NewSeries() Regards Jaydeep Patil From ben+python at benfinney.id.au Thu Feb 13 06:11:48 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Feb 2014 22:11:48 +1100 Subject: AttributeError: '' object has no attribute 'SeriesCollection' References: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> Message-ID: <85zjlv8dxn.fsf@benfinney.id.au> Jaydeep Patil writes: > I have created chart object. But unable to add series into chart. Your code isn't self-contained (we are not able to run it as you presented it). Are you relying on some specific third-party library? If so, you need to be explicit. You may also get better response if you ask for help on the specific discussion forums for that library. -- \ ?My classmates would copulate with anything that moved, but I | `\ never saw any reason to limit myself.? ?Emo Philips | _o__) | Ben Finney From jaiprakash at wisepromo.com Thu Feb 13 06:21:45 2014 From: jaiprakash at wisepromo.com (Jaiprakash Singh) Date: Thu, 13 Feb 2014 03:21:45 -0800 (PST) Subject: querry to get status code in selinium webdriver , unable to find it , requesting to please help me Message-ID: <7a9cc6d8-c18c-4dd4-862e-c07b3b31b1c9@googlegroups.com> hello all, i am searching how to get status code in selinium (with python), but unable to find it . can anyone help me in this matter actually my aim is to scroll a page and after each scroll i want to find the status so that on bad status i can exit my code. here ismy code in python for i in range(0,60): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # i want status code here" time.sleep(1) From python.list at tim.thechases.com Thu Feb 13 06:39:52 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 13 Feb 2014 05:39:52 -0600 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <52fc45e6$0$11128$c3e8da3@news.astraweb.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> Message-ID: <20140213053952.1f41b21b@bigbox.christie.dr> On 2014-02-13 04:11, Steven D'Aprano wrote: > give_me_an_even_number() > => returns 42 > give_me_an_even_number() > => returns 23 > > Hmmm. There's a bug in give_me_an_even_number(). How do I reproduce > that bug? What arguments do I pass? Oh, the same no-arguments as > for the working call. > > Clearly, the function must have *hidden state*. Hidden state (e.g. > a global variable) makes it hard to reason about the function call, > since you don't know what the hidden state is. So that's also a bit > smelly. I'd even go so far as to claim that this is the primary reason a zero-argument function is a code-smell. Not because zero-argument functions smell, but because hidden-state smells and zero-argument functions imply hidden-state. Date/time functions are a personal pet peeve for just this reason, and require addressing the hidden-state of the system clock regardless of parameter-count. Thus instead of something like class Person: def __init__(self, name, dob): self.name = name self.dob = dob def age(self): return datetime.date.today() - self.dob I do def age(self, as_of=None): if as_of is None: as_of = datetime.date.today() return as_of = self.dob allowing me to test the function with known dates. > > There are code smells that are the opposite in fact, methods with > > long parameter lists are generally seen as code smell (?passing a > > paragraph?). > > Absolutely! You'll get no disagreement from me there. *coughtkintercough* -tkc From gandalf at shopzeus.com Thu Feb 13 06:31:33 2014 From: gandalf at shopzeus.com (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Thu, 13 Feb 2014 12:31:33 +0100 Subject: querry to get status code in selinium webdriver , unable to find it , requesting to please help me In-Reply-To: <7a9cc6d8-c18c-4dd4-862e-c07b3b31b1c9@googlegroups.com> References: <7a9cc6d8-c18c-4dd4-862e-c07b3b31b1c9@googlegroups.com> Message-ID: <52FCAD15.80900@shopzeus.com> > here ismy code in python > > for i in range(0,60): > driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") > # i want status code here" > time.sleep(1) Status of what? Are you asking the HTTP status of the page downloaded? That has nothing to do with your javascript code. AFAIK window.scrollTo has no return value. So what kind of status are you talking about? From ned at nedbatchelder.com Thu Feb 13 06:50:36 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 13 Feb 2014 06:50:36 -0500 Subject: singleton ... again In-Reply-To: References: Message-ID: On 2/13/14 4:00 AM, Piet van Oostrum wrote: > Ben Finney writes: > >> Gregory Ewing writes: >> >>> Roy Smith wrote: >>>> It looks to me like he's trying to implement a classic Gang of Four >>>> singleton pattern. >>> >>> Which I've never really seen the point of in Python, or any other >>> language for that matter. Just create one instance of the class during >>> initialisation, put it in a global somewhere, and use it thereafter. >> >> Make that ?somewhere? a module namespace, and you effectively have a >> Singleton for all practical purposes. So yes, I see the point of it; but >> we already have it built in :-) > > There is a use case for a singleton class: when creating the singleton > object takes considerable resources and you don't need it always in your > program. > I still don't see it. To convince me that a singleton class makes sense, you'd have to explain why by virtue of the class's very nature, it never makes sense for there ever to be more than one of them. Your example is an expensive-to-create object. Why does that mean I might not want two of them? I can see how it makes sense to have a factory function, which will make one only when asked, and will hold onto that object for the next time it's needed. But that's different than a class which pretends to make instances but actually always returns the same instance. -- Ned Batchelder, http://nedbatchelder.com From python.list at tim.thechases.com Thu Feb 13 06:51:42 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 13 Feb 2014 05:51:42 -0600 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <20140213053952.1f41b21b@bigbox.christie.dr> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> <20140213053952.1f41b21b@bigbox.christie.dr> Message-ID: <20140213055142.7a8d835c@bigbox.christie.dr> On 2014-02-13 05:39, Tim Chase wrote: > def age(self, as_of=None): > if as_of is None: > as_of = datetime.date.today() > return as_of = self.dob and of course I mean return as_of - self.dob which is what I get for typing in the dark and the "-" and "=" keys are adjacent. :-/ -tkc From gandalf at shopzeus.com Thu Feb 13 06:53:12 2014 From: gandalf at shopzeus.com (=?ISO-8859-2?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Thu, 13 Feb 2014 12:53:12 +0100 Subject: Install python 2 and 3 in the "wrong" order Message-ID: <52FCB228.5040301@shopzeus.com> I have Python 3.3 installed on my Windows 7 x64 box. Today I had to install Python 2.7 for an older app of mine. Here is my problem: although "#!/usr/bin/env python3" is given in the file and "py -3" program works fine, apparently the installation of python 2 simply has overwritten my settings (e.g. assignment *.py files to py.exe). Question: is there a way to fix this? Or do I have to reinstall Python 3 from scratch? (It would be a pity, I have tons of third party modules installed for it...) Thanks Laszlo From rosuav at gmail.com Thu Feb 13 06:57:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Feb 2014 22:57:22 +1100 Subject: singleton ... again In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder wrote: > I still don't see it. To convince me that a singleton class makes sense, > you'd have to explain why by virtue of the class's very nature, it never > makes sense for there ever to be more than one of them. There's a huge difference, btw, between mutable and immutable singletons. With immutables like None, True/False, integers, strings, and tuples thereof, returning a preexisting object is just an optimization. Do it if you want, don't if you don't, nobody's going to hugely care. With mutables, it's hugely different. A singleton "database connection" object would, imo, be hugely confusing; you'd think you created a separate connection object, but no, what you do on this one affects the other. Better there to have module-level functions; at least Python programmers should understand that reimporting a module gives you back another reference to the same module. ChrisA From mail at timgolden.me.uk Thu Feb 13 06:59:05 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Feb 2014 11:59:05 +0000 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FCB228.5040301@shopzeus.com> References: <52FCB228.5040301@shopzeus.com> Message-ID: <52FCB389.3070402@timgolden.me.uk> On 13/02/2014 11:53, Nagy L?szl? Zsolt wrote: > I have Python 3.3 installed on my Windows 7 x64 box. Today I had to > install Python 2.7 for an older app of mine. > > Here is my problem: although "#!/usr/bin/env python3" is given in the > file and "py -3" program works fine, apparently the installation of > python 2 simply has overwritten my settings (e.g. assignment *.py files > to py.exe). > > Question: is there a way to fix this? Or do I have to reinstall Python 3 > from scratch? (It would be a pity, I have tons of third party modules > installed for it...) >From a cmd window: ftype python.file="C:\Windows\py.exe" "%1" %* ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* TJG From patil.jay2009 at gmail.com Thu Feb 13 06:58:06 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Thu, 13 Feb 2014 03:58:06 -0800 (PST) Subject: AttributeError: '' object has no attribute 'SeriesCollection' In-Reply-To: References: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> Message-ID: On Thursday, 13 February 2014 16:41:48 UTC+5:30, Ben Finney wrote: > Jaydeep Patil writes: > > > > > I have created chart object. But unable to add series into chart. > > > > Your code isn't self-contained (we are not able to run it as you > > presented it). > > > > Are you relying on some specific third-party library? If so, you need to > > be explicit. You may also get better response if you ask for help on the > > specific discussion forums for that library. > > > > -- > > \ "My classmates would copulate with anything that moved, but I | > > `\ never saw any reason to limit myself." --Emo Philips | > > _o__) | > > Ben Finney Hi... Just consider that you have chart object & you need to add data series for that chart. How you can add this? Let me know. I try to add data series using below command. But it gives error. Command: chartObj.SeriesCollection().NewSeries() Error: Traceback (most recent call last): File "", line 1, in chartObj.SeriesCollection().NewSeries() File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 465, in __getattr__ raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr)) AttributeError: '' object has no attribute 'SeriesCollection' >>> se = chartObj.SeriesCollection().NewSeries() Regards Jay From gandalf at shopzeus.com Thu Feb 13 07:03:56 2014 From: gandalf at shopzeus.com (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Thu, 13 Feb 2014 13:03:56 +0100 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FCB389.3070402@timgolden.me.uk> References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> Message-ID: <52FCB4AC.3010608@shopzeus.com> > From a cmd window: > > ftype python.file="C:\Windows\py.exe" "%1" %* > > ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* > > TJG Thank you. It worked. Although I must note that it only works if you start the cmd.exe as administrator (under Windows 7). Is it the only thing that was possibly overwritten by the python 2 installer? From mail at timgolden.me.uk Thu Feb 13 07:13:00 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Feb 2014 12:13:00 +0000 Subject: AttributeError: '' object has no attribute 'SeriesCollection' In-Reply-To: References: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> Message-ID: <52FCB6CC.9000603@timgolden.me.uk> On 13/02/2014 11:58, Jaydeep Patil wrote: > Just consider that you have chart object & you need to add data series for that chart. How you can add this? Jaydeep: you're writing to a general Python list. Few of the people here run on Windows; fewer still will use Python to automate Excel via COM; a tiny number (possibly zero) will have experience of generating Charts in Excel. It's not that people are unwilling to help, but you have to meet us halfway: write a few lines of code which take us to the point you're at that we can run with *just* Python and the pywin32 libraries. Don't call a function you've defined somewhere else because we can't see the function. Something like this: import win32com.client xl = win32com.client.gencache.EnsureDispatch("Excel.Application") wb = xl.Workbooks.Add() # # Something here to create a chart so we can help you out # TJG From mail at timgolden.me.uk Thu Feb 13 07:23:24 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Feb 2014 12:23:24 +0000 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FCB4AC.3010608@shopzeus.com> References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> <52FCB4AC.3010608@shopzeus.com> Message-ID: <52FCB93C.3000205@timgolden.me.uk> On 13/02/2014 12:03, Nagy L?szl? Zsolt wrote: > >> From a cmd window: >> >> ftype python.file="C:\Windows\py.exe" "%1" %* >> >> ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* >> >> TJG > Thank you. It worked. Although I must note that it only works if you > start the cmd.exe as administrator (under Windows 7). > > Is it the only thing that was possibly overwritten by the python 2 > installer? Probably: things like .dlls are Python-2 specific. And the registry entries are per-version as well. TJG From tjreedy at udel.edu Thu Feb 13 07:31:17 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Feb 2014 07:31:17 -0500 Subject: AttributeError: 'Or' object has no attribute 'as_independent' In-Reply-To: <512a3958-7f8e-4af0-a0d6-1c4dec4b1955@googlegroups.com> References: <512a3958-7f8e-4af0-a0d6-1c4dec4b1955@googlegroups.com> Message-ID: On 2/13/2014 4:03 AM, wilsonmonde at gmail.com wrote: > Traceback (most recent call last): > File "testcsv.py", line 17, in > print(sy.solve([x^2+x+1-t, x^3+x^2-t], x)) > File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 902, in so > lve > solution = _solve_system(f, symbols, **flags) > File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 1434, in _ > solve_system > i, d = _invert(g, *symbols) > File "C:\Python27\lib\site-packages\sympy\solvers\solvers.py", line 2422, in _ > invert > indep, dep = lhs.as_independent(*symbols) > AttributeError: 'Or' object has no attribute 'as_independent' You should report this on the sympy list. It is mirrored on news.gmane.org as gmane,comp.python.sympy. > Code: > > import csv as csv > import os > import numpy as np > import sympy as sy > #from sympy import solve, Poly, Eq, Function, exp > from sympy import * > from numpy import * > from numpy.linalg import * > from sympy.polys.polyfuncs import interpolate > from sympy import Function, dsolve, Eq, Derivative, sin, cos > from sympy.abc import x > > f = sy.Function('f') > x = sy.Symbol("x") > t = sy.Symbol("t") > > print(sy.solve([x^2+x+1-t, x^3+x^2-t], x)) > print(sy.solve((x^2+x+1-t, x^3+x^2-t), x)) > > -- Terry Jan Reedy From oscar.j.benjamin at gmail.com Thu Feb 13 07:48:03 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 13 Feb 2014 12:48:03 +0000 Subject: Working with the set of real numbers In-Reply-To: <85eh38bq5z.fsf@benfinney.id.au> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f219c5$0$29972$c3e8da3$5496439d@news.astraweb.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: On 12 February 2014 10:07, Ben Finney wrote: > Chris Angelico writes: > >> On Wed, Feb 12, 2014 at 7:56 PM, Ben Finney wrote: >> > So, if I understand you right, you want to say that you've not found >> > a computer that works with the *complete* set of real numbers. Yes? >> >> Correct. [...] My point is that computers *do not* work with real >> numbers, but only ever with some subset thereof [...] > > You've done it again: by saying that "computers *do not* work with real > numbers", that if I find a real number - e.g. the number 4 - your > position is that, since it's a real number, computers don't work with > that number. > > That's why I think you need to be clear that your point isn't "computers > don't work with real numbers", but rather "computers work only with a > limited subset of real numbers". I think Chris' statement above is pretty clear. Also I didn't find the original statement confusing and it is a reasonable point to make. While computers can (with some limitations) do a pretty good job of integers and rational numbers they cannot truly represent real computation. Other people have mentioned that there are computer algebra systems that can handle surds and other algebraic numbers or some transcendental numbers but none of these comes close to the set of reals. This isn't even a question of resource constraints: a digital computer with infinite memory and computing power would still be limited to working with countable sets, and the real numbers are just not countable. The fundamentally discrete nature of digital computers prevents them from being able to truly handle real numbers and real computation. A hypothetical idealised analogue computer would be able to truly do real arithmetic (but I think in practice the errors would be worse than single precision floating point). Oscar From 7441980 at gmail.com Thu Feb 13 08:18:26 2014 From: 7441980 at gmail.com (weixixiao) Date: Thu, 13 Feb 2014 05:18:26 -0800 (PST) Subject: How to begin Message-ID: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> http://www.codecademy.com I have learned the basic rules of Python in this website. What should I do next?where to go? I download the Pycharm the free version and I think I dunno how to use it except a "Hello world" From marko at pacujo.net Thu Feb 13 09:00:37 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Feb 2014 16:00:37 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: <871tz7864a.fsf@elektro.pacujo.net> Oscar Benjamin : > This isn't even a question of resource constraints: a digital computer > with infinite memory and computing power would still be limited to > working with countable sets, and the real numbers are just not > countable. The fundamentally discrete nature of digital computers > prevents them from being able to truly handle real numbers and real > computation. Well, if your idealized, infinite, digital computer had ?? bytes of RAM and ran at ?? hertz and Python supported transfinite iteration, you could easily do reals: def real_sqrt(y): for x in continuum(0, max(1, y)): # Note: x is not traversed in the < order but some other # well-ordering, which has been proved to exist. if x * x == y: return x assert False The function could well return in finite time with a precise result for any given nonnegative real argument. Marko From info at wingware.com Thu Feb 13 09:53:43 2014 From: info at wingware.com (Wingware) Date: Thu, 13 Feb 2014 09:53:43 -0500 Subject: ANN: Wing IDE 5.0.3 released Message-ID: <52FCDC77.3030804@wingware.com> Hi, Wingware has released version 5.0.3 of Wing IDE, our cross-platform integrated development environment for the Python programming language. Wing IDE includes a professional quality code editor with vi, emacs, visual studio, and other key bindings, auto-completion, call tips, goto-definition, find uses, refactoring, context-aware auto-editing, a powerful graphical debugger, version control, unit testing, search, and many other features. For details see http://wingware.com/ Changes in this minor release include: * Support for Python 3.4rc1 * Fix debugging matplotlib code with MacOSX backend * Fix hanging on large Perforce repositories * Fix debugging Django 1.6 templates * Fix problems starting QThreads in Python 3.x * Improve auto-spacing * Fix multi-line typing * Fix potential for CPU intensive hanging on Linux * Report recursion exceptions correctly under Python 3.x * 30 other bug fixes For details see http://wingware.com/pub/wingide/5.0.3/CHANGELOG.txt A summary of new features in Wing 5: * Redesigned GUI based on Qt and PySide * Native GUI on OS X (and better overall OS-native look and feel) * Tools and editors can be dragged around * Toolbar and editor and Project context menus are configurable * Optional mode that opens different sets of files in each editor split * Sharable color palettes and syntax highlighting configurations * Auto-editing is on by default (except some operations that have a learning curve) * Named file sets * Sharable launch configurations * Named entry points * More control over unit testing environment * Lockable editor splits * Initial preferences dialog for new users * Support for Python 3.4 * Support for Django 1.6 * Support for matplotlib on Anaconda and with MacOSX backend For more information on what's new in Wing 5, see http://wingware.com/wingide/whatsnew Free trial: http://wingware.com/wingide/trial Downloads: http://wingware.com/downloads Feature list: http://wingware.com/wingide/features Sales: http://wingware.com/store/purchase Upgrades: https://wingware.com/store/upgrade Questions? Don't hesitate to email us at support at wingware.com. Thanks, -- Stephan Deibel Wingware | Python IDE The Intelligent Development Environment for Python Programmers wingware.com From roy at panix.com Thu Feb 13 09:58:25 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 09:58:25 -0500 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > Whether it's a module-level function, a bound method, a closure, or a > callable object, a zero-arg function in Python always has some kind of > implicit state. Sometimes, it has a *lot* of implicit state: os.fork() From SSchukat at dspace.de Thu Feb 13 10:08:05 2014 From: SSchukat at dspace.de (Stefan Schukat) Date: Thu, 13 Feb 2014 15:08:05 +0000 Subject: AttributeError: '' object has no attribute 'SeriesCollection' In-Reply-To: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> References: <942ed7d6-aec9-4bb5-9b88-60ce62b3ff2e@googlegroups.com> Message-ID: <19A216758DA7374193F26E107EDA37EA0165F13D13@Exchange2010.dspace.de> Hello, the "chartObj" is not a Chart object it is a shape see >> from win32com.client import Dispatch >>> Excel = Dispatch("Excel.Application") >>> WB = Excel.Workbooks.Add() >>> Shape = WB.Sheets[0].Shapes.AddChart() >>> Shape.Chart.SeriesCollection >> Regards Stefan Schukat -----Original Message----- From: Python-list [mailto:python-list-bounces+sschukat=dspace.de at python.org] On Behalf Of Jaydeep Patil Sent: Thursday, February 13, 2014 12:05 PM To: python-list at python.org Subject: AttributeError: '' object has no attribute 'SeriesCollection' I have created chart object. But unable to add series into chart. Look at below collection Code: chartObj = addNewChart(newws,-4169,350,600) >>> print chartObj; >>> chartObj.SeriesCollection().NewSeries() Traceback (most recent call last): File "", line 1, in chartObj.SeriesCollection().NewSeries() File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 465, in __getattr__ raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr)) AttributeError: '' object has no attribute 'SeriesCollection' >>> se = chartObj.SeriesCollection().NewSeries() Regards Jaydeep Patil -- https://mail.python.org/mailman/listinfo/python-list From visiondoctor2020 at gmail.com Thu Feb 13 10:06:03 2014 From: visiondoctor2020 at gmail.com (pete suchsland) Date: Thu, 13 Feb 2014 07:06:03 -0800 (PST) Subject: How to begin In-Reply-To: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> Message-ID: <92b6e6be-7e55-41c9-81e6-22f494639aa0@googlegroups.com> On Thursday, February 13, 2014 6:18:26 AM UTC-7, weixixiao wrote: > http://www.codecademy.com > > > > I have learned the basic rules of Python in this website. > > > > What should I do next?where to go? > > > > I download the Pycharm the free version and I think I dunno how to use it except a "Hello world" ...well use it some more! Try print("hello world"*10) and then print(9+9) make a variable ... x =99 if x = 99: print("hello world") make a class ... class Hello: def __init__(self, word): self.word = word def returnme(self) return (self.word) a = Hello("yo whazzup?") b = Hello("Allo") c = Hello("Guttentag") make a list: l = [ a , b , c] make a for loop: for i in l: print(i.returnme()) read the Python tutorial, lots of ways to get your feet wet! I have PyCharm, Eclipse (with PyDev), and Idle, (all free) and I like them all. CodeAcademy is a good idea too if you want an online course to get your started. From invalid at invalid.invalid Thu Feb 13 10:13:33 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 13 Feb 2014 15:13:33 +0000 (UTC) Subject: Python programming References: <201402112314.42370.gheskett@wdtv.com> Message-ID: On 2014-02-13, Chris Angelico wrote: > On Thu, Feb 13, 2014 at 2:04 PM, Roy Smith wrote: >> You know you're working with a Real Computer (tm) when the +5V power >> supply can deliver as much current as an arc welder. > > That'd run a reasonable number of devices..... That depends. Back in the days of bipolar glue logic and NMOS microprocessors and peripherals, an Amp didn't get you very much. :) -- Grant Edwards grant.b.edwards Yow! INSIDE, I have the at same personality disorder gmail.com as LUCY RICARDO!! From walter.hughey at okbu.edu Thu Feb 13 10:22:51 2014 From: walter.hughey at okbu.edu (Walter Hughey) Date: Thu, 13 Feb 2014 10:22:51 -0500 (EST) Subject: Newcomer Help In-Reply-To: Message-ID: <678160030.7639221.1392304971969.JavaMail.root@okbu.edu> ----- Original Message ----- From: "Chris Angelico" Cc: "Python-List" Sent: Wednesday, February 12, 2014 3:22:57 PM Subject: Re: Newcomer Help On Thu, Feb 13, 2014 at 8:07 AM, Tim Delaney wrote: > On 13 February 2014 02:17, Grant Edwards wrote: >> I've always worked in corporations where the email "culture" is the >> Microsoft-induced "lazy and stupid" style as you describe. ChrisA -- https://mail.python.org/mailman/listinfo/python-list I am addressing this to the entire site - I thinks. And this will be my final answer on this subject. It remains to be seen if I remain on this site or tell all good bye. For the most part, the few people who responded have responded in a polite manner, in an attempt to help me understand how this site works. And I have tried to fall into line when responding to emails. It probably appeared to some I was not trying to get on board but this is a significant change to the 20+years of my being involved in emails. And yes Gisle Vanem, in spite of your doubts, I have been involved in emails in excess of 20 years. I suppose most of that has been in the "Microsoft-induced 'lazy and stupid' style" as identified by {Grant Edward}. However, I have responded to news lists and email groups previously. As I have stated, most people have been kind and helpful. Some have addressed my lack of conformance to the policies and procedures and have attempted to instruct me in a polite manner. To those I say Thank You for your understanding and attempts to help me. Some have provided answers to the initial issues I had. And as a novice to programming, I do appreciate their assistance. I have not attempted all the possible fixes yet but I will i the near future. I say Thank You to each of you. To those who responded in a much less friendly attitude, even at times coming across in a very rude manner - I really have nothing to say. You have not attempted to help resolve my initial issues and your attitudes have caused me to feel this is not a place where I can learn much. Yes, there is a lot I could learn, but some attitudes make me desire to no longer be involved in discussions. Walter From roy at panix.com Thu Feb 13 10:24:07 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 10:24:07 -0500 Subject: singleton ... again References: Message-ID: In article , Chris Angelico wrote: > On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder > wrote: > > I still don't see it. To convince me that a singleton class makes sense, > > you'd have to explain why by virtue of the class's very nature, it never > > makes sense for there ever to be more than one of them. > > There's a huge difference, btw, between mutable and immutable > singletons. With immutables like None, True/False, integers, strings, > and tuples thereof, returning a preexisting object is just an > optimization. Do it if you want, don't if you don't, nobody's going to > hugely care. People *depend* on None being a singleton (and are encouraged to do so), when they use "is" as the test-for-Noneness. > With mutables, it's hugely different. A singleton > "database connection" object would, imo, be hugely confusing; you'd > think you created a separate connection object, but no, what you do on > this one affects the other. Except that if you do caching in the database connector, you would certainly want the cache to be shared between all the users. There's no right answer here. Each way has it's advantages and disadvantages. And it would only be confusing if the documentation didn't spell out which way it was doing it, leaving people to make (possibly wrong) assumptions. > Better there to have module-level functions; at least Python > programmers should understand that reimporting a module gives you > back another reference to the same module. Except when it doesn't. Singleton-ness of modules depends on the names under which they were imported. Symlinks, for example, can fool the import machinery. $ ls -l s1 s2 lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s1 -> s lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s2 -> s $ ls -l s total 12 -rw-rw-r-- 1 roy roy 0 Feb 13 10:13 __init__.py -rw-rw-r-- 1 roy roy 101 Feb 13 10:14 __init__.pyc -rw-rw-r-- 1 roy roy 9 Feb 13 10:12 singleton.py -rw-rw-r-- 1 roy roy 123 Feb 13 10:14 singleton.pyc >>> import s1.singleton >>> import s2.singleton >>> s1.singleton == s2.singleton False From neilc at norwich.edu Thu Feb 13 10:30:27 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 15:30:27 +0000 (UTC) Subject: Python programming References: Message-ID: On 2014-02-12, Tim Delaney wrote: > OK - it's degenerated into one of these threads - I'm going to > participate. Me, too! I wrote lots of programs, strictly for fun, on every personal computer I got my hands on. Toward the end of the 80's personal computer's stopped coming equipped with programming environments, and I stopped programming. I eventually learned some computing theory in college where they taught C and the rudiments of C++. Thanks to the open-source movement we've returned to the days when anybody can program for zero cash. You can program well enough to amuse yourself with very little effort indeed. To get from there to being able to write programs to do useful things for yourself is a lot harder, but this is the niche that Python fills excellent well. If this is what you want to do, Python is a good way to go. That's still just the beginning, but it's a pretty good place. -- Neil Cerutti From bagratte at live.com Thu Feb 13 08:54:25 2014 From: bagratte at live.com (bagrat lazaryan) Date: Thu, 13 Feb 2014 17:54:25 +0400 Subject: imperative mood in docstrings In-Reply-To: <002d01cf2595$9e4b17f0$dae147d0$@live.com> References: <002d01cf2595$9e4b17f0$dae147d0$@live.com> Message-ID: thank you all! bagratte From demianbrecht at gmail.com Thu Feb 13 11:15:02 2014 From: demianbrecht at gmail.com (Demian Brecht) Date: Thu, 13 Feb 2014 08:15:02 -0800 Subject: Using a subclass for __dict__ Message-ID: Hey all, Using bases in a metaclass, I've been able to easily figure out when an attribute is being added to an instance of a class. However, what I'm /actually/ looking to do is to intercept when attributes are being added to a class (not an instance of). I thought that I'd be able to do so by passing in a subclass of dict to type.__new__ of the metaclass's __new__ and implementing a custom __setitem__, but apparently that's not the case. If you're curious as to why I'm doing this, I'm trying to clean up https://gist.github.com/demianbrecht/6944269 and get rid of the late_bind method there in favour of using the appropriate magic methods. The intention is to piggyback off of abc's __abstractmethods__ in order to implement a "looks_like" method that checks that one class conforms to an unrelated class's interface rather than using inheritance to enforce interface implementations at class creation time. This is /only/ intended to be a proof of concept for demonstration purposes and nothing that I'd ever actually implement, so no need for flaming the concept :) # test.py class Dict(dict): def __setattr__(self, key, value): print 'Dict.__setattr__' dict.__setattr__(self, key, value) def __setitem__(self, key, value): print 'Dict.__setitem__' dict.__setitem__(self, key, value) class Bar(object): def __setattr__(self, key, value): print 'Bar.__setattr__' object.__setattr__(self, key, value) class metafoo(type): def __new__(mcls, name, bases, dct): return type.__new__(mcls, name, (Bar,), Dict(dct)) class Foo(object): __metaclass__ = metafoo >>> import test >>> f = test.Foo() >>> f.foo = 'bar' Bar.__setattr__ # expected >>> test.Foo.foo = 'bar' # I'm expecting Dict.__setattr__ here, but... *crickets* Am I missing something here, or do I just have to live with what I currently have in my gist? Thanks, -- Demian Brecht http://demianbrecht.github.com From rustompmody at gmail.com Thu Feb 13 11:22:46 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 13 Feb 2014 08:22:46 -0800 (PST) Subject: Newcomer Help In-Reply-To: References: Message-ID: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> On Thursday, February 13, 2014 8:52:51 PM UTC+5:30, Walter Hughey wrote: > I am addressing this to the entire site - I thinks. And this will be my final answer on this subject. > It remains to be seen if I remain on this site or tell all good bye. > For the most part, the few people who responded have responded in a polite manner, > in an attempt to help me understand how this site works. And I have tried to fall into line when > responding to emails. It probably appeared to some I was not trying to get on board but this > is a significant change to the 20+years of my being involved in emails. > And yes Gisle Vanem, in spite of your doubts, I have been involved in emails in excess of 20 years. > I suppose most of that has been in the "Microsoft-induced 'lazy and stupid' style" as identified by > {Grant Edward}. However, I have responded to news lists and email groups previously. > As I have stated, most people have been kind and helpful. Some have addressed my lack of conformance > to the policies and procedures and have attempted to instruct me in a polite manner. To those I say > Thank You for your understanding and attempts to help me. > Some have provided answers to the initial issues I had. And as a novice to programming, I do > appreciate their assistance. I have not attempted all the possible fixes yet but I will i the > near future. I say Thank You to each of you. > To those who responded in a much less friendly attitude, even at times coming across in a very rude > manner - I really have nothing to say. You have not attempted to help resolve my initial issues and > your attitudes have caused me to feel this is not a place where I can learn much. Yes, there is a lot > I could learn, but some attitudes make me desire to no longer be involved in discussions. I am reminded of a story from the book Outliers. It regards a Colombian plane crash near New York some decades ago. The plane had run out of fuel. The pilot and his assistant tried to communicate this to the control tower. Now the NY control tower guys are described as the most efficient in the world -- and the rudest. So when the pilots got some piece of NY rudeness they said "Yes Sir!" slunk off and crashed the plane! (Instead of shouting MAYDAY or whatever pilots are supposed to do in such circumstances). This is Usenet. You'll learn much here and you'll find a bunch of rude people. No you are not going to crash your plane but you will likely crash your python-learning attempts if you give an occasional asshole more importance than is his due. I suggest 1. You focus on your goal -- learning python or whatever is the larger personal goal of which learning python is a part 2. A bullet-proof vest From larry.martell at gmail.com Thu Feb 13 11:32:46 2014 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 13 Feb 2014 11:32:46 -0500 Subject: Newcomer Help In-Reply-To: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 11:22 AM, Rustom Mody wrote: > > This is Usenet. You'll learn much here and you'll find a bunch of rude people. > > No you are not going to crash your plane but you will likely crash your > python-learning attempts if you give an occasional asshole more importance > than is his due. > > I suggest > 1. You focus on your goal -- learning python or whatever is the larger > personal goal of which learning python is a part > 2. A bullet-proof vest This reminds me of post that was circulating in the early 90's: Welcome to the Internet. No one here likes you. We're going to offend, insult, abuse, and belittle the living hell out of you. And when you rail against us with "FUCK YOU YOU GEEK WIMP SKATER GOTH LOSER PUNK FAG BITCH!1!!", we smile to ourselves. We laugh at you because you don't get it. Then we turn up the heat, hoping to draw more entertainment from your irrational fuming. We will judge you, and we will find you unworthy. It is a trial by fire, and we won't even think about turning down the flames until you finally understand. Some of you are smart enough to realize that, when you go online, it's like entering a foreign country ... and you know better than to ignorantly fuck with the locals. You take the time to listen and think before speaking. You learn, and by learning are gladly welcomed. For some of you, it takes a while, then one day it all dawns on you - you get it, and are welcomed into the fold. Some of you give up, and we breathe a sigh of relief - we didn't want you here anyway. And some of you just never get it. The offensively clueless have a special place in our hearts - as objects of ridicule. We don't like you, but we do love you. You will get mad. You will tell us to go to hell, and call us "nerds" and "geeks". Don't bother ... we already know exactly what we are. And, much like the way hardcore rap has co-opted the word "nigger", turning an insult around on itself to become a semiserious badge of honor, so have we done. "How dare you! I used to beat the crap out of punks like you in high school/college!" You may have owned the playing field because you were an athlete. You may have owned the student council because you were more popular. You may have owned the hallways and sidewalks because you were big and intimidating. Well, welcome to our world. Things like athleticism, popularity, and physical prowess mean nothing here. We place no value on them ... or what car you drive, the size of your bank account, what you do for a living or where you went to school. Allow us to introduce you to the concept of a "meritocracy" - the closest thing to a form of self-government we have. In The United Meritocratic nation-states of the Internet, those who can do, rule. Those who wish to rule, learn. Everyone else watches from the stands. You may posses everything in the off-line world. We don't care. You come to the Internet penniless, lacking the only thing of real value here: knowledge. "Who cares? The Internet isn't real anyway!" This attitude is universally unacceptable. The Internet is real. Real people live behind those handles and screen names. Real machines allow it to exist. It's real enough to change government policy, real enough to feed the world's hungry, and even, for some of us, real enough to earn us a paycheck. Using your own definition, how "real" is your job? Your stock portfolio? Your political party? What is the meaning of "real", anyway? Do I sound arrogant? Sure ... to you. Because you probably don't get it yet. If you insist on staying, then, at the very least, follow this advice: 1) No one, ESPECIALLY YOU, will make any law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances. 2) Use your brain before ever putting fingers to keys. 3) Do you want a picture of you getting anally raped by Bill Clinton while you're performing oral sex on a cow saved to hundreds of thousands of people's hard drives? No? Then don't put your fucking picture on the Internet. We can, will, and probably already HAVE altered it in awful ways. Expect it to show up on an equally offensive website. 4) Realize that you are never, EVER going to get that, or any other, offensive web page taken down. Those of us who run those sites LIVE to piss off people like you. Those of us who don't run those sites sometimes visit them just to read the hatemail from fools like you. 5) Oh, you say you're going to a lawyer? Be prepared for us to giggle with girlish delight, and for your lawyer to laugh in your face after he explains current copyright and parody law. 6) The Web is not the Internet. Stop referring to it that way. 7) We have already received the e-mail you are about to forward to us. Shut up. 8) Don't reply to spam. You are not going to be "unsubscribed". 9) Don't ever use the term "cyberspace" (only William Gibson gets to say that, and even he hasn't really used it for two or three books now). Likewise, you prove yourself a marketing-hype victim if you ever use the term "surfing". 10) With one or two notable exceptions, chat rooms will not get you laid. 11) It's a hoax, not a virus warning. 12) The internet is made up of thousands of computers, all connected but owned by different people. Learn how to use *your* computer before attempting to connect it to someone else's. 13) The first person who offers to help you is really just trying to fuck with you for entertainment. So is the second. And the third. And me. 14) Never insult someone who's been active in any group longer than you have. You may as well paint a damn target on your back. 15) Never get comfortable and arrogant behind your supposed mask of anonymity. Don't be surprised when your name, address, and home phone number get thrown back in your smug face. Hell, some of us will snail-mail you a printed satellite photograph of your house to drive the point home. Realize that you are powerless if this happens ... it's all public information, and information is our stock and trade. 16) No one thinks you are as cool as you think you are. 17) You aren't going to win any argument that you start. 18) If you're on AOL, don't worry about anything I've said here. You're already a fucking laughing stock, and there's no hope for you. 19) If you can't take a joke, immediately sell your computer to someone who can. RIGHT NOW. Pissed off? It's the TRUTH, not these words, that hurts your feelings. Don't ever even pretend like I've gone & hurt them. We don't like you. We don't want you here. We never will. Save us all the trouble and go away. From ben+python at benfinney.id.au Thu Feb 13 11:57:14 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Feb 2014 03:57:14 +1100 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> Message-ID: <85vbwj7xxx.fsf@benfinney.id.au> Oscar Benjamin writes: > I think Chris' statement above is pretty clear. I disagree, as explained. > Also I didn't find the original statement confusing I'm happy for you. > and it is a reasonable point to make. Yes, and I was not addressing that. -- \ ?It is well to remember that the entire universe, with one | `\ trifling exception, is composed of others.? ?John Andrew Holmes | _o__) | Ben Finney From ben+python at benfinney.id.au Thu Feb 13 12:05:09 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Feb 2014 04:05:09 +1100 Subject: Community standards of behaviour (was: Newcomer Help) References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> Message-ID: <85r4777xkq.fsf_-_@benfinney.id.au> Larry Martell writes: > On Thu, Feb 13, 2014 at 11:22 AM, Rustom Mody wrote: [?] > > I suggest > > 1. You focus on your goal -- learning python or whatever is the larger > > personal goal of which learning python is a part > > 2. A bullet-proof vest > > This reminds me of post that was circulating in the early 90's: > > Welcome to the Internet. > > No one here likes you. [?] > We don't like you. We don't want you here. We never will. Save us all > the trouble and go away. That may be true of some parts of the internet. But this is the Python community discussion forum. We have a much more pleasant code of conduct . We require each other to be open, considerate, and respectful. Please don't perpetuate awful behaviour (especially by the risible euphemism ?meritocracy?) here by appealing to the poor standards of others. -- \ ?If I haven't seen as far as others, it is because giants were | `\ standing on my shoulders.? ?Hal Abelson | _o__) | Ben Finney From john_ladasky at sbcglobal.net Thu Feb 13 12:34:38 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 13 Feb 2014 09:34:38 -0800 (PST) Subject: How to begin In-Reply-To: <92b6e6be-7e55-41c9-81e6-22f494639aa0@googlegroups.com> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <92b6e6be-7e55-41c9-81e6-22f494639aa0@googlegroups.com> Message-ID: <2eb077bd-f74c-45c5-bef3-5f30916b2fcd@googlegroups.com> On Thursday, February 13, 2014 7:06:03 AM UTC-8, pete suchsland wrote: > if x = 99: Surely, Pete, you meant to write "if x == 99:" ? From ethan at stoneleaf.us Thu Feb 13 11:57:50 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 08:57:50 -0800 Subject: singleton ... again In-Reply-To: References: Message-ID: <52FCF98E.9000604@stoneleaf.us> On 02/13/2014 03:50 AM, Ned Batchelder wrote: > On 2/13/14 4:00 AM, Piet van Oostrum wrote: >> Ben Finney writes: >> >>> Gregory Ewing writes: >>> >>>> Roy Smith wrote: >>>>> It looks to me like he's trying to implement a classic Gang of Four >>>>> singleton pattern. >>>> >>>> Which I've never really seen the point of in Python, or any other >>>> language for that matter. Just create one instance of the class during >>>> initialisation, put it in a global somewhere, and use it thereafter. >>> >>> Make that ?somewhere? a module namespace, and you effectively have a >>> Singleton for all practical purposes. So yes, I see the point of it; but >>> we already have it built in :-) >> >> There is a use case for a singleton class: when creating the singleton >> object takes considerable resources and you don't need it always in your >> program. >> > > I still don't see it. To convince me that a singleton class makes sense, you'd have to explain why by virtue of the > class's very nature, it never makes sense for there ever to be more than one of them. Say you have a database with a column that can only have a handful of values (like an enumeration, for instance) and this database can have hundreds of thousands of rows. When you're working with all those rows at once having just one object for the third enum value is a useful optimization. Say you have a class that represents serial ports or your computer. You should get the same object every time you ask for SerialPort(2). -- ~Ethan~ From eneskristo at gmail.com Thu Feb 13 12:46:50 2014 From: eneskristo at gmail.com (eneskristo at gmail.com) Date: Thu, 13 Feb 2014 09:46:50 -0800 (PST) Subject: Wait... WHAT? In-Reply-To: References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> <20140212212953.458b810a@bigbox.christie.dr> Message-ID: <8778c4cc-334b-4254-aed7-0f33acbf1d8f@googlegroups.com> Can we please revert back to the original problem? def save(): target = open ("save.swroc", 'w') target.write([counter, loop, number_of_competitors, competitors]) def load(): the_array = list(open("save.swroc", 'r')) the_array = target counter = the_array[0] loop = the_array[1] number_of_competitors = the_array[2] competitors = the_array[3] Is this better? From john_ladasky at sbcglobal.net Thu Feb 13 12:49:06 2014 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Thu, 13 Feb 2014 09:49:06 -0800 (PST) Subject: Welcome to the Internet. No one here likes you. (was: Newcomer Help) In-Reply-To: References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> Message-ID: <84fcf77d-4c82-4f04-b5d6-608e31bf6aa3@googlegroups.com> On Thursday, February 13, 2014 8:32:46 AM UTC-8, Larry.... at gmail.com wrote: > This reminds me of post that was circulating in the early 90's: > > Welcome to the Internet. > > No one here likes you. > > We're going to offend, insult, abuse, and belittle the living hell out > of you. And when you rail against us with "FUCK YOU YOU GEEK WIMP > SKATER GOTH LOSER PUNK FAG BITCH!1!!", we smile to ourselves. We laugh > at you because you don't get it. Then we turn up the heat, hoping to > draw more entertainment from your irrational fuming. [snip] Ummm... Larry, I hope you are just posting this rant because Rustom Mody's remarks reminded you of it. I hope that you do not personally subscribe to this behavior. Yes, I too was a bullied nerd when I was young. I don't use my history as an excuse to do unto others what was done unto me. No one should. No one should bully another person, period. It's not "entertainment," it's a deeply harmful practice, and does not deserve any respect. From roy at panix.com Thu Feb 13 12:57:43 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 12:57:43 -0500 Subject: singleton ... again References: Message-ID: In article , Ethan Furman wrote: > Say you have a class that represents serial ports or your computer. You > should get the same object every time you ask > for SerialPort(2). Why? Certainly, you should get objects which refer to the same physical port. So: port_a = SerialPort(2) port_b = SerialPort(2) port_a.enable() assert port_b.is_shutdown() == False port_a.shutdown() assert port_b.is_shutdown() == True But, why do they have to be the same object? Why should I care if port_a is port_b is False, as long as all operations I perform on either are reflected in correct state changes on the other one? From invalid at invalid.invalid Thu Feb 13 13:02:54 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 13 Feb 2014 18:02:54 +0000 (UTC) Subject: Newcomer Help References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> Message-ID: On 2014-02-13, Larry Martell wrote: > 9) Don't ever use the term "cyberspace" (only William Gibson gets to > say that, and even he hasn't really used it for two or three books > now). Likewise, you prove yourself a marketing-hype victim if you ever > use the term "surfing". 9b) And don't use any other term beginning with "cyber" either. That will infallibly identify you as somebody who hasn't a clue and are most likely a half-witted local news reporter or government official. -- Grant Edwards grant.b.edwards Yow! Sometime in 1993 at NANCY SINATRA will lead a gmail.com BLOODLESS COUP on GUAM!! From python at mrabarnett.plus.com Thu Feb 13 13:25:16 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Feb 2014 18:25:16 +0000 Subject: Wait... WHAT? In-Reply-To: <8778c4cc-334b-4254-aed7-0f33acbf1d8f@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> <20140212212953.458b810a@bigbox.christie.dr> <8778c4cc-334b-4254-aed7-0f33acbf1d8f@googlegroups.com> Message-ID: <52FD0E0C.5080102@mrabarnett.plus.com> On 2014-02-13 17:46, eneskristo at gmail.com wrote: > Can we please revert back to the original problem? > def save(): > target = open ("save.swroc", 'w') This opens the file for writing text (assuming you're using Python 3). > target.write([counter, loop, number_of_competitors, competitors]) This tries to write a list to the file. You can't do that. A list isn't text. > def load(): > the_array = list(open("save.swroc", 'r')) This open the file for reading text. Using 'list' will make it read lines of text and return them as a list. > the_array = target What's 'target'? > counter = the_array[0] This will set 'counter' to the first line of text that was read. > loop = the_array[1] This will set 'loop' to the second line of text. > number_of_competitors = the_array[2] This will set 'number_of_competitors' to the third line of text. > competitors = the_array[3] This will set 'number_of_competitors' to the fourth line of text. > Is this better? > Not really! :-) Have a look at the "pickle" module, or the "json" module. From forman.simon at gmail.com Thu Feb 13 13:37:34 2014 From: forman.simon at gmail.com (forman.simon at gmail.com) Date: Thu, 13 Feb 2014 10:37:34 -0800 (PST) Subject: A curious bit of code... Message-ID: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. if key[:1] + key[-1:] == '<>': ... Some possibilities that occurred to me: if key.startswith('<') and key.endswith('>'): ... and: if (key[:1], key[-1:]) == ('<', '>'): ... I haven't run these through a profiler yet, but it seems like the original might be the fastest after all? From roy at panix.com Thu Feb 13 13:45:44 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 13:45:44 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article <4cc09129-43ee-4205-a24c-03f92b594abc at googlegroups.com>, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing it, but > then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... if re.match(r'^<.*>$', key): sheesh. (if you care how fast it is, pre-compile the pattern) From ethan at stoneleaf.us Thu Feb 13 13:31:12 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 10:31:12 -0800 Subject: singleton ... again In-Reply-To: References: Message-ID: <52FD0F70.4080906@stoneleaf.us> On 02/13/2014 09:57 AM, Roy Smith wrote: > In article , > Ethan Furman wrote: > >> Say you have a class that represents serial ports or your computer. You >> should get the same object every time you ask >> for SerialPort(2). > > Why? Certainly, you should get objects which refer to the same physical > port. So: > > port_a = SerialPort(2) > port_b = SerialPort(2) > > port_a.enable() > assert port_b.is_shutdown() == False > > port_a.shutdown() > assert port_b.is_shutdown() == True > > But, why do they have to be the same object? Why should I care if > > port_a is port_b > > is False, as long as all operations I perform on either are reflected in > correct state changes on the other one? You mean use the Borg pattern instead of the Singleton pattern? As far as I can tell they are two shades of the same thing. Are there any drastic differences between the two? Besides one having many instances that share one __dict__ and the other just having one instance and one __dict__? -- ~Ethan~ From roy at panix.com Thu Feb 13 14:03:15 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 14:03:15 -0500 Subject: singleton ... again References: Message-ID: In article , Ethan Furman wrote: > On 02/13/2014 09:57 AM, Roy Smith wrote: > > In article , > > Ethan Furman wrote: > > > >> Say you have a class that represents serial ports or your computer. You > >> should get the same object every time you ask > >> for SerialPort(2). > > > > Why? Certainly, you should get objects which refer to the same physical > > port. So: > > > > port_a = SerialPort(2) > > port_b = SerialPort(2) > > > > port_a.enable() > > assert port_b.is_shutdown() == False > > > > port_a.shutdown() > > assert port_b.is_shutdown() == True > > > > But, why do they have to be the same object? Why should I care if > > > > port_a is port_b > > > > is False, as long as all operations I perform on either are reflected in > > correct state changes on the other one? > > You mean use the Borg pattern instead of the Singleton pattern? As far as I > can tell they are two shades of the same > thing. Are there any drastic differences between the two? Besides one > having many instances that share one __dict__ > and the other just having one instance and one __dict__? I envision SerialPort being a thin layer on top of a bunch of OS-specific system calls to give them a pythonic interface. Things like is_shutdown() and set_bit_rate() presumably turn into ioctls. No need to have any state at all beyond a file descriptor. From ethan at stoneleaf.us Thu Feb 13 13:45:09 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 10:45:09 -0800 Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD12B5.9000203@stoneleaf.us> On 02/13/2014 10:37 AM, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... > > > I haven't run these through a profiler yet, but it seems like the original might be the fastest after all? Unless that line of code is a bottleneck, don't worry about speed, go for readability. In which case I'd go with the second option, then the first, and definitely avoid the third. -- ~Ethan~ From breamoreboy at yahoo.co.uk Thu Feb 13 14:09:56 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Feb 2014 19:09:56 +0000 Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 13/02/2014 18:37, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... > > > I haven't run these through a profiler yet, but it seems like the original might be the fastest after all? > All I can say is that if you're worried about the speed of a single line of code like the above then you've got problems. Having said that, I suspect that using an index to extract a single character has to be faster than using a slice, but I haven't run these through a profiler yet :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Thu Feb 13 14:10:30 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Feb 2014 20:10:30 +0100 Subject: Using a subclass for __dict__ References: Message-ID: Demian Brecht wrote: > Using bases in a metaclass, I've been able to easily figure out when > an attribute is being added to an instance of a class. However, what > I'm /actually/ looking to do is to intercept when attributes are being > added to a class (not an instance of). I thought that I'd be able to > do so by passing in a subclass of dict to type.__new__ of the > metaclass's __new__ and implementing a custom __setitem__, but > apparently that's not the case. > > If you're curious as to why I'm doing this, I'm trying to clean up > https://gist.github.com/demianbrecht/6944269 and get rid of the > late_bind method there in favour of using the appropriate magic > methods. The intention is to piggyback off of abc's > __abstractmethods__ in order to implement a "looks_like" method that > checks that one class conforms to an unrelated class's interface > rather than using inheritance to enforce interface implementations at > class creation time. This is /only/ intended to be a proof of concept > for demonstration purposes and nothing that I'd ever actually > implement, so no need for flaming the concept :) > > # test.py > > class Dict(dict): > def __setattr__(self, key, value): > print 'Dict.__setattr__' > dict.__setattr__(self, key, value) > > def __setitem__(self, key, value): > print 'Dict.__setitem__' > dict.__setitem__(self, key, value) > > class Bar(object): > def __setattr__(self, key, value): > print 'Bar.__setattr__' > object.__setattr__(self, key, value) > > class metafoo(type): > def __new__(mcls, name, bases, dct): > return type.__new__(mcls, name, (Bar,), Dict(dct)) > > class Foo(object): > __metaclass__ = metafoo > >>>> import test >>>> f = test.Foo() >>>> f.foo = 'bar' > Bar.__setattr__ # expected >>>> test.Foo.foo = 'bar' > # I'm expecting Dict.__setattr__ here, but... *crickets* > > Am I missing something here, or do I just have to live with what I > currently have in my gist? I don't really understand what you are trying to do in the gist, perhaps you want ? Anyway, intercepting __setattr__() in the class becomes easy once you remember that a class is just an instance of its metaclass: >>> class FooMeta(type): ... def __setattr__(self, name, value): ... print value, "-->", name ... super(FooMeta, self).__setattr__(name, value) ... >>> class Foo: ... __metaclass__ = FooMeta ... >>> Foo.bar = "baz" baz --> bar Python 3 has a bit more to offer in this area, see From timothy.c.delaney at gmail.com Thu Feb 13 14:16:10 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Fri, 14 Feb 2014 06:16:10 +1100 Subject: singleton ... again In-Reply-To: References: Message-ID: On 13 February 2014 20:00, Piet van Oostrum wrote: > Ben Finney writes: > > Make that ?somewhere? a module namespace, and you effectively have a > > Singleton for all practical purposes. So yes, I see the point of it; but > > we already have it built in :-) > > There is a use case for a singleton class: when creating the singleton > object takes considerable resources and you don't need it always in your > program. > Then have that resource in its own module, and import that module only when needed e.g. inside a function. Python already has the machinery - no need to reinvent the wheel. Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Thu Feb 13 14:17:29 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 19:17:29 +0000 (UTC) Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2014-02-13, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of > doing it, but then after further consideration I wasn't so > sure. > > if key[:1] + key[-1:] == '<>': ... > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... > > > I haven't run these through a profiler yet, but it seems like > the original might be the fastest after all? I think the following would occur to someone first: if key[0] == '<' and key[-1] == '>': ... It is wrong to avoid the obvious. Needlessly ornate or clever code will only irritate the person who has to read it later; most likely yourself. -- Neil Cerutti From rosuav at gmail.com Thu Feb 13 14:17:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 06:17:56 +1100 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Fri, Feb 14, 2014 at 1:58 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> Whether it's a module-level function, a bound method, a closure, or a >> callable object, a zero-arg function in Python always has some kind of >> implicit state. > > Sometimes, it has a *lot* of implicit state: > > os.fork() os.fork() always returns 0, so it *clearly* has no state whatsoever. It also always returns the next available PID, which is only a small amount of extra state (from the OS). Nothing else affects its return value! ChrisA From alain at dpt-info.u-strasbg.fr Thu Feb 13 14:05:19 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 13 Feb 2014 20:05:19 +0100 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <87zjlu4yvk.fsf@dpt-info.u-strasbg.fr> forman.simon at gmail.com writes: > I ran across this and I thought there must be a better way of doing > it, but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... I would do: if key[0] == '<' and key[-1] == '>' ... -- Alain. From ethan at stoneleaf.us Thu Feb 13 14:20:33 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 11:20:33 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD1B01.80200@stoneleaf.us> On 02/13/2014 11:09 AM, Mark Lawrence wrote: > > All I can say is that if you're worried about the speed of a single line of code like the above then you've got > problems. Having said that, I suspect that using an index to extract a single character has to be faster than using a > slice, but I haven't run these through a profiler yet :) The problem with using indices in the code sample is that if the string is 0 or 1 characters long you'll get an exception instead of a False. -- ~Ethan~ From ethan at stoneleaf.us Thu Feb 13 14:25:15 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 11:25:15 -0800 Subject: A curious bit of code... In-Reply-To: <52FD1B01.80200@stoneleaf.us> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD1B01.80200@stoneleaf.us> Message-ID: <52FD1C1B.8060104@stoneleaf.us> On 02/13/2014 11:20 AM, Ethan Furman wrote: > On 02/13/2014 11:09 AM, Mark Lawrence wrote: >> >> All I can say is that if you're worried about the speed of a single >> line of code like the above then you've got problems. Having said >> that, I suspect that using an index to extract a single character >> has to be faster than using a slice, but I haven't run these through >> a profiler yet :) > > The problem with using indices in the code sample is that if the > string is 0 or 1 characters long you'll get an exception instead > of a False. Oops, make that zero characters. ;) -- ~Ethan~ From rosuav at gmail.com Thu Feb 13 14:25:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 06:25:37 +1100 Subject: Working with the set of real numbers In-Reply-To: <871tz7864a.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 14, 2014 at 1:00 AM, Marko Rauhamaa wrote: > Well, if your idealized, infinite, digital computer had ?? bytes of RAM > and ran at ?? hertz and Python supported transfinite iteration, you > could easily do reals: > > def real_sqrt(y): > for x in continuum(0, max(1, y)): > # Note: x is not traversed in the < order but some other > # well-ordering, which has been proved to exist. > if x * x == y: > return x > assert False How exactly do you iterate over a continuum, with a digital computer? Even adding to your requirements that it have an ?? Hz bus (which, by the way, I *totally* want - the uses are endless), it would take a finite amount of time to assign to x the "next number", ergo your algorithm can't guarantee to finish in finite time. ChrisA From neilc at norwich.edu Thu Feb 13 14:25:27 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 19:25:27 +0000 (UTC) Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD1B01.80200@stoneleaf.us> Message-ID: On 2014-02-13, Ethan Furman wrote: > On 02/13/2014 11:09 AM, Mark Lawrence wrote: >> All I can say is that if you're worried about the speed of a >> single line of code like the above then you've got problems. >> Having said that, I suspect that using an index to extract a >> single character has to be faster than using a slice, but I >> haven't run these through a profiler yet :) > > The problem with using indices in the code sample is that if > the string is 0 or 1 characters long you'll get an exception > instead of a False. There will be an exception only if it is zero-length. But good point! That's a pretty sneaky way to avoid checking for a zero-length string. Is it a popular idiom? -- Neil Cerutti From hseuming at gmail.com Thu Feb 13 14:27:27 2014 From: hseuming at gmail.com (ming) Date: Thu, 13 Feb 2014 11:27:27 -0800 (PST) Subject: XML parsing ExpatError with xml.dom.minidom at line 1, column 0 Message-ID: Hi, i've a Python script which stopped working about a month ago. But until then, it worked flawlessly for months (if not years). A tiny self-contained 7-line script is provided below. i ran into an XML parsing problem with xml.dom.minidom and the error message is included below. The weird thing is if i used an XML validator on the web to validate against this particular URL directly, it is all good. Moreover, i saved the page source in Firefox or Chrome then validated against the saved XML file, it's also all good. Since the error happened at the very beginning of the input (line 1, column 0) as indicated below, i was wondering if this is an encoding mismatch. However, according to the saved page source in FireFox or Chrome, there is the following at the beginning: ================================================= #!/usr/bin/env python import urllib2 from xml.dom.minidom import parseString fd = urllib2.urlopen('http://api.worldbank.org/countries') data = fd.read() fd.close() dom = parseString(data) ================================================= ================================================= Traceback (most recent call last): File "./bugReport.py", line 9, in dom = parseString(data) File "/usr/lib/python2.7/xml/dom/minidom.py", line 1931, in parseString return expatbuilder.parseString(string) File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 940, in parseString return builder.parseString(string) File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 223, in parseString parser.Parse(string, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 0 ================================================= i'm running Python 2.7.5+ on Ubuntu 13.10. Thanks. From roy at panix.com Thu Feb 13 14:28:41 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 14:28:41 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article , Ethan Furman wrote: > On 02/13/2014 11:09 AM, Mark Lawrence wrote: > > > > All I can say is that if you're worried about the speed of a single line of > > code like the above then you've got > > problems. Having said that, I suspect that using an index to extract a > > single character has to be faster than using a > > slice, but I haven't run these through a profiler yet :) > > The problem with using indices in the code sample is that if the string is 0 > or 1 characters long you'll get an > exception instead of a False. My re.match() solution handles those edge cases just fine. From breamoreboy at yahoo.co.uk Thu Feb 13 14:32:17 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Feb 2014 19:32:17 +0000 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD1B01.80200@stoneleaf.us> Message-ID: On 13/02/2014 19:25, Neil Cerutti wrote: > On 2014-02-13, Ethan Furman wrote: >> On 02/13/2014 11:09 AM, Mark Lawrence wrote: >>> All I can say is that if you're worried about the speed of a >>> single line of code like the above then you've got problems. >>> Having said that, I suspect that using an index to extract a >>> single character has to be faster than using a slice, but I >>> haven't run these through a profiler yet :) >> >> The problem with using indices in the code sample is that if >> the string is 0 or 1 characters long you'll get an exception >> instead of a False. > > There will be an exception only if it is zero-length. But good > point! That's a pretty sneaky way to avoid checking for a > zero-length string. Is it a popular idiom? > I hope not. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Thu Feb 13 14:43:58 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Feb 2014 20:43:58 +0100 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing it, > but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... > > > I haven't run these through a profiler yet, but it seems like the original > might be the fastest after all? $ python -m timeit -s 's = ""' 's[:1]+s[-1:] == "<>"' 1000000 loops, best of 3: 0.37 usec per loop $ python -m timeit -s 's = ""' 's[:1] == "<" and s[-1:] == ">"' 1000000 loops, best of 3: 0.329 usec per loop $ python -m timeit -s 's = ""' 's.startswith("<") and s.endswith(">")' 1000000 loops, best of 3: 0.713 usec per loop The first is too clever for my taste. The second is fast and easy to understand. It might attract "improvements" replacing the slice with an index, but I trust you will catch that with your unit tests ;) Personally, I'm willing to spend the few extra milliseconds and use the foolproof third. From ethan at stoneleaf.us Thu Feb 13 14:23:59 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 11:23:59 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD1BCF.9010208@stoneleaf.us> On 02/13/2014 11:17 AM, Neil Cerutti wrote: > On 2014-02-13, forman.simon at gmail.com > wrote: >> I ran across this and I thought there must be a better way of >> doing it, but then after further consideration I wasn't so >> sure. >> >> if key[:1] + key[-1:] == '<>': ... >> >> Some possibilities that occurred to me: >> >> if key.startswith('<') and key.endswith('>'): ... >> >> and: >> >> if (key[:1], key[-1:]) == ('<', '>'): ... >> >> >> I haven't run these through a profiler yet, but it seems like >> the original might be the fastest after all? > > I think the following would occur to someone first: > > if key[0] == '<' and key[-1] == '>': > ... > > It is wrong to avoid the obvious. Needlessly ornate or clever > code will only irritate the person who has to read it later; most > likely yourself. Not whet the obvious is wrong: -> key = '' --> if key[0] == '<' and key[-1] == '>': ... print "good key!" ... else: ... print "bad key" ... Traceback (most recent call last): File "", line 1, in IndexError: string index out of range -- ~Ethan~ From marko at pacujo.net Thu Feb 13 14:47:48 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Feb 2014 21:47:48 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: <87fvnm7q1n.fsf@elektro.pacujo.net> Chris Angelico : > On Fri, Feb 14, 2014 at 1:00 AM, Marko Rauhamaa wrote: >> Well, if your idealized, infinite, digital computer had ?? bytes of RAM >> and ran at ?? hertz and Python supported transfinite iteration, you >> could easily do reals: >> >> for x in continuum(0, max(1, y)): > > How exactly do you iterate over a continuum, with a digital computer? How "digital" our idealized computers are is a matter for a debate. However, iterating over the continuum is provably "possible:" http://en.wikipedia.org/wiki/Transfinite_induction > it would take a finite amount of time to assign to x the "next > number", ergo your algorithm can't guarantee to finish in finite time. My assumption was you could execute ?? statements per second. That doesn't guarantee a finite finish time but would make it possible. That is because ?? * ?? = ?? = ?? * 1 This computer is definitely more powerful than a Turing machine, which only has ?? bytes of RAM and thus can't even store an arbitrary real value in memory. Marko From rosuav at gmail.com Thu Feb 13 14:50:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 06:50:06 +1100 Subject: singleton ... again In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 6:03 AM, Roy Smith wrote: > In article , > Ethan Furman wrote: >> >> You mean use the Borg pattern instead of the Singleton pattern? As far as I >> can tell they are two shades of the same >> thing. Are there any drastic differences between the two? Besides one >> having many instances that share one __dict__ >> and the other just having one instance and one __dict__? > > I envision SerialPort being a thin layer on top of a bunch of > OS-specific system calls to give them a pythonic interface. Things like > is_shutdown() and set_bit_rate() presumably turn into ioctls. No need > to have any state at all beyond a file descriptor. I'd go a bit further. The SerialPort instance would have its own effective state: the file descriptor. Two of them can be created and one of them closed, and the fd for that one would be closed while the other stays open. It's then two objects dealing with a common external facility. ChrisA From neilc at norwich.edu Thu Feb 13 14:51:25 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 19:51:25 +0000 (UTC) Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2014-02-13, Peter Otten <__peter__ at web.de> wrote: > forman.simon at gmail.com wrote: > The first is too clever for my taste. > > The second is fast and easy to understand. It might attract > "improvements" replacing the slice with an index, but I trust > you will catch that with your unit tests ;) It's easy to forget exactly why startswith and endswith even exist. -- Neil Cerutti From beliavsky at aol.com Thu Feb 13 14:50:44 2014 From: beliavsky at aol.com (beliavsky at aol.com) Date: Thu, 13 Feb 2014 11:50:44 -0800 (PST) Subject: Python(x,y) interferes with earlier Numpy installation Message-ID: <8d25f041-4d53-428d-9701-24a1622a8d11@googlegroups.com> I am running Python 2.7.5 on Windows 7 and installed Numpy, which worked. Then I installed Python(x,y) from a file Python(x,y)-2.7.5.2.exe, and now running the script from numpy import array, size, shape, min, max, sum a = array([1, 2, 3]) print shape(a) gives the error messages Traceback (most recent call last): File "x.py", line 1, in from numpy import array, size, shape, min, max, sum File "c:\python27\lib\site-packages\numpy\__init__.py", line 153, in from . import add_newdocs File "c:\python27\lib\site-packages\numpy\add_newdocs.py", line 13, in from numpy.lib import add_newdoc File "c:\python27\lib\site-packages\numpy\lib\__init__.py", line 18, in from .polynomial import * File "c:\python27\lib\site-packages\numpy\lib\polynomial.py", line 19, in from numpy.linalg import eigvals, lstsq, inv File "c:\python27\lib\site-packages\numpy\linalg\__init__.py", line 50, in from .linalg import * File "c:\python27\lib\site-packages\numpy\linalg\linalg.py", line 29, in from numpy.linalg import lapack_lite, _umath_linalg ImportError: DLL load failed: The specified path is invalid. How can I get Numpy working again? Thanks. From ethan at stoneleaf.us Thu Feb 13 14:59:10 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 11:59:10 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD240E.2060005@stoneleaf.us> On 02/13/2014 11:43 AM, Peter Otten wrote: > forman.simon at gmail.com wrote: > >> I ran across this and I thought there must be a better way of doing it, >> but then after further consideration I wasn't so sure. >> >> if key[:1] + key[-1:] == '<>': ... >> >> >> Some possibilities that occurred to me: >> >> if key.startswith('<') and key.endswith('>'): ... >> >> and: >> >> if (key[:1], key[-1:]) == ('<', '>'): ... >> >> >> I haven't run these through a profiler yet, but it seems like the original >> might be the fastest after all? > > $ python -m timeit -s 's = ""' 's[:1]+s[-1:] == "<>"' > 1000000 loops, best of 3: 0.37 usec per loop > > $ python -m timeit -s 's = ""' 's[:1] == "<" and s[-1:] == ">"' > 1000000 loops, best of 3: 0.329 usec per loop > > $ python -m timeit -s 's = ""' 's.startswith("<") and > s.endswith(">")' > 1000000 loops, best of 3: 0.713 usec per loop > > The first is too clever for my taste. > > The second is fast and easy to understand. It might attract "improvements" > replacing the slice with an index, but I trust you will catch that with your > unit tests ;) > > Personally, I'm willing to spend the few extra milliseconds and use the > foolproof third. For completeness: # the slowest method from Peter $ python -m timeit -s 's = ""' 's.startswith("<") and s.endswith(">")' 1000000 loops, best of 3: 0.309 usec per loop # the re method from Roy $ python -m timeit -s "import re;pattern=re.compile(r'^<.*>$');s = ''" "pattern.match(s)" 1000000 loops, best of 3: 0.466 usec per loop -- ~Ethan~ From marko at pacujo.net Thu Feb 13 14:56:02 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Feb 2014 21:56:02 +0200 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <87bnya7pnx.fsf@elektro.pacujo.net> Peter Otten <__peter__ at web.de>: > Personally, I'm willing to spend the few extra milliseconds and use > the foolproof third. Speaking of foolproof, what is this "key?" Is it an XML start tag, maybe? Then, how does your test fare with, say, which is equivalent to Marko From rosuav at gmail.com Thu Feb 13 15:03:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:03:44 +1100 Subject: singleton ... again In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 2:24 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder >> wrote: >> > I still don't see it. To convince me that a singleton class makes sense, >> > you'd have to explain why by virtue of the class's very nature, it never >> > makes sense for there ever to be more than one of them. >> >> There's a huge difference, btw, between mutable and immutable >> singletons. With immutables like None, True/False, integers, strings, >> and tuples thereof, returning a preexisting object is just an >> optimization. Do it if you want, don't if you don't, nobody's going to >> hugely care. > > People *depend* on None being a singleton (and are encouraged to do so), > when they use "is" as the test-for-Noneness. Circular argument, though. If None weren't a singleton, people would use == to test for Noneness. Since it's been guaranteed to be optimized to a singleton, the comparison can also be optimized, but it's still just an optimization, as can be seen with integers. In CPython, you could test for small integer equality using 'is', but since that optimization isn't guaranteed, neither is that code pattern. >> With mutables, it's hugely different. A singleton >> "database connection" object would, imo, be hugely confusing; you'd >> think you created a separate connection object, but no, what you do on >> this one affects the other. > > Except that if you do caching in the database connector, you would > certainly want the cache to be shared between all the users. There's no > right answer here. Each way has it's advantages and disadvantages. And > it would only be confusing if the documentation didn't spell out which > way it was doing it, leaving people to make (possibly wrong) assumptions. Compare these: # Style 1: import magicsql import othermodule conn = magicsql.MagicSQL("127.0.0.1") conn.set_parameter("foobar", True) othermodule.do_stuff() conn.query("select foo from bar") # Style 2: import magicsql import othermodule magicsql.connect("127.0.0.1") magicsql.set_parameter("foobar", True) othermodule.do_stuff() magicsql.query("select foo from bar") Suppose othermodule.do_stuff() does the same sort of calls except that it sets parameter foobar to False. With Style 1, I would expect that conn is independent of any connection object used by othermodule, and it would be a major source of bugs (look at PHP's persistent connections and how extremely careful you have to be with changing *any* connection settings). But with Style 2, it's obvious that anyone else importing magicsql and changing parameters will affect me. That's why module-level functions are the clearer way to do this than singleton classes. >> Better there to have module-level functions; at least Python >> programmers should understand that reimporting a module gives you >> back another reference to the same module. > > Except when it doesn't. Singleton-ness of modules depends on the names > under which they were imported. Symlinks, for example, can fool the > import machinery. > > $ ls -l s1 s2 > lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s1 -> s > lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s2 -> s > > $ ls -l s > total 12 > -rw-rw-r-- 1 roy roy 0 Feb 13 10:13 __init__.py > -rw-rw-r-- 1 roy roy 101 Feb 13 10:14 __init__.pyc > -rw-rw-r-- 1 roy roy 9 Feb 13 10:12 singleton.py > -rw-rw-r-- 1 roy roy 123 Feb 13 10:14 singleton.pyc > >>>> import s1.singleton >>>> import s2.singleton >>>> s1.singleton == s2.singleton > False Sure, they're not a guarantee. And if you fork a subprocess, then you have copies of the singleton, too. That's not the point here. If you have two modules and each one types "import random", you would not be surprised to learn that the name "random" in each is bound to the exact same random, and that they effectively share state. If you're calling random.random(), and then you call another module which imports random and calls random.random(), you don't complain that your sequence of random numbers was disrupted. But if you were to get yourself a random.Random() instance and someone else does the same, then the style of code makes it *look like* you should be working with independent objects. And in the case of the random module, that is exactly what happens. Instantiate? Separate. Module-level functions? Shared. ChrisA From marko at pacujo.net Thu Feb 13 14:56:02 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 13 Feb 2014 21:56:02 +0200 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <87bnya7pnx.fsf@elektro.pacujo.net> Peter Otten <__peter__ at web.de>: > Personally, I'm willing to spend the few extra milliseconds and use > the foolproof third. Speaking of foolproof, what is this "key?" Is it an XML start tag, maybe? Then, how does your test fare with, say, which is equivalent to Marko From zachary.ware+pylist at gmail.com Thu Feb 13 14:59:41 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 13 Feb 2014 13:59:41 -0600 Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 12:37 PM, wrote: > I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... > > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... > > and: > > if (key[:1], key[-1:]) == ('<', '>'): ... > > > I haven't run these through a profiler yet, but it seems like the original might be the fastest after all? In a fit of curiosity, I did some timings: 'and'ed indexing: C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" 1000000 loops, best of 3: 0.35 usec per loop C:\tmp>py -m timeit -s "key = ''" 1000000 loops, best of 3: 0.398 usec per loop C:\tmp>py -m timeit -s "key = 'test>'" "key[0] == '<' and key[-1] == '>'" 1000000 loops, best of 3: 0.188 usec per loop C:\tmp>py -m timeit -s "key = 'test'" "key[0] == '<' and key[-1] == '>'" 10000000 loops, best of 3: 0.211 usec per loop C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" Traceback (most recent call last): File "P:\Python34\lib\timeit.py", line 292, in main x = t.timeit(number) File "P:\Python34\lib\timeit.py", line 178, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner key[0] == '<' and key[-1] == '>' IndexError: string index out of range Slice concatenation: C:\tmp>py -m timeit -s "key = ''" "key[:1] + key[-1:] == '<>'" 1000000 loops, best of 3: 0.649 usec per loop C:\tmp>py -m timeit -s "key = ''" 1000000 loops, best of 3: 0.7 usec per loop C:\tmp>py -m timeit -s "key = 'test>'" "key[:1] + key[-1:] == '<>'" 1000000 loops, best of 3: 0.663 usec per loop C:\tmp>py -m timeit -s "key = 'test'" "key[:1] + key[-1:] == '<>'" 1000000 loops, best of 3: 0.665 usec per loop C:\tmp>py -m timeit -s "key = ''" "key[:1] + key[-1:] == '<>'" 1000000 loops, best of 3: 0.456 usec per loop String methods: C:\tmp>py -m timeit -s "key = ''" "key.startswith('<') and key.endswith('>')" 1000000 loops, best of 3: 1.03 usec per loop C:\tmp>py -m timeit -s "key = '')" 1000000 loops, best of 3: 1.02 usec per loop C:\tmp>py -m timeit -s "key = 'test>'" "key.startswith('<') and key.endswith('>')" 1000000 loops, best of 3: 0.504 usec per loop C:\tmp>py -m timeit -s "key = 'test'" "key.startswith('<') and key.endswith('>')" 1000000 loops, best of 3: 0.502 usec per loop C:\tmp>py -m timeit -s "key = ''" "key.startswith('<') and key.endswith('>')" 1000000 loops, best of 3: 0.49 usec per loop Tuple comparison: C:\tmp>py -m timeit -s "key = ''" "(key[:1], key[-1:]) == ('<', '>')" 1000000 loops, best of 3: 0.629 usec per loop C:\tmp>py -m timeit -s "key = '')" 1000000 loops, best of 3: 0.689 usec per loop C:\tmp>py -m timeit -s "key = 'test>'" "(key[:1], key[-1:]) == ('<', '>')" 1000000 loops, best of 3: 0.676 usec per loop C:\tmp>py -m timeit -s "key = 'test'" "(key[:1], key[-1:]) == ('<', '>')" 1000000 loops, best of 3: 0.675 usec per loop C:\tmp>py -m timeit -s "key = ''" "(key[:1], key[-1:]) == ('<', '>')" 1000000 loops, best of 3: 0.608 usec per loop re.match(): C:\tmp>py -m timeit -s "import re;key = ''" "re.match(r'^<.*>$', key)" 100000 loops, best of 3: 3.39 usec per loop C:\tmp>py -m timeit -s "import re;key = '$', key)" 100000 loops, best of 3: 3.27 usec per loop C:\tmp>py -m timeit -s "import re;key = 'test>'" "re.match(r'^<.*>$', key)" 100000 loops, best of 3: 2.94 usec per loop C:\tmp>py -m timeit -s "import re;key = 'test'" "re.match(r'^<.*>$', key)" 100000 loops, best of 3: 2.97 usec per loop C:\tmp>py -m timeit -s "import re;key = ''" "re.match(r'^<.*>$', key)" 100000 loops, best of 3: 2.97 usec per loop Pre-compiled re: C:\tmp>py -m timeit -s "import re;r = re.compile(r'^<.*>$');key = ''" "r.match(key)" 1000000 loops, best of 3: 0.932 usec per loop C:\tmp>py -m timeit -s "import re;r = re.compile(r'^<.*>$');key = 'py -m timeit -s "import re;r = re.compile(r'^<.*>$');key = 'test>'" "r.match(key)" 1000000 loops, best of 3: 0.718 usec per loop C:\tmp>py -m timeit -s "import re;r = re.compile(r'^<.*>$');key = 'test'" "r.match(key)" 1000000 loops, best of 3: 0.755 usec per loop C:\tmp>py -m timeit -s "import re;r = re.compile(r'^<.*>$');key = ''" "r.match(key)" 1000000 loops, best of 3: 0.731 usec per loop Pre-compiled re with pre-fetched method: C:\tmp>py -m timeit -s "import re;m = re.compile(r'^<.*>$').match;key = ''" "m(key)" 1000000 loops, best of 3: 0.777 usec per loop C:\tmp>py -m timeit -s "import re;m = re.compile(r'^<.*>$').match;key = 'py -m timeit -s "import re;m = re.compile(r'^<.*>$').match;key = 'test>'" "m(key)" 1000000 loops, best of 3: 0.652 usec per loop C:\tmp>py -m timeit -s "import re;m = re.compile(r'^<.*>$').match;key = 'test'" "m(key)" 1000000 loops, best of 3: 0.576 usec per loop C:\tmp>py -m timeit -s "import re;m = re.compile(r'^<.*>$').match;key = ''" "m(key)" 1000000 loops, best of 3: 0.58 usec per loop And the winner is: C:\tmp>py -m timeit -s "key = ''" "key and key[0] == '<' and key[-1] == '>'" 1000000 loops, best of 3: 0.388 usec per loop C:\tmp>py -m timeit -s "key = ''" 1000000 loops, best of 3: 0.413 usec per loop C:\tmp>py -m timeit -s "key = 'test>'" "key and key[0] == '<' and key[-1] == '>'" 1000000 loops, best of 3: 0.219 usec per loop C:\tmp>py -m timeit -s "key = 'test'" "key and key[0] == '<' and key[-1] == '>'" 1000000 loops, best of 3: 0.215 usec per loop C:\tmp>py -m timeit -s "key = ''" "key and key[0] == '<' and key[-1] == '>'" 10000000 loops, best of 3: 0.0481 usec per loop So, the moral of the story? Use short-circuit logic wherever you can, don't use re for simple stuff (because while it may be very fast, it's dominated by attribute lookup and function call overhead), and unless you expect to be doing this test many many millions of times in a very short space of time, go for readability over performance. -- Zach From demianbrecht at gmail.com Thu Feb 13 15:07:09 2014 From: demianbrecht at gmail.com (Demian Brecht) Date: Thu, 13 Feb 2014 12:07:09 -0800 Subject: Using a subclass for __dict__ In-Reply-To: References: Message-ID: On Thu, Feb 13, 2014 at 11:10 AM, Peter Otten <__peter__ at web.de> wrote: > I don't really understand what you are trying to do in the gist, perhaps you want > > Even though you've already answered my question, here's what I'm trying to do: High level goal (again, purely proof of concept): Piggy back on CPython's abc implementation in order to ensure that class A implements the interface implemented by unrelated class B. Using abc's as intended, when @abc.abstractmethod is used, it tags the method with __isabstractmethod__. When ABCMeta.__new__ executes, it compiles a frozenset (__abstractmethods__) of all methods still tagged as __isabstractmethod__ (in other words, those that haven't been implemented in a child class). During object creation in the interpreter layer, it checks to see if there are any __abstractmethods__. If there is, then it fails at that point, citing those methods as not being implemented. All I did (and it definitely needs some good cleaning) is inject abstractmethods in class A where implementations matching class B's interface were not present. The specific problem that I ran into was when methods are bound to a class definition after initial class construction. Having said that, this seems to be more of an issue with 2.7's abc implemention: import abc class A(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def fn(self): pass class B(A): pass try: B() except TypeError: pass B.fn = lambda: 'foo' B() The above code works fine in 3.3, but fails in 2.7. Cool, glad that's explained. > > ? > > Anyway, intercepting __setattr__() in the class becomes easy once you remember that a class is just > an instance of its metaclass *Throws keyboard across the office* FFS. I could have SWORN I tried that (because I /know/ that a class is an instance of its metaclass :/). An instance of looking at something far too long without a fresh set of eyes. Thanks! -- Demian Brecht http://demianbrecht.github.com From rosuav at gmail.com Thu Feb 13 15:08:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:08:16 +1100 Subject: Working with the set of real numbers In-Reply-To: <87fvnm7q1n.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <87fvnm7q1n.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 14, 2014 at 6:47 AM, Marko Rauhamaa wrote: > My assumption was you could execute ?? statements per second. That > doesn't guarantee a finite finish time but would make it possible. That > is because > > ?? * ?? = ?? = ?? * 1 Hmm. I never actually covered this stuff in grade school - the construction of infinite computing power didn't exactly come up. But as I understand it, just calculating the "next number" requires ?? RAM operations, and you have to do that ?? times per second. So what you're saying is that it's possible to do that? You can execute ?? operations where each operation has to wait for ?? bus actions before continuing? This would do my head in if I hadn't already thoroughly broken my brain on other insanities. ChrisA From __peter__ at web.de Thu Feb 13 15:10:34 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Feb 2014 21:10:34 +0100 Subject: XML parsing ExpatError with xml.dom.minidom at line 1, column 0 References: Message-ID: ming wrote: > Hi, > i've a Python script which stopped working about a month ago. But until > then, it worked flawlessly for months (if not years). A tiny > self-contained 7-line script is provided below. > > i ran into an XML parsing problem with xml.dom.minidom and the error > message is included below. The weird thing is if i used an XML validator > on the web to validate against this particular URL directly, it is all > good. Moreover, i saved the page source in Firefox or Chrome then > validated against the saved XML file, it's also all good. > > Since the error happened at the very beginning of the input (line 1, > column 0) as indicated below, i was wondering if this is an encoding > mismatch. However, according to the saved page source in FireFox or > Chrome, there is the following at the beginning: > > > > > ================================================= > #!/usr/bin/env python > > import urllib2 > from xml.dom.minidom import parseString > > fd = urllib2.urlopen('http://api.worldbank.org/countries') > data = fd.read() > fd.close() > dom = parseString(data) > ================================================= > > > > ================================================= > Traceback (most recent call last): > File "./bugReport.py", line 9, in > dom = parseString(data) > File "/usr/lib/python2.7/xml/dom/minidom.py", line 1931, in parseString > return expatbuilder.parseString(string) > File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 940, in > parseString > return builder.parseString(string) > File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 223, in > parseString > parser.Parse(string, True) > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, > column 0 ================================================= > > > i'm running Python 2.7.5+ on Ubuntu 13.10. > > Thanks. Looking into the data returned from the server: >>> data = urllib2.urlopen("http://api.worldbank.org/countries").read() >>> with open("tmp.dat", "w") as f: f.write(data) ... >>> [1]+ Angehalten python $ file tmp.dat tmp.dat: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT) OK, let's expand: $ fg python >>> import gzip, StringIO >>> expanded_data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read() >>> import xml.dom.minidom >>> xml.dom.minidom.parseString(expanded_data) There may be a way to uncompress the gzipped data transparently, but I'm too lazy to look it up... From python at mrabarnett.plus.com Thu Feb 13 15:19:26 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Feb 2014 20:19:26 +0000 Subject: XML parsing ExpatError with xml.dom.minidom at line 1, column 0 In-Reply-To: References: Message-ID: <52FD28CE.5080404@mrabarnett.plus.com> On 2014-02-13 20:10, Peter Otten wrote: > ming wrote: > >> Hi, >> i've a Python script which stopped working about a month ago. But until >> then, it worked flawlessly for months (if not years). A tiny >> self-contained 7-line script is provided below. >> >> i ran into an XML parsing problem with xml.dom.minidom and the error >> message is included below. The weird thing is if i used an XML validator >> on the web to validate against this particular URL directly, it is all >> good. Moreover, i saved the page source in Firefox or Chrome then >> validated against the saved XML file, it's also all good. >> >> Since the error happened at the very beginning of the input (line 1, >> column 0) as indicated below, i was wondering if this is an encoding >> mismatch. However, according to the saved page source in FireFox or >> Chrome, there is the following at the beginning: >> >> >> >> >> ================================================= >> #!/usr/bin/env python >> >> import urllib2 >> from xml.dom.minidom import parseString >> >> fd = urllib2.urlopen('http://api.worldbank.org/countries') >> data = fd.read() >> fd.close() >> dom = parseString(data) >> ================================================= >> >> >> >> ================================================= >> Traceback (most recent call last): >> File "./bugReport.py", line 9, in >> dom = parseString(data) >> File "/usr/lib/python2.7/xml/dom/minidom.py", line 1931, in parseString >> return expatbuilder.parseString(string) >> File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 940, in >> parseString >> return builder.parseString(string) >> File "/usr/lib/python2.7/xml/dom/expatbuilder.py", line 223, in >> parseString >> parser.Parse(string, True) >> xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, >> column 0 ================================================= >> >> >> i'm running Python 2.7.5+ on Ubuntu 13.10. >> >> Thanks. > > Looking into the data returned from the server: > >>>> data = urllib2.urlopen("http://api.worldbank.org/countries").read() >>>> with open("tmp.dat", "w") as f: f.write(data) > ... >>>> > [1]+ Angehalten python > $ file tmp.dat > tmp.dat: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT) > > OK, let's expand: > > $ fg > python > > >>>> import gzip, StringIO >>>> expanded_data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read() >>>> import xml.dom.minidom >>>> xml.dom.minidom.parseString(expanded_data) > > > There may be a way to uncompress the gzipped data transparently, but I'm too > lazy to look it up... > From a brief look at the docs, it looks like you can specify the format. For example, for JSON: fd = urlopen('http://api.worldbank.org/countries?format=json') From rosuav at gmail.com Thu Feb 13 15:29:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:29:40 +1100 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD1B01.80200@stoneleaf.us> Message-ID: On Fri, Feb 14, 2014 at 6:32 AM, Mark Lawrence wrote: >> There will be an exception only if it is zero-length. But good >> point! That's a pretty sneaky way to avoid checking for a >> zero-length string. Is it a popular idiom? >> > > I hope not. The use of slicing rather than indexing to avoid problems when the string's too short? I don't know about popular, but I've certainly used it a good bit. For the specific case of string comparisons you can use startswith/endswith, but slicing works with other types as well. Also worth noting: Python 2.7.4 (default, Apr 6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> s1,s2=b"asdf",u"asdf" >>> s1[:1],s2[:1] ('a', u'a') >>> s1[0],s2[0] ('a', u'a') Python 3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 16:23:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> s1,s2=b"asdf",u"asdf" >>> s1[:1],s2[:1] (b'a', 'a') >>> s1[0],s2[0] (97, 'a') When you slice, you get back the same type as you started with. (Also true of lists, tuples, and probably everything else that can be sliced.) When you index, you might not; strings are a special case (since Python lacks a "character" type), and if your code has to run on Py2 and Py3, byte strings stop being that special case in Py3. So if you're working with a byte string, it might be worth slicing rather than indexing. (Though you can still use startswith/endswith, if they suit your purpose.) ChrisA From rosuav at gmail.com Thu Feb 13 15:32:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:32:17 +1100 Subject: Using a subclass for __dict__ In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 7:07 AM, Demian Brecht wrote: > *Throws keyboard across the office* > > FFS. I could have SWORN I tried that (because I /know/ that a class is > an instance of its metaclass :/). An instance of looking at something > far too long without a fresh set of eyes. This is why we have mailing lists like this... because it's considered marginally less creepy than keeping a jar of fresh eyes on your desk. ChrisA http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=244695 From python.list at tim.thechases.com Thu Feb 13 15:39:27 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 13 Feb 2014 14:39:27 -0600 Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <20140213143927.51fa877c@bigbox.christie.dr> On 2014-02-13 10:37, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing > it, but then after further consideration I wasn't so sure. > > Some possibilities that occurred to me: > > if key.startswith('<') and key.endswith('>'): ... This is my favorite because it doesn't break on the empty string like some of your alternatives. Your k[0] and k[-1] assume there's at least one character in the string, otherwise an IndexError is raised. -tkc From roy at panix.com Thu Feb 13 15:44:37 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 15:44:37 -0500 Subject: Using a subclass for __dict__ References: Message-ID: In article , Chris Angelico wrote: > http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=244695 That seems badly specified. What if you kill a cyclops? Or a beholder? From rosuav at gmail.com Thu Feb 13 15:45:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:45:02 +1100 Subject: How to begin In-Reply-To: <2eb077bd-f74c-45c5-bef3-5f30916b2fcd@googlegroups.com> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <92b6e6be-7e55-41c9-81e6-22f494639aa0@googlegroups.com> <2eb077bd-f74c-45c5-bef3-5f30916b2fcd@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 4:34 AM, John Ladasky wrote: > On Thursday, February 13, 2014 7:06:03 AM UTC-8, pete suchsland wrote: > >> if x = 99: > > Surely, Pete, you meant to write "if x == 99:" ? Maybe. Or maybe he wanted the OP to do stuff that would result in exceptions, since exceptions are a way of life in Python! :) ChrisA From rosuav at gmail.com Thu Feb 13 15:55:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 07:55:18 +1100 Subject: Using a subclass for __dict__ In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 7:44 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=244695 > > That seems badly specified. What if you kill a cyclops? Or a beholder? That matter was dealt with by Doug Beyer in response to a reader letter. http://www.wizards.com/magic/magazine/Article.aspx?x=mtg/daily/stf/180 (scroll down to "Ocular Correctness") ChrisA From emile at fenx.com Thu Feb 13 15:55:35 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 13 Feb 2014 12:55:35 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2/13/2014 11:59 AM, Zachary Ware wrote: > In a fit of curiosity, I did some timings: Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) But I didn't see this one: s[::len(s)-1] Emile From beliavsky at aol.com Thu Feb 13 15:56:01 2014 From: beliavsky at aol.com (beliavsky at aol.com) Date: Thu, 13 Feb 2014 12:56:01 -0800 (PST) Subject: Python(x,y) interferes with earlier Numpy installation In-Reply-To: <8d25f041-4d53-428d-9701-24a1622a8d11@googlegroups.com> References: <8d25f041-4d53-428d-9701-24a1622a8d11@googlegroups.com> Message-ID: I fixed the problem by reinstalling Numpy. From rosuav at gmail.com Thu Feb 13 16:01:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 08:01:15 +1100 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 7:55 AM, Emile van Sebille wrote: > On 2/13/2014 11:59 AM, Zachary Ware wrote: >> >> In a fit of curiosity, I did some timings: > > > Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) > > But I didn't see this one: > > s[::len(s)-1] .... AAAAAAAAAAAAAAAAAAARGGGGGGGGGGHHHH! Really, I actually did pause, double-take, and then scream under my breath, when I saw that. Yes, it works. But please, if you EVER do this, save me the trouble and just submit your code to thedailywtf.com straight away! ChrisA From neilc at norwich.edu Thu Feb 13 16:01:10 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 21:01:10 +0000 (UTC) Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2014-02-13, Zachary Ware wrote: > In a fit of curiosity, I did some timings: > > 'and'ed indexing: > > C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" > 1000000 loops, best of 3: 0.35 usec per loop > > C:\tmp>py -m timeit -s "key = ''" > 1000000 loops, best of 3: 0.398 usec per loop > > C:\tmp>py -m timeit -s "key = 'test>'" "key[0] == '<' and key[-1] == '>'" > 1000000 loops, best of 3: 0.188 usec per loop > > C:\tmp>py -m timeit -s "key = 'test'" "key[0] == '<' and key[-1] == '>'" > 10000000 loops, best of 3: 0.211 usec per loop > > C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" > Traceback (most recent call last): > File "P:\Python34\lib\timeit.py", line 292, in main > x = t.timeit(number) > File "P:\Python34\lib\timeit.py", line 178, in timeit > timing = self.inner(it, self.timer) > File "", line 6, in inner > key[0] == '<' and key[-1] == '>' > IndexError: string index out of range The corrected version key and key[0] == '<' and key[-1] == '>' probably still wins the Pretty Unimportant Olympics. -- Neil Cerutti From __peter__ at web.de Thu Feb 13 16:06:31 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Feb 2014 22:06:31 +0100 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: Chris Angelico wrote: > On Fri, Feb 14, 2014 at 7:55 AM, Emile van Sebille wrote: >> On 2/13/2014 11:59 AM, Zachary Ware wrote: >>> >>> In a fit of curiosity, I did some timings: >> >> >> Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) >> >> But I didn't see this one: >> >> s[::len(s)-1] > > .... AAAAAAAAAAAAAAAAAAARGGGGGGGGGGHHHH! > > Really, I actually did pause, double-take, and then scream under my > breath, when I saw that. Yes, it works. But please, if you EVER do > this, save me the trouble and just submit your code to thedailywtf.com > straight away! For the record: >>> s = "x" >>> s[::len(s)-1] Traceback (most recent call last): File "", line 1, in ValueError: slice step cannot be zero From rosuav at gmail.com Thu Feb 13 16:10:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 08:10:44 +1100 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 8:06 AM, Peter Otten <__peter__ at web.de> wrote: > For the record: > >>>> s = "x" >>>> s[::len(s)-1] > Traceback (most recent call last): > File "", line 1, in > ValueError: slice step cannot be zero And that, my friends, is a classic example of a Python exception that ought to be a subclass of UnhingedProgrammerError. ChrisA From robert.kern at gmail.com Thu Feb 13 16:13:21 2014 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 13 Feb 2014 21:13:21 +0000 Subject: singleton ... again In-Reply-To: References: Message-ID: On 2014-02-13 20:03, Chris Angelico wrote: > On Fri, Feb 14, 2014 at 2:24 AM, Roy Smith wrote: >> In article , >> Chris Angelico wrote: >> >>> On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder >>> wrote: >>>> I still don't see it. To convince me that a singleton class makes sense, >>>> you'd have to explain why by virtue of the class's very nature, it never >>>> makes sense for there ever to be more than one of them. >>> >>> There's a huge difference, btw, between mutable and immutable >>> singletons. With immutables like None, True/False, integers, strings, >>> and tuples thereof, returning a preexisting object is just an >>> optimization. Do it if you want, don't if you don't, nobody's going to >>> hugely care. >> >> People *depend* on None being a singleton (and are encouraged to do so), >> when they use "is" as the test-for-Noneness. > > Circular argument, though. If None weren't a singleton, people would > use == to test for Noneness. Since it's been guaranteed to be > optimized to a singleton, the comparison can also be optimized, but > it's still just an optimization, as can be seen with integers. In > CPython, you could test for small integer equality using 'is', but > since that optimization isn't guaranteed, neither is that code > pattern. We don't use `is None` instead of `== None` for the speed. We use it for robustness. We don't want arbitrary __eq__()s to interfere with our sentinel tests. If None weren't a singleton that we could use as such a sentinel, we'd make one. -- 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 breamoreboy at yahoo.co.uk Thu Feb 13 16:14:09 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Feb 2014 21:14:09 +0000 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 13/02/2014 21:01, Neil Cerutti wrote: > On 2014-02-13, Zachary Ware wrote: >> In a fit of curiosity, I did some timings: >> >> 'and'ed indexing: >> >> C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" >> 1000000 loops, best of 3: 0.35 usec per loop >> >> C:\tmp>py -m timeit -s "key = ''" >> 1000000 loops, best of 3: 0.398 usec per loop >> >> C:\tmp>py -m timeit -s "key = 'test>'" "key[0] == '<' and key[-1] == '>'" >> 1000000 loops, best of 3: 0.188 usec per loop >> >> C:\tmp>py -m timeit -s "key = 'test'" "key[0] == '<' and key[-1] == '>'" >> 10000000 loops, best of 3: 0.211 usec per loop >> >> C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" >> Traceback (most recent call last): >> File "P:\Python34\lib\timeit.py", line 292, in main >> x = t.timeit(number) >> File "P:\Python34\lib\timeit.py", line 178, in timeit >> timing = self.inner(it, self.timer) >> File "", line 6, in inner >> key[0] == '<' and key[-1] == '>' >> IndexError: string index out of range > > The corrected version > > key and key[0] == '<' and key[-1] == '>' > > probably still wins the Pretty Unimportant Olympics. > Exactly how I'd write it. To me it wins awards for being most boring and most obvious, obviously YMMV or we wouldn't be having this discussion. Or argument. Or contradiction :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From zachary.ware+pylist at gmail.com Thu Feb 13 16:19:52 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 13 Feb 2014 15:19:52 -0600 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 2:55 PM, Emile van Sebille wrote: > On 2/13/2014 11:59 AM, Zachary Ware wrote: >> >> In a fit of curiosity, I did some timings: > > > Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) > > But I didn't see this one: > > s[::len(s)-1] It's not great, around 0.520 usec (the builtin lookup and function call is what gets it). Also, uglier than sin itself. -- Zach From zachary.ware+pylist at gmail.com Thu Feb 13 16:20:09 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 13 Feb 2014 15:20:09 -0600 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 3:01 PM, Neil Cerutti wrote: > On 2014-02-13, Zachary Ware wrote: >> C:\tmp>py -m timeit -s "key = ''" "key[0] == '<' and key[-1] == '>'" >> Traceback (most recent call last): >> File "P:\Python34\lib\timeit.py", line 292, in main >> x = t.timeit(number) >> File "P:\Python34\lib\timeit.py", line 178, in timeit >> timing = self.inner(it, self.timer) >> File "", line 6, in inner >> key[0] == '<' and key[-1] == '>' >> IndexError: string index out of range > > The corrected version > > key and key[0] == '<' and key[-1] == '>' > > probably still wins the Pretty Unimportant Olympics. Indeed, see the last set of timings and moral ;) -- Zach From emile at fenx.com Thu Feb 13 16:23:20 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 13 Feb 2014 13:23:20 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2/13/2014 1:10 PM, Chris Angelico wrote: > On Fri, Feb 14, 2014 at 8:06 AM, Peter Otten <__peter__ at web.de> wrote: >> For the record: >> >>>>> s = "x" >>>>> s[::len(s)-1] >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: slice step cannot be zero > > And that, my friends, is a classic example of a Python exception that > ought to be a subclass of UnhingedProgrammerError. > And certainly s[::len(s)-1 or 1] isn't any better. :) Emile From roy at panix.com Thu Feb 13 16:24:35 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 16:24:35 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article , Emile van Sebille wrote: > On 2/13/2014 11:59 AM, Zachary Ware wrote: > > In a fit of curiosity, I did some timings: > > Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) > > But I didn't see this one: > > s[::len(s)-1] > > Emile I love it. I need to add this to my list of Python trivia questions. From rosuav at gmail.com Thu Feb 13 16:27:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 08:27:49 +1100 Subject: singleton ... again In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 8:13 AM, Robert Kern wrote: > We don't use `is None` instead of `== None` for the speed. We use it for > robustness. We don't want arbitrary __eq__()s to interfere with our sentinel > tests. If None weren't a singleton that we could use as such a sentinel, > we'd make one. Sure. Yes, its identity is important as part of its being the Python equivalent of C's null pointer. But the main point of singletons is to be able to be "instantiated" without creating new elements; the sentinel status of None is no different from the classic way of recognizing the presence of an argument: _SENTINEL = object() def foo(arg1, arg2=_SENTINEL): if arg2 is not _SENTINEL: do_stuff_with(arg2) That's not a singleton in that sense; it's just a unique object. You could use [] for that instead of object() and it would work just the same. So None is serving multiple purposes: it's an empty object, but it's also a sentinel. In many uses, it wouldn't be a problem to have more Nones floating around, hence it's mostly like your classic singleton. My main point about mutable vs immutable is more clearly seen with integers and strings. Some integers are cached; some strings are interned; nobody particularly cares about the exact boundaries, except when playing around with id() or introspection of some sort. ChrisA From martin.schoon at gmail.com Thu Feb 13 16:27:13 2014 From: martin.schoon at gmail.com (Martin =?UTF-8?Q?Sch=C3=B6=C3=B6n?=) Date: 13 Feb 2014 21:27:13 GMT Subject: better and user friendly IDE recommended? References: <091bbe36-8cf9-412f-b7e9-2b3cc89dd363@googlegroups.com> Message-ID: Den 2013-09-17 skrev rusi : > On Wednesday, September 11, 2013 7:44:04 PM UTC+5:30, > mnishpsyched wrote: >> Hey i am a programmer but new to python. Can anyone guide >> me in knowing which is a better IDE used to develop web >> related apps that connect to DB using python? > > Just saw this > http://www.youtube.com/watch?v=1-dUkyn_fZA > > Yeah... scientific programming and web programming are hardly the same :-) > Still it might be worth 20 minutes of your time I have started testing this. It is early days so too early to pass judgement. Anyone out there using Emacs + Python + Orgmode like this? I might to need ask some questions :-) /Martin From sg552 at hotmail.co.uk Thu Feb 13 16:29:37 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Thu, 13 Feb 2014 21:29:37 +0000 Subject: Working with the set of real numbers In-Reply-To: <871tz7864a.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: What's this? A discussion about angels dancing on a the head of a pin? Great, I'm in. On 13/02/2014 14:00, Marko Rauhamaa wrote: > Oscar Benjamin : > >> This isn't even a question of resource constraints: a digital computer >> with infinite memory and computing power would still be limited to >> working with countable sets, and the real numbers are just not >> countable. The fundamentally discrete nature of digital computers >> prevents them from being able to truly handle real numbers and real >> computation. > > Well, if your idealized, infinite, digital computer had ?? bytes of RAM > and ran at ?? hertz and Python supported transfinite iteration, you > could easily do reals: > > def real_sqrt(y): > for x in continuum(0, max(1, y)): > # Note: x is not traversed in the < order but some other > # well-ordering, which has been proved to exist. > if x * x == y: > return x > assert False > > The function could well return in finite time with a precise result for > any given nonnegative real argument. Minor point: ?? does not mean the cardinality c of the continuum, it means the smallest cardinal larger than ??. It has been proved that the question of whether ?? == c is independent of ZFC, so it is in a sense unanswerable. More importantly, though, such a computer could not complete the above iteration in finite time unless time itself is not real-valued. That's because if k is an uncountable ordinal then there is no strictly order-preserving function from k to the unit interval [0, 1]. For suppose otherwise, and let f be such a function. Let S denote the set of successor ordinals in k, and let L denote the set of limit ordinals in k. Then lambda x: x + 1 is an injective function from L (or L with a single point removed if k is the successor of a limit ordinal) to S, so that S is at least as large as L and since k == S | L it follows that S is uncountable. For each x + 1 in S, let g(x + 1) = f(x + 1) - f(x) > 0. Let F be any finite subset of S and let y = max(F). It is clear that f(y) >= sum(g(x) for x in F). Since also f(y) <= 1, we have sum(g(x) for x in F) if <= 1 for all finite F. In particular, for any integer n > 0, the set S_n = {x for x in S if g(x) > 1/n} has len(S_n) < n. But then S is the union of the countable collection {S_n for n in N} of finite sets, so is countable; a contradiction. On 13/02/2014 19:47, Marko Rauhamaa wrote: > My assumption was you could execute ?? statements per second. That > doesn't guarantee a finite finish time but would make it possible. That > is because > > ?? * ?? = ?? = ?? * 1 I don't think that's enough - assuming the operations of your processor during a second can be indexed by some ordinal k with len(k) == c, if each of the c operations per iteration must be complete before the next step of the for loop is complete then you need an injective function from c * c to k that preserves the lexicographic ordering. I don't know whether such a function exists for arbitrary such k, but k can be chosen in advance so that it does. From rosuav at gmail.com Thu Feb 13 16:31:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 08:31:11 +1100 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 8:19 AM, Zachary Ware wrote: > Also, uglier than sin itself. Hey hey, no need to insult our lovely trigonometric functions! ChrisA From martin.schoon at gmail.com Thu Feb 13 16:31:45 2014 From: martin.schoon at gmail.com (Martin =?UTF-8?Q?Sch=C3=B6=C3=B6n?=) Date: 13 Feb 2014 21:31:45 GMT Subject: Python(x,y) interferes with earlier Numpy installation References: <8d25f041-4d53-428d-9701-24a1622a8d11@googlegroups.com> Message-ID: Den 2014-02-13 skrev beliavsky at aol.com : > I fixed the problem by reinstalling Numpy. Good. Just one note since I happened to look into updating Python(x,y) at work today and stumbled on this: The Python(x,y) guys recommend that one removes other Python installations prior to installing Python(x,y) or there may be interference. /Martin From roy at panix.com Thu Feb 13 16:38:00 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 16:38:00 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article , Chris Angelico wrote: > On Fri, Feb 14, 2014 at 8:19 AM, Zachary Ware > wrote: > > Also, uglier than sin itself. > > Hey hey, no need to insult our lovely trigonometric functions! This newsgroup is taylor made for that kind of abuse. From zachary.ware+pylist at gmail.com Thu Feb 13 16:47:12 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 13 Feb 2014 15:47:12 -0600 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 3:31 PM, Chris Angelico wrote: > On Fri, Feb 14, 2014 at 8:19 AM, Zachary Ware > wrote: >> Also, uglier than sin itself. > > Hey hey, no need to insult our lovely trigonometric functions! Here's your sine... -- Zach From storchaka at gmail.com Thu Feb 13 16:49:15 2014 From: storchaka at gmail.com (Serhiy Storchaka) Date: Thu, 13 Feb 2014 23:49:15 +0200 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: 13.02.14 21:59, Zachary Ware ???????(??): > don't use re for simple stuff (because while it may be very fast, it's > dominated by attribute lookup and function call overhead), And the time of re variant depends on the size of input. From roy at panix.com Thu Feb 13 16:51:50 2014 From: roy at panix.com (Roy Smith) Date: Thu, 13 Feb 2014 16:51:50 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article , Serhiy Storchaka wrote: > 13.02.14 21:59, Zachary Ware ??????????????(????): > > don't use re for simple stuff (because while it may be very fast, it's > > dominated by attribute lookup and function call overhead), > > And the time of re variant depends on the size of input. That's a good point. It's nice, for a change, to see somebody shoot down a regex solution for a valid reason :-) From ethan at stoneleaf.us Thu Feb 13 16:33:47 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 13:33:47 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD3A3B.1060300@stoneleaf.us> On 02/13/2014 01:01 PM, Chris Angelico wrote: > On Fri, Feb 14, 2014 at 7:55 AM, Emile van Sebille wrote: >> On 2/13/2014 11:59 AM, Zachary Ware wrote: >>> >>> In a fit of curiosity, I did some timings: >> >> >> Snip of lots of TMTOWTDT/TIMTOWTDI/whatever... timed examples :) >> >> But I didn't see this one: >> >> s[::len(s)-1] > > .... AAAAAAAAAAAAAAAAAAARGGGGGGGGGGHHHH! > > Really, I actually did pause, double-take, and then scream under my > breath, when I saw that. Yes, it works. But please, if you EVER do > this, save me the trouble and just submit your code to thedailywtf.com > straight away! Oh, it's not that bad! All you have to do is handle the edge case of an empty string: s[::len(s)-1 if s else True] *ducks and runs* -- ~Ethan~ From ian.g.kelly at gmail.com Thu Feb 13 17:00:05 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Feb 2014 15:00:05 -0700 Subject: PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!) In-Reply-To: <52fc45e6$0$11128$c3e8da3@news.astraweb.com> References: <85c2698c-d681-4511-b111-bb1e549ece93@googlegroups.com> <52f9c392$0$11128$c3e8da3@news.astraweb.com> <52fc45e6$0$11128$c3e8da3@news.astraweb.com> Message-ID: On Feb 12, 2014 9:16 PM, "Steven D'Aprano" wrote: > > On Tue, 11 Feb 2014 07:36:34 -0800, Travis Griggs wrote: > > > On Feb 10, 2014, at 10:30 PM, Steven D'Aprano > > wrote: > > > > > >>> 1. Parenthesis should not be required for parameter- less > >>> functions. > >> > >> Of course they should. Firstly, parameter-less functions are a code- > >> smell, and ought to be discouraged. Secondly, even if you have a good > >> reason for using one -- for example, random.random -- then the > >> difference between referring to the object and calling the object > >> should be clear. > > > > Interesting. Can you clarify or provide some links to the > > "parameter-less functions are a code-smell" bit? > > > Functions map a value to another value. They can be one-to-one, or many- > to-one. (Mathematically, they cannot be one-to-many or many-to-many, > that's called a relation.) What about zero-to-one? > > If the function always returns the same result, e.g.: > > def spam(): > return "spam spam spam" That's still one-to-one. There is no such thing as a zero-to-one mapping. Mathematical functions map a single value to a single value. To represent multi-argument functions then, the single input takes on the value of an ordered sequence. The input value of a 0-argument function then is the empty sequence. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko at pacujo.net Thu Feb 13 17:00:37 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 00:00:37 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: <877g8y7jwa.fsf@elektro.pacujo.net> Rotwang : >> for x in continuum(0, max(1, y)): >> # Note: x is not traversed in the < order but some other >> # well-ordering, which has been proved to exist. >> if x * x == y: >> return x > > [...] > > More importantly, though, such a computer could not complete the above > iteration in finite time unless time itself is not real-valued. That's > because if k is an uncountable ordinal then there is no strictly > order-preserving function from k to the unit interval [0, 1]. If you read the code comment above, the transfinite iterator yields the whole continuum, not in the < order (which is impossible), but in some other well-ordering (which is known to exist). Thus, we can exhaust the continuum in ?? discrete steps. (Yes, the continuum hypothesis was used to make the notation easier to read.) Marko From rosuav at gmail.com Thu Feb 13 17:13:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 09:13:28 +1100 Subject: A curious bit of code... In-Reply-To: <52FD3A3B.1060300@stoneleaf.us> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD3A3B.1060300@stoneleaf.us> Message-ID: On Fri, Feb 14, 2014 at 8:33 AM, Ethan Furman wrote: > Oh, it's not that bad! All you have to do is handle the edge case of an > empty string: > > s[::len(s)-1 if s else True] > > *ducks and runs* And the edge case of the one-character string. Also, it's been noted that calling the built-in function len() is slow, so I propose changing that. s[::(sys.getsizeof("\N{MATHEMATICAL BOLD CAPITAL L}"+s)-sys.getsizeof("\N{MATHEMATICAL BOLD CAPITAL E}\N{MATHEMATICAL BOLD CAPITAL N}") or 4)//4] Note the elegance of using the word LEN across two string literals (because string literals are fast) as a means of clearly describing what we are doing - an optimization of the built-in len() function. ChrisA From torriem at gmail.com Thu Feb 13 17:22:55 2014 From: torriem at gmail.com (Michael Torrie) Date: Thu, 13 Feb 2014 15:22:55 -0700 Subject: Wait... WHAT? In-Reply-To: <8778c4cc-334b-4254-aed7-0f33acbf1d8f@googlegroups.com> References: <6c76ef4e-8c7c-4199-b30d-c4d55c1061c8@googlegroups.com> <20140212161427.0a9843d5@bigbox.christie.dr> <20140212184432.1df9b491@bigbox.christie.dr> <20140212212953.458b810a@bigbox.christie.dr> <8778c4cc-334b-4254-aed7-0f33acbf1d8f@googlegroups.com> Message-ID: <52FD45BF.9040500@gmail.com> On 02/13/2014 10:46 AM, eneskristo at gmail.com wrote: > Can we please revert back to the original problem? > def save(): > target = open ("save.swroc", 'w') > target.write([counter, loop, number_of_competitors, competitors]) ^^^^^^^^^ Have you tried to run this code? Does it even produce a file? On my python it says that write() is expecting a string on Python 3, or a character buffer object on Python 2.7. Have you broken out the code into a minimal, standalone file you can work on? > def load(): > the_array = list(open("save.swroc", 'r')) ^^^^^^^^^^^ That's better. You know it reads in the text file one line at a time into a list right? This would work if your file was actually written with one variable in text form on each line. > the_array = target ^^^^^^^^^^ You have now reassigned the_array to an undefined object. If target is defined somewhere (I can't see that it is here in your code snippet), then you've now lost the array of lines you just read in. > counter = the_array[0] > loop = the_array[1] > number_of_competitors = the_array[2] > competitors = the_array[3] > Is this better? Well it doesn't run, so we can't say it's better. A couple of points/questions/hints/suggestions: 1. make a minimal, complete, example of what you are trying to do. Code you can run without the rest of your program. 2. What are your variables, "counter," "loop," "number_of_competitors," "competitors?" 3. What format is the file supposed to be in? 4. If you pullup the file in an editor does it look right? (IE do you know what the output from your save function actually looks like?) 5. If you're dealing with numbers, remember the text file has no concept of numbers. You'll have to parse them from text when you read them. 6. Consider using the pickle module if you really want to store and load python objects without encoding and decoding a text file. Hope this helps. From sg552 at hotmail.co.uk Thu Feb 13 17:21:40 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Thu, 13 Feb 2014 22:21:40 +0000 Subject: Working with the set of real numbers In-Reply-To: <877g8y7jwa.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <877g8y7jwa.fsf@elektro.pacujo.net> Message-ID: On 13/02/2014 22:00, Marko Rauhamaa wrote: > Rotwang : > >>> for x in continuum(0, max(1, y)): >>> # Note: x is not traversed in the < order but some other >>> # well-ordering, which has been proved to exist. >>> if x * x == y: >>> return x >> >> [...] Restoring for context: >>> The function could well return in finite time with a precise result >>> for any given nonnegative real argument. >> More importantly, though, such a computer could not complete the above >> iteration in finite time unless time itself is not real-valued. That's >> because if k is an uncountable ordinal then there is no strictly >> order-preserving function from k to the unit interval [0, 1]. > > If you read the code comment above, the transfinite iterator yields the > whole continuum, not in the < order (which is impossible), but in some > other well-ordering (which is known to exist). Thus, we can exhaust the > continuum in ?? discrete steps. Yes, I understood that. But my point was that it can't carry out those ?? discrete steps in finite time (assuming that time is real-valued), because there's no way to embed them in any time interval without changing their order. Note that this is different to the case of iterating over a countable set, since the unit interval does have countable well-ordered subsets. From cs at zip.com.au Thu Feb 13 17:25:07 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 14 Feb 2014 09:25:07 +1100 Subject: How to begin In-Reply-To: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> Message-ID: <20140213222507.GA45957@cskk.homeip.net> On 13Feb2014 05:18, weixixiao <7441980 at gmail.com> wrote: > http://www.codecademy.com > > I have learned the basic rules of Python in this website. > What should I do next?where to go? > I download the Pycharm the free version and I think I dunno how to use it except a "Hello world" It helps to have something you want done. Find something small you'd like to do. Do it in Python. If you already have a collection of small scripts, try rewriting some in Python. Start small. As you skill grows, work up. Cheers, -- Cameron Simpson Death before dishonor / Drugs before lunch. - Aspen Gun and Drug Club From ethan at stoneleaf.us Thu Feb 13 17:26:12 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 14:26:12 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <52FD3A3B.1060300@stoneleaf.us> Message-ID: <52FD4684.2000101@stoneleaf.us> On 02/13/2014 02:13 PM, Chris Angelico wrote: > On Fri, Feb 14, 2014 at 8:33 AM, Ethan Furman wrote: >> Oh, it's not that bad! All you have to do is handle the edge case of an >> empty string: >> >> s[::len(s)-1 if s else True] > > And the edge case of the one-character string. Oops, my description should have said "edge case of a one-character string". The empty string needs no extra handling. -- ~Ethan~ From invalid at invalid.invalid Thu Feb 13 17:28:04 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 13 Feb 2014 22:28:04 +0000 (UTC) Subject: singleton ... again References: Message-ID: On 2014-02-13, Roy Smith wrote: > I envision SerialPort being a thin layer on top of a bunch of > OS-specific system calls to give them a pythonic interface. Yep, that's pretty much what pyserial is http://pyserial.sourceforge.net/ > Things like is_shutdown() and set_bit_rate() presumably turn into > ioctls. No need to have any state at all beyond a file descriptor. There are OS-dependent things that it's handy to cache in the object (e.g. a Posix port's current termios settings). It can eliminate a lot of ioctl() calls if the app spends a lot of time doing things like messing with modem control lines. The savings in ioctl() calls may not be worth worrying about, but it's actually simpler/easier to write that way. OTOH, caching the termios settings it can cause breakage if two different processes or port objects are messing with the configuration of a single port. People who do that are just begging for breakage anyway, so they get no sympathy from me... -- Grant Edwards grant.b.edwards Yow! I smell a RANCID at CORN DOG! gmail.com From ben+python at benfinney.id.au Thu Feb 13 17:31:55 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Feb 2014 09:31:55 +1100 Subject: How to begin References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <20140213222507.GA45957@cskk.homeip.net> Message-ID: <854n428x0k.fsf@benfinney.id.au> Cameron Simpson writes: > On 13Feb2014 05:18, weixixiao <7441980 at gmail.com> wrote: > > I have learned the basic rules of Python in this website. > > What should I do next?where to go? > > It helps to have something you want done. > > Find something small you'd like to do. Do it in Python. Good advice. Alternatively, there is a whole tutorial of exercises with the things to do already existing . Start at the beginning, work through each exercise ? *do* them and experiment until you understand them ? before continuing. Ask questions if your experiments leave you confused, and be prepared to show what exercise you're doing and the code of your experiment. By the end of the tutorial you'll have a solid grasp of all of Python. -- \ ?If you pick up a starving dog and make him prosperous, he will | `\ not bite you. This is the principal difference between a dog | _o__) and a man.? ?Mark Twain, _Pudd'n'head Wilson_ | Ben Finney From marko at pacujo.net Thu Feb 13 18:16:11 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 01:16:11 +0200 Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <877g8y7jwa.fsf@elektro.pacujo.net> Message-ID: <8738jm7gec.fsf@elektro.pacujo.net> Rotwang : > But my point was that it can't carry out those ?? discrete steps in > finite time (assuming that time is real-valued), because there's no > way to embed them in any time interval without changing their order. I'd have to think so I take your word for it. Marko From larry.martell at gmail.com Thu Feb 13 13:03:04 2014 From: larry.martell at gmail.com (Larry Martell) Date: Thu, 13 Feb 2014 13:03:04 -0500 Subject: Welcome to the Internet. No one here likes you. (was: Newcomer Help) In-Reply-To: <84fcf77d-4c82-4f04-b5d6-608e31bf6aa3@googlegroups.com> References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> <84fcf77d-4c82-4f04-b5d6-608e31bf6aa3@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 12:49 PM, John Ladasky wrote: > On Thursday, February 13, 2014 8:32:46 AM UTC-8, Larry.... at gmail.com wrote: > >> This reminds me of post that was circulating in the early 90's: >> >> Welcome to the Internet. >> >> No one here likes you. >> >> We're going to offend, insult, abuse, and belittle the living hell out >> of you. And when you rail against us with "FUCK YOU YOU GEEK WIMP >> SKATER GOTH LOSER PUNK FAG BITCH!1!!", we smile to ourselves. We laugh >> at you because you don't get it. Then we turn up the heat, hoping to >> draw more entertainment from your irrational fuming. > [snip] > > Ummm... Larry, I hope you are just posting this rant because Rustom Mody's remarks reminded you of it. Yes, that is why I posted it. > I hope that you do not personally subscribe to this behavior. No, not any more. But that rant is a somewhat tongue in cheek look back at how things were back in the day. > Yes, I too was a bullied nerd when I was young. I don't use my history as an excuse to do unto others what was done unto me. No one should. No one should bully another person, period. It's not "entertainment," it's a deeply harmful practice, and does not deserve any respect. Back in the day I was both a major flamer and flamee. I did enjoy being the flamer and I laughed at being flamed. And I don't equate that with being bullied in any way (which I was when I was a kid). But I am older and kinder nowadays and have better things to do with my time. From rymg19 at gmail.com Thu Feb 13 17:50:40 2014 From: rymg19 at gmail.com (Ryan Gonzalez) Date: Thu, 13 Feb 2014 16:50:40 -0600 Subject: How to begin In-Reply-To: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> Message-ID: <52FD4C40.9050001@gmail.com> On 02/13/2014 07:18 AM, weixixiao wrote: > http://www.codecademy.com > > I have learned the basic rules of Python in this website. > > What should I do next?where to go? > > I download the Pycharm the free version and I think I dunno how to use it except a "Hello world" > Read the Python reference. I know it's long, but it saves you trouble of accidentally reinventing the wheel. -- --Ryan If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated." -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Feb 13 19:29:33 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Feb 2014 19:29:33 -0500 Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: On 2/13/2014 1:37 PM, forman.simon at gmail.com wrote: > I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. > > if key[:1] + key[-1:] == '<>': ... if key[:1] == '<' and key[-1:] == '>: ... is the obvious choice to me. If the first clause is false, it never computes the second. -- Terry Jan Reedy From ethan at stoneleaf.us Thu Feb 13 19:23:40 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Feb 2014 16:23:40 -0800 Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <52FD620C.3010702@stoneleaf.us> On 02/13/2014 01:24 PM, Roy Smith wrote: > Emile van Sebille wrote: >> >> But I didn't see this one: >> >> s[::len(s)-1] > > I love it. I need to add this to my list of Python trivia questions. Great interview question: What does this do? What is its weakness? How would you fix it? -- ~Ethan~ From ben+python at benfinney.id.au Thu Feb 13 19:57:53 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Feb 2014 11:57:53 +1100 Subject: How to begin References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <52FD4C40.9050001@gmail.com> Message-ID: <85zjlu7bou.fsf@benfinney.id.au> Ryan Gonzalez writes: > Read the Python reference. I know it's long, but it saves you trouble > of accidentally reinventing the wheel. Hmm, the language reference is targeted at people *implementing* Python, not people who are learning to use it (though it is valuable for them also). It would be rather overwhelming for a beginner, IMO. You should instead be directing newcomers to beginner documentation, such as and especially the Python tutorial . -- \ ?If you get invited to your first orgy, don't just show up | `\ nude. That's a common mistake. You have to let nudity | _o__) ?happen.?? ?Jack Handey | Ben Finney From forman.simon at gmail.com Thu Feb 13 21:45:16 2014 From: forman.simon at gmail.com (forman.simon at gmail.com) Date: Thu, 13 Feb 2014 18:45:16 -0800 (PST) Subject: A curious bit of code... In-Reply-To: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: <839842ff-e0d4-4bec-93fa-b8c25b3ca471@googlegroups.com> For the record I wasn't worried about the performance. ;-) It was for Tkinter event strings not markup tags. I'm glad this was the time winner! "key and key[0] == '<' and key[-1] == '>'" Cheers to the folks who did the timings (and saved me from the trouble!) Last but not least... s[::len(s)-1] omg!!? ;-D From jdoe at usenetlove.invalid Thu Feb 13 22:17:36 2014 From: jdoe at usenetlove.invalid (John Doe) Date: Fri, 14 Feb 2014 03:17:36 +0000 (UTC) Subject: Pythonwin forum? Message-ID: What's the best place for asking questions about the Pythonwin IDE? I'm a novice programmer, so in an effort to be more clear I'm talking about the program at this path on my hard drive... C:\Python27\Lib\site-packages\pythonwin\Pythonwin.exe It appears to be an editor and a compiler. I have some questions about the color scheme. I'd like light/white text on a black background. I realize you can manually change the colors, but I'd like to find out if anyone has a good starting point. I don't see any obvious places on the Internet to ask. Thanks. From ned at nedbatchelder.com Thu Feb 13 22:26:48 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 13 Feb 2014 22:26:48 -0500 Subject: A curious bit of code... In-Reply-To: <839842ff-e0d4-4bec-93fa-b8c25b3ca471@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <839842ff-e0d4-4bec-93fa-b8c25b3ca471@googlegroups.com> Message-ID: On 2/13/14 9:45 PM, forman.simon at gmail.com wrote: > For the record I wasn't worried about the performance. ;-) > > It was for Tkinter event strings not markup tags. > > I'm glad this was the time winner! > > "key and key[0] == '<' and key[-1] == '>'" > > > Cheers to the folks who did the timings (and saved me from the trouble!) > > Last but not least... s[::len(s)-1] omg!!? ;-D > If you aren't worried about performance, why are you choosing your code based on which is the fastest? There are other characteristics (clarity, flexibility, robustness, ...) that could be more useful. -- Ned Batchelder, http://nedbatchelder.com From rvernucio at gmail.com Thu Feb 13 22:30:05 2014 From: rvernucio at gmail.com (Renato) Date: Thu, 13 Feb 2014 19:30:05 -0800 (PST) Subject: Problem importing libraries installed with PIP in Eclipse Message-ID: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Hi guys, I'm using Python 2.7.5 64 bits and I have a problem when importing libraries that were installed via PIP when importing them inside Eclipse (version 4.3.1). Outside Eclipse (directly in Python's shell) everything works fine, here is an example: >>> import numpy # installed from repositories >>> from numpy import array >>> import pybrain # installed via PIP >>> from pybrain import Network >>> Everything works outside Eclipse. But inside Eclipse I can't import libraries installed via PIP using "from x import y" format, it will give an error. The only way I can import libraries installed via PIP is using "import x" format. Here is an example: import numpy # no errors (installed from repositories) from numpy import array # no errors import pybrain # no errors (installed via PIP) from pybrain import Network # gives the error below Traceback (most recent call last): File "/media/arquivos/pybrain_import_test.py", line 4, in from pybrain import Network ImportError: cannot import name Network I suspected it could be related to virtualenv, but here is a print screen (http://imageshack.com/a/img534/4307/3x0m.png) of my Python's PATH. The directory /usr/lib/python2.7/site-packages where PyBrain is installed is already in Python's PATH inside Eclipse. Could someone help me, please? From rustompmody at gmail.com Thu Feb 13 22:52:23 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 13 Feb 2014 19:52:23 -0800 (PST) Subject: better and user friendly IDE recommended? In-Reply-To: References: <091bbe36-8cf9-412f-b7e9-2b3cc89dd363@googlegroups.com> Message-ID: <7eab4785-4db6-416f-9bc2-56470ab9d7db@googlegroups.com> On Friday, February 14, 2014 2:57:13 AM UTC+5:30, Martin Sch??n wrote: > Den 2013-09-17 skrev rusi > > On Wednesday, September 11, 2013 7:44:04 PM UTC+5:30, > > mnishpsyched wrote: > >> Hey i am a programmer but new to python. Can anyone guide > >> me in knowing which is a better IDE used to develop web > >> related apps that connect to DB using python? > > Just saw this > > http://www.youtube.com/watch?v=1-dUkyn_fZA > > Yeah... scientific programming and web programming are hardly the same :-) > > Still it might be worth 20 minutes of your time > I have started testing this. It is early days so too early to pass > judgement. > Anyone out there using Emacs + Python + Orgmode like this? > I might to need ask some questions :-) The speaker -- Kitchin -- is quite active on the org mode list. And a bunch of other babel users. You should try there. And please do report back your findings! From greg.ewing at canterbury.ac.nz Fri Feb 14 00:06:44 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 14 Feb 2014 18:06:44 +1300 Subject: singleton ... again In-Reply-To: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> References: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote: > >>If you really want to make sure nobody creates another instance by >>accident, delete the class out of the namespace after instantiating it. > > That does not work. It is trivial to get the type from an instance: I said *by accident*. Of course it's nearly impossible to prevent someone who is determined enough from making another instance, but it will prevent them from doing so by mistake, if, e.g. they fail to notice the line in the docs that says "don't try to instantiate this directly, use the factory function". -- Greg From greg.ewing at canterbury.ac.nz Fri Feb 14 00:15:21 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 14 Feb 2014 18:15:21 +1300 Subject: singleton ... again In-Reply-To: <52fc490d$0$11128$c3e8da3@news.astraweb.com> References: <52fc34e5$0$11128$c3e8da3@news.astraweb.com> <52fc490d$0$11128$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Of course it can happen by accident. It's happened to me, where I've > accidentally called NoneType() (which raises, rather than returning a new > instance). Well, "unlikely to happen by accident", then. -- Greg From greg.ewing at canterbury.ac.nz Fri Feb 14 00:21:40 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 14 Feb 2014 18:21:40 +1300 Subject: singleton ... again In-Reply-To: References: Message-ID: Ethan Furman wrote: > Say you have a class that represents serial ports or your computer. You > should get the same object every time you ask for SerialPort(2). No, you shouldn't ask for SerialPort(2) at all, you should call get_serial_port(2). Then you won't be fooled into thinking that you're creating an independent object each time. -- Greg From greg.ewing at canterbury.ac.nz Fri Feb 14 00:26:03 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 14 Feb 2014 18:26:03 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <8761okcx8z.fsf@elektro.pacujo.net> <87txc4bers.fsf@elektro.pacujo.net> Message-ID: Dave Angel wrote: > Actually, the particular example you use can be done. When > printing the infinite sum of two infinite decimal streams, you > can simply hold back whenever you get one or more nines. But you only have a finite amount of space for keeping track of how many nines you've seen, so there will be some inputs with more nines than you can handle. (Infinitely many such inputs, in fact!) -- Greg From jeanpierreda at gmail.com Fri Feb 14 01:05:18 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 13 Feb 2014 22:05:18 -0800 Subject: Working with the set of real numbers In-Reply-To: <87fvnm7q1n.fsf@elektro.pacujo.net> References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <87fvnm7q1n.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 13, 2014 at 11:47 AM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Fri, Feb 14, 2014 at 1:00 AM, Marko Rauhamaa wrote: >>> Well, if your idealized, infinite, digital computer had ?? bytes of RAM >>> and ran at ?? hertz and Python supported transfinite iteration, you >>> could easily do reals: >>> >>> for x in continuum(0, max(1, y)): >> >> How exactly do you iterate over a continuum, with a digital computer? > > How "digital" our idealized computers are is a matter for a debate. > However, iterating over the continuum is provably "possible:" > > http://en.wikipedia.org/wiki/Transfinite_induction You missed the most important point on that page, which is the "limit case". There is no way to iterate over all the reals one at a time, no matter how fast you execute instructions. If you could, it would be trivial to show that the reals have the same cardinality as the positive integers: correspond n with the whatever is returned by the nth call to it.next. It doesn't matter if you call your magical iterator "transfinite", that doesn't make it so. -- Devin From greg.ewing at canterbury.ac.nz Fri Feb 14 01:37:12 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 14 Feb 2014 19:37:12 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: Chris Angelico wrote: > Even adding to your requirements that it have an ?? Hz bus (which, by > the way, I *totally* want - the uses are endless), it would take a > finite amount of time to assign to x the "next number", ergo your > algorithm can't guarantee to finish in finite time. If it's a quantum computer, it may be able to execute all branches of the iteration in parallel. But it would only have a probability of returning the right answer (in other cases it would kill your cat). -- Greg From rosuav at gmail.com Fri Feb 14 01:44:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Feb 2014 17:44:31 +1100 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 14, 2014 at 5:37 PM, Gregory Ewing wrote: > Chris Angelico wrote: >> >> Even adding to your requirements that it have an ?? Hz bus (which, by >> the way, I *totally* want - the uses are endless), it would take a >> >> finite amount of time to assign to x the "next number", ergo your >> algorithm can't guarantee to finish in finite time. > > > If it's a quantum computer, it may be able to execute > all branches of the iteration in parallel. But it > would only have a probability of returning the right > answer (in other cases it would kill your cat). Oh, that's fine, he's not my cat anyway. Go ahead, build it. ChrisA From mail at timgolden.me.uk Fri Feb 14 03:16:57 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 14 Feb 2014 08:16:57 +0000 Subject: Pythonwin forum? In-Reply-To: References: Message-ID: <52FDD0F9.9050609@timgolden.me.uk> On 14/02/2014 03:17, John Doe wrote: > What's the best place for asking questions about the Pythonwin > IDE? > > I'm a novice programmer, so in an effort to be more clear I'm > talking about the program at this path on my hard drive... > > C:\Python27\Lib\site-packages\pythonwin\Pythonwin.exe > > It appears to be an editor and a compiler. I have some questions > about the color scheme. I'd like light/white text on a black > background. I realize you can manually change the colors, but I'd > like to find out if anyone has a good starting point. I don't see > any obvious places on the Internet to ask. The pywin32 packages (which includes the Pythonwin editor) do have their own sourceforge project with trackers etc.: http://sourceforge.net/projects/pywin32/ But I suggest that you'd do better to join the python-win32 mailing list: https://mail.python.org/mailman/listinfo/python-win32 TJG From anjutiwari5 at gmail.com Fri Feb 14 01:20:57 2014 From: anjutiwari5 at gmail.com (anju tiwari) Date: Fri, 14 Feb 2014 11:50:57 +0530 Subject: Python version problem for rpm Message-ID: Hi all, I have two version of python 2.4 and 2.7. By default python version is 2.4 . I want to install need to install some rpm which needs python 2.7 interpreter. how can I enable 2.7 interpreter for only those packages which are requiring python 2.7, I don't want to change my default python version(2.4). Thank you ANJU TIWARI -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Feb 14 03:55:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Feb 2014 03:55:22 -0500 Subject: How to begin In-Reply-To: <85zjlu7bou.fsf@benfinney.id.au> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <52FD4C40.9050001@gmail.com> <85zjlu7bou.fsf@benfinney.id.au> Message-ID: On 2/13/2014 7:57 PM, Ben Finney wrote: > Ryan Gonzalez writes: > >> Read the Python reference. I know it's long, but it saves you trouble >> of accidentally reinventing the wheel. > > Hmm, the language reference is targeted at people *implementing* Python, This is the first time I have read that. It is definitely aimed at users who have already ready the tutorial and need the information that is not in the tutorial. > not people who are learning to use it (though it is valuable for them > also). It would be rather overwhelming for a beginner, IMO. > > You should instead be directing newcomers to beginner documentation, > such as and especially > the Python tutorial . > -- Terry Jan Reedy From nw.rabea at gmail.com Fri Feb 14 05:39:17 2014 From: nw.rabea at gmail.com (nw.rabea at gmail.com) Date: Fri, 14 Feb 2014 02:39:17 -0800 (PST) Subject: IronPython + Selenium2Library + Visual Studio + Robot Framwork Message-ID: Hi All, I already familiar with the python, selenium2library and robot framwork. But i don't know how to connect those things with the ironpython in visual studio. How to integrate pyhton with selenium2library in visual studio by using ironpython, is there a special dll to make import to selenium2library on visual studio iron python? Thank you, Rabea From greg.ewing at canterbury.ac.nz Fri Feb 14 06:30:15 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 15 Feb 2014 00:30:15 +1300 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <87fvnm7q1n.fsf@elektro.pacujo.net> Message-ID: Devin Jeanpierre wrote: > There is no way to iterate over all the reals one at a time, no matter > how fast you execute instructions. If you could, it would be trivial > to show that the reals have the same cardinality as the positive > integers: correspond n with the whatever is returned by the nth call > to it.next. You're assuming that the calls to it.next are discrete events separated by some nonzero time interval. A decent transfinite processor would make a continuum of calls, and execute uncountably many of them in any finite period of time. -- Greg From davea at davea.name Fri Feb 14 07:12:12 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Feb 2014 07:12:12 -0500 (EST) Subject: Python version problem for rpm References: Message-ID: anju tiwari Wrote in message: > I have two version of python 2.4 and 2.7. > By default python version is 2.4 . I want to install need to install some rpm which needs python 2.7 interpreter. how can I enable 2.7 interpreter for only those packages which are requiring python 2.7, I don???t want to change my default python version(2.4) You don't say what OS you're running, but I'll assume some version of Linux. If you have some scripts that require 2.7, then change the shebang line to point explicitly to the 2.7 executable, rather than using #/usr/bin/env python Or make a symlink called python27 and use that explicitly when non default version is needed. -- DaveA From davea at davea.name Fri Feb 14 07:19:32 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Feb 2014 07:19:32 -0500 (EST) Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: Terry Reedy Wrote in message: > On 2/13/2014 1:37 PM, forman.simon at gmail.com wrote: >> I ran across this and I thought there must be a better way of doing it, but then after further consideration I wasn't so sure. >> >> if key[:1] + key[-1:] == '<>': ... > > if key[:1] == '<' and key[-1:] == '>: ... > is the obvious choice to me. If the first clause is false, it never > computes the second. > And therefore no need for the second colon. if key[:1] == '<' and key[-1] == '>: ... -- DaveA From davea at davea.name Fri Feb 14 07:30:09 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Feb 2014 07:30:09 -0500 (EST) Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: Chris Angelico Wrote in message: > On Fri, Feb 14, 2014 at 5:37 PM, Gregory Ewing >> >> >> If it's a quantum computer, it may be able to execute >> all branches of the iteration in parallel. But it >> would only have a probability of returning the right >> answer (in other cases it would kill your cat). > > Oh, that's fine, he's not my cat anyway. Go ahead, build it. > That cat has got to be at least 79 by now. Probably starved by now. -- DaveA From drobinow at gmail.com Fri Feb 14 09:02:15 2014 From: drobinow at gmail.com (David Robinow) Date: Fri, 14 Feb 2014 09:02:15 -0500 Subject: Newcomer Help In-Reply-To: References: <8355e670-5d3e-4ce1-8db1-64264a173cda@googlegroups.com> Message-ID: On Thu, Feb 13, 2014 at 11:32 AM, Larry Martell wrote: > 18) If you're on AOL, don't worry about anything I've said here. > You're already a fucking laughing stock, and there's no hope for you. Ah, the email bigots. That's why I keep an AOL address around for occasional use against these jerks. From roy at panix.com Fri Feb 14 09:06:48 2014 From: roy at panix.com (Roy Smith) Date: Fri, 14 Feb 2014 09:06:48 -0500 Subject: A curious bit of code... References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> Message-ID: In article , Dave Angel wrote: > Terry Reedy Wrote in message: > > On 2/13/2014 1:37 PM, forman.simon at gmail.com wrote: > >> I ran across this and I thought there must be a better way of doing it, > >> but then after further consideration I wasn't so sure. > >> > >> if key[:1] + key[-1:] == '<>': ... > > > > if key[:1] == '<' and key[-1:] == '>: ... > > is the obvious choice to me. If the first clause is false, it never > > computes the second. > > > And therefore no need for the second colon. > > if key[:1] == '<' and key[-1] == '>: ... I'd leave the second colon in. It makes the statement more uniform, and therefor easier to understand. From invalid at invalid.invalid Fri Feb 14 10:09:18 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 14 Feb 2014 15:09:18 +0000 (UTC) Subject: Working with the set of real numbers References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: On 2014-02-14, Gregory Ewing wrote: > If it's a quantum computer, it may be able to execute > all branches of the iteration in parallel. But it > would only have a probability of returning the right > answer (in other cases it would kill your cat). I know somebody who would claim that _is_ the right answer. -- Grant Edwards grant.b.edwards Yow! Hello, GORRY-O!! at I'm a GENIUS from HARVARD!! gmail.com From rustompmody at gmail.com Fri Feb 14 10:13:46 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 07:13:46 -0800 (PST) Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <888bd2fc-54b0-4c46-9d7b-d81d01a78b52@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> Message-ID: <09f907b2-dba0-4b5d-8387-1f8ea453d020@googlegroups.com> On Friday, February 14, 2014 12:14:31 PM UTC+5:30, Chris Angelico wrote: > Oh, that's fine, he's not my cat anyway. Go ahead, build it. Now Now! I figured you were the cat out here! From lightaiyee at gmail.com Fri Feb 14 11:10:22 2014 From: lightaiyee at gmail.com (Sam) Date: Fri, 14 Feb 2014 08:10:22 -0800 (PST) Subject: Best practices to overcome python's dynamic data type nature Message-ID: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Dynamic data type has pros and cons. It is easier to program but also easier to create bugs. What are the best practices to reduce bugs caused by Python's dynamic data-type characteristic? Can the experienced Python programmers here advise? Thank you. From maikwo at gmail.com Fri Feb 14 11:09:56 2014 From: maikwo at gmail.com (Connor) Date: Fri, 14 Feb 2014 17:09:56 +0100 Subject: error handling in multithreaded extension callbacks Message-ID: <52FE3FD4.1030703@gmail.com> Hi, In my extension I'm calling python functions as callbacks from a thread generated in an external module. This works very well, but I'm not sure about the error handling. 1. Normally the python interpreter exits if it runs on an unhandled error. Is this the preferred standard behavior for this case too ? 2. How can I implement this in my error handling ? Here is my code so far. If an error happens in the python code it is printed to stderr, but the python script is still running in the main thread. void FUNC_C_DECL coreCommandReadyCallback(TML_COMMAND_HANDLE cmd, TML_POINTER data) { // Calling Python out of a non- python created thread PyGILState_STATE gstate; try { gstate = PyGILState_Ensure(); PythonCallbackData* callbackData = (PythonCallbackData*) data; PyObject *arglist; PyObject *pythonCBFunc = callbackData->pCBFunc; /* Time to call the callback */ arglist = Py_BuildValue("(LO)", cmd, callbackData->pCBData); PyObject* result = PyEval_CallObject(pythonCBFunc, arglist); Py_DECREF(arglist); if ( PyErr_Occurred() ) { PyErr_Print(); PyErr_SetString(PyExc_TypeError, "PyErr_Occurred"); } // Release calling Python out of a non- python created thread PyGILState_Release(gstate); } catch (...) { printf ("An Exception Happened\n"); } } Cheers, Connor From davea at davea.name Fri Feb 14 11:42:37 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Feb 2014 11:42:37 -0500 (EST) Subject: Best practices to overcome python's dynamic data type nature References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: Sam Wrote in message: > Dynamic data type has pros and cons. It is easier to program but also easier to create bugs. What are the best practices to reduce bugs caused by Python's dynamic data-type characteristic? Can the experienced Python programmers here advise? > > Thank you. > Claiming that bugs are caused by pythons dynamics type data characteristic is like saying that's great, mistakes are caused bye for spell checkers. -- DaveA From breamoreboy at yahoo.co.uk Fri Feb 14 11:39:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Feb 2014 16:39:01 +0000 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: On 14/02/2014 16:10, Sam wrote: > Dynamic data type has pros and cons. It is easier to program but also easier to create bugs. What are the best practices to reduce bugs caused by Python's dynamic data-type characteristic? Can the experienced Python programmers here advise? > > Thank you. > Bugs are caused by the programmer, regardless of the language. The best way of know of avoiding bugs in Python is a combination of running Pylint in the Pydev editor as I type (I'd assume other IDEs let you do this as well) and testing, more testing and yet more testing. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From stutzman at cat2.kjsl.com Fri Feb 14 11:38:06 2014 From: stutzman at cat2.kjsl.com (Frank Stutzman) Date: Fri, 14 Feb 2014 16:38:06 +0000 (UTC) Subject: Emacs python-mode.el bug #1207470 Message-ID: According to https://bugs.launchpad.net/python-mode/+bug/1207470 this bug was fixed in version 6.1.2 of python-mode.el. I am trying to run 6.1.3 and am running into it. I back dated to 6.1.2 and still see it there. I am running GNU Emacs 23.3.1. Its possible that something I'm doing it causing it, but I have no idea what. I can start emacs with no init file, load python mode, hit enter and I get the error. Has anyone else experienced this? I am sure that Andreas Roehler (the maintainer of python-mode.el) fixed it, but am thinking that it somehow didn't make it into the released code. Frank -- From breamoreboy at yahoo.co.uk Fri Feb 14 11:43:21 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Feb 2014 16:43:21 +0000 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: On 14/02/2014 16:42, Dave Angel wrote: > Sam Wrote in message: >> Dynamic data type has pros and cons. It is easier to program but also easier to create bugs. What are the best practices to reduce bugs caused by Python's dynamic data-type characteristic? Can the experienced Python programmers here advise? >> >> Thank you. >> > > > Claiming that bugs are caused by pythons dynamics type data > characteristic is like saying that's great, mistakes are caused > bye for spell checkers. > > Shouldn't that be "spell chequers"? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From marko at pacujo.net Fri Feb 14 11:54:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 18:54:58 +0200 Subject: Best practices to overcome python's dynamic data type nature References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: <8761ohprbx.fsf@elektro.pacujo.net> Sam : > Dynamic data type has pros and cons. It is easier to program but also > easier to create bugs. What are the best practices to reduce bugs > caused by Python's dynamic data-type characteristic? Can the > experienced Python programmers here advise? Here's some advice from a very experienced programmer: become a very experienced programmer. When you are comfortable with the freedoms a dynamic environment gives you and know how to use them appropriately, you can perform miracles in a short time. I like Java a lot, but boy does the boilerplate get in your way. When you start writing a feature, you have to produce 2000 lines of code *before writing a single statement*! That's why experienced Java programmers tend to resort to code generators. I'm saying a language has a serious issue if you need a code generator to use it. Marko From ethan at stoneleaf.us Fri Feb 14 11:32:32 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Feb 2014 08:32:32 -0800 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: <52FE4520.70905@stoneleaf.us> On 02/14/2014 08:10 AM, Sam wrote: > > Dynamic data type has pros and cons. It is easier to program but > also easier to create bugs. What are the best practices to reduce > bugs caused by Python's dynamic data-type characteristic? Can the > experienced Python programmers here advise? Unit tests. -- ~Ethan~ From gary.herron at islandtraining.com Fri Feb 14 12:09:18 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Fri, 14 Feb 2014 09:09:18 -0800 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: <52FE4DBE.1010803@islandtraining.com> On 02/14/2014 08:10 AM, Sam wrote: > Dynamic data type has pros and cons. It is easier to program but also easier to create bugs. What are the best practices to reduce bugs caused by Python's dynamic data-type characteristic? Can the experienced Python programmers here advise? > > Thank you. The assumptions in that question are misleading. In fact, Python, with it's dynamic nature and other features, allows me to write fewer lines of code with fewer bugs-per-line. That's a win-win situation, not a problem which needs to be worked around. Still, when bugs do creep into code, the best strategy to find them is a good testing strategy. Gary Herron From andreas.roehler at online.de Fri Feb 14 12:35:38 2014 From: andreas.roehler at online.de (=?ISO-8859-1?Q?Andreas_R=F6hler?=) Date: Fri, 14 Feb 2014 18:35:38 +0100 Subject: Emacs python-mode.el bug #1207470 In-Reply-To: References: Message-ID: <52FE53EA.6060105@online.de> Am 14.02.2014 17:38, schrieb Frank Stutzman: > According to https://bugs.launchpad.net/python-mode/+bug/1207470 this bug > was fixed in version 6.1.2 of python-mode.el. I am trying to run 6.1.3 and > am running into it. I back dated to 6.1.2 and still see it there. I am > running GNU Emacs 23.3.1. > > Its possible that something I'm doing it causing it, but I have no idea > what. I can start emacs with no init file, load python mode, hit enter > and I get the error. > > Has anyone else experienced this? I am sure that Andreas Roehler (the > maintainer of python-mode.el) fixed it, but am thinking that it somehow > didn't make it into the released code. > > Frank > Re-opened the ticket mentioned. Please subscribe there, so you may get the bug-mail. Andreas From ethan at stoneleaf.us Fri Feb 14 12:02:59 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Feb 2014 09:02:59 -0800 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: <8761ohprbx.fsf@elektro.pacujo.net> References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> <8761ohprbx.fsf@elektro.pacujo.net> Message-ID: <52FE4C43.9020205@stoneleaf.us> On 02/14/2014 08:54 AM, Marko Rauhamaa wrote: > > Here's some advice from a very experienced programmer: become a very > experienced programmer. +1 QOTW From daveandem2000 at gmail.com Fri Feb 14 13:08:04 2014 From: daveandem2000 at gmail.com (dave em) Date: Fri, 14 Feb 2014 10:08:04 -0800 (PST) Subject: Explanation of list reference Message-ID: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Hello, Background: My twelve y/o son and I are still working our way through Invent Your Own Computer Games with Python, 2nd Edition. (We finished the Khan Academy Javascript Tutorials is the extent of our experience) He is asking a question I am having trouble answering which is how a variable containing a value differs from a variable containing a list or more specifically a list reference. I tried the to explain as best I can remember is that a variable is assigned to a specific memory location with a value inside of it. Therefore, the variable is kind of self contained and if you change the variable, you change the value in that specific memory location. However, when a variable contains a list reference, the memory location of the variable points to a separate memory location that stores the list. It is also possible to have multiple variable that point to the memory location of the list reference. And all of those variable can act upon the list reference. Question: Is my explanation correct? If not please set me straight :) And does anyone have an easier to digest explanation? Thanks in advance, Dave From jpiitula at ling.helsinki.fi Fri Feb 14 13:26:13 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 14 Feb 2014 20:26:13 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: dave em writes: > He is asking a question I am having trouble answering which is how a > variable containing a value differs from a variable containing a > list or more specifically a list reference. My quite serious answer is: not at all. In particular, a list is a value. All those pointers to references to locations are implementation details. The user of the language needs to understand that an object keeps its identity when it's passed around: passed as an argument, returned by a function, stored in whatever location, retrieved from whatever location. From ned at nedbatchelder.com Fri Feb 14 13:42:21 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 14 Feb 2014 13:42:21 -0500 Subject: Explanation of list reference In-Reply-To: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: On 2/14/14 1:08 PM, dave em wrote: > Hello, > > Background: My twelve y/o son and I are still working our way through Invent Your Own Computer Games with Python, 2nd Edition. > (We finished the Khan Academy Javascript Tutorials is the extent of our experience) > > He is asking a question I am having trouble answering which is how a variable containing a value differs from a variable containing a list or more specifically a list reference. > > I tried the to explain as best I can remember is that a variable is assigned to a specific memory location with a value inside of it. Therefore, the variable is kind of self contained and if you change the variable, you change the value in that specific memory location. > > However, when a variable contains a list reference, the memory location of the variable points to a separate memory location that stores the list. It is also possible to have multiple variable that point to the memory location of the list reference. And all of those variable can act upon the list reference. > > Question: Is my explanation correct? If not please set me straight :) > > And does anyone have an easier to digest explanation? > > Thanks in advance, > Dave > Names in Python refer to values. Thinking in terms of memory locations might just confuse things. This is my best explanation of the details: http://nedbatchelder.com/text/names.html -- Ned Batchelder, http://nedbatchelder.com From stutzman at cat2.kjsl.com Fri Feb 14 13:53:56 2014 From: stutzman at cat2.kjsl.com (Frank Stutzman) Date: Fri, 14 Feb 2014 18:53:56 +0000 (UTC) Subject: Emacs python-mode.el bug #1207470 References: Message-ID: Andreas R?hler wrote: > Re-opened the ticket mentioned. Please subscribe there, so you may get the bug-mail. I've subscribed at launchpad and have given you a few more details there. Much appreciate you taking the time to look at this. -- Frank Stutzman From daveandem2000 at gmail.com Fri Feb 14 13:54:29 2014 From: daveandem2000 at gmail.com (dave em) Date: Fri, 14 Feb 2014 10:54:29 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> On Friday, February 14, 2014 11:26:13 AM UTC-7, Jussi Piitulainen wrote: > dave em writes: > > > > > He is asking a question I am having trouble answering which is how a > > > variable containing a value differs from a variable containing a > > > list or more specifically a list reference. > > > > My quite serious answer is: not at all. In particular, a list is a > > value. > > > > All those pointers to references to locations are implementation > > details. The user of the language needs to understand that an object > > keeps its identity when it's passed around: passed as an argument, > > returned by a function, stored in whatever location, retrieved from > > whatever location. Jessi, Thanks for your quick response. I'm still not sure we understand. The code below illustrates the concept we are trying to understand. Case 1: Example of variable with a specific value from P 170 of IYOCGWP >>> spam = 42 >>> cheese = spam >>> spam = 100 >>> spam 100 >>> cheese 42 Case 2: Example of variable with a list reference from p 170 >>> spam = [0, 1, 2, 3, 4, 5] >>> cheese = spam >>> cheese[1] = 'Hello!' >>> spam [0, 'Hello!', 2, 3, 4, 5] >>> cheese [0, 'Hello!', 2, 3, 4, 5] What I am trying to explain is this, why in case 1 when acting on spam (changing the value from 42 to 100) only affects spam and not cheese. Meanwhile, in case two acting on cheese also affects spam. Thanks and v/r, Dave From rymg19 at gmail.com Fri Feb 14 13:31:56 2014 From: rymg19 at gmail.com (Ryan Gonzalez) Date: Fri, 14 Feb 2014 12:31:56 -0600 Subject: Explanation of list reference In-Reply-To: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: <52FE611C.3040908@gmail.com> On 02/14/2014 12:08 PM, dave em wrote: > Hello, > > Background: My twelve y/o son and I are still working our way through Invent Your Own Computer Games with Python, 2nd Edition. > (We finished the Khan Academy Javascript Tutorials is the extent of our experience) > > He is asking a question I am having trouble answering which is how a variable containing a value differs from a variable containing a list or more specifically a list reference. > > I tried the to explain as best I can remember is that a variable is assigned to a specific memory location with a value inside of it. Therefore, the variable is kind of self contained and if you change the variable, you change the value in that specific memory location. > > However, when a variable contains a list reference, the memory location of the variable points to a separate memory location that stores the list. It is also possible to have multiple variable that point to the memory location of the list reference. And all of those variable can act upon the list reference. > > Question: Is my explanation correct? If not please set me straight :) > > And does anyone have an easier to digest explanation? > > Thanks in advance, > Dave You've got it backwards. In Python, /everything/ is a reference. The variable is just a "pointer" to the actual value. When you change a variable, you're just changing the memory location it points to. Strings, ints, tuples, and floats behave differently because they're /immutable/. That means that they CANNOT modify themselves. That's why all of the string methods return a new string. It also means that, when you pass one two a function, a /copy/ of it is made and passed instead. So, back to the original subject. Everything is a reference. When you do this: |x = [1,2,3] x = [4,5,6] | x now points to a different memory location. And, when you do this: |x[0] =99000 x[0] =100 | you're just changing the memory location that |x[0]| points to. -- --Ryan If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated." -------------- next part -------------- An HTML attachment was scrubbed... URL: From denismfmcmahon at gmail.com Fri Feb 14 14:20:43 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 14 Feb 2014 19:20:43 +0000 (UTC) Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: On Fri, 14 Feb 2014 10:54:29 -0800, dave em wrote: > On Friday, February 14, 2014 11:26:13 AM UTC-7, Jussi Piitulainen wrote: >> dave em writes: >> >> >> >> > He is asking a question I am having trouble answering which is how a >> >> > variable containing a value differs from a variable containing a >> >> > list or more specifically a list reference. >> >> >> >> My quite serious answer is: not at all. In particular, a list is a >> >> value. >> >> >> >> All those pointers to references to locations are implementation >> >> details. The user of the language needs to understand that an object >> >> keeps its identity when it's passed around: passed as an argument, >> >> returned by a function, stored in whatever location, retrieved from >> >> whatever location. > > Jessi, > > Thanks for your quick response. I'm still not sure we understand. The > code below illustrates the concept we are trying to understand. > > Case 1: Example of variable with a specific value from P 170 of IYOCGWP > >>>> spam = 42 cheese = spam spam = 100 spam > 100 >>>> cheese > 42 > > Case 2: Example of variable with a list reference from p 170 > >>>> spam = [0, 1, 2, 3, 4, 5] >>>> cheese = spam cheese[1] = 'Hello!' spam > [0, 'Hello!', 2, 3, 4, 5] >>>> cheese > [0, 'Hello!', 2, 3, 4, 5] > > What I am trying to explain is this, why in case 1 when acting on spam > (changing the value from 42 to 100) only affects spam and not cheese. > Meanwhile, in case two acting on cheese also affects spam. A list is a container for multiple values, when you do: cheese = spam You're pointing cheese and spam at the same container. Now anything you do to the container (whether by referencing it as cheese or spam) will affect the container. If you want cheese and spam to start out as separate copies of the same list that you can manipulate independently, then you can use: cheese = [ x for x in spam ] eggs = spam[:] ham = list( spam ) >>> spam = [1,2,3,4,5] >>> cheese = [ x for x in spam ] >>> ham = list( spam ) >>> eggs = spam[:] >>> spam [1, 2, 3, 4, 5] >>> cheese [1, 2, 3, 4, 5] >>> ham [1, 2, 3, 4, 5] >>> eggs [1, 2, 3, 4, 5] >>> cheese[3] = "fred" >>> ham[4] = 'ham' >>> eggs[4] ='eggs' >>> spam [1, 2, 3, 4, 5] >>> cheese [1, 2, 3, 'fred', 5] >>> ham [1, 2, 3, 4, 'ham'] >>> eggs [1, 2, 3, 4, 'eggs'] -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Fri Feb 14 14:42:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 06:42:41 +1100 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: <8761ohprbx.fsf@elektro.pacujo.net> References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> <8761ohprbx.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 3:54 AM, Marko Rauhamaa wrote: > Sam : > >> Dynamic data type has pros and cons. It is easier to program but also >> easier to create bugs. What are the best practices to reduce bugs >> caused by Python's dynamic data-type characteristic? Can the >> experienced Python programmers here advise? > > Here's some advice from a very experienced programmer: become a very > experienced programmer. Definitely. > I like Java a lot, but boy does the boilerplate get in your way. When > you start writing a feature, you have to produce 2000 lines of code > *before writing a single statement*! That's why experienced Java > programmers tend to resort to code generators. Also this. It's been shown that, for any given programmer, the number of bugs per thousand lines of code is approximately stable. This means that, all other things being equal, a more expressive language will help you write less buggy code. When you have to write 2000 lines of boilerplate in a 200 line program, that's 2200 lines that might potentially be wrong; if, instead, you use a language that requires just 20 lines of boilerplate for the same number of lines of your code, that gives you one tenth the total program size and, in very rough figures, probably about a tenth the number of bugs. It gets even better than that, though. The more expressive the language, the easier it is to notice bugs when they do occur. Tell me, can you see a couple of bugs in this code? make_combined_color: push bp mov bp,sp mov bx,[bp+8] cmp bx,16 ja .err lea ax,[color_data+bx*4+8] pop bp ret 8 .err: ; Handle error by returning 0 mov ax,0 pop bp ret 8 color_data dw 110000, 001011 dw 000000h, 00007Fh, 007F00h, 007F7Fh, 7F0000h, 7F007Fh, 7F7F00h, C0C0C0h dw 7F7F7Fh, 0000FFh, 00FF00h, 00FFFFh, FF0000h, FF00FFh, FFFF00h, FFFFFFh No? Isn't it obvious? Hmm, okay. Well, here's a C version: int color_data[] = {0x000000,0x00007F,0x007F00,0x007F7F,0x7F0000,0x7F007F,0x7F7F00,0xC0C0C0, 0x7F7F7F,0x0000FF,0x00FF00,0x00FFFF,0xFF0000,0xFF00FF,0xFFFF00,0xFFFFFF}; int make_combined_color(int fg, int bg) { if (fg>ARRAY_SIZE(color_data)) return 0; return color_data[fg]; } If you know C, you should be able to spot a couple of errors here. (Assume that ARRAY_SIZE gives you the number of elements in an array. It's an easy enough macro to define, using sizeof.) Now here's the high level equivalent: array color_data=({0x000000,0x00007F,0x007F00,0x007F7F,0x7F0000,0x7F007F,0x7F7F00,0xC0C0C0, 0x7F7F7F,0x0000FF,0x00FF00,0x00FFFF,0xFF0000,0xFF00FF,0xFFFF00,0xFFFFFF}); int make_combined_color(int fg, int bg) { return color_data[fg]; } One of the bugs doesn't even exist now! It's a off-by-one error in array bounds checking. With the high level code, I'm not checking my own array bounds, so it's impossible for me to get that wrong. As to the other bug, it's now patently obvious that it's taking two arguments and ignoring one of them. That's not necessarily a problem, but the name make_combined_color suggests that it should be, well, combining something. Every line of code you write could potentially have a bug in it. If you can write less code to achieve your goals, then - all other things being equal, which of course they never quite are - you'll generally have less bugs. And of course, when you have something that looks weird but is intentional (maybe the above function is _supposed_ to ignore its bg argument, for some reason), you use a code comment. Here's one of my favourites, just for its brevity: gc->set_foreground(bg); //(sic) It's clear from the context this code is in that it's correct to set the display's foreground color to bg, but since it looks wrong at first glance, it merits a comment :) So use a language that lets you say things succinctly and readably (sorry APL). You'll still make bugs, but you'll be able to spot them in subsequent editing. Also: Use source control. Get familiar with a DVCS (I usually recommend either git or hg for all new projects) and get used to checking back on the origin of the code. This gives you two benefits: Firstly, you can know exactly what was written when and why, which helps hugely when you're trying to figure out whether something's correct or not. And secondly - more subtly but perhaps more importantly - it frees you from the need to write all that sort of thing in code comments. You don't need to retain the history of a block of code by commenting out the failed attempts; go back to source control for that. You don't need to predict in advance which bits of code you'll, in six months time, wonder about. (I guarantee you'll predict wrong.) When you come to something that seems odd, you look it up, and *then* add the comments. Consider it a YAGNI policy for verbiage, if you like. Saves you a huge amount of trouble, and keeps your source code lean and clean - which, see above, will tend to reduce your bug count. Huh. My primary point is "keep your code as short as possible"... and look how long this post is. That's a textbook example of irony, right there... ChrisA From theller at ctypes.org Fri Feb 14 14:50:15 2014 From: theller at ctypes.org (Thomas Heller) Date: Fri, 14 Feb 2014 20:50:15 +0100 Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: Am 14.02.2014 17:32, schrieb Ethan Furman: > On 02/14/2014 08:10 AM, Sam wrote: >> >> Dynamic data type has pros and cons. It is easier to program but >> also easier to create bugs. What are the best practices to reduce >> bugs caused by Python's dynamic data-type characteristic? Can the >> experienced Python programmers here advise? > > Unit tests. Lint-like tools - there are a few - also help to discover bugs, even before running or testing the code. They also help in other ways to write better code. Myself I use the 'frosted' tool. Thomas From marko at pacujo.net Fri Feb 14 14:56:07 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 21:56:07 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: <871tz5piy0.fsf@elektro.pacujo.net> dave em : > Case 1: Example of variable with a specific value from P 170 of IYOCGWP > >>>> spam = 42 >>>> cheese = spam >>>> spam = 100 >>>> spam > 100 >>>> cheese > 42 > > Case 2: Example of variable with a list reference from p 170 > >>>> spam = [0, 1, 2, 3, 4, 5] >>>> cheese = spam >>>> cheese[1] = 'Hello!' >>>> spam > [0, 'Hello!', 2, 3, 4, 5] >>>> cheese > [0, 'Hello!', 2, 3, 4, 5] > > What I am trying to explain is this, why in case 1 when acting on spam > (changing the value from 42 to 100) only affects spam and not cheese. > Meanwhile, in case two acting on cheese also affects spam. A very good question! Elementary and advanced at the same time. There are two fundamentally different kinds of values in Python: "small" values and "big" values. A variable can only hold a small value. A list element can only hold a small value. A dictionary entry can only hold a small value. The same is true for an object member (aka field). So we have four kinds of (memory) slots: variables, list elements, dictionary entries and fields. Any slot can only hold a small value. The small values include numbers, booleans (True or False) and references. All other values are big, too big to fit in a slot. They have to be stored in a "vault" big enough to hold them. This vault is called the heap. Big values cannot be stored in slots directly; instead, references to big values are used. Let me now annotate your excellent example: spam = 42 # put the small value 42 (number) in a memory slot, # namely a variable named "spam" cheese = spam # copy the contents of the variable "spam" into # another memory slot, a variable named "cheese;" # now both variables contain the same small value 42 spam = 100 # replace the contents of the variable "spam" with the # small value 100; leave the contents of the variable # "cheese" intact spam > 100 # as expected cheese > 42 # ditto spam = [0, 1, 2, 3, 4, 5] # a list is a "big" value; the statement creates a # list of six slots in the heap an puts a number in # each slot; then, a reference to the list is placed # in the variable "spam" cheese = spam # copy the reference to the six-element list from the # variable "spam" into the variable "cheese;" the heap # still contains only one list, and the two variables # refer to the same one # (rationale: big values take time and space to copy # in full, and almost always copying references is # good for the problem at hand; if a full copy is # needed, Python has ways to do that, too) cheese[1] = 'Hello!' # a character string (text snippet) is a "big" value; # the statement creates the six-character string # 'Hello!' in the heap; then, a reference to the # string is placed in the second element of the list # referred to by the variable "cheese" # (that's a complicated sentence with lots to chew # even though the Python statement looks so innocently # simple) # there still is a single list in the heap; the list # is still referred to by both variables; however the # second slot of the list, which used to hold the # number 1, has been replaced with a reference to the # "big" string 'Hello!' spam > [0, 'Hello!', 2, 3, 4, 5] # as expected, right? cheese > [0, 'Hello!', 2, 3, 4, 5] # right? The final situation is represented by this picture of Python's memory: spam cheese +-----+ +-----+ | . | | . | +--+--+ +--+--+ | | | | VARIABLES = = =|= = = = = = =|= = = = = = = = = = = = = = = = = = = | / THE HEAP | --------- | / | | v v +-----+-----+-----+-----+-----+-----+ | 0 | . | 2 | 3 | 4 | 5 | a list +-----+--+--+-----+-----+-----+-----+ | | | | v a string +--------+ | Hello! | a string +--------+ Marko From forman.simon at gmail.com Fri Feb 14 15:04:02 2014 From: forman.simon at gmail.com (forman.simon at gmail.com) Date: Fri, 14 Feb 2014 12:04:02 -0800 (PST) Subject: A curious bit of code... In-Reply-To: References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <839842ff-e0d4-4bec-93fa-b8c25b3ca471@googlegroups.com> Message-ID: <6940c818-e8dc-483e-8795-9e5493050e3b@googlegroups.com> On Thursday, February 13, 2014 7:26:48 PM UTC-8, Ned Batchelder wrote: > On 2/13/14 9:45 PM, forman.simon at gmail.com wrote: > > > For the record I wasn't worried about the performance. ;-) > > > > > > It was for Tkinter event strings not markup tags. > > > > > > I'm glad this was the time winner! > > > > > > "key and key[0] == '<' and key[-1] == '>'" > > > > > > > > > Cheers to the folks who did the timings (and saved me from the trouble!) > > > > > > Last but not least... s[::len(s)-1] omg!!? ;-D > > > > > > > If you aren't worried about performance, why are you choosing your code > > based on which is the fastest? There are other characteristics > > (clarity, flexibility, robustness, ...) that could be more useful. I guess I'm taking the word "worried" a little too seriously. Back story: I am hoping to contribute to IDLE and am reading the code as a first step. I came across that line of code (BTW, I was wrong: it is NOT processing Tkinter event strings but rather special " entries" in linecache.cache [1]) and had to resist the urge to change it to something more readable (to me.) But when I thought about it I wasn't able to discern if any of the new versions would actually be enough of an improvement to justify changing it. To be clear: I have no intention of modifying the IDLE codebase just for fairly trivial points like this one line. The most satisfying (to me) of the possibilities is "if key and key[0] == '<' and key[-1] == '>':" in the dimensions, if you will, of readability and, uh, unsurprising-ness, and so I was pleased to learn that that was also the fastest. (FWIW, it seems to me that whoever wrote that line was influenced by shell programming. It's a shell sort of a trick to my eye.) When writing Python code I *do* value "clarity, flexibility, robustness" and almost never worry about performance unless something is actually slow in a way that affects something.. Warm regards, ~Simon [1] http://hg.python.org/cpython/file/3a1db0d2747e/Lib/idlelib/PyShell.py#l117 From ian.g.kelly at gmail.com Fri Feb 14 15:12:51 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Feb 2014 13:12:51 -0700 Subject: Explanation of list reference In-Reply-To: <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 11:54 AM, dave em wrote: > Thanks for your quick response. I'm still not sure we understand. The code below illustrates the concept we are trying to understand. > > Case 1: Example of variable with a specific value from P 170 of IYOCGWP > >>>> spam = 42 >>>> cheese = spam >>>> spam = 100 >>>> spam > 100 >>>> cheese > 42 > > Case 2: Example of variable with a list reference from p 170 > >>>> spam = [0, 1, 2, 3, 4, 5] >>>> cheese = spam >>>> cheese[1] = 'Hello!' >>>> spam > [0, 'Hello!', 2, 3, 4, 5] >>>> cheese > [0, 'Hello!', 2, 3, 4, 5] > > What I am trying to explain is this, why in case 1 when acting on spam (changing the value from 42 to 100) only affects spam and not cheese. Meanwhile, in case two acting on cheese also affects spam. In the first case, after the assignment "cheese = spam", the names spam and cheese are bound to the same object (42). If you were to modify the object 42 (which you cannot do in this case, because ints are immutable) then you would see the change reflected in the object regardless of which name you used to access it. You then rebind the name "spam" to a different object (100), which does not affect the binding of the name "cheese" at all; the names end up referring to different objects. In the second case, after the assignment "cheese = spam", the names again are bound to the same object, a list. The assignment "cheese[1] = 'Hello!'" then *modifies* that list, without rebinding cheese. cheese and spam continue to refer to the same object, and since it was modified you can see the change in that object regardless of which name you used to access it. If in the second case, you were to explicitly copy the list (e.g. "cheese = list(spam)") prior to modifying it, then the two names would instead be bound to different objects, and so subsequently modifying one would not affect the other. So the short answer is that there is no difference at all between the way that names are bound to ints and the way they are bound to lists. There only superficially appears to be a difference because ints are immutable and lists are not. From ian.g.kelly at gmail.com Fri Feb 14 15:17:33 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Feb 2014 13:17:33 -0700 Subject: Explanation of list reference In-Reply-To: <871tz5piy0.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 14, 2014 at 12:56 PM, Marko Rauhamaa wrote: > There are two fundamentally different kinds of values in Python: "small" > values and "big" values. A variable can only hold a small value. A list > element can only hold a small value. A dictionary entry can only hold a > small value. The same is true for an object member (aka field). > > So we have four kinds of (memory) slots: variables, list elements, > dictionary entries and fields. Any slot can only hold a small value. > > The small values include numbers, booleans (True or False) and > references. All other values are big, too big to fit in a slot. They > have to be stored in a "vault" big enough to hold them. This vault is > called the heap. Big values cannot be stored in slots directly; instead, > references to big values are used. This is nonsense. Python the language makes no such distinction between "big" and "small" values. *All* objects in CPython are stored internally on the heap. Other implementations may use different memory management schemes. From ngangsia at gmail.com Fri Feb 14 15:29:29 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Fri, 14 Feb 2014 12:29:29 -0800 (PST) Subject: Python programming In-Reply-To: References: Message-ID: <6cfc8a2a-8c9f-45de-b39a-41142ab57eea@googlegroups.com> wow wow Thanks for the contutions Thanks guys, many more are welcome From jpiitula at ling.helsinki.fi Fri Feb 14 15:36:20 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 14 Feb 2014 22:36:20 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: dave em writes: > On Friday, February 14, 2014 11:26:13 AM UTC-7, Jussi Piitulainen wrote: > > dave em writes: > > > > > He is asking a question I am having trouble answering which is > > > how a variable containing a value differs from a variable > > > containing a list or more specifically a list reference. > > > > My quite serious answer is: not at all. In particular, a list is a > > value. > > > > All those pointers to references to locations are implementation > > details. The user of the language needs to understand that an > > object keeps its identity when it's passed around: passed as an > > argument, returned by a function, stored in whatever location, > > retrieved from whatever location. > > Thanks for your quick response. I'm still not sure we understand. > The code below illustrates the concept we are trying to understand. > > Case 1: Example of variable with a specific value from P 170 of IYOCGWP > > >>> spam = 42 > >>> cheese = spam > >>> spam = 100 > >>> spam > 100 > >>> cheese > 42 In case 1, you have only assignments to variables. After spam = 100, the value of spam is another number. The previous number 42 itself is still 42 - number are not mutable, and no attempt was made to change the number. In cheese = spam, cheese is the variable while spam is a variable reference and stands for 42. > Case 2: Example of variable with a list reference from p 170 > > >>> spam = [0, 1, 2, 3, 4, 5] > >>> cheese = spam > >>> cheese[1] = 'Hello!' > >>> spam > [0, 'Hello!', 2, 3, 4, 5] > >>> cheese > [0, 'Hello!', 2, 3, 4, 5] The first two statements in case 2 are assignments to variables, just like in case 1, but the third statement is different: it doesn't change the value of the variable (the value is still the same object) but it does change the value (replaces one element of the list with another). You don't need to mention the variable cheese here. Note how the value of spam is now different (though still the same object), even though you didn't mention spam at all when you changed it. Python syntax to replace an element of a list looks much like an assignment - many languages do this - but it's not. Behind the scenes it's a method call >>> cheese.__setitem__(1, 'spam') where cheese is a variable reference. You are calling a method of the list that is the value of the variable. > What I am trying to explain is this, why in case 1 when acting on > spam (changing the value from 42 to 100) only affects spam and not > cheese. Meanwhile, in case two acting on cheese also affects spam. Would it help to say that in case 1 the relevant statement acts on the variable while in case 2 it acts on the value of the variable? This is accurate, I just don't know if it happens to be the thing that helps. One last thing: a variable is not an object. From ned at nedbatchelder.com Fri Feb 14 15:45:23 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 14 Feb 2014 15:45:23 -0500 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> Message-ID: On 2/14/14 3:17 PM, Ian Kelly wrote: > On Fri, Feb 14, 2014 at 12:56 PM, Marko Rauhamaa wrote: >> There are two fundamentally different kinds of values in Python: "small" >> values and "big" values. A variable can only hold a small value. A list >> element can only hold a small value. A dictionary entry can only hold a >> small value. The same is true for an object member (aka field). >> >> So we have four kinds of (memory) slots: variables, list elements, >> dictionary entries and fields. Any slot can only hold a small value. >> >> The small values include numbers, booleans (True or False) and >> references. All other values are big, too big to fit in a slot. They >> have to be stored in a "vault" big enough to hold them. This vault is >> called the heap. Big values cannot be stored in slots directly; instead, >> references to big values are used. > > This is nonsense. Python the language makes no such distinction > between "big" and "small" values. *All* objects in CPython are stored > internally on the heap. Other implementations may use different > memory management schemes. > Marko, I have to agree with Ian. While I really like the picture you drew, the distinction between big and small values is pure fiction. CPython does not store ints directly in list elements, for example. All names are references to values. All list elements (and dictionary values, dictionary keys, set elements, etc) are references to values. A value can be another container like a list, or it can be something "simple" like an int. This covers all the details, including pictures like Marko's, but with an explanation why we draw the ints inside the boxes: http://nedbatchelder.com/text/names.html -- Ned Batchelder, http://nedbatchelder.com From marko at pacujo.net Fri Feb 14 15:58:15 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 22:58:15 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> Message-ID: <87vbwho1i0.fsf@elektro.pacujo.net> Ian Kelly : > This is nonsense. Python the language makes no such distinction > between "big" and "small" values. *All* objects in CPython are stored > internally on the heap. Other implementations may use different memory > management schemes. You're right, of course. Conceptually, the "everything is a reference" and the "small"/"big" distinction are equivalent (produce the same outcomes). The question is, which model is easier for a beginner to grasp. Say you write: 1 + 2 You may not find it most intuitive to follow through the object instantiation and reference manipulation implicit in the "everything is a reference" model when you think you understand numbers but have little idea of memory, objects, heap, allocation etc. Marko From breamoreboy at yahoo.co.uk Fri Feb 14 16:01:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Feb 2014 21:01:48 +0000 Subject: A curious bit of code... In-Reply-To: <6940c818-e8dc-483e-8795-9e5493050e3b@googlegroups.com> References: <4cc09129-43ee-4205-a24c-03f92b594abc@googlegroups.com> <839842ff-e0d4-4bec-93fa-b8c25b3ca471@googlegroups.com> <6940c818-e8dc-483e-8795-9e5493050e3b@googlegroups.com> Message-ID: On 14/02/2014 20:04, forman.simon at gmail.com wrote: > On Thursday, February 13, 2014 7:26:48 PM UTC-8, Ned Batchelder wrote: >> On 2/13/14 9:45 PM, forman.simon at gmail.com wrote: >> >>> For the record I wasn't worried about the performance. ;-) >> >>> >> >>> It was for Tkinter event strings not markup tags. >> >>> >> >>> I'm glad this was the time winner! >> >>> >> >>> "key and key[0] == '<' and key[-1] == '>'" >> >>> >> >>> >> >>> Cheers to the folks who did the timings (and saved me from the trouble!) >> >>> >> >>> Last but not least... s[::len(s)-1] omg!!? ;-D >> >>> >> >> >> >> If you aren't worried about performance, why are you choosing your code >> >> based on which is the fastest? There are other characteristics >> >> (clarity, flexibility, robustness, ...) that could be more useful. > > > I guess I'm taking the word "worried" a little too seriously. > > Back story: I am hoping to contribute to IDLE and am reading the code as a first step. I came across that line of code (BTW, I was wrong: it is NOT processing Tkinter event strings but rather special " entries" in linecache.cache [1]) and had to resist the urge to change it to something more readable (to me.) But when I thought about it I wasn't able to discern if any of the new versions would actually be enough of an improvement to justify changing it. > > To be clear: I have no intention of modifying the IDLE codebase just for fairly trivial points like this one line. > > The most satisfying (to me) of the possibilities is "if key and key[0] == '<' and key[-1] == '>':" in the dimensions, if you will, of readability and, uh, unsurprising-ness, and so I was pleased to learn that that was also the fastest. > > > (FWIW, it seems to me that whoever wrote that line was influenced by shell programming. It's a shell sort of a trick to my eye.) > > > When writing Python code I *do* value "clarity, flexibility, robustness" and almost never worry about performance unless something is actually slow in a way that affects something.. > > Warm regards, > ~Simon > > > [1] http://hg.python.org/cpython/file/3a1db0d2747e/Lib/idlelib/PyShell.py#l117 > Pleased to have you on board, as I'm know that Terry Reedy et al can do with a helping hand. But please note you appear to be using google groups, hence the double line spacing above and trying to reply to paragraphs that run as a single line across the screen. Therefore would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From jcasale at activenetwerx.com Fri Feb 14 16:08:20 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Fri, 14 Feb 2014 21:08:20 +0000 Subject: Unitest mock issue Message-ID: <53bea73a79434de6b45da4ea74aadb30@exch.activenetwerx.com> I am trying to patch a method of a class thats proving to be less than trivial. The module I am writing a test for, ModuleA imports another ModuleB and instantiates a class from this. Problem is, ModuleA incorporates multiprocessing queues and I suspect I am missing the patch as the object in question is retrieved from a queue and unpickled, at which point the method is invoked on that retrieved object immediately. Before the class I am patching is pickled, I don't invoke the method, but if I mock the entire class, I can clearly see I am replacing it before pickling. So, given it is this same module I am pickling/unpickling, what nuance have I missed in just replacing the method of interest during unpickling? Thanks for any guidance, jlc From rosuav at gmail.com Fri Feb 14 16:16:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 08:16:41 +1100 Subject: Explanation of list reference In-Reply-To: <87vbwho1i0.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 7:58 AM, Marko Rauhamaa wrote: > Say you write: > > 1 + 2 > > You may not find it most intuitive to follow through the object > instantiation and reference manipulation implicit in the "everything is > a reference" model when you think you understand numbers but have little > idea of memory, objects, heap, allocation etc. I don't object to a bit of handwaving where it doesn't matter (especially as regards language design versus language interpreter design - I'll happily talk about "storing an object on the heap" without going into the details of allocating memory, managing reference counts, and so on; the details of how CPython goes about storing stuff on the heap isn't particularly significant), but be careful of simplifications that will cause problems down the line. Distinguishing "small values" from "big values" leads to the obvious question: Which is which? And why doesn't this work? >>> x = 3000 >>> z = x >>> z is x True Seems legit... you set z equal to x, and then z is the same as x. Okay, let's try that slightly differently. >>> x = 1000 >>> y = 2000 >>> z = x + y >>> z is 3000 False What's different? How come I can do comparisons with 'is' sometimes but not other times? (And just to make things more confusing, if you do this in CPython with small numbers, it'll *seem* to work.) The only way to explain it thoroughly is to fully distinguish between names and objects, and explain what assignment actually means. Then it's obvious that, in the first case, the identity check passes, while in the second case, it doesn't. ChrisA From marko at pacujo.net Fri Feb 14 16:20:01 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 23:20:01 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> Message-ID: <87r475o0hq.fsf@elektro.pacujo.net> Marko Rauhamaa : > You're right, of course. Conceptually, the "everything is a reference" > and the "small"/"big" distinction are equivalent (produce the same > outcomes). The question is, which model is easier for a beginner to > grasp. In fact, if you adjust my annotations to the given example from the "everything is a reference" point of view, you'll see that the explanations become a whole deal longer and probably more confusing. Also, the picture becomes much messier with more strings attached. Marko From tjreedy at udel.edu Fri Feb 14 16:37:39 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Feb 2014 16:37:39 -0500 Subject: Explanation of list reference In-Reply-To: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: On 2/14/2014 1:08 PM, dave em wrote: > He is asking a question I am having trouble answering which is how a > variable containing a value differs from a variable containing a list > or more specifically a list reference. > > I tried the to explain as best I can remember is that a variable is > assigned to a specific memory location with a value inside of it. The data model of C and other memory-oriented languages is *different* from the object model of Python and similar languages. The concept of 'memory address' is fundamental to C and absent from Python. To understand Python, one must think in terms of its referenced object model and not C's memory-address model. Consider name-binding statements, also called assignment statements. The simplest form is = As always, the expression evaluates to a Python object. It may be an existing object or it may by a newly created. Either way, the name is associated with the object. Subsequent to the name binding, the name, as an expression, evaluates to the object it points to. An object can have 0 to many names associated with it. That set of names can change. A name can be associated with only one object at a time, but can be rebound to other objects. All objects have class (type) and a value. The value of some objects can be changed (lists, sets, dicts, most user-defined classes), others are fixed (numbers, strings, tuples, frozensets). a = 1 # a points to int object with value 1; a == 1 b = a # b points to the same int object; b == 1 and b is a a = '1' # a now points to a str object with value '1'; a == '1' c = [1,2,3] # c points to a list object whose value is the # given sequence of int objects; c == [1,2,3] d = c # d is the same list object as c d[1] = '2' # This associates the indicated 'slot' in the collection object d (which is also c) with a '2' string object. 'Variable' in C (a fixed memory location with a mutable value) is quite different from 'variable' in Python. Most people in Python mean a fixed name, potentially associated with a sequence of objects. In CPython, each object would usually be at a different C location. 'Variable' in math has multiple meanings. -- Terry Jan Reedy From martin.schoon at gmail.com Fri Feb 14 16:35:43 2014 From: martin.schoon at gmail.com (Martin =?UTF-8?Q?Sch=C3=B6=C3=B6n?=) Date: 14 Feb 2014 21:35:43 GMT Subject: better and user friendly IDE recommended? References: <091bbe36-8cf9-412f-b7e9-2b3cc89dd363@googlegroups.com> <7eab4785-4db6-416f-9bc2-56470ab9d7db@googlegroups.com> Message-ID: Den 2014-02-14 skrev Rustom Mody : > On Friday, February 14, 2014 2:57:13 AM UTC+5:30, Martin Sch??n wrote: >> Den 2013-09-17 skrev rusi >> > On Wednesday, September 11, 2013 7:44:04 PM UTC+5:30, >> > mnishpsyched wrote: >> > Just saw this >> > http://www.youtube.com/watch?v=1-dUkyn_fZA >> > Yeah... scientific programming and web programming are hardly the same :-) >> > Still it might be worth 20 minutes of your time > >> I have started testing this. It is early days so too early to pass >> judgement. > >> Anyone out there using Emacs + Python + Orgmode like this? >> I might to need ask some questions :-) > > The speaker -- Kitchin -- is quite active on the org mode list. > And a bunch of other babel users. You should try there. > And please do report back your findings! Right. I expected this response. I hoped to keep a cap on the number of cyberpubs I hang out in :-) And I prefer the usenet above all other alternatives. OK, I will dive into the Orgmode pond and I will report back but please be patient. This is a pure spare time activity. /Martin From marko at pacujo.net Fri Feb 14 16:43:57 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 14 Feb 2014 23:43:57 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> Message-ID: <87mwhtnzdu.fsf@elektro.pacujo.net> Chris Angelico : > be careful of simplifications that will cause problems down the line. Sure. Let it be said, though, that sometimes you learn through inaccuracies, a technique used intentionally by Knuth's TeXBook, for example. In fact, you get through highschool mathematics successfully without knowing what numbers and variables actually are. > Distinguishing "small values" from "big values" leads to the obvious > question: Which is which? And why doesn't this work? This is related to the recent id(string) question on this forum. Unfortunately neither the "everything is a reference" model nor the "small/big" model help you predict the value of an "is" operator in the ambiguous cases. Back to the original question, though. Python, I think, is a great introductory programming language to a complete newbie. Explaining Python's memory model at some level is necessary right off the bat. However, it is far from easy to understand. I'm not sure the small/big way is the best approach, but it seeks to bridge the gap from the naive understanding of tutorial day one to the presented question (tutorial day two). Marko From sforman at hushmail.com Fri Feb 14 16:21:17 2014 From: sforman at hushmail.com (Simon Forman) Date: Fri, 14 Feb 2014 13:21:17 -0800 Subject: A curious bit of code... Message-ID: <20140214212117.3891D200F2@smtp.hushmail.com> On Friday, February 14, 2014 1:01:48 PM UTC-8, Mark Lawrence wrote: [snip] > > Pleased to have you on board, as I'm know that Terry Reedy et al can do > with a helping hand. > > But please note you appear to be using google groups, hence the double > line spacing above and trying to reply to paragraphs that run as a > single line across the screen. Therefore would you please read and > action this https://wiki.python.org/moin/GoogleGroupsPython, thanks. Ah! Thanks for the tip. ;-) (Just last night I was trying to explain to a friend about Usenet and how it's not Google Groups.) I really hope I can be of use with IDLE. I've been using it for years now. :) Warm regards, ~Simon -- http://phoenixbureau.org/ http://phoenixbureau.org/blog.html http://twitter.com/SimonForman "The history of mankind for the last four centuries is rather like that of an imprisoned sleeper, stirring clumsily and uneasily while the prison that restrains and shelters him catches fire, not waking but incorporating the crackling and warmth of the fire with ancient and incongruous dreams, than like that of a man consciously awake to danger and opportunity." --H. P. Wells, "A Short History of the World" From prometheus235 at gmail.com Fri Feb 14 17:27:58 2014 From: prometheus235 at gmail.com (Nick Timkovich) Date: Fri, 14 Feb 2014 16:27:58 -0600 Subject: Generator using item[n-1] + item[n] memory Message-ID: I have a Python 3.x program that processes several large text files that contain sizeable arrays of data that can occasionally brush up against the memory limit of my puny workstation. From some basic memory profiling, it seems like when using the generator, the memory usage of my script balloons to hold consecutive elements, using up to twice the memory I expect. I made a simple, stand alone example to test the generator and I get similar results in Python 2.7, 3.3, and 3.4. My test code follows, `memory_usage()` is a modifed version of [this function from an SO question](http://stackoverflow.com/a/898406/194586) which uses `/proc/self/status` and agrees with `top` as I watch it. `resource` is probably a more cross-platform method: ############### import sys, resource, gc, time def biggen(): sizes = 1, 1, 10, 1, 1, 10, 10, 1, 1, 10, 10, 20, 1, 1, 20, 20, 1, 1 for size in sizes: data = [1] * int(size * 1e6) #time.sleep(1) yield data def consumer(): for data in biggen(): rusage = resource.getrusage(resource.RUSAGE_SELF) peak_mb = rusage.ru_maxrss/1024.0 print('Peak: {0:6.1f} MB, Data Len: {1:6.1f} M'.format( peak_mb, len(data)/1e6)) #print(memory_usage()) data = None # go del data # away gc.collect() # please. # def memory_usage(): # """Memory usage of the current process, requires /proc/self/status""" # # http://stackoverflow.com/a/898406/194586 # result = {'peak': 0, 'rss': 0} # for line in open('/proc/self/status'): # parts = line.split() # key = parts[0][2:-1].lower() # if key in result: # result[key] = int(parts[1])/1024.0 # return 'Peak: {peak:6.1f} MB, Current: {rss:6.1f} MB'.format(**result) print(sys.version) consumer() ############### In practice I'll process data coming from such a generator loop, saving just what I need, then discard it. When I run the above script, and two large elements come in series (the data size can be highly variable), it seems like Python computes the next before freeing the previous, leading to up to double the memory usage. $ python genmem.py 2.7.3 (default, Sep 26 2013, 20:08:41) [GCC 4.6.3] Peak: 7.9 MB, Data Len: 1.0 M Peak: 11.5 MB, Data Len: 1.0 M Peak: 45.8 MB, Data Len: 10.0 M Peak: 45.9 MB, Data Len: 1.0 M Peak: 45.9 MB, Data Len: 1.0 M Peak: 45.9 MB, Data Len: 10.0 M # ^^ not much different versus previous 10M-list Peak: 80.2 MB, Data Len: 10.0 M # ^^ same list size, but new memory peak at roughly twice the usage Peak: 80.2 MB, Data Len: 1.0 M Peak: 80.2 MB, Data Len: 1.0 M Peak: 80.2 MB, Data Len: 10.0 M Peak: 80.2 MB, Data Len: 10.0 M Peak: 118.3 MB, Data Len: 20.0 M # ^^ and again... (20+10)*c Peak: 118.3 MB, Data Len: 1.0 M Peak: 118.3 MB, Data Len: 1.0 M Peak: 118.3 MB, Data Len: 20.0 M Peak: 156.5 MB, Data Len: 20.0 M # ^^ and again. (20+20)*c Peak: 156.5 MB, Data Len: 1.0 M Peak: 156.5 MB, Data Len: 1.0 M The crazy belt-and-suspenders-and-duct-tape approach `data = None`, `del data`, and `gc.collect()` does nothing. I'm pretty sure the generator itself is not doubling up on memory because otherwise a single large value it yields would increase the peak usage, and in the *same iteration* a large object appeared; it's only large consecutive objects. How can I save my memory? Cheers, Nick cc: StackOverflow http://stackoverflow.com/q/21787099/194586 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pecore at pascolo.net Fri Feb 14 17:34:04 2014 From: pecore at pascolo.net (pecore at pascolo.net) Date: Fri, 14 Feb 2014 23:34:04 +0100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: <87iosh9vdv.fsf@pascolo.net> dave em writes: > He is asking a question I am having trouble answering which is how a > variable containing a value differs from a variable containing a > list or more specifically a list reference. s/list/mutable object/ # Mr Bond and Mr Tont are two different ob^H^H persons james_bond = SecretAgent() james_tont = SecretAgent() # in some circles, Mr Bond is know as agent 007 agent_007 = james_bond # Mr Bond, aka 007, is sent to the Caribbeans to crush Spectre agent_007.move_to('Barbados') print agent_007.location print james_bond.location # Mr Bond, alas, retires and his place in the Mi5 is taken, alas, by Mr Tont agent_007 = james_tont # Mr Tont, aka 007, is sent to Hong Kong to, to, whatever... agent_007.move_to('Hong Kong') print agent_007.location print james_bond.location From davea at davea.name Fri Feb 14 18:03:21 2014 From: davea at davea.name (Dave Angel) Date: Fri, 14 Feb 2014 18:03:21 -0500 (EST) Subject: Generator using item[n-1] + item[n] memory References: Message-ID: Nick Timkovich Wrote in message: > def biggen(): ?? ?? sizes = 1, 1, 10, 1, 1, 10, 10, 1, 1, 10, 10, 20, 1, 1, 20, 20, 1, 1 ?? ?? for size in sizes: ?? ?? ?? ?? data = [1] * int(size * 1e6) ?? ?? ?? ?? #time.sleep(1) ?? ?? ?? ?? yield data > def consumer(): ?? ?? for data in biggen(): ?? ?? ?? ?? rusage = resource.getrusage(resource.RUSAGE_SELF) ?? ?? ?? ?? peak_mb = rusage.ru_maxrss/1024.0 ?? ?? ?? ?? print('Peak: {0:6.1f} MB, Data Len: {1:6.1f} M'.format( ?? ?? ?? ?? ?? ?? ?? ?? peak_mb, len(data)/1e6)) ?? ?? ?? ?? #print(memory_usage()) ?? ?? ?? ?? data = None ??# go ?? ?? ?? ?? del data ?? ?? # away ?? ?? ?? ?? gc.collect() # please. ............ I think one problem is in the generator itself. After the yield, set data=None -- DaveA From ian.g.kelly at gmail.com Fri Feb 14 17:59:05 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Feb 2014 15:59:05 -0700 Subject: Generator using item[n-1] + item[n] memory In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 3:27 PM, Nick Timkovich wrote: > I have a Python 3.x program that processes several large text files that > contain sizeable arrays of data that can occasionally brush up against the > memory limit of my puny workstation. From some basic memory profiling, it > seems like when using the generator, the memory usage of my script balloons > to hold consecutive elements, using up to twice the memory I expect. > > I made a simple, stand alone example to test the generator and I get similar > results in Python 2.7, 3.3, and 3.4. My test code follows, `memory_usage()` > is a modifed version of [this function from an SO > question](http://stackoverflow.com/a/898406/194586) which uses > `/proc/self/status` and agrees with `top` as I watch it. `resource` is > probably a more cross-platform method: > > ############### > > import sys, resource, gc, time > > def biggen(): > sizes = 1, 1, 10, 1, 1, 10, 10, 1, 1, 10, 10, 20, 1, 1, 20, 20, 1, 1 > for size in sizes: > data = [1] * int(size * 1e6) > #time.sleep(1) > yield data > > def consumer(): > for data in biggen(): > rusage = resource.getrusage(resource.RUSAGE_SELF) > peak_mb = rusage.ru_maxrss/1024.0 > print('Peak: {0:6.1f} MB, Data Len: {1:6.1f} M'.format( > peak_mb, len(data)/1e6)) > #print(memory_usage()) > > data = None # go > del data # away > gc.collect() # please. > > # def memory_usage(): > # """Memory usage of the current process, requires /proc/self/status""" > # # http://stackoverflow.com/a/898406/194586 > # result = {'peak': 0, 'rss': 0} > # for line in open('/proc/self/status'): > # parts = line.split() > # key = parts[0][2:-1].lower() > # if key in result: > # result[key] = int(parts[1])/1024.0 > # return 'Peak: {peak:6.1f} MB, Current: {rss:6.1f} MB'.format(**result) > > print(sys.version) > consumer() > > ############### > > In practice I'll process data coming from such a generator loop, saving just > what I need, then discard it. > > When I run the above script, and two large elements come in series (the data > size can be highly variable), it seems like Python computes the next before > freeing the previous, leading to up to double the memory usage. > > [...] > > The crazy belt-and-suspenders-and-duct-tape approach `data = None`, `del > data`, and `gc.collect()` does nothing. Because at the time you call gc.collect(), the generator still holds a reference to the data, so it can't be collected. Assuming this is running in CPython and there are no reference cycles in the data, the collection is unnecessary anyway, since CPython will automatically free the data immediately when there are no references (but this is not guaranteed for other implementations of Python). > I'm pretty sure the generator itself is not doubling up on memory because > otherwise a single large value it yields would increase the peak usage, and > in the *same iteration* a large object appeared; it's only large consecutive > objects. Look again. What happens to the data between two iterations of the generator? 1) data variable holds the data from the prior iteration 2) the loop jumps back up to the top 3) the data for the next iteration is constructed 4) the data for the next iteration is assigned to the data variable It is not until step 4 that the variable stops referencing the data from the prior iteration. So there is a brief period where both of these objects must still be in memory. > How can I save my memory? Try unreferencing the data in the generator at the end of each iteration. From sforman at hushmail.com Fri Feb 14 17:08:52 2014 From: sforman at hushmail.com (Simon Forman) Date: Fri, 14 Feb 2014 14:08:52 -0800 Subject: A curious bit of code... In-Reply-To: Message-ID: <20140214220853.242A1200F8@smtp.hushmail.com> (Apologies if this results in a double-post.) On Friday, February 14, 2014 1:01:48 PM UTC-8, Mark Lawrence wrote: [snip] > > Pleased to have you on board, as I'm know that Terry Reedy et al can do > with a helping hand. > > But please note you appear to be using google groups, hence the double > line spacing above and trying to reply to paragraphs that run as a > single line across the screen. Therefore would you please read and > action this https://wiki.python.org/moin/GoogleGroupsPython, thanks. Ah! Thanks for the tip. ;-) (Just last night I was trying to explain to a friend about Usenet and how it's not Google Groups.) I really hope I can be of use with IDLE. I've been using it for years now. :) Warm regards, ~Simon -- http://phoenixbureau.org/ http://phoenixbureau.org/blog.html http://twitter.com/SimonForman "The history of mankind for the last four centuries is rather like that of an imprisoned sleeper, stirring clumsily and uneasily while the prison that restrains and shelters him catches fire, not waking but incorporating the crackling and warmth of the fire with ancient and incongruous dreams, than like that of a man consciously awake to danger and opportunity." --H. P. Wells, "A Short History of the World" From ned at nedbatchelder.com Fri Feb 14 19:00:36 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 14 Feb 2014 19:00:36 -0500 Subject: Explanation of list reference In-Reply-To: <87mwhtnzdu.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: On 2/14/14 4:43 PM, Marko Rauhamaa wrote: > Chris Angelico: > >> >be careful of simplifications that will cause problems down the line. > Sure. Let it be said, though, that sometimes you learn through > inaccuracies, a technique used intentionally by Knuth's TeXBook, for > example. In fact, you get through highschool mathematics successfully > without knowing what numbers and variables actually are. > Yes, sometimes for teaching reasons, you have to over-simplify or even introduce artificial constructs. I'd recommend acknowledging them as such. When you say, "There are two fundamentally different kinds of values in Python," or "So we have four kinds of (memory) slots," you aren't letting on that this is a teaching construct. It sounds like you mean that this is how Python actually works. I'd use words like, "This is an oversimplification, but might help...", or "You can think of it like ...". -- Ned Batchelder, http://nedbatchelder.com From jeanpierreda at gmail.com Fri Feb 14 19:26:23 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 14 Feb 2014 16:26:23 -0800 Subject: Working with the set of real numbers In-Reply-To: References: <8e4c1ab1-e65d-483f-ad9d-6933ae2052c3@googlegroups.com> <52f59aeb$0$29972$c3e8da3$5496439d@news.astraweb.com> <7cc8f49d-a4c7-48c2-a0af-ac58c847d794@googlegroups.com> <71e578f8-0d23-4b8e-b9f2-b987bdc9c01d@googlegroups.com> <85r478bv99.fsf_-_@benfinney.id.au> <85ioskbtfm.fsf@benfinney.id.au> <85eh38bq5z.fsf@benfinney.id.au> <871tz7864a.fsf@elektro.pacujo.net> <87fvnm7q1n.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 14, 2014 at 3:30 AM, Gregory Ewing wrote: > Devin Jeanpierre wrote: >> There is no way to iterate over all the reals one at a time, no matter >> how fast you execute instructions. If you could, it would be trivial >> to show that the reals have the same cardinality as the positive >> integers: correspond n with the whatever is returned by the nth call >> to it.next. > > > You're assuming that the calls to it.next are discrete > events separated by some nonzero time interval. I'm not. If you want to imagine infinitely fast computers, you must allow for things to "precede" each other in the program's execution, or else you can't execute any program at all. In such an infinitely fast computer, if iteration works by calling a .next() method repeatedly, it can't iterate uncountably many times, by construction. If you're executing uncountably many instructions per second, the loop would terminate immediately, having executed countably infinitely many iterations. > A decent transfinite processor would make a continuum > of calls, and execute uncountably many of them in any > finite period of time. Yes, you could imagine a computer that does a thing for every real. My issue is that the cited thing is transfinite induction, for which the induction covers countably many values; handling of the rest of the values is a second step. This is also the implication of such a word as "iteration". I suppose this was accidental on the part of the poster, and I shouldn't have disagreed so strongly. I suspect they meant what you are getting at, instead, which is that there is no successor to any iteration, and between any two iterations there are uncountably many iterations that happened. Operations occur in an order, but not sequentially. (Of course, such a machine would be alien and absurd.) -- Devin From daveandem2000 at gmail.com Fri Feb 14 19:26:34 2014 From: daveandem2000 at gmail.com (dave em) Date: Fri, 14 Feb 2014 16:26:34 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: All, Thanks for the excellent explanations and for sharing your knowledge. I definitely have a better understanding than I did this morning. Best regards, Dave From rosuav at gmail.com Fri Feb 14 19:57:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 11:57:33 +1100 Subject: Explanation of list reference In-Reply-To: <87mwhtnzdu.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 8:43 AM, Marko Rauhamaa wrote: > Unfortunately neither the "everything is a reference" model nor the > "small/big" model help you predict the value of an "is" operator in the > ambiguous cases. Can you give an example of an ambiguous case? Fundamentally, the 'is' operator tells you whether its two operands are exactly the same object, nothing more and nothing less, so I assume your "ambiguous cases" are ones where it's possible for two things to be either the same object or two indistinguishable ones. The only situation I can think of is that immutables are allowed to be interned, which is why this comes up True (in CPython) when it would come up False with larger values (as I demonstrated earlier): >>> x = 1 >>> y = 2 >>> z = x + y >>> z is 3 True ChrisA From roy at panix.com Fri Feb 14 20:47:10 2014 From: roy at panix.com (Roy Smith) Date: Fri, 14 Feb 2014 20:47:10 -0500 Subject: How to turn a package into something pip can install Message-ID: I want to use (https://github.com/timetric/python-metar). Our deployment process more or less requires that it be installed via pip. We maintain our own cache of packages and install using: pip install --no-index --quiet --find-links packages --requirement requirements.txt What I can't figure out is what I need to do to go from a clone of the github repo to a tarball I can drop into our packages directory. Is there some tutorial somewhere that explains this? From rymg19 at gmail.com Fri Feb 14 20:58:09 2014 From: rymg19 at gmail.com (Ryan Gonzalez) Date: Fri, 14 Feb 2014 19:58:09 -0600 Subject: How to begin In-Reply-To: <85zjlu7bou.fsf@benfinney.id.au> References: <8a78be96-7d26-47ff-9627-246d85410cd2@googlegroups.com> <52FD4C40.9050001@gmail.com> <85zjlu7bou.fsf@benfinney.id.au> Message-ID: Ack, I meant that, not the whole reference. On Thu, Feb 13, 2014 at 6:57 PM, Ben Finney wrote: > Ryan Gonzalez writes: > > > Read the Python reference. I know it's long, but it saves you trouble > > of accidentally reinventing the wheel. > > Hmm, the language reference is targeted at people *implementing* Python, > not people who are learning to use it (though it is valuable for them > also). It would be rather overwhelming for a beginner, IMO. > > You should instead be directing newcomers to beginner documentation, > such as and especially > the Python tutorial . > > -- > \ "If you get invited to your first orgy, don't just show up | > `\ nude. That's a common mistake. You have to let nudity | > _o__) 'happen.'" --Jack Handey | > Ben Finney > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Ryan If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated." -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Fri Feb 14 20:55:52 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 17:55:52 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> On Saturday, February 15, 2014 6:27:33 AM UTC+5:30, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 8:43 AM, Marko Rauhamaa wrote: > > Unfortunately neither the "everything is a reference" model nor the > > "small/big" model help you predict the value of an "is" operator in the > > ambiguous cases. > Can you give an example of an ambiguous case? Fundamentally, the 'is' > operator tells you whether its two operands are exactly the same > object, nothing more and nothing less, so I assume your "ambiguous > cases" are ones where it's possible for two things to be either the > same object or two indistinguishable ones. Fundamentally your definition above is circular: In effect the python expr "a is b" is the same as a is b. The only way to move ahead on that circularity is to 'leak-out' the under-belly of python's object-model. My own preference: No is operator; only id when we deliberately need to poke into the implementation. Of course I am in a miniscule minority I guess on that :-) From rymg19 at gmail.com Fri Feb 14 21:00:18 2014 From: rymg19 at gmail.com (Ryan Gonzalez) Date: Fri, 14 Feb 2014 20:00:18 -0600 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: python setup.py sdist On Fri, Feb 14, 2014 at 7:47 PM, Roy Smith wrote: > I want to use (https://github.com/timetric/python-metar). Our > deployment process more or less requires that it be installed via pip. > We maintain our own cache of packages and install using: > > pip install --no-index --quiet --find-links packages --requirement > requirements.txt > > What I can't figure out is what I need to do to go from a clone of the > github repo to a tarball I can drop into our packages directory. Is > there some tutorial somewhere that explains this? > -- > https://mail.python.org/mailman/listinfo/python-list > -- Ryan If anybody ever asks me why I prefer C++ to C, my answer will be simple: "It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was nul-terminated." -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Fri Feb 14 21:08:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 13:08:39 +1100 Subject: Explanation of list reference In-Reply-To: <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 12:55 PM, Rustom Mody wrote: > On Saturday, February 15, 2014 6:27:33 AM UTC+5:30, Chris Angelico wrote: >> Can you give an example of an ambiguous case? Fundamentally, the 'is' >> operator tells you whether its two operands are exactly the same >> object, nothing more and nothing less > > Fundamentally your definition above is circular: In effect > the python expr "a is b" is the same as a is b. It's not circular, it's stating the definition of the operator. And since the definition is so simple, it's impossible - at that level - for it to be ambiguous. It's possible for equality to be ambiguous, if you have two types which define __eq__: class Everyone: def __eq__(self, other): return True class Noone: def __eq__(self, other): return False >>> Everyone()==Noone() True >>> Noone()==Everyone() False But it's not possible for 'is' to behave like that. ChrisA From roy at panix.com Fri Feb 14 21:26:03 2014 From: roy at panix.com (Roy Smith) Date: Fri, 14 Feb 2014 21:26:03 -0500 Subject: How to turn a package into something pip can install References: Message-ID: In article , Ryan Gonzalez wrote: > python setup.py sdist OK, I run that and I get a metar-1.4.0.tar.gz under dist. If I move that tarfile to my packages directory, and run pip, I get: $ pip install --no-index --quiet --find-links packages metar==1.4.0 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 504, in run self.__target(*self.__args, **self.__kwargs) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1. 1-py2.7.egg/pip/index.py", line 245, in _get_queued_page page = self._get_page(location, req) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1. 1-py2.7.egg/pip/index.py", line 335, in _get_page return HTMLPage.get_page(link, req, cache=self.cache) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1. 1-py2.7.egg/pip/index.py", line 452, in get_page resp = urlopen(url) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1. 1-py2.7.egg/pip/download.py", line 85, in __call__ response = urllib2.urlopen(self.get_request(url)) File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 392, in open protocol = req.get_type() File "/usr/lib/python2.7/urllib2.py", line 254, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: packages Could not find any downloads that satisfy the requirement metar==1.4.0 No distributions at all found for metar==1.4.0 Storing complete log in /home/roy/.pip/pip.log > > > On Fri, Feb 14, 2014 at 7:47 PM, Roy Smith wrote: > > > I want to use (https://github.com/timetric/python-metar). Our > > deployment process more or less requires that it be installed via pip. > > We maintain our own cache of packages and install using: > > > > pip install --no-index --quiet --find-links packages --requirement > > requirements.txt > > > > What I can't figure out is what I need to do to go from a clone of the > > github repo to a tarball I can drop into our packages directory. Is > > there some tutorial somewhere that explains this? > > -- > > https://mail.python.org/mailman/listinfo/python-list > > From rustompmody at gmail.com Fri Feb 14 21:34:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 18:34:39 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> Message-ID: On Saturday, February 15, 2014 7:38:39 AM UTC+5:30, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 12:55 PM, Rustom Mody wrote: > > On Saturday, February 15, 2014 6:27:33 AM UTC+5:30, Chris Angelico wrote: > >> Can you give an example of an ambiguous case? Fundamentally, the 'is' > >> operator tells you whether its two operands are exactly the same > >> object, nothing more and nothing less > > Fundamentally your definition above is circular: In effect > > the python expr "a is b" is the same as a is b. > It's not circular, it's stating the definition of the operator. And > since the definition is so simple, it's impossible - at that level - > for it to be ambiguous. It's possible for equality to be ambiguous, if > you have two types which define __eq__: At what level can you explain the following? >>> x = 1234567 * 1234567 >>> x 1524155677489L >>> y = 1234567 * 1234567 >>> y 1524155677489L >>> x is y False >>> 1524155677489 == x True >>> 1524155677489 is x False >>> As against >>> x = 2*3 >>> y= 2*3 >>> x == y True >>> x is y True >>> 6 is x True >>> "Interning" you will say. Is interning a simple matter for example at the level of questioning of the OP? From rosuav at gmail.com Fri Feb 14 21:42:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 13:42:14 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 1:34 PM, Rustom Mody wrote: > At what level can you explain the following? > >>>> x = 1234567 * 1234567 >>>> x > 1524155677489L Well, for a start, I'd use Python 3, so there's no need to explain why some numbers have an L after them :) > As against > >>>> x = 2*3 >>>> 6 is x > True > > "Interning" you will say. > Is interning a simple matter for example at the level of questioning of the OP? When it's utterly impossible for it to matter in any way, Python is allowed to reuse objects. I think that's simple enough to explain. There's nothing you can do to distinguish one 6 from another, so Python's allowed to have them the same. ChrisA From prometheus235 at gmail.com Fri Feb 14 21:57:31 2014 From: prometheus235 at gmail.com (Nick Timkovich) Date: Fri, 14 Feb 2014 20:57:31 -0600 Subject: Generator using item[n-1] + item[n] memory Message-ID: Ah, I think I was equating `yield` too closely with `return` in my head. Whereas `return` results in the destruction of the function's locals, `yield` I should have known keeps them around, a la C's `static` functions. Many thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Fri Feb 14 22:14:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 19:14:13 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> Message-ID: <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> On Saturday, February 15, 2014 8:12:14 AM UTC+5:30, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 1:34 PM, Rustom Mody wrote: > > At what level can you explain the following? > >>>> x = 1234567 * 1234567 > >>>> x > > 1524155677489L > Well, for a start, I'd use Python 3, so there's no need to explain why > some numbers have an L after them :) Nice point! And only sharpens what I am saying -- python 3 is probably more confusing than 2 wrt object identity > > As against > >>>> x = 2*3 > >>>> 6 is x > > True > > "Interning" you will say. > > Is interning a simple matter for example at the level of questioning of the OP? > When it's utterly impossible for it to matter in any way, Python is > allowed to reuse objects. > I think that's simple enough to explain. There's nothing you can do to > distinguish one 6 from another, so Python's allowed to have them the > same. Simple?? >>> x=1234 >>> y=1234 >>> x is y False >>> 1234 is 1234 True >>> x=123 >>> y=123 >>> x is y True ------------- "utterly impossible to matter"... "nothing you can do to distinguish one 6 from another" All depend on doing one of these 3 for dealing with object identity 1. Circular definition 2. Delve into implementation 3. Wildly wave the hands As a teacher Ive done more than my fair share of all especially 3 but if you have a 4th option Id be interested to know! Philosophically"to be" called the copula is such a knotty problem that there is an entire movement to create a version of English without any form of "is,are,be" etc http://en.wikipedia.org/wiki/E-Prime From roy at panix.com Fri Feb 14 22:21:11 2014 From: roy at panix.com (Roy Smith) Date: Fri, 14 Feb 2014 22:21:11 -0500 Subject: Generator using item[n-1] + item[n] memory References: Message-ID: In article , Nick Timkovich wrote: > Ah, I think I was equating `yield` too closely with `return` in my head. > Whereas `return` results in the destruction of the function's locals, > `yield` I should have known keeps them around, a la C's `static` functions. > Many thanks! It's not quite like C's static. With C's static, the static variables are per-function. In Python, yield creates a context per invocation. Thus, I can do def f(): for i in range(10000): yield i g1 = f() g2 = f() print g1.next() print g1.next() print g1.next() print g2.next() print g1.next() which prints 0, 1, 2, 0, 3. There's two contexts active at the same time, with a distinct instance of "i" in each one. From gheskett at wdtv.com Fri Feb 14 22:25:59 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Fri, 14 Feb 2014 22:25:59 -0500 Subject: Question on using FP numbers in python 2 Message-ID: <201402142225.59647.gheskett@wdtv.com> Greetings; Is there something I can search for and fix in some python code that is giving me bogus answers that get good only when there is a valid digit to the left of the decimal point? 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) Genes Web page NOTICE: Will pay 100 USD for an HP-4815A defective but complete probe assembly. From prometheus235 at gmail.com Fri Feb 14 22:31:49 2014 From: prometheus235 at gmail.com (Nick Timkovich) Date: Fri, 14 Feb 2014 21:31:49 -0600 Subject: Generator using item[n-1] + item[n] memory In-Reply-To: References: Message-ID: OK, now the trick; adding `data = None` inside the generator works, but in my actual code I wrap my generator inside of `enumerate()`, which seems to obviate the "fix". Can I get it to play nice or am I forced to count manually. Is that a feature? On Fri, Feb 14, 2014 at 9:21 PM, Roy Smith wrote: > In article , > Nick Timkovich wrote: > > > Ah, I think I was equating `yield` too closely with `return` in my head. > > Whereas `return` results in the destruction of the function's locals, > > `yield` I should have known keeps them around, a la C's `static` > functions. > > Many thanks! > > It's not quite like C's static. With C's static, the static variables > are per-function. In Python, yield creates a context per invocation. > Thus, I can do > > def f(): > for i in range(10000): > yield i > > g1 = f() > g2 = f() > print g1.next() > print g1.next() > print g1.next() > print g2.next() > print g1.next() > > > which prints 0, 1, 2, 0, 3. There's two contexts active at the same > time, with a distinct instance of "i" in each one. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Fri Feb 14 22:33:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 14:33:36 +1100 Subject: Explanation of list reference In-Reply-To: <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 2:14 PM, Rustom Mody wrote: > On Saturday, February 15, 2014 8:12:14 AM UTC+5:30, Chris Angelico wrote: >> Well, for a start, I'd use Python 3, so there's no need to explain why >> some numbers have an L after them :) > > Nice point! > And only sharpens what I am saying -- python 3 is probably more confusing than > 2 wrt object identity How so? Py3 eliminates an unnecessary difference: >>> 1L == 1 True >>> 1L is 1 False In Py3, this can't happen, because there simply is no distinction. (That said, the Py3 unification does mean that small integers pay the performance cost of long integers. I've mentioned before that it may be worth having an "under the covers" optimization whereby small integers are stored in a machine word - but this should be utterly invisible to the user. As far as the programmer's concerned, an int is an int is an int.) >> When it's utterly impossible for it to matter in any way, Python is >> allowed to reuse objects. >> >> I think that's simple enough to explain. There's nothing you can do to >> distinguish one 6 from another, so Python's allowed to have them the >> same. > > Simple?? > >>>> x=1234 >>>> y=1234 >>>> x is y > False >>>> 1234 is 1234 > True >>>> x=123 >>>> y=123 >>>> x is y > True In all three cases, Python is allowed to use separate objects. Nothing forces them to be shared. But in all three cases, there's no way you could distinguish one from another, so Python's allowed to reuse the same object. > "utterly impossible to matter"... > "nothing you can do to distinguish one 6 from another" > > All depend on doing one of these 3 for dealing with object identity > 1. Circular definition > 2. Delve into implementation > 3. Wildly wave the hands How do you distinguish between any other identical things? Once you've decided that they're equal, somehow you need to separate identity from value. I could have three six-sided dice, all made from the same mould, and yet each one is a separate object. If I hold all three in my hand and toss them onto the table, can I recognize which one is which? No, they're identical. Are they distinct objects? Yes. ChrisA From rosuav at gmail.com Fri Feb 14 22:39:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 14:39:43 +1100 Subject: Question on using FP numbers in python 2 In-Reply-To: <201402142225.59647.gheskett@wdtv.com> References: <201402142225.59647.gheskett@wdtv.com> Message-ID: On Sat, Feb 15, 2014 at 2:25 PM, Gene Heskett wrote: > Is there something I can search for and fix in some python code that is > giving me bogus answers that get good only when there is a valid digit to > the left of the decimal point? > Interesting. I'd look for anything that mixes very large and very small numbers, first off. Otherwise, just follow the standard debugging technique of stripping code out of your program and seeing if the problem's still there. Continue until you have the barest minimum, and hope hope hope that it's a Bohr bug and not a Heisenbug! If it really is a floating point issue, you probably don't have to worry about, for instance, a segfault that happens when a garbage collection run occurs between this statement and that statement... yes, I've had to deal with that sort of thing! (Turned out to be a refcount bug in C code. When the gc ran, something got disposed of that shouldn't have.) ChrisA From ben+python at benfinney.id.au Fri Feb 14 23:20:36 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Feb 2014 15:20:36 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <85vbwh6m7f.fsf@benfinney.id.au> Marko Rauhamaa writes: > Chris Angelico : > > Distinguishing "small values" from "big values" leads to the obvious > > question: Which is which? And why doesn't this work? > > This is related to the recent id(string) question on this forum. > > Unfortunately neither the "everything is a reference" model nor the > "small/big" model help you predict the value of an "is" operator in the > ambiguous cases. You should never need to predict the result of an ?is? operation. (More precisely, for *some* cases you can predict it, but for other cases you can't.) The Python implementation is free to behave unpredictably for the state of object identity. It may have some objects that conceptually may be different (i.e. you'd predict the ?is? operation would return False) actually be the same object (i.e. the ?is? operation would return True). Exactly the same case may behave differently in this regard on other Python implementations, or different versions of the same Python implementation, or even exactly the same version of the Python implementation under different circumstances. The management of object identity is an implementation detail, not to be relied on in your Python code. So, if your teaching method depends on general principles for predicting object identity, you're already losing. > Explaining Python's memory model at some level is necessary right off > the bat. However, it is far from easy to understand. The use of the term ?variable?, and all the implications that has for ?variables contain values? etc., is IMO too confusing, and its use in the Python documentation is not helping this. Rather, I recommend that people teaching Python should avoid the term ?variable? entirely, and use the term ?reference? which much more accurately implies Python's data model. An addressable item in a container is a reference, as is a name. Assignment binds a reference to a value. And so on. This article by the Effbot corrects similar misconceptions , and is a valuable approach to teaching the Python data model. -- \ ?Theology is the effort to explain the unknowable in terms of | `\ the not worth knowing.? ?Henry L. Mencken | _o__) | Ben Finney From flebber.crue at gmail.com Fri Feb 14 23:20:44 2014 From: flebber.crue at gmail.com (flebber) Date: Fri, 14 Feb 2014 20:20:44 -0800 (PST) Subject: Best practices to overcome python's dynamic data type nature In-Reply-To: References: <5fd7e804-820e-4fe1-b36b-67e553f3aedf@googlegroups.com> Message-ID: <1f83e525-2c3a-4b03-9625-90e22f0e30ae@googlegroups.com> Here's a great resource http://www.anrdoezrs.net/click-7079286-11260198?url=http%3A%2F%2Fshop.oreilly.com%2Fproduct%2F0636920029533.do%3Fcmp%3Daf-code-book-product_cj_9781449367794_%7BPID%7D&cjsku=0636920029533 Sayth From rustompmody at gmail.com Fri Feb 14 23:24:20 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 20:24:20 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Saturday, February 15, 2014 9:03:36 AM UTC+5:30, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 2:14 PM, Rustom Mody wrote: > > On Saturday, February 15, 2014 8:12:14 AM UTC+5:30, Chris Angelico wrote: > >> Well, for a start, I'd use Python 3, so there's no need to explain why > >> some numbers have an L after them :) > > Nice point! > > And only sharpens what I am saying -- python 3 is probably more confusing than > > 2 wrt object identity > How so? Py3 eliminates an unnecessary difference: > >>> 1L == 1 > True > >>> 1L is 1 > False > In Py3, this can't happen, because there simply is no distinction. > (That said, the Py3 unification does mean that small integers pay the > performance cost of long integers. I've mentioned before that it may > be worth having an "under the covers" optimization whereby small > integers are stored in a machine word - but this should be utterly > invisible to the user. As far as the programmer's concerned, an int is > an int is an int.) > >> When it's utterly impossible for it to matter in any way, Python is > >> allowed to reuse objects. > >> I think that's simple enough to explain. There's nothing you can do to > >> distinguish one 6 from another, so Python's allowed to have them the > >> same. > > Simple?? > >>>> x=1234 > >>>> y=1234 > >>>> x is y > > False > >>>> 1234 is 1234 > > True > >>>> x=123 > >>>> y=123 > >>>> x is y > > True > In all three cases, Python is allowed to use separate objects. Nothing > forces them to be shared. But in all three cases, there's no way you > could distinguish one from another, so Python's allowed to reuse the > same object. > > "utterly impossible to matter"... > > "nothing you can do to distinguish one 6 from another" > > All depend on doing one of these 3 for dealing with object identity > > 1. Circular definition > > 2. Delve into implementation > > 3. Wildly wave the hands > How do you distinguish between any other identical things? Once you've > decided that they're equal, somehow you need to separate identity from > value. Implicit circularity problem continues... See below > I could have three six-sided dice, all made from the same > mould, and yet each one is a separate object. If I hold all three in > my hand and toss them onto the table, can I recognize which one is > which? No, they're identical. Are they distinct objects? Yes. In the case of physical objects like dice there is a fairly unquestionable framing that makes identity straightforward -- 4-dimensional space-time coordiantes. If the space-time coordinates of 2 objects are all equal then the objects are identical, else not. Now we analogize the space-time identity of physical objects to computer identity of computer objects (so-called) and all sorts of problems ensue. To start with we say two objects are identical if they have the same memory address. Then what happens to the same memory address on different computers? If you say nothing on two different computers are identical then how do you define the correctness of a serialization protocol? And is 'different computer' even well-defined? Think of clusters, COWs NOWs, and other beasties ending in the cloud... IOW when we analogize 4-dim infinite space-time into the confines of 'a computer' weve bought bigger problems than we disposed off, because - for space-time it is unreasonable to imagine a larger frame into which that is embedded - for computers that larger frame is a key part -- starting with the fact that you and I are having a conversation right now tl;dr Analogizing physical objects to computer 'objects' is a mistake From steve+comp.lang.python at pearwood.info Fri Feb 14 23:26:14 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 04:26:14 GMT Subject: Question on using FP numbers in python 2 References: Message-ID: <52feec65$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 22:25:59 -0500, Gene Heskett wrote: > Greetings; > > Is there something I can search for and fix in some python code that is > giving me bogus answers that get good only when there is a valid digit > to the left of the decimal point? Er, yes? Anything which involves floating point maths? Your question is to vague to really answer. You are basically saying "I'm doing some calculations [what sort of calculations?] with floats [how many floats? of what values?], and they're wrong [wrong in what way? how badly wrong?] unless there is a valid digit [which digits count as valid and which as invalid?] to the left of the decimal point in some number." Can you extract the float calculations and show us, together with some sample data, expected result, and actual result? -- Steven From pabloeruggeri at gmail.com Fri Feb 14 23:27:45 2014 From: pabloeruggeri at gmail.com (pabloeruggeri at gmail.com) Date: Fri, 14 Feb 2014 20:27:45 -0800 (PST) Subject: I'm trying to do this code, can somebody help me Message-ID: <045b1b2d-625c-4499-9fa8-d536b1ec4da4@googlegroups.com> 1)Given the variables x , y , and z , each associated with an int , write a fragment of code that assigns the smallest of these to min this is what I have def main(): x = eval ( input ("dame el numero X")) y = eval ( input ("dame el numero Y")) z = eval ( input ("dame el numero Z")) if(x>y and z>y): min=y print(min) else: if(y>x and z>x): min=x print(min) else: min=z print(min) main() From rosuav at gmail.com Fri Feb 14 23:37:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 15:37:20 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 3:24 PM, Rustom Mody wrote: >> I could have three six-sided dice, all made from the same >> mould, and yet each one is a separate object. If I hold all three in >> my hand and toss them onto the table, can I recognize which one is >> which? No, they're identical. Are they distinct objects? Yes. > > In the case of physical objects like dice there is a fairly > unquestionable framing that makes identity straightforward -- > 4-dimensional space-time coordiantes. If the space-time coordinates of > 2 objects are all equal then the objects are identical, else not. Not once you roll them, which is why I specifically used dice. This exact situation comes up in roleplaying games - suppose you want to get a random number from 0 to 999 (or 1 to 1000, by declaring that a result of 0 is interpreted as 1000). The most common way to do this is to roll 10-sided dice for the digits; you can either roll one d10 three times, or three dice all at once. In the latter case, you somehow need to pre-declare which one is the hundreds digit, which is the tens, and which is the units, which means you need some way to distinguish the three dice after you roll them (as you can't recognize by position). This is why dice exist in a variety of colors [1]. Indistinguishable yet distinct dice... and it's actually possible to merge all three into a single object (which is what happens when you roll one three times instead of rolling three once), just as Python is allowed to do. By the way, if you get into quantum physics, you can't depend on three dimensions of space and one of time to distinguish objects. You also need spin. And I think you also need insanity, because you'll be given it on arrival if you don't have enough. ChrisA [1] Well, that and to look cool. I don't know that any system other than FATAL requires you to roll d1,000,000 on six dice, so three colors would normally be sufficient. But it's fun to have the full spectrum. From invalid at invalid.invalid Fri Feb 14 23:35:14 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Feb 2014 04:35:14 +0000 (UTC) Subject: Question on using FP numbers in python 2 References: Message-ID: On 2014-02-15, Gene Heskett wrote: > Is there something I can search for and fix in some python code that > is giving me bogus answers that get good only when there is a valid > digit to the left of the decimal point? Yes. Search for incorrectly written code and fix it. I'd start part way down in that one file, and then also look in that other file, but not as far down. At least he doesn't think he's using real numbers... From gheskett at wdtv.com Fri Feb 14 23:46:17 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Fri, 14 Feb 2014 23:46:17 -0500 Subject: Question on using FP numbers in python 2 In-Reply-To: References: <201402142225.59647.gheskett@wdtv.com> Message-ID: <201402142346.17752.gheskett@wdtv.com> On Friday 14 February 2014 23:37:53 Chris Angelico did opine: > On Sat, Feb 15, 2014 at 2:25 PM, Gene Heskett wrote: > > Is there something I can search for and fix in some python code that > > is giving me bogus answers that get good only when there is a valid > > digit to the left of the decimal point? > > Interesting. I'd look for anything that mixes very large and very > small numbers, first off. Otherwise, just follow the standard > debugging technique of stripping code out of your program and seeing > if the problem's still there. Continue until you have the barest > minimum, and hope hope hope that it's a Bohr bug and not a Heisenbug! > > If it really is a floating point issue, you probably don't have to > worry about, for instance, a segfault that happens when a garbage > collection run occurs between this statement and that statement... > yes, I've had to deal with that sort of thing! (Turned out to be a > refcount bug in C code. When the gc ran, something got disposed of > that shouldn't have.) > > ChrisA It is the top utility in this page of linuxcnc code generators: I looked at it, just enough to understand I haven't learned a thing in 2 years of lurking on this list. I see Big John has a bug note, and its possible this might be related. You can get it at the upper link, or there is a copy on my pages, under Genes-os9-stf/LCNC directory. 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) Genes Web page NOTICE: Will pay 100 USD for an HP-4815A defective but complete probe assembly. From rosuav at gmail.com Fri Feb 14 23:47:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 15:47:33 +1100 Subject: I'm trying to do this code, can somebody help me In-Reply-To: <045b1b2d-625c-4499-9fa8-d536b1ec4da4@googlegroups.com> References: <045b1b2d-625c-4499-9fa8-d536b1ec4da4@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 3:27 PM, wrote: > 1)Given the variables x , y , and z , each associated with an int , write a fragment of code that assigns the smallest of these to min This is homework. Please be honest about it; we will help you to learn, but we won't write your code for you. > this is what I have > > def main(): > x = eval ( input ("dame el numero X")) > y = eval ( input ("dame el numero Y")) > z = eval ( input ("dame el numero Z")) Using eval is slow and dangerous; what you probably want here is simply int(). > if(x>y and z>y): > min=y > print(min) Oh, you're so close here :) The name "min" should be a clue. If you type this into a Python-sensitive editor like IDLE, it might even be highlighted in a different color. > else: > if(y>x and z>x): > min=x > print(min) > else: > min=z > print(min) > > main() Okay. So why are you posting your code? Is it doing the wrong thing? Is it throwing an exception? Is it sneaking out and kissing your girlfriend? (I will never tolerate a program doing that, especially as it would imply that I have a girlfriend.) Is it working perfectly but you'd like to see it shorter? Are you hoping for a general code review? Ask a question regarding the code. Since you haven't asked anything else, I'll make a few stylistic recommendations. Firstly, indenting by a single space is a bit too compact; it's hard to see exactly how far in you are. I like to use one tab for each indentation level; some prefer to use four spaces, or eight spaces. Two spaces is usually considered too tight; more than eight (or more than one tab) is extremely sparse; three, five, six, and seven are just weird. Four or eight spaces, or exactly one tab, would be the most common. Also, putting your code inside main() and then immediately calling main() doesn't help you much. If you want your module to be importable from elsewhere, you'll need to check __name__, but I suspect you haven't learned that yet. Otherwise, just put all your code at top level and avoid the boiler-plate. Instead of nesting 'if' inside 'else', you can merge the two into a single 'elif', which makes good sense here. What happens if two of your inputted numbers are equal? ChrisA From gheskett at wdtv.com Sat Feb 15 00:07:49 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Sat, 15 Feb 2014 00:07:49 -0500 Subject: Question on using FP numbers in python 2 In-Reply-To: <52feec65$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <52feec65$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <201402150007.49667.gheskett@wdtv.com> On Friday 14 February 2014 23:47:26 Steven D'Aprano did opine: > On Fri, 14 Feb 2014 22:25:59 -0500, Gene Heskett wrote: > > Greetings; > > > > Is there something I can search for and fix in some python code that > > is giving me bogus answers that get good only when there is a valid > > digit to the left of the decimal point? > > Er, yes? Anything which involves floating point maths? > > Your question is to vague to really answer. You are basically saying > "I'm doing some calculations [what sort of calculations?] with floats > [how many floats? of what values?], and they're wrong [wrong in what > way? how badly wrong?] unless there is a valid digit [which digits > count as valid and which as invalid?] to the left of the decimal point > in some number." > > Can you extract the float calculations and show us, together with some > sample data, expected result, and actual result? Not extract, but let you get & look at the code, its the top entry on this page: Assume no bolt size is clicked on, but a wanted diameter is entered in the lower left pair of boxes, and its to carve .700" deep in the other box. The cutting tool is .250 in diameter, its to do a stepover of 25% of the tool diameter, while carving an additional .015" out of the .850" hole with the tool bit turning 2000 rpm as it spirals down. But the hole it will cut will only be .650" in diameter, And the backplot, shown in the axis interface, shows no spiral, its doing what it thinks is full diameter in one circular plunge cut. That would leave a big post of steel in the center, so I will have to drill it to perhaps a half an inch just to keep from pinching & breaking a $20 bit. But that is a separate problem. So, I added a .2" offset to the hole diameter, making that entry 1.05". Then I do get the spiral outward feed, but to make a hole 1.05" in diameter. As for me fixing it, that 30+ kilobytes of python may as well be Navajo. IOW, help please? 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) Genes Web page From ian.g.kelly at gmail.com Sat Feb 15 00:20:35 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Feb 2014 22:20:35 -0700 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: > In the case of physical objects like dice there is a fairly > unquestionable framing that makes identity straightforward -- > 4-dimensional space-time coordiantes. If the space-time coordinates of > 2 objects are all equal then the objects are identical, else not. > > Now we analogize the space-time identity of physical objects to > computer identity of computer objects (so-called) and all sorts of > problems ensue. > > To start with we say two objects are identical if they have the same > memory address. This is false. It happens to hold for CPython, but that's an implementation detail. The definition of object identity does not depend on memory address. It also doesn't have anything to do with space-time coordinates. The concept of object identity is an abstraction, not an analogy from physics. The language reference states, "Every object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object's address in memory." Okay, so that quote does bring up memory address, but in my interpretation that's just an analogy to introduce the concept. The more important part of that sentence is the first part, which ties an object's identity to its creation. If two objects share the same creation, then they're the same object. From rosuav at gmail.com Sat Feb 15 00:28:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 16:28:16 +1100 Subject: Question on using FP numbers in python 2 In-Reply-To: <201402150007.49667.gheskett@wdtv.com> References: <52feec65$0$29973$c3e8da3$5496439d@news.astraweb.com> <201402150007.49667.gheskett@wdtv.com> Message-ID: On Sat, Feb 15, 2014 at 4:07 PM, Gene Heskett wrote: > Not extract, but let you get & look at the code, its the top entry on this > page: > > Code_Generators#Counterbore_Software> Interesting. At the top of the file, it says GPL3 or later; but then it puts a requirement on making money off the software. I'm not sure that's a good thing (what if someone lifts a small part of that code out and into another GPL project?), and I'm not sure it's legal/enforceable anyway. The GUI creation code calls to mind the discussion we had a little while ago about an alternative way to create a GUI in Python. Especially compare the GTK2Table() function that I posited - I'm sure it wouldn't be hard to make a Python (and Tkinter) equivalent. Massively complicated code for laying out a grid/table. But check out these comments: def GeneratePath(self): # If ToolDiameter > HoleDiameter then Complain # If ToolDiameter == HoleDiameter then Plunge to HoleDepth # If (ToolDiameter*1.25) <= HoleDiameter then Plunge to each Level and Spiral out to HoleDiameter # If (ToolDiameter*1.25) > HoleDiameter then Spiral to each Level and Spiral out to HoleDiameter (Also, owwww! The GeneratePath function is indented with a mixture of spaces and tabs. Most of it is indented "four spaces and then a tab", but some lines use other mixtures. Ow ow ow!) Does all that make sense, and are you seeing those boundaries correctly? I strongly suspect you're not seeing a floating-point error, but a deliberate piece of code and maybe some other form of bug. I very much doubt the boundary is anything to do with going over 1" in diameter; the numbers you're working with here are easily within Python's capability (you get roughly 15 decimal digits of accuracy with the default float type). I'm afraid I can't really help more, as I don't speak CNC. But have a look at GeneratePath(); it does have comments, and for all of being two hundred lines of code, it's reasonably segmented into sections. Manually step through it, see where it's going wrong. Standard Python debugging, nothing to do with floats AFAICT. ChrisA From rosuav at gmail.com Sat Feb 15 00:31:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 16:31:35 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 4:20 PM, Ian Kelly wrote: > On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: >> To start with we say two objects are identical if they have the same >> memory address. > > This is false. It happens to hold for CPython, but that's an > implementation detail. The definition of object identity does not > depend on memory address. It also doesn't have anything to do with > space-time coordinates. The concept of object identity is an > abstraction, not an analogy from physics. With the restrictions of computer memory, I suspect that two objects with the same address must be identical, simply because it's not possible for it to be otherwise. However, the converse isn't necessarily true; two objects may have the same identity while being at different addresses (or, more likely, one object may occupy different memory addresses over time, if the gc moves it around). But since memory addresses are completely inaccessible to Python code, we can't say whether two objects have the same address. ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 15 00:36:12 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 05:36:12 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 12:31:56 -0600, Ryan Gonzalez wrote: > On 02/14/2014 12:08 PM, dave em wrote: >> Hello, >> >> Background: My twelve y/o son and I are still working our way through >> Invent Your Own Computer Games with Python, 2nd Edition. (We finished >> the Khan Academy Javascript Tutorials is the extent of our experience) >> >> He is asking a question I am having trouble answering which is how a >> variable containing a value differs from a variable containing a list >> or more specifically a list reference. >> >> I tried the to explain as best I can remember is that a variable is >> assigned to a specific memory location with a value inside of it. >> Therefore, the variable is kind of self contained and if you change the >> variable, you change the value in that specific memory location. >> >> However, when a variable contains a list reference, the memory location >> of the variable points to a separate memory location that stores the >> list. It is also possible to have multiple variable that point to the >> memory location of the list reference. And all of those variable can >> act upon the list reference. >> >> Question: Is my explanation correct? If not please set me straight :) >> >> And does anyone have an easier to digest explanation? >> >> Thanks in advance, >> Dave > > You've got it backwards. In Python, /everything/ is a reference. What's a reference? How is the value 23 a reference? What is it a reference to? > The > variable is just a "pointer" to the actual value. When you change a > variable, you're just changing the memory location it points to. What do memory locations have to do with Python code? When I execute Python code in my head, perhaps using a pencil and paper, or build a quantum computer (or analog clockwork device) to execute Python code, where are the memory locations? I think you are conflating the *implementation* of Python's virtual machine in a C-like language written for a digital computer with the *defined behaviour* of the Python virtual machine. If you think about the Python execution model, there is almost nothing about memory locations in it. The only exception I can think of is the id() function, which uses the memory address of the object as the ID, and even that is *explicitly* described as an implementation detail and not a language feature. And in fact Jython and IronPython assign IDs to objects consecutively from 1, and PyPy has to go through heroic and complicated measures to ensure that objects have the same ID at all times. Thinking about the implementation of Python as written for certain types of digital computing devices can be useful, but we must be very careful to avoid mixing up details at the underlying C (or Java, or Haskell, or Lisp, or ...) layer with questions about the Python execution model. As soon as you mention "pointers", you're in trouble, because Python has no pointers. There is nothing in Python that will give you a pointer to an object, or dereference a pointer to get the object at the other end. Pointers in the sense of C or Pascal pointers to memory addresses simply don't have any existence in Python. Python compilers can even be written in languages like Java that don't have pointers. The fact that the C implementation of Python uses pointers internally is not very interesting, any more than the fact that a Python implementation running on a Turing Machine would use a pencil and eraser that can draw marks on a very long paper tape. > Strings, ints, tuples, and floats behave differently because they're > /immutable/. That means that they CANNOT modify themselves. That's why > all of the string methods return a new string. It also means that, when > you pass one two a function, a /copy/ of it is made and passed instead. Yes, strings etc. are immutable, but no, they are not copied when you pass them to a function. We can be sure of this for two reasons: (1) We can check the id() of the string from the inside and the outside of the function, and see that they are the same; and (2) We can create a HUGE string, hundreds of megabytes, and pass it to dozens of functions, and see no performance slowdown. It might take a second or five to build the initial string, and microseconds or less to pass it to function after function after function. > So, back to the original subject. Everything is a reference. To really under stand Python's behaviour, we need to see that there are two kinds of entities, names and values. Or another way to put it, references and objects. Or another way to put it, there's actually only one kind of thing in Python, that is, everything in Python is an object, but Python *code* can refer to objects indirectly by names and other references. Names aren't "things", but the things that names refer to are things. Objects have a clear definition in the Python world: they are an entity that has a type (e.g. a string), a set of behaviour (methods), and a value ("Hello World"). References can be names like `mystring`, or list items `mylist[0]`, or items in mappings `mydict["key"]`, or attributes `myobject.attr`, or even expressions `x+y*(1-z)`. References themselves aren't "things" as such (although in Python, *names* are implemented as string keys in namespaces), but a way to indirectly refer to things (values, objects). > When you do this: > > x = [1,2,3] > x = [4,5,6] > > x now points to a different memory location. Memory locations are irrelevant. Objects may not even have a single, well- defined memory location. (If you think this is impossible, you're focusing too much on a single computer architecture.) They might use some sort of copy-on-write mechanism so that objects don't even exist until you modify them. Who knows? Instead, we should say that x now refers to a different object. An analogy, the name "President of the United States" stopped referring to George Bush Jr and started referring to Barack Obama a few years back, but the "objects" (people) have an existence separate from the name used to refer to them. (By the way, I try to avoid using the term "points to" if I can, since it has connotations to those familiar with C which don't apply to Python.) > And, when you do this: > > x[0] =99000 > x[0] =100 > > you're just changing the memory location that |x[0]| points to. Again, I'd say that x[0] now refers to a different object. -- Steven From gheskett at wdtv.com Sat Feb 15 00:50:51 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Sat, 15 Feb 2014 00:50:51 -0500 Subject: Question on using FP numbers in python 2 In-Reply-To: References: <201402150007.49667.gheskett@wdtv.com> Message-ID: <201402150050.51950.gheskett@wdtv.com> On Saturday 15 February 2014 00:43:53 Chris Angelico did opine: > On Sat, Feb 15, 2014 at 4:07 PM, Gene Heskett wrote: > > Not extract, but let you get & look at the code, its the top entry on > > this page: > > > > > Code_Generators#Counterbore_Software> > > Interesting. At the top of the file, it says GPL3 or later; but then > it puts a requirement on making money off the software. I'm not sure > that's a good thing (what if someone lifts a small part of that code > out and into another GPL project?), and I'm not sure it's > legal/enforceable anyway. > > The GUI creation code calls to mind the discussion we had a little > while ago about an alternative way to create a GUI in Python. > Especially compare the GTK2Table() function that I posited - I'm sure > it wouldn't be hard to make a Python (and Tkinter) equivalent. > Massively complicated code for laying out a grid/table. > > But check out these comments: > > def GeneratePath(self): > # If ToolDiameter > HoleDiameter then Complain > # If ToolDiameter == HoleDiameter then Plunge to HoleDepth > # If (ToolDiameter*1.25) <= HoleDiameter then Plunge to each > Level and Spiral out to HoleDiameter > # If (ToolDiameter*1.25) > HoleDiameter then Spiral to each > Level and Spiral out to HoleDiameter > > (Also, owwww! The GeneratePath function is indented with a mixture of > spaces and tabs. Most of it is indented "four spaces and then a tab", > but some lines use other mixtures. Ow ow ow!) > > Does all that make sense, and are you seeing those boundaries > correctly? I strongly suspect you're not seeing a floating-point > error, but a deliberate piece of code and maybe some other form of > bug. I very much doubt the boundary is anything to do with going over > 1" in diameter; the numbers you're working with here are easily within > Python's capability (you get roughly 15 decimal digits of accuracy > with the default float type). > > I'm afraid I can't really help more, as I don't speak CNC. Actually, the output is RS-274-D, originally from NIST. But it has developed some pretty distinct "accents" in the 20 some years its been in the wild. The NIST version was, shall we say, quite incomplete but a lot of the stuff shoved in to scratch this or that itch is often vaguely incompatible with the next vendors version of that particular function. > But have a > look at GeneratePath(); it does have comments, and for all of being > two hundred lines of code, it's reasonably segmented into sections. > Manually step through it, see where it's going wrong. Standard Python > debugging, nothing to do with floats AFAICT. > > ChrisA I'll do that when next I have both eyes open at the same time. That is usually about halfway thru the third cuppa. :) Thanks Chris 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) Genes Web page NOTICE: Will pay 100 USD for an HP-4815A defective but complete probe assembly. From rosuav at gmail.com Sat Feb 15 01:07:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 17:07:17 +1100 Subject: Explanation of list reference In-Reply-To: <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 4:36 PM, Steven D'Aprano wrote: > References can be names like `mystring`, or list items `mylist[0]`, or > items in mappings `mydict["key"]`, or attributes `myobject.attr`, or even > expressions `x+y*(1-z)`. I agree with most of what you've said, but I'm not sure I like that last bit. The expression evaluates to an object, yes, but it's not itself a reference... is it? It has references to x, y, 1, and z, but it's not itself a reference to anything. If you take a reference and assign it to a name, and take that same reference and assign it to another name, I would expect those two names to now refer to the same object: >>> lst = [1000, 2000, 3000] >>> x = lst[1] >>> y = lst[1] >>> x is y True But with expressions, it's not so, and new objects may be created. The expression isn't a reference to its result, but it can yield an object, which it (naturally) does by reference. ChrisA From rosuav at gmail.com Sat Feb 15 01:08:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 17:08:44 +1100 Subject: Question on using FP numbers in python 2 In-Reply-To: <201402150050.51950.gheskett@wdtv.com> References: <201402150007.49667.gheskett@wdtv.com> <201402150050.51950.gheskett@wdtv.com> Message-ID: On Sat, Feb 15, 2014 at 4:50 PM, Gene Heskett wrote: >> I'm afraid I can't really help more, as I don't speak CNC. > > Actually, the output is RS-274-D, originally from NIST. But it has > developed some pretty distinct "accents" in the 20 some years its been in > the wild. The NIST version was, shall we say, quite incomplete but a lot > of the stuff shoved in to scratch this or that itch is often vaguely > incompatible with the next vendors version of that particular function. Ehh, I don't speak that either, but now I feel like a guy who's told "Polly voo Fronsay?" and says that he don't speak no Eyetalon. :) ChrisA From rustompmody at gmail.com Sat Feb 15 01:07:18 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 22:07:18 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Saturday, February 15, 2014 10:50:35 AM UTC+5:30, Ian wrote: > On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: > > In the case of physical objects like dice there is a fairly > > unquestionable framing that makes identity straightforward -- > > 4-dimensional space-time coordiantes. If the space-time coordinates of > > 2 objects are all equal then the objects are identical, else not. > > Now we analogize the space-time identity of physical objects to > > computer identity of computer objects (so-called) and all sorts of > > problems ensue. > > To start with we say two objects are identical if they have the same > > memory address. > This is false. It happens to hold for CPython, but that's an > implementation detail. The definition of object identity does not > depend on memory address. It also doesn't have anything to do with > space-time coordinates. The concept of object identity is an > abstraction, not an analogy from physics. > The language reference states, "Every object has an identity, a type > and a value. An object's identity never changes once it has been > created; you may think of it as the object's address in memory." > Okay, so that quote does bring up memory address, but in my > interpretation that's just an analogy to introduce the concept. The > more important part of that sentence is the first part, which ties an > object's identity to its creation. If two objects share the same > creation, then they're the same object. Whats the notion of object identity is the question. Ok so you reject the memory addr as an 'implementation detail' Then you are obliged to provide some other way of understanding object-identity On Saturday, February 15, 2014 11:01:35 AM UTC+5:30, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 4:20 PM, Ian Kelly wrote: > > On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: > >> To start with we say two objects are identical if they have the same > >> memory address. > > This is false. It happens to hold for CPython, but that's an > > implementation detail. The definition of object identity does not > > depend on memory address. It also doesn't have anything to do with > > space-time coordinates. The concept of object identity is an > > abstraction, not an analogy from physics. > With the restrictions of computer memory, I suspect that two objects > with the same address must be identical, simply because it's not > possible for it to be otherwise. However, the converse isn't > necessarily true; two objects may have the same identity while being > at different addresses (or, more likely, one object may occupy > different memory addresses over time, if the gc moves it around). But > since memory addresses are completely inaccessible to Python code, we > can't say whether two objects have the same address. Nice point! I earlier talked of the macro problems of identity, viz across machines. You are bringing up a more 'micro' angle, viz gc. An even more micro (or lower level) example would be the mismatch between physical and virtual memory, dram and cache etc etc. Is memory such a clear concept? Just different examples to show that object identity is anything but straightforward From steve+comp.lang.python at pearwood.info Sat Feb 15 01:07:25 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 06:07:25 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <52ff041c$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 19:00:36 -0500, Ned Batchelder wrote: > On 2/14/14 4:43 PM, Marko Rauhamaa wrote: >> Chris Angelico: >> >>> >be careful of simplifications that will cause problems down the line. >> Sure. Let it be said, though, that sometimes you learn through >> inaccuracies, a technique used intentionally by Knuth's TeXBook, for >> example. In fact, you get through highschool mathematics successfully >> without knowing what numbers and variables actually are. >> >> > Yes, sometimes for teaching reasons, you have to over-simplify or even > introduce artificial constructs. I'd recommend acknowledging them as > such. The mathematician Ian Stewart and biologist Jack Cohen call these "lies for children". They don't mean it as a pejorative. In fact, calling them "lies for children" is itself a lie for children :-) (Lies for children are not lies, nor are they just for children.) -- Steven From ben+python at benfinney.id.au Sat Feb 15 01:19:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Feb 2014 17:19:38 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <85mwhs7v9h.fsf@benfinney.id.au> Rustom Mody writes: > Then you are obliged to provide some other way of understanding > object-identity How about: Every object has an identity, which is unique among all concurrently-existing objects. The ?is? operator queries whether two references are referring to objects with the same identity, which implies they are actually referring to the same object. Is that sufficient? > I earlier talked of the macro problems of identity, viz across > machines. Python doesn't make any promises about object identity beyond the current run-time of a single instance of a program. So while the problem you describe is interesting, it isn't relevant when talking about Python object identity. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From steve+comp.lang.python at pearwood.info Sat Feb 15 01:15:00 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 06:15:00 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> Message-ID: <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 17:55:52 -0800, Rustom Mody wrote: > My own preference: No is operator; only id when we deliberately need to > poke into the implementation. > > Of course I am in a miniscule minority I guess on that :-) If I have understood you, I think that's a poor way of looking at it. We can have an `is` operator to determine whether or not two objects are the same, without having a concept of object IDs; but you can't have a concept of object IDs without having distinct objects. `is` is more fundamental than id(). IDs are a proxy for distinct objects. If you live in a country with an ID card of some sort, then the IDs acts as an identifier for each unique individual. But countries without ID cards don't lack unique individual people. -- Steven From rosuav at gmail.com Sat Feb 15 01:23:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 17:23:45 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 5:07 PM, Rustom Mody wrote: > Nice point! > I earlier talked of the macro problems of identity, viz across machines. > You are bringing up a more 'micro' angle, viz gc. > An even more micro (or lower level) example would be the mismatch between > physical and virtual memory, dram and cache etc etc. > Is memory such a clear concept? > > Just different examples to show that object identity is anything but > straightforward Not really; they just show that object identity is nothing to do with memory location. An object is itself, and is not anything else, and neither of those truisms has anything to do with memory. I could implement Python using a pencil and paper, using physical pieces of string to create references; if a gust of wind blows all the paper around, it won't change anything. (Though it might be a problem if I have any weak references...) You could walk up to me and look at my pieces of paper, and you'll know if two strings are linking to the same paper; it's obvious that that paper is the same thing as itself. ChrisA From rustompmody at gmail.com Sat Feb 15 01:24:25 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 22:24:25 -0800 (PST) Subject: Explanation of list reference In-Reply-To: <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0da49167-a452-4910-ad4d-9b94d23ad448@googlegroups.com> On Saturday, February 15, 2014 11:45:00 AM UTC+5:30, Steven D'Aprano wrote: > On Fri, 14 Feb 2014 17:55:52 -0800, Rustom Mody wrote: > > My own preference: No is operator; only id when we deliberately need to > > poke into the implementation. > > Of course I am in a miniscule minority I guess on that :-) > If I have understood you, I think that's a poor way of looking at it. We > can have an `is` operator to determine whether or not two objects are the > same, without having a concept of object IDs; but you can't have a > concept of object IDs without having distinct objects. `is` is more > fundamental than id(). Pick is or id. Matters little To define either you need the notion of 'same' > IDs are a proxy for distinct objects. If you live in a country with an ID > card of some sort, then the IDs acts as an identifier for each unique > individual. But countries without ID cards don't lack unique individual > people. With humans like Chris' dice the notion of 'same' is unexceptionable [well sci-fi, teleportation etc aside :-) ] To define is or id or same you need to 1 use machine details or 2 do mathematics or 3 wave our hands -- Dont we all know that same is same? My bet is that python's id/is cannot be defined with 2 so we use a combo of 1 and 3 From rustompmody at gmail.com Sat Feb 15 01:31:16 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 14 Feb 2014 22:31:16 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <464e5b36-914d-42c2-8d71-7189f36544c8@googlegroups.com> On Saturday, February 15, 2014 11:49:38 AM UTC+5:30, Ben Finney wrote: > Rustom Mody writes: > > Then you are obliged to provide some other way of understanding > > object-identity > How about: Every object has an identity, which is unique among all > concurrently-existing objects. The 'is' operator queries whether two > references are referring to objects with the same identity, which > implies they are actually referring to the same object. > Is that sufficient? Are you explaining or defining identity? As an explanation its ok though a bit tautologous As a definition its circular [Just for context remember the OP -- a noob father-son duo confused by python's memory model] > > I earlier talked of the macro problems of identity, viz across > > machines. > Python doesn't make any promises about object identity beyond the > current run-time of a single instance of a program. So while the problem > you describe is interesting, it isn't relevant when talking about Python > object identity. Hard as a nail the problem persists -- Non-promise of identity implies we understand it!! > -- > \ "When in doubt tell the truth. It will confound your enemies | > `\ and astound your friends." --Mark Twain, _Following the Equator_ | > _o__) | > Ben Finney From steve+comp.lang.python at pearwood.info Sat Feb 15 01:44:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 06:44:08 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <52ff0cb7$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 20:24:20 -0800, Rustom Mody wrote: > In the case of physical objects like dice there is a fairly > unquestionable framing that makes identity straightforward -- > 4-dimensional space-time coordiantes. If the space-time coordinates of 2 > objects are all equal then the objects are identical, else not. That simply is not correct. (1) General relativity tells us that not all observers will agree on the space-time coordinates of two objects, since not all observers agree on a single frame of reference. (2) Quantum mechanics tells us that objects are not located at a single space-time coordinate. Objects are "smeared out" over space (and time). We cannot really talk about the location of an object, but only about the probability of a measurement registering the object at a certain location. > Now we analogize the space-time identity of physical objects to computer > identity of computer objects (so-called) and all sorts of problems > ensue. > > To start with we say two objects are identical if they have the same > memory address. Not quite. We say that two objects are identical (that is, that they actually are the same object) if they exist simultaneously, in the same process, and have the same ID. Normally we don't bother to say that they must be in the same process, as that is implied by our understanding of how computers normally work. In fact, even the above is a simplification, since processes may share certain objects. This is why Python prohibits Ruby-style monkey-patching of built-in types. If we could add or remove methods from (say) lists, that could affect more than one Python process. But ignoring complications like that, we can say that for a wide range of implementations, the condition "two objects exist at the same time and have the same ID" is equivalent to saying that they exist at the same time with the same memory address. > Then what happens to the same memory address on different computers? If > you say nothing on two different computers are identical then how do you > define the correctness of a serialization protocol? I would not expect that the None object running on my computer is the same None object running on another computer. None is a singleton *within a single running process*, not over the entire universe of Python virtual machines. > And is 'different computer' even well-defined? Think of clusters, COWs > NOWs, and other beasties ending in the cloud... But for all of these things, we can create the abstraction of "a single process running at a single moment". True, observers in orbit around a black hole a thousand light-years away will disagree about that single moment, but we're not talking to them and don't care what they think. > IOW when we analogize 4-dim infinite space-time into the confines of 'a > computer' weve bought bigger problems than we disposed off, because > > - for space-time it is unreasonable to imagine a larger frame into which > that is embedded > > - for computers that larger frame is a key part -- starting with the > fact that you and I are having a conversation right now > > tl;dr Analogizing physical objects to computer 'objects' is a mistake Over-philosophising abstractions without the sanity check of what happens in real life is an even bigger mistake. You may or may not choose to lie awake at night obsessing whether changing a tyre on your car makes it a different car (see the paradox of the Ax of my Grandfather), but the rest of us are too busy actually programming to care about such edge cases. They make good discussions for a philosophy class, but 99.999% of the time, the abstraction of computer objects being like physical objects is a good one. If you want to demonstrate the fact that this abstraction sometimes leaks, you don't need to concern yourself with cloud computing, shared process memory space, or any such thing. You just need to recognise that objects can contain themselves: py> L = [] py> L.append(L) py> L in L True Of course, if you are a fan of the Doctor Who television show, you won't be concerned by this. If the TARDIS can materialise inside itself, then there isn't any problem with lists containing themselves either. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 01:48:37 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 06:48:37 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 17:07:17 +1100, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 4:36 PM, Steven D'Aprano > wrote: >> References can be names like `mystring`, or list items `mylist[0]`, or >> items in mappings `mydict["key"]`, or attributes `myobject.attr`, or >> even expressions `x+y*(1-z)`. > > I agree with most of what you've said, but I'm not sure I like that last > bit. The expression evaluates to an object, yes, but it's not itself a > reference... is it? [snip discussion] You may be right. I will have to think about it a little more. Or a lot more. Ah wait, I got it: I chose a bad example for the expression. Here is a better one: myobj.alist[12]["some key"].attribute I think it is fair to call that both an expression and a reference. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 01:54:56 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 06:54:56 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <52ff0f3f$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 15:37:20 +1100, Chris Angelico wrote: [...] > This is why dice exist in a variety of colors [1]. Indistinguishable yet > distinct dice... Since they have different colours, they can be distinguished and aren't indistinguishable. One might also distinguish three dice by position in space ("the die closest to the wall counts as the HUNDREDS digit, the one closest to me counts as the TENS digit, and the one closest to you counts as the UNITS digit") or by space ("roll this die first for the HUNDREDS, then roll that one for TENS, then this third one for UNITS"). Or scent, or texture, or the typeface used for the numbers. -- Steven From rosuav at gmail.com Sat Feb 15 01:57:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 17:57:40 +1100 Subject: Explanation of list reference In-Reply-To: <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 5:48 PM, Steven D'Aprano wrote: > On Sat, 15 Feb 2014 17:07:17 +1100, Chris Angelico wrote: > >> On Sat, Feb 15, 2014 at 4:36 PM, Steven D'Aprano >> wrote: >>> References can be names like `mystring`, or list items `mylist[0]`, or >>> items in mappings `mydict["key"]`, or attributes `myobject.attr`, or >>> even expressions `x+y*(1-z)`. >> >> I agree with most of what you've said, but I'm not sure I like that last >> bit. The expression evaluates to an object, yes, but it's not itself a >> reference... is it? > > You may be right. I will have to think about it a little more. Or a lot > more. Ah wait, I got it: I chose a bad example for the expression. Here > is a better one: > > myobj.alist[12]["some key"].attribute > > I think it is fair to call that both an expression and a reference. Sure. If it helps, the part that's a reference is the ".attribute" at the end; the rest is an expression which determines what object's attribute you're looking at. Same with the earlier parts; the [12] is a form of reference (albeit one that requires another object). But yes, this is an expression, and it evaluates to a reference. In any case, your main point is still valid: each of those forms will yield a reference to something. (Aside from the possibility of raising KeyError. As an expression, it has to yield a reference to an object.) ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 15 02:03:17 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 07:03:17 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <52ff1134$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 22:20:35 -0700, Ian Kelly wrote: > On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody > wrote: >> In the case of physical objects like dice there is a fairly >> unquestionable framing that makes identity straightforward -- >> 4-dimensional space-time coordiantes. If the space-time coordinates of >> 2 objects are all equal then the objects are identical, else not. >> >> Now we analogize the space-time identity of physical objects to >> computer identity of computer objects (so-called) and all sorts of >> problems ensue. >> >> To start with we say two objects are identical if they have the same >> memory address. > > This is false. It happens to hold for CPython, but that's an > implementation detail. The definition of object identity does not > depend on memory address. It also doesn't have anything to do with > space-time coordinates. The concept of object identity is an > abstraction, not an analogy from physics. Correct. CPython does not move objects around in memory during their lifespan, so CPython can reuse the memory address as the ID. Jython and IronPython do move objects around, so they cannot use memory addresses as IDs. Instead they number each object sequentially. PyPy is even more complicated. Objects, like particles in quantum mechanics, can appear and disappear from existence between observations as the optimizing compiler does its work. For example, a list of Python float objects may be transparently converted into an array of machine doubles, then turned back into a Python object when you try to access it again. The PyPy compiler has to take great care to ensure that the list (and the floats!) get the same IDs before and after, since that is defined behaviour in the language spec. -- Steven From rosuav at gmail.com Sat Feb 15 02:05:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 18:05:00 +1100 Subject: Explanation of list reference In-Reply-To: <52ff0cb7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <52ff0cb7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 5:44 PM, Steven D'Aprano wrote: > You just need to recognise that > objects can contain themselves: > > py> L = [] > py> L.append(L) > py> L in L > True > > > Of course, if you are a fan of the Doctor Who television show, you won't > be concerned by this. If the TARDIS can materialise inside itself, then > there isn't any problem with lists containing themselves either. They certainly can. In my MUD, every object has a location (which may be the equivalent of None); generally, a person's location is a room, and a grabbable object's location is either a room or a person, but it's possible for a room to have a location... a Dungeon Master can create a workroom, which is in his inventory, and then enter that workroom. Incidentally, the destruction of an object simply involves moving it to nowhere. Since "nowhere" doesn't keep any references to the things put there, those objects promptly cease to exist. It's just like Western society - you don't actually destroy anything, you just throw it away (out of sight, out of mind), and let the garbage collector dispose of it for you :) ChrisA From rosuav at gmail.com Sat Feb 15 02:19:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 18:19:08 +1100 Subject: Explanation of list reference In-Reply-To: <52ff0f3f$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <52ff0f3f$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 5:54 PM, Steven D'Aprano wrote: > On Sat, 15 Feb 2014 15:37:20 +1100, Chris Angelico wrote: > > [...] >> This is why dice exist in a variety of colors [1]. Indistinguishable yet >> distinct dice... > > Since they have different colours, they can be distinguished and aren't > indistinguishable. Sorry, what I meant was that different colors are available for purchase, as a means of avoiding this problem. If you buy a dozen dice in mixed colors, you can simply declare "the red one is the hundreds, the blue one is tens, the green one is units", which is the most common solution to this exact issue of dice being indistinguishable yet distinct. > One might also distinguish three dice by position in space ("the die > closest to the wall counts as the HUNDREDS digit, the one closest to me > counts as the TENS digit, and the one closest to you counts as the UNITS > digit") Yes, but prior to rolling, you can't necessarily know what's going to be easy to determine. Rolling dice tends to randomize their positions somewhat, and it's impractical to get out the tape measure to determine which one is closest to the wall :) > or by space ("roll this die first for the HUNDREDS, then roll > that one for TENS, then this third one for UNITS"). Distinguishing by time is the other common method that I mentioned. In that case, there's really no reason to distinguish them at all, so you can use the same object three times - like using the string "foobar" three times and perhaps finding that it's the same object. > Or scent, or texture, or the typeface used for the numbers. Then they're not indistinguishable :) Having grown up in a business that sells dice (though, oddly enough, not for RPGs - I learned that d12s are popular for practicing multiplication tables, not that they're used for a barbarian's hit points and great-axe damage), I know how many identical dice you can get hold of. We had trays and trays of them at one point... then migrated to bulk bags. Though we usually tried to split them up, 50 dice per bag, so we could keep some track of inventory. And we were retailing, and dice weren't a huge part of our business. There are plenty of ways for dice to differ, but that's like having 5, 5.0, 5L (if Py2), and (5+0j), all of which are five, but all of which are distinct and must be kept separate. ChrisA From ian.g.kelly at gmail.com Sat Feb 15 02:27:02 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 00:27:02 -0700 Subject: Generator using item[n-1] + item[n] memory In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 8:31 PM, Nick Timkovich wrote: > OK, now the trick; adding `data = None` inside the generator works, but in > my actual code I wrap my generator inside of `enumerate()`, which seems to > obviate the "fix". Can I get it to play nice or am I forced to count > manually. Is that a feature? Yeah, looks like enumerate also doesn't release its reference to the previous object until after it gets the next one. You'll just have to make do without. From rosuav at gmail.com Sat Feb 15 02:41:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 18:41:25 +1100 Subject: Generator using item[n-1] + item[n] memory In-Reply-To: References: Message-ID: On Sat, Feb 15, 2014 at 6:27 PM, Ian Kelly wrote: > On Fri, Feb 14, 2014 at 8:31 PM, Nick Timkovich wrote: >> OK, now the trick; adding `data = None` inside the generator works, but in >> my actual code I wrap my generator inside of `enumerate()`, which seems to >> obviate the "fix". Can I get it to play nice or am I forced to count >> manually. Is that a feature? > > Yeah, looks like enumerate also doesn't release its reference to the > previous object until after it gets the next one. You'll just have to > make do without. You could write your own enumerate function. def enumerate(it, i=0): it = iter(it) while True: yield i, next(it) i += 1 That shouldn't keep any extra references around. ChrisA From ian.g.kelly at gmail.com Sat Feb 15 03:08:07 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 01:08:07 -0700 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 11:07 PM, Rustom Mody wrote: > On Saturday, February 15, 2014 10:50:35 AM UTC+5:30, Ian wrote: >> This is false. It happens to hold for CPython, but that's an >> implementation detail. The definition of object identity does not >> depend on memory address. It also doesn't have anything to do with >> space-time coordinates. The concept of object identity is an >> abstraction, not an analogy from physics. > >> The language reference states, "Every object has an identity, a type >> and a value. An object's identity never changes once it has been >> created; you may think of it as the object's address in memory." >> Okay, so that quote does bring up memory address, but in my >> interpretation that's just an analogy to introduce the concept. The >> more important part of that sentence is the first part, which ties an >> object's identity to its creation. If two objects share the same >> creation, then they're the same object. > > Whats the notion of object identity is the question. > Ok so you reject the memory addr as an 'implementation detail' > Then you are obliged to provide some other way of understanding object-identity I thought that I did. Repeating myself from what you quoted above: If two objects share the same creation, then they're the same object. From marko at pacujo.net Sat Feb 15 04:00:46 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 11:00:46 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <877g8woim9.fsf@elektro.pacujo.net> Ned Batchelder : > On 2/14/14 4:43 PM, Marko Rauhamaa wrote: > Yes, sometimes for teaching reasons, you have to over-simplify or even > introduce artificial constructs. I'd recommend acknowledging them as > such. > > When you say, "There are two fundamentally different kinds of values > in Python," or "So we have four kinds of (memory) slots," you aren't > letting on that this is a teaching construct. It sounds like you mean > that this is how Python actually works. > > I'd use words like, "This is an oversimplification, but might > help...", or "You can think of it like ...". Strictly speaking, I'm not simplifying, but giving an equivalent, alternative description. I admit that the word "fundamentally" was a bad choice. I'm not even sure my description was a good illustration. I definitely was not referring to CPython and was trying to keep the discussion separate from the implementation of the day. BTW, I also wasn't oversimplifying, but complicating by bringing in an unnecessary dichotomy. The challenge is how to present Python's value model in the most digestible way. For example, how is a beginnger to understand what's going on in: n += 1 Is it easier to think that the number held by the variable n is incremented by 1, or is it easier to understand it orthodoxly through instantiations and references? Marko From marko at pacujo.net Sat Feb 15 04:10:46 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 11:10:46 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <8738jkoi5l.fsf@elektro.pacujo.net> Chris Angelico : > On Sat, Feb 15, 2014 at 8:43 AM, Marko Rauhamaa wrote: >> Unfortunately neither the "everything is a reference" model nor the >> "small/big" model help you predict the value of an "is" operator in >> the ambiguous cases. > > Can you give an example of an ambiguous case? The "x is y" test may yield different outcomes in different, valid Python implementations: 4 is 4 (x,) is (x,) "hello" is "hello" Marko From luke.geelen at gmail.com Sat Feb 15 04:18:36 2014 From: luke.geelen at gmail.com (luke.geelen at gmail.com) Date: Sat, 15 Feb 2014 01:18:36 -0800 (PST) Subject: decimal numbers Message-ID: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> hello, i have been working on a python resistor calculator to let my class show what you can do with python. now i have a script that makes the more speekable value of the resistance (res) #if len(str(res)) > 9: # res2 = res / 1000000000 # print "de weerstand is %s,%s giga ohms" % (res2) #elif len(str(res)) > 6: # res2 = res / 1000000 # print "de weerstand is %s,%s Mega ohm" % (res2) #elif len(str(res)) > 3: # res2 = res / 1000 # print "de weerstand is", res2,"kilo ohm" #elif len(str(res)) < 4: # res2 = res # print "de weerstand is", res2,"ohm" i commented it because it doesn't work (yet), when i have a resistance of 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural number, anyway of using decimals insted so that it says : the resistance is 9.9 Giga Ohms instead of 9 ? From luke.geelen at gmail.com Sat Feb 15 04:19:59 2014 From: luke.geelen at gmail.com (Luke Geelen) Date: Sat, 15 Feb 2014 01:19:59 -0800 (PST) Subject: decimal numbers In-Reply-To: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen: > hello, > > i have been working on a python resistor calculator to let my class show what you can do with python. > > now i have a script that makes the more speekable value of the resistance (res) > > > > #if len(str(res)) > 9: > > # res2 = res / 1000000000 > > # print "de weerstand is %s,%s giga ohms" % (res2) > > #elif len(str(res)) > 6: > > # res2 = res / 1000000 > > # print "de weerstand is %s,%s Mega ohm" % (res2) > > #elif len(str(res)) > 3: > > # res2 = res / 1000 > > # print "de weerstand is", res2,"kilo ohm" > > #elif len(str(res)) < 4: > > # res2 = res > > # print "de weerstand is", res2,"ohm" > > > > i commented it because it doesn't work (yet), when i have a resistance of > > 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural number, anyway of using decimals insted so that it says : the resistance is 9.9 Giga Ohms instead of 9 ? , wait i have put one %s to much in the print function. this is from a other attempt so please excuse me From marko at pacujo.net Sat Feb 15 04:31:42 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 11:31:42 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <87y51cn2m9.fsf@elektro.pacujo.net> Ben Finney : > You should never need to predict the result of an ?is? operation. > (More precisely, for *some* cases you can predict it, but for other > cases you can't.) No problem there. You have to understand "is" well to use it. Referring to "objects in memory" when defininig "is" leads to circular definitions. It think the best way to define the semantics of "is" is through constraints: 1. if x is y then y ix x 2. if x is y and y is z then x is z 3. after x = y, x is y 4. if x is y, then x == y That's why "is" is not introductory material. The constraints define a relation that coincides with == wherever it is defined. So why would you ever use "is" instead of "=="? After all, all well-defined programs would behave identically after replacing "is" with "==". Really, the only reason would be performance; "is" is often faster to evaluate than "==". Marko From auriocus at gmx.de Sat Feb 15 04:38:22 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 15 Feb 2014 10:38:22 +0100 Subject: Explanation of list reference In-Reply-To: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: Hi Dave, Am 14.02.14 19:08, schrieb dave em: > He is asking a question I am having trouble answering which is how a > variable containing a value differs from a variable containing a list > or more specifically a list reference. as others have explained better and in more detail, there are mutable and immutable values. The point is, that in a=b and a[1] = x the "=" behaves differently. In the first case, you discard the reference, where a is pointing to, and bind to the same thing as b is pointing to. In the second case, you modify the thing that a is pointing to. Recently, we tripped upon such a thing in a bad way; we were doing least squares fitting with numpy, and the parameters passed through were modified in the residuals function. That caused the LS algorithm to fail. After we got suspicious about this, we tried to remedy by copying the parameters param_copy = param[:] It still didn't work, because a list behaves differently than a numpy array in this respect, to our big surprise: # list slicing, as we know it >>> a=[1,2,3,4] >>> b=a[:] # list slicing creates a copy >>> b[1]=123 >>> b [1, 123, 3, 4] >>> a [1, 2, 3, 4] # now numpy array slicing >>> import numpy as np >>> a=np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> b=a[:] # numpy slicing creates a reference >>> b[1]=123 >>> b array([ 1, 123, 3, 4]) >>> a array([ 1, 123, 3, 4]) Lesson learned: Don't modify parameters you got passed, if possible. It is rarely what you want and can sometimes even happen, when you know you don't want it. Christian From auriocus at gmx.de Sat Feb 15 04:44:39 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 15 Feb 2014 10:44:39 +0100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: Am 15.02.14 01:57, schrieb Chris Angelico: > Can you give an example of an ambiguous case? Fundamentally, the 'is' > operator tells you whether its two operands are exactly the same > object, nothing more and nothing less, so I assume your "ambiguous > cases" are ones where it's possible for two things to be either the > same object or two indistinguishable ones. What about the thing I posted down in this thread? >>> import numpy as np >>> a=np.array([1, 2, 3, 4]) >>> b=a[:] >>> id(a) 140267900969344 >>> id(b) 140267901045920 So, a and b are different things, right? >>> b[1]=37 >>> b array([ 1, 37, 3, 4]) >>> a array([ 1, 37, 3, 4]) Still they are connected. I can imagin that id() is just a debugging tool for extensions. What useful applications does it have outside of this? Christian From frank at chagford.com Sat Feb 15 05:04:17 2014 From: frank at chagford.com (Frank Millman) Date: Sat, 15 Feb 2014 12:04:17 +0200 Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: "Luke Geelen" wrote in message news:ec88852e-1384-4aa5-834b-85135be94ab9 at googlegroups.com... > Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen: > hello, > > i have been working on a python resistor calculator to let my class show > what you can do with python. > > now i have a script that makes the more speekable value of the resistance > (res) > [...] > > i commented it because it doesn't work (yet), when i have a resistance of > > 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural > number, anyway of using decimals insted so that it says : the resistance > is 9.9 Giga Ohms instead of 9 ? > You don't say which version of python you are using. If you are using python2, an integer divided by an integer always returns an integer - >>> 10/3 3 It was changed in python3 to return a float - >>> 10/3 3.3333333333333335 You can reproduce the python3 behaviour in python2 by adding a 'future' directive - >>> from __future__ import division >>> 10/3 3.3333333333333335 HTH Frank Millman From marko at pacujo.net Sat Feb 15 05:10:02 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 12:10:02 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <87r474n0ud.fsf@elektro.pacujo.net> Christian Gollwitzer : > Still they are connected. I can imagin that id() is just a debugging > tool for extensions. What useful applications does it have outside of > this? Calculating hash keys quickly. Marko From rosuav at gmail.com Sat Feb 15 05:13:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 21:13:20 +1100 Subject: decimal numbers In-Reply-To: References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 9:04 PM, Frank Millman wrote: > If you are using python2, an integer divided by an integer always returns an > integer - > >>>> 10/3 > 3 > > It was changed in python3 to return a float - > >>>> 10/3 > 3.3333333333333335 > > You can reproduce the python3 behaviour in python2 by adding a 'future' > directive - > >>>> from __future__ import division >>>> 10/3 > 3.3333333333333335 > Conversely, you can get an integer result by using floor division: >>> 10//3 3 ChrisA From marko at pacujo.net Sat Feb 15 05:13:54 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 12:13:54 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> Message-ID: <87mwhsn0nx.fsf@elektro.pacujo.net> Marko Rauhamaa : > 1. if x is y then y ix x > 2. if x is y and y is z then x is z > 3. after x = y, x is y > 4. if x is y, then x == y A new attempt: 0. x is x 1. if x is y then y ix x 2. if x is y and y is z then x is z 3. after x = y, x is y 4. if x is y and x == x, then x == y 5. id(x) == id(y) iff x is y Does that cover it? Marko From steve+comp.lang.python at pearwood.info Sat Feb 15 05:31:00 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 10:31:00 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <8738jkoi5l.fsf@elektro.pacujo.net> Message-ID: <52ff41e3$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 11:10:46 +0200, Marko Rauhamaa wrote: > Chris Angelico : > >> On Sat, Feb 15, 2014 at 8:43 AM, Marko Rauhamaa >> wrote: >>> Unfortunately neither the "everything is a reference" model nor the >>> "small/big" model help you predict the value of an "is" operator in >>> the ambiguous cases. >> >> Can you give an example of an ambiguous case? > > The "x is y" test may yield different outcomes in different, valid > Python implementations: > > 4 is 4 > (x,) is (x,) > "hello" is "hello" But none of those examples are ambiguous. They're merely unspecified by the language definition. Any specific implementation of Python will return either True or False; it may be predictable, or it might be impossible to predict until runtime, but either way we know that every non-broken Python virtual machine must either treat the two operands as the same object or different objects. These are ambiguous sentences: I saw the man with the binoculars. Police help assault victim. Once there was a blind carpenter who picked up his hammer and saw. Look at that cat with one eye. "A Python implementation can choose whether or not to re-use immutable objects" is not ambiguous. It's just a choice. -- Steven From luke.geelen at gmail.com Sat Feb 15 05:32:39 2014 From: luke.geelen at gmail.com (Luke Geelen) Date: Sat, 15 Feb 2014 02:32:39 -0800 (PST) Subject: decimal numbers In-Reply-To: References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman: > "Luke Geelen" wrote in message > > news:ec88852e-1384-4aa5-834b-85135be94ab9 at googlegroups.com... > > > Op zaterdag 15 februari 2014 10:18:36 UTC+1 schreef Luke Geelen: > > > hello, > > > > > > i have been working on a python resistor calculator to let my class show > > > what you can do with python. > > > > > > now i have a script that makes the more speekable value of the resistance > > > (res) > > > > > [...] > > > > > > i commented it because it doesn't work (yet), when i have a resistance of > > > > > > 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural > > > number, anyway of using decimals insted so that it says : the resistance > > > is 9.9 Giga Ohms instead of 9 ? > > > > > > > You don't say which version of python you are using. > > > > If you are using python2, an integer divided by an integer always returns an > > integer - > > > > >>> 10/3 > > 3 > > > > It was changed in python3 to return a float - > > > > >>> 10/3 > > 3.3333333333333335 > > > > You can reproduce the python3 behaviour in python2 by adding a 'future' > > directive - > > > > >>> from __future__ import division > > >>> 10/3 > > 3.3333333333333335 > > > > HTH > > > > Frank Millman how (and where) would i add this rule into a script? by import or the calculation? From steve+comp.lang.python at pearwood.info Sat Feb 15 05:40:43 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 10:40:43 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> Message-ID: <52ff442b$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 11:31:42 +0200, Marko Rauhamaa wrote: > It think the best way to define the semantics of "is" is > through constraints: > > 1. if x is y then y ix x > > 2. if x is y and y is z then x is z > > 3. after x = y, x is y > > 4. if x is y, then x == y Incorrect. py> x = float('nan') py> y = x py> x is y True py> x == y False > That's why "is" is not introductory material. No. "is" is not introductory material because it is an attractive nuisance for beginners. Beginners have a tendency to think that "is" is a synonym for "equals", as it can be in English. Sometimes it appears to work: x = 2 y = x*3 - 4 x is y => probably returns True but in other cases it fails, confusing the beginner. With the exception of "is None", beginners almost never need "is". > The constraints define a relation that coincides with == wherever it is > defined. It certainly does not. class Wacky: def __eq__(self, other): return random.random() < 0.5 > So why would you ever use "is" instead of "=="? After all, all > well-defined programs would behave identically after replacing "is" with > "==". Really, the only reason would be performance; "is" is often > faster to evaluate than "==". Incorrect. "is" is NOT equivalent to ==, the two are not guaranteed to do the same thing, you CANNOT safely replace "is" with == or visa versa, and the meaning of the "is" operator is completely different from the meaning of the == operator. The "is" operator tests whether the two operands are the same object, nothing more, nothing less. The == operator tests whether the two operands compare equal. -- Steven From frank at chagford.com Sat Feb 15 05:49:35 2014 From: frank at chagford.com (Frank Millman) Date: Sat, 15 Feb 2014 12:49:35 +0200 Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: "Luke Geelen" wrote in message news:ae0da085-6c41-4166-92d2-92611a990885 at googlegroups.com... > Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman: >> "Luke Geelen" wrote in message >> >> news:ec88852e-1384-4aa5-834b-85135be94ab9 at googlegroups.com... >> [...] >> >> You can reproduce the python3 behaviour in python2 by adding a 'future' >> directive - >> >> >>> from __future__ import division >> >> >>> 10/3 >> >> 3.3333333333333335 >> > > how (and where) would i add this rule into a script? by import or the > calculation? Treat it like any other import - add it as a new line at the top of your script. Frank From steve+comp.lang.python at pearwood.info Sat Feb 15 05:53:48 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 10:53:48 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: <52ff473b$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 10:44:39 +0100, Christian Gollwitzer wrote: > Am 15.02.14 01:57, schrieb Chris Angelico: >> Can you give an example of an ambiguous case? Fundamentally, the 'is' >> operator tells you whether its two operands are exactly the same >> object, nothing more and nothing less, so I assume your "ambiguous >> cases" are ones where it's possible for two things to be either the >> same object or two indistinguishable ones. > > What about the thing I posted down in this thread? > > >>> import numpy as np > >>> a=np.array([1, 2, 3, 4]) > >>> b=a[:] > >>> id(a) > 140267900969344 > >>> id(b) > 140267901045920 > > So, a and b are different things, right? Correct. They are different objects. But they may share underlying state. > >>> b[1]=37 > >>> b > array([ 1, 37, 3, 4]) > >>> a > array([ 1, 37, 3, 4]) And indeed numpy arrays do share state. Why? No idea. Somebody thought that it was a good idea. (Not me though...) > Still they are connected. I can imagin that id() is just a debugging > tool for extensions. What useful applications does it have outside of > this? Very few. -- Steven From frank at chagford.com Sat Feb 15 05:56:25 2014 From: frank at chagford.com (Frank Millman) Date: Sat, 15 Feb 2014 12:56:25 +0200 Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: "Frank Millman" wrote in message news:ldngnf$c3r$1 at ger.gmane.org... > > "Luke Geelen" wrote in message > news:ae0da085-6c41-4166-92d2-92611a990885 at googlegroups.com... >> Op zaterdag 15 februari 2014 11:04:17 UTC+1 schreef Frank Millman: >>> "Luke Geelen" wrote in message >>> >>> news:ec88852e-1384-4aa5-834b-85135be94ab9 at googlegroups.com... >>> > [...] >>> >>> You can reproduce the python3 behaviour in python2 by adding a 'future' >>> directive - >>> >>> >>> from __future__ import division >>> >>> >>> 10/3 >>> >>> 3.3333333333333335 >>> >> >> how (and where) would i add this rule into a script? by import or the >> calculation? > > Treat it like any other import - add it as a new line at the top of your > script. > Actually I did not answer that very accurately. From the documentation - """ A future statement must appear near the top of the module. The only lines that can appear before a future statement are: the module docstring (if any), comments, blank lines, and other future statements. """ Frank From steve+comp.lang.python at pearwood.info Sat Feb 15 06:03:27 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 11:03:27 GMT Subject: Generator using item[n-1] + item[n] memory References: Message-ID: <52ff497e$0$29973$c3e8da3$5496439d@news.astraweb.com> On Fri, 14 Feb 2014 22:21:11 -0500, Roy Smith used a generator: > print g1.next() Roy, unless you're stuck with Python 2.5 (or older!), you ought to use the built-in function next(g1) rather than directly call the next method. Not only is this the recommended way to do it, but it's also more future- proof (Python 3 drops the next method and makes it a dunder method) and has more functionality (the next() function takes an optional default value). -- Steven From rosuav at gmail.com Sat Feb 15 06:17:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 22:17:27 +1100 Subject: Explanation of list reference In-Reply-To: <87y51cn2m9.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 8:31 PM, Marko Rauhamaa wrote: > Referring to "objects in memory" when defininig "is" leads to circular > definitions. It think the best way to define the semantics of "is" is > through constraints: > > 1. if x is y then y ix x > > 2. if x is y and y is z then x is z > > 3. after x = y, x is y Yes. Yes. Yes. > 4. if x is y, then x == y No. >>> x = float("nan") >>> x == x False > The constraints define a relation that coincides with == wherever it is > defined. So why would you ever use "is" instead of "=="? After all, all > well-defined programs would behave identically after replacing "is" with > "==". Really, the only reason would be performance; "is" is often faster > to evaluate than "==". Because your criteria are one-way. If x is y, then usually x == y, but plenty of things compare equal that aren't identical. >>> x = [1,2,3] >>> y = [1,2,3] >>> x == y True >>> x.pop() 3 >>> x == y False Two things may be equal now and not later, or vice versa, but if they're identical, they will always be (because they're not "two things" but one thing), and if they're not identical, they will never be (because they really are two things, and the traditional marriage ceremony with the "two becoming one" doesn't happen in computing). Identity and equality are quite different states, and should be tested for differently. ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 15 06:17:56 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 11:17:56 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> Message-ID: <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: > Marko Rauhamaa : > >> 1. if x is y then y ix x >> 2. if x is y and y is z then x is z >> 3. after x = y, x is y >> 4. if x is y, then x == y > > A new attempt: > > 0. x is x > 1. if x is y then y ix x > 2. if x is y and y is z then x is z > 3. after x = y, x is y > 4. if x is y and x == x, then x == y > 5. id(x) == id(y) iff x is y Python implementations are free to re-use IDs after the object is destroyed. CPython does; Jython and IronPython do not. So #5 needs to point out that the condition id(x) == id(y) only applies if x and y still exist. # Counter-example py> x = 230000 py> idx = id(x) py> del x py> y = 420000 py> idy = id(y) py> idx == idy True (This is *implementation dependent* so your mileage my vary.) > Does that cover it? No. Your definition describes some properties of identity-equivalence, but doesn't explain what identity actually means. -- Steven From rosuav at gmail.com Sat Feb 15 06:21:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 22:21:29 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 8:44 PM, Christian Gollwitzer wrote: >>>> import numpy as np >>>> a=np.array([1, 2, 3, 4]) >>>> b=a[:] >>>> id(a) > 140267900969344 >>>> id(b) > 140267901045920 > > So, a and b are different things, right? > >>>> b[1]=37 >>>> b > array([ 1, 37, 3, 4]) >>>> a > array([ 1, 37, 3, 4]) > > Still they are connected. Well, yes, they are different things; but that doesn't mean they can't affect each other. And you don't need numpy to see that: >>> d = {} >>> k1 = d.keys() >>> k2 = d.keys() >>> k1 is k2 False >>> k1 == k2 True >>> d[1]=1 >>> k1 dict_keys([1]) >>> k2 dict_keys([1]) Two separate keys views on the same dictionary will, by definition, always show the same keys (and, I think, in the same order). But they're still separate objects. Their identities are distinct, their values are linked. ChrisA From gandalf at shopzeus.com Sat Feb 15 06:25:19 2014 From: gandalf at shopzeus.com (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Sat, 15 Feb 2014 12:25:19 +0100 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FCB389.3070402@timgolden.me.uk> References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> Message-ID: <52FF4E9F.7070209@shopzeus.com> > From a cmd window: > > ftype python.file="C:\Windows\py.exe" "%1" %* > > ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* There is a serious problem with this! Example code test.py: #!/usr/bin/env python3 import sys print(sys.argv) Test run: C:\Temp>test.py 1 2 3 ['C:\\Temp\\test.py'] This is too bad! Can somebody tell me what would be the good setup for py.exe? Do I have to reinstall Python3 with all libs? :-s From __peter__ at web.de Sat Feb 15 06:27:19 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Feb 2014 12:27:19 +0100 Subject: Generator using item[n-1] + item[n] memory References: Message-ID: Chris Angelico wrote: > On Sat, Feb 15, 2014 at 6:27 PM, Ian Kelly wrote: >> On Fri, Feb 14, 2014 at 8:31 PM, Nick Timkovich >> wrote: >>> OK, now the trick; adding `data = None` inside the generator works, but >>> in my actual code I wrap my generator inside of `enumerate()`, which >>> seems to >>> obviate the "fix". Can I get it to play nice or am I forced to count >>> manually. Is that a feature? >> >> Yeah, looks like enumerate also doesn't release its reference to the >> previous object until after it gets the next one. You'll just have to >> make do without. > > You could write your own enumerate function. > > def enumerate(it, i=0): > it = iter(it) > while True: > yield i, next(it) > i += 1 > > That shouldn't keep any extra references around. An alternative approach ist to yield weak refs and thus have the generator control the object lifetime. This doesn't work with the built-in list type though: import weakref try: from itertools import imap # py2 except ImportError: imap = map # py3 N = 0 def log_deleted(*args): global N N -= 1 print("deleted, new N: {}".format(N)) def log_created(): global N N += 1 print("created, new N: {}".format(N)) def weakrefs(f): def weakrefs(*args, **kw): return imap(lambda x: weakref.proxy(x, log_deleted), f(*args, **kw)) return weakrefs class List(list): def __str__(self): s = str(self[:5]) if len(self) > 10: s = s[:-1] + ", ... ]" return s @weakrefs def biggen(): sizes = 1, 1, 10, 1, 1, 10, 10, 1, 1, 10, 10, 20, 1, 1, 20, 20, 1, 1 for size in sizes: data = List([1] * int(size * 1e4)) log_created() yield data data = None if __name__ == "__main__": for i, x in enumerate(biggen()): print("{} {}".format(i, x)) From greg.ewing at canterbury.ac.nz Sat Feb 15 06:29:20 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Feb 2014 00:29:20 +1300 Subject: Explanation of list reference In-Reply-To: <52ff0cb7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <52ff0cb7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > (1) General relativity tells us that not all observers will agree on the > space-time coordinates of two objects, since not all observers agree on a > single frame of reference. But that doesn't mean they won't agree about whether objects are identical or not! The coordinates they use to describe spacetime locations may differ, but they will agree on whether or not they are equal. A Lorentz transformation can't cause a single point in spacetime to split into two, or two distinct points to merge into one. > (2) Quantum mechanics tells us that objects are not located at a single > space-time coordinate. Objects are "smeared out" over space (and time). > We cannot really talk about the location of an object, but only about the > probability of a measurement registering the object at a certain location. But that doesn't mean you can stuff two objects into the same space at the same time. What we perceive as solid objects are composed of fermions, which obey the Pauli exclusion principle. That means you can't have more than one of them in a given quantum state. While you *could* have two of them equally spread out over all of space, they would then have to be separated in some other dimension such as momentum or spin. So if you replace "space-time coordinates" with "quantum state", the original statement remains essentially true. -- Greg From rosuav at gmail.com Sat Feb 15 06:31:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 22:31:18 +1100 Subject: Explanation of list reference In-Reply-To: <87mwhsn0nx.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 9:13 PM, Marko Rauhamaa wrote: > A new attempt: Sorry, hadn't seen this when I posted. > 0. x is x This is the definition of identity. > 1. if x is y then y ix x Yes, because if x is y, there is absolutely no difference between using one of those names or the other, in any context. > 2. if x is y and y is z then x is z Extension of the above. The first statement proves that you can substitute 'x' for 'y' in the second without changing its truthiness; therefore, based on the definition of identity, 'x is z' must be identical to 'y is z'. > 3. after x = y, x is y This is the definition of assignment. (Obviously this axiom depends on x and y being simple names and nothing tampering with the situation in any way. But yes, this is exactly what assignment is.) > 4. if x is y and x == x, then x == y Yes. As in case 2, 'x is y' implies that you can substitute 'x' for 'y' or vice versa. Therefore, if x == x, then y == y, and x == y, and y == x; because in each case, what you're doing is "object #1423443, are you equal to object #1423443 or not?", regardless of the name you use to access that object. > 5. id(x) == id(y) iff x is y This is the definition of id(). Note that it does depend on something holding a reference to each of x and y; if it's possible for the objects' lifetimes to not overlap, it's possible for them to reuse ids: >>> [1,2,3] is [2,3,4] False >>> id([1,2,3]) == id([2,3,4]) True But if x and y are simple names (and therefore retaining their referent objects), then your statement is valid. > Does that cover it? Largely axiomatically, yes. ChrisA From greg.ewing at canterbury.ac.nz Sat Feb 15 06:32:28 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Feb 2014 00:32:28 +1300 Subject: Explanation of list reference In-Reply-To: <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > IDs are a proxy for distinct objects. If you live in a country with an ID > card of some sort, then the IDs acts as an identifier for each unique > individual. But countries without ID cards don't lack unique individual > people. "You are Number Six." "I am not an id()! I am an individual object!" -- Greg From rosuav at gmail.com Sat Feb 15 06:36:04 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 22:36:04 +1100 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FF4E9F.7070209@shopzeus.com> References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> <52FF4E9F.7070209@shopzeus.com> Message-ID: On Sat, Feb 15, 2014 at 10:25 PM, Nagy L?szl? Zsolt wrote: >> From a cmd window: >> >> ftype python.file="C:\Windows\py.exe" "%1" %* >> >> ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* > > There is a serious problem with this! Example code test.py: > > #!/usr/bin/env python3 > import sys > print(sys.argv) > > Test run: > > C:\Temp>test.py 1 2 3 > ['C:\\Temp\\test.py'] > Just because I have a distrust of Windows's command interpreter, what happens when you type: ftype python.file ? Does it echo back what you thought it had, or has %* been eaten? If the %* is missing, that would explain the loss of arguments. ChrisA From rosuav at gmail.com Sat Feb 15 06:37:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 22:37:41 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <52ff05e3$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 10:32 PM, Gregory Ewing wrote: > Steven D'Aprano wrote: >> >> IDs are a proxy for distinct objects. If you live in a country with an ID >> card of some sort, then the IDs acts as an identifier for each unique >> individual. But countries without ID cards don't lack unique individual >> people. > > > "You are Number Six." > "I am not an id()! I am an individual object!" Make it so, Number One. ChrisA From greymaus at mail.com Sat Feb 15 06:55:16 2014 From: greymaus at mail.com (greymausg) Date: 15 Feb 2014 11:55:16 GMT Subject: ipython Message-ID: using IPython, is there any way of recording the commands I have entered? -- maus . . ... From greg.ewing at canterbury.ac.nz Sat Feb 15 07:03:22 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Feb 2014 01:03:22 +1300 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: Jussi Piitulainen wrote: > Would it help to say that in case 1 the relevant statement acts on the > variable while in case 2 it acts on the value of the variable? I would try to avoid using words like "value" and "variable", because they don't have well-defined meanings in Python. The way I would put it is that a = b changes which object the name 'a' refers to, whereas a[i] = b does not. -- Greg From marko at pacujo.net Sat Feb 15 07:07:35 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 14:07:35 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87iosgmveg.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: >> 0. x is x >> 1. if x is y then y ix x >> 2. if x is y and y is z then x is z >> 3. after x = y, x is y >> 4. if x is y and x == x, then x == y >> 5. id(x) == id(y) iff x is y > > # Counter-example > py> x = 230000 > py> idx = id(x) > py> del x > py> y = 420000 > py> idy = id(y) > py> idx == idy > True I don't accept that as a counterexample. You will have to produce: (id(x) == id(y)) == (x is y) > False > (This is *implementation dependent* so your mileage my vary.) > >> Does that cover it? > > No. Your definition describes some properties of identity-equivalence, > but doesn't explain what identity actually means. That's the point. I don't think id() and "is" have any abstract meaning on top of the formal axioms. Marko From greg.ewing at canterbury.ac.nz Sat Feb 15 07:18:34 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Feb 2014 01:18:34 +1300 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico wrote: > But yes, this is an expression, and it evaluates to a reference. Well, *all* expressions in Python evaluate to references, so that's not really saying much. -- Greg From ben+python at benfinney.id.au Sat Feb 15 07:21:13 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Feb 2014 23:21:13 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> Message-ID: <85iosg7eiu.fsf@benfinney.id.au> Jussi Piitulainen writes: > In cheese = spam, cheese is the variable while spam is a variable > reference and stands for 42. Oof. This distinction between ?variable? and ?variable reference? is bogus and unnecessary, and highlights what is wrong with talking about ?variable? at all. In the Python code ?cheese = spam?, ?cheese? is a name, and ?spam? is a name. Both of them are references (because all names are references). The assignment binds the name ?cheese? to whatever object the name ?spam? was bound to at that point in time. In either case, a different kind of reference (for example, a list item) could have been used. Names are merely one kind of reference. > > >>> spam = [0, 1, 2, 3, 4, 5] > > >>> cheese = spam > > >>> cheese[1] = 'Hello!' > > >>> spam > > [0, 'Hello!', 2, 3, 4, 5] > > >>> cheese > > [0, 'Hello!', 2, 3, 4, 5] > > The first two statements in case 2 are assignments to variables, just > like in case 1, but the third statement is different: it doesn't > change the value of the variable (the value is still the same object) > but it does change the value (replaces one element of the list with > another). Again, this distinction is nonsense and confusing. What is happening in all those assignments is: A reference (the expression on the left-hand-side of the ?=? symbol) is bound to an object (the value resulting from the expression on the right-hand-side of the ?=? symbol). In the first two cases, the reference happens to be a name. In the third case, the reference happens to be a list item. > Would it help to say that in case 1 the relevant statement acts on the > variable while in case 2 it acts on the value of the variable? This is > accurate, I just don't know if it happens to be the thing that helps. I think not. What would help is to abandon the ?variable? baggage, and focus on what assignment actually does: binds a reference to an object. > One last thing: a variable is not an object. Right. Also: a reference is not an object, but a reference always refers to exactly one object. -- \ ?Science is a way of trying not to fool yourself. The first | `\ principle is that you must not fool yourself, and you are the | _o__) easiest person to fool.? ?Richard P. Feynman, 1964 | Ben Finney From rosuav at gmail.com Sat Feb 15 07:24:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Feb 2014 23:24:06 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 15, 2014 at 11:18 PM, Gregory Ewing wrote: > Chris Angelico wrote: >> >> But yes, this is an expression, and it evaluates to a reference. > > > Well, *all* expressions in Python evaluate to references, > so that's not really saying much. Because everything in Python is an object, and objects always are handled by their references. This wouldn't be true in every language (eg it's not true of Java's unboxed types), but it's intrinsic to Python's object model. ChrisA From breamoreboy at yahoo.co.uk Sat Feb 15 07:25:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 12:25:48 +0000 Subject: ipython In-Reply-To: References: Message-ID: On 15/02/2014 11:55, greymausg wrote: > using IPython, is there any way of recording the commands I have entered? > I believe ipython automatically stores the commands you enter. Searching for ipython+command+history should get you more detail than I can offer :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Sat Feb 15 07:28:53 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 12:28:53 +0000 Subject: Generator using item[n-1] + item[n] memory In-Reply-To: References: Message-ID: On 15/02/2014 03:31, Nick Timkovich wrote: > OK, now the trick; adding `data = None` inside the generator works, but > in my actual code I wrap my generator inside of `enumerate()`, which > seems to obviate the "fix". Can I get it to play nice or am I forced to > count manually. Is that a feature? > > > On Fri, Feb 14, 2014 at 9:21 PM, Roy Smith > wrote: > > In article >, > Nick Timkovich > wrote: > > > Ah, I think I was equating `yield` too closely with `return` in > my head. > > Whereas `return` results in the destruction of the function's > locals, > > `yield` I should have known keeps them around, a la C's `static` > functions. > > Many thanks! > > It's not quite like C's static. With C's static, the static variables > are per-function. In Python, yield creates a context per invocation. > Thus, I can do > > def f(): > for i in range(10000): > yield i > > g1 = f() > g2 = f() > print g1.next() > print g1.next() > print g1.next() > print g2.next() > print g1.next() > > > which prints 0, 1, 2, 0, 3. There's two contexts active at the same > time, with a distinct instance of "i" in each one. > -- > https://mail.python.org/mailman/listinfo/python-list > Nick, please don't top post on this list, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Sat Feb 15 07:42:47 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 12:42:47 +0000 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On 15/02/2014 06:07, Rustom Mody wrote: > Then you are obliged to provide some other way of understanding object-identity I have no interest in understanding object identity, I can write code quite happily without it. If you (plural) are interested in understanding this subject I hope you enjoy comparing the various Python implementations while I'm *STILL* writing code. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From davea at davea.name Sat Feb 15 08:14:09 2014 From: davea at davea.name (Dave Angel) Date: Sat, 15 Feb 2014 08:14:09 -0500 (EST) Subject: ipython References: Message-ID: greymausg Wrote in message: > using IPython, is there any way of recording the commands I have entered? > Try the history command. http://ipython.org/ipython-doc/rel-1.1.0/api/generated/IPython. core.magics.history.html -- DaveA From marko at pacujo.net Sat Feb 15 08:25:35 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 15:25:35 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87d2iomrsg.fsf@elektro.pacujo.net> Chris Angelico : > Because everything in Python is an object, and objects always are > handled by their references. This wouldn't be true in every language > (eg it's not true of Java's unboxed types), but it's intrinsic to > Python's object model. Well, it's part of Python's reference model. Any model that produces valid Python behavior is equally good. An implementation that boxes some or all immutable objects would still be perfectly valid. Anyway, an object is a fairly advanced and abstract concept. A beginning programmer wouldn't be equipped to understand the ultimate abstraction; an object is too all-encompassing to express anything. It might be productive to lead the aspirant to the mountain summit through a more concrete model. Identifying the references with RAM addresses and objects with RAM snippets might keep object tangible for the first few months, although a more mundane model would be welcome. I'm reminded of Raymond Smullyan's excellent "To Mock the Mockingbird," which models combinatory logic with a forest full of chirping birds. Marko From joshua at landau.ws Fri Feb 14 22:52:24 2014 From: joshua at landau.ws (Joshua Landau) Date: Sat, 15 Feb 2014 03:52:24 +0000 Subject: Explanation of list reference In-Reply-To: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: On 14 February 2014 18:08, dave em wrote: > > Question: Is my explanation correct? If not please set me straight :) > > And does anyone have an easier to digest explanation? > Here, I give you a pdf. Hopefully this isn't anti mailing-list-etiquette. Also, if you can't read my handwriting but want to, just give me a shout. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: A_PDF_THAT_GOT_MUCH_LONGER_THAN_I_EXPECTED_IT_TO,_MUCH_LIKE_THIS_TITLE_HAS.pdf Type: application/pdf Size: 893373 bytes Desc: not available URL: From kwa at kuwata-lab.com Fri Feb 14 23:39:14 2014 From: kwa at kuwata-lab.com (Makoto Kuwata) Date: Sat, 15 Feb 2014 13:39:14 +0900 Subject: [Q] Beaker 1.6.4 not work on Python3 Message-ID: Hi, Does Beaker 1.6.4 work on Python3 ? Is there anyone using Beaker on Python3? I got the following error on Python 3.3: File "/opt/lang/python/3.2.2/lib/python3.2/http/cookies.py", line 486, in __setitem__ rval, cval = self.value_encode(value) File "/opt/lang/python/3.2.2/lib/python3.2/site-packages/Beaker-1.6.4-py3.2.egg/beaker/session.py", line 70, in value_encode sig = HMAC.new(self.secret, val.encode('UTF-8'), SHA1).hexdigest() AttributeError: 'bytes' object has no attribute 'encode' The following is a monkey patch to avoid this error, but I'm not sure that it is correct solution. from beaker.crypto import hmac as HMAC, hmac_sha1 as SHA1 from beaker.session import SignedCookie def value_encode(self, val): #sig = HMAC.new(self.secret, val.encode('UTF-8'), SHA1).hexdigest() sig = HMAC.new(self.secret, val, SHA1).hexdigest() return str(val), ("%s%s" % (sig, val)) SignedCookie.value_encode = value_encode And, even with monkey patching, Beaker's SessionMiddleware doesn't save session correctly on Python3. Please help me: I want to run Beaker 1.6.4 on Python 3. (Pyton 3.3.3, MacOSX) Here is my sample code (which works on Python2.7 very well!): ------------------------------------------------------ # -*- coding: utf-8 -*- import sys import waitress from beaker.middleware import SessionMiddleware def testapp(environ, start_response): session = environ.get('beaker.session') count = session.get('count', 0) + 1 session['count'] = count session.save() content = "count=%s" % count # start_response('200 OK', [('Content-Type', 'text/plain')]) return [content.encode('utf-8')] config = { 'session.type': 'cookie', 'session.validate_key': 'mysecretstring', } app = SessionMiddleware(testapp, config=config) ## monkey patch for Python3 python3 = sys.version_info[0] == 3 if 0 and python3: from beaker.crypto import hmac as HMAC, hmac_sha1 as SHA1 from beaker.session import SignedCookie def value_encode(self, val): #sig = HMAC.new(self.secret, val.encode('UTF-8'), SHA1).hexdigest() sig = HMAC.new(self.secret, val, SHA1).hexdigest() return str(val), ("%s%s" % (sig, val)) SignedCookie.value_encode = value_encode ## ---- waitress.serve(app, port=8080) ------------------------------------------------------ -- regards, makoto kuwata -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwa at kuwata-lab.com Sat Feb 15 00:28:44 2014 From: kwa at kuwata-lab.com (Makoto Kuwata) Date: Sat, 15 Feb 2014 14:28:44 +0900 Subject: [RELEASED] Python 3.3.4 In-Reply-To: <52F93CCC.70304@python.org> References: <52F93CCC.70304@python.org> Message-ID: Congrat! By the way, I can't find Python-3.3.4.tar.bz2 in: http://www.python.org/ftp/python/3.3.4/ Python-3.3.{1,2,3}.tar.bz2 and Python-3.4.0.tar.bz2 are provided, but Python-3.3.4.tar.bz2 is not. Why? # I hope that Python-3.3.4.tar.bz2 is also provided. -- regards, makoto kuwata On Tue, Feb 11, 2014 at 5:55 AM, Georg Brandl wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team, I'm very happy to announce > the release of Python 3.3.4. > > Python 3.3.4 includes several security fixes and over 120 bug fixes > compared to the Python 3.3.3 release. > > This release fully supports OS X 10.9 Mavericks. In particular, this > release fixes an issue that could cause previous versions of Python to > crash when typing in interactive mode on OS X 10.9. > > Python 3.3 includes a range of improvements of the 3.x series, as well > as easier porting between 2.x and 3.x. In total, almost 500 API items > are new or improved in Python 3.3. For a more extensive list of > changes in the 3.3 series, see > > http://docs.python.org/3.3/whatsnew/3.3.html > > To download Python 3.3.4 visit: > > http://www.python.org/download/releases/3.3.4/ > > > This is a production release, please report any bugs to > > http://bugs.python.org/ > > > Enjoy! > > - -- > Georg Brandl, Release Manager > georg at python.org > (on behalf of the entire python-dev team and 3.3's contributors) > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.22 (GNU/Linux) > > iEYEARECAAYFAlL5PMwACgkQN9GcIYhpnLCv4wCePNVqwsOYCHdJBix2bKk4PNpK > GBoAnRML2x6obCssnUJe5xwuUZYw8ZSY > =+/Nz > -----END PGP SIGNATURE----- > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Sat Feb 15 06:43:50 2014 From: gandalf at shopzeus.com (=?UTF-8?B?TmFneSBMw6FzemzDsyBac29sdA==?=) Date: Sat, 15 Feb 2014 12:43:50 +0100 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> <52FF4E9F.7070209@shopzeus.com> Message-ID: <52FF52F6.5060507@shopzeus.com> > Just because I have a distrust of Windows's command interpreter, what > happens when you type: > > ftype python.file > > ? Does it echo back what you thought it had, or has %* been eaten? If > the %* is missing, that would explain the loss of arguments. Already tought of that: C:\Temp>ftype python.file python.file="C:\Windows\py.exe" "%1" %* C:\Temp> Something else is going on. From marko at pacujo.net Sat Feb 15 08:44:39 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 15:44:39 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <878utcmqwo.fsf@elektro.pacujo.net> Mark Lawrence : > I have no interest in understanding object identity, I can write code > quite happily without it. Luckily, what we are now debating is mostly terminology and points of view where the outcomes are unaffected. However, as an example, it is important to know if you should write: if x is not None: ... or if if x != None: ... is more robust. As an aside, thousands upon thousands of Java programmers churn out code quite happily with no interest in understanding the "happens before" relation (), which is heavily leaned on by Hotspot's JIT optimizer. I find that disconcerting. Marko From greymaus at mail.com Sat Feb 15 08:55:16 2014 From: greymaus at mail.com (greymausg) Date: 15 Feb 2014 13:55:16 GMT Subject: ipython References: Message-ID: On 2014-02-15, Mark Lawrence wrote: > On 15/02/2014 11:55, greymausg wrote: >> using IPython, is there any way of recording the commands I have entered? >> > > I believe ipython automatically stores the commands you enter. > Searching for ipython+command+history should get you more detail than I > can offer :) > What I was thinking of is like a perl Module WWW::Mechanize::Shell, which has a script included, "wwwshell.pl", which allows you to enter commands to explore web sites, then enter "source x", and it will save the commands you have used to a script, 'x'. This can be run straight to do what you want, say scraping a web site. -- maus . . ... From ben+python at benfinney.id.au Sat Feb 15 08:59:52 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Feb 2014 00:59:52 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> <87d2iomrsg.fsf@elektro.pacujo.net> Message-ID: <85eh3479ye.fsf@benfinney.id.au> Marko Rauhamaa writes: > Anyway, an object is a fairly advanced and abstract concept. It is a concept that, in natural language, has the huge advantage of producing correct inferences most of the time. You don't need to give a formal definition when first introducing the term ?object?. Just use it, and the student will produce inferences: * an object is a distinct concrete entity * an object is distinct from other objects * an object may or may not change, but remains the same object * an object belongs to a class of similar objects, and is different from objects of different classes * an object has behaviours that are mostly the same as other objects of the same class None of this needs to be spelled out when the term is introduced; all of it will follow from the connotations of the term ?object? in English. > A beginning programmer wouldn't be equipped to understand the ultimate > abstraction; an object is too all-encompassing to express anything. Nevertheless, ?object? as a term in normal English will produce a bunch of helpful inferences, and avoid the need for coming up with some less-familiar term. It will also allow you to postpone a formal definition until later. -- \ ?Try to learn something about everything and everything about | `\ something.? ?Thomas Henry Huxley | _o__) | Ben Finney From kwpolska at gmail.com Sat Feb 15 09:09:03 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sat, 15 Feb 2014 15:09:03 +0100 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: On Sat, Feb 15, 2014 at 3:26 AM, Roy Smith wrote: > In article , > Ryan Gonzalez wrote: > >> python setup.py sdist > > OK, I run that and I get a metar-1.4.0.tar.gz under dist. If I move > that tarfile to my packages directory, and run pip, I get: > > $ pip install --no-index --quiet --find-links packages metar==1.4.0 [snip] > ValueError: unknown url type: packages The path to your cache directory is incorrect. I suggest using absolute paths (eg. /home/user/packages) instead of relative paths, which is likely what caused this issue. On Fri, Feb 14, 2014 at 7:47 PM, Roy Smith wrote: > What I can't figure out is what I need to do to go from a clone of the > github repo to a tarball I can drop into our packages directory. Is > there some tutorial somewhere that explains this? Actually, you could even tar up that entire repo (or even get a nice ready tarball from GItHub) and you will get something usable with pip. For example, we in the Nikola project (https://github.com/getnikola/nikola) upload the GitHub tarballs to PyPI because we ship 99.9% of our tree anyways and hiring `setup.py sdist` would be a waste of time (and would produce two almost-identical-but-not-quite tarballs). -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From anand at chatimity.com Sat Feb 15 09:13:51 2014 From: anand at chatimity.com (anand at chatimity.com) Date: Sat, 15 Feb 2014 06:13:51 -0800 (PST) Subject: Localized Type Inference of Atomic Types in Python In-Reply-To: References: Message-ID: On Wednesday, May 25, 2005 4:41:34 AM UTC+5:30, Brett C. wrote: > My thesis, "Localized Type Inference of Atomic Types in Python", was > successfully defended today for my MS in Computer Science at the California > Polytechnic State University, San Luis Obispo. With that stamp of approval I > am releasing it to the world. You can grab a copy at > http://www.drifty.org/thesis.pdf . Hi, This link seems to be down. Can you point us to some current link? Am trying to contribute to https://code.google.com/p/py2c/ and reading up on type inference for python. Thanks and Regards, Anand > > For those of you who attended my talk at PyCon 2005 this is the thesis that > stemmed from the presented data. > > As of this exact moment I am not planning to release the source code mainly > because it's a mess, I am not in the mood to pull the patches together, and the > last thing I want happening is people finding mistakes in the code. =) But if > enough people request the source I will take the time to generate a tar.bz2 > file of patches against the 2.3.4 source release and put them up somewhere. > > Below is the abstract culled directly from the thesis itself. > > -Brett C. > > --------------------------------- > ABSTRACT > > Types serve multiple purposes in programming. One such purpose is in providing > information to allow for improved performance. Unfortunately, specifying the > types of all variables in a program does not always fit within the design of a > programming language. > > Python is a language where specifying types does not fit within the language > design. An open source, dynamic programming language, Python does not support > type specifications of variables. This limits the opportunities in Python for > performance optimizations based on type information compared to languages that > do allow or require the specification of types. > > Type inference is a way to derive the needed type information for optimizations > based on types without requiring type specifications in the source code of a > program. By inferring the types of variables based on flow control and other > hints in a program, the type information can be derived and used in a > constructive manner. > > This thesis is an exploration of implementing a type inference algorithm for > Python without changing the semantics of the language. It also explores the > benefit of adding type annotations to method calls in order to garner more type > information. From ben+python at benfinney.id.au Sat Feb 15 09:20:00 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Feb 2014 01:20:00 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> Message-ID: <858utc790v.fsf@benfinney.id.au> Joshua Landau writes: > Here, I give you a pdf. Hopefully this isn't anti > mailing-list-etiquette. This forum is read in many different contexts, and attachments aren't appropriate. You should simply put the text directly into your message, if it's short enough. If it's long, then put it online somewhere and send a link with a description; or, better, make it shorter so it is reasonable to put the text in a message :-) -- \ ?Smoking cures weight problems. Eventually.? ?Steven Wright | `\ | _o__) | Ben Finney From rosuav at gmail.com Sat Feb 15 09:24:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 01:24:55 +1100 Subject: Localized Type Inference of Atomic Types in Python In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 1:13 AM, wrote: > On Wednesday, May 25, 2005 4:41:34 AM UTC+5:30, Brett C. wrote: >> My thesis, "Localized Type Inference of Atomic Types in Python", was >> successfully defended today for my MS in Computer Science at the California >> Polytechnic State University, San Luis Obispo. With that stamp of approval I >> am releasing it to the world. You can grab a copy at >> http://www.drifty.org/thesis.pdf . > > > Hi, > This link seems to be down. Can you point us to some current link? Am trying to contribute to https://code.google.com/p/py2c/ and reading up on type inference for python. I think you realize that you're responding to a nine-year-old post here, but it's possible not everyone does :) Anyway... Tracing the file through the Internet Archive comes up with this: https://web.archive.org/web/20061223193827/http://www.ocf.berkeley.edu/~bac/thesis.pdf I don't know if Brett Cannon (author of the post and thesis) reads python-list/c.l.p, but as a core developer, he's visible on python-dev. Depending on what you're trying to do, it may be appropriate to post there, if after a while (maybe a week) you haven't heard anything useful from here. ChrisA From rosuav at gmail.com Sat Feb 15 09:26:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 01:26:17 +1100 Subject: Explanation of list reference In-Reply-To: <858utc790v.fsf@benfinney.id.au> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <858utc790v.fsf@benfinney.id.au> Message-ID: On Sun, Feb 16, 2014 at 1:20 AM, Ben Finney wrote: > Joshua Landau writes: > >> Here, I give you a pdf. Hopefully this isn't anti >> mailing-list-etiquette. > > This forum is read in many different contexts, and attachments aren't > appropriate. You should simply put the text directly into your message, > if it's short enough. > > If it's long, then put it online somewhere and send a link with a > description; or, better, make it shorter so it is reasonable to put the > text in a message :-) I skimmed it, and... uhh... it's not text :) Well, it's mostly text, but it's arranged on the page with positioning and arrows and stuff. So a link would be more useful than trying to cram it into the post itself. ChrisA From breamoreboy at yahoo.co.uk Sat Feb 15 09:38:15 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 14:38:15 +0000 Subject: Localized Type Inference of Atomic Types in Python In-Reply-To: References: Message-ID: On 15/02/2014 14:13, anand at chatimity.com wrote: > On Wednesday, May 25, 2005 4:41:34 AM UTC+5:30, Brett C. wrote: >> My thesis, "Localized Type Inference of Atomic Types in Python", was >> successfully defended today for my MS in Computer Science at the California >> Polytechnic State University, San Luis Obispo. With that stamp of approval I >> am releasing it to the world. You can grab a copy at >> http://www.drifty.org/thesis.pdf . > > > Hi, > This link seems to be down. Can you point us to some current link? Am trying to contribute to https://code.google.com/p/py2c/ and reading up on type inference for python. > > Thanks and Regards, > Anand > Hardly surprising for a nine year old link but search for brett+cannon+python+thesis and you'll find it :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From steve+comp.lang.python at pearwood.info Sat Feb 15 09:41:49 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 14:41:49 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> Message-ID: <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 14:07:35 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: >>> 0. x is x >>> 1. if x is y then y ix x >>> 2. if x is y and y is z then x is z >>> 3. after x = y, x is y >>> 4. if x is y and x == x, then x == y >>> 5. id(x) == id(y) iff x is y >> >> # Counter-example >> py> x = 230000 >> py> idx = id(x) >> py> del x >> py> y = 420000 >> py> idy = id(y) >> py> idx == idy >> True > > I don't accept that as a counterexample. Why? Do you think I lied and just faked the output I put into my post? It is a clear case where two distinct objects, in this case 230000 and 420000, have the same ID. You cut out the explanation I gave explaining the example, which is crucial. Your description of identity leaves out a critical factor, namely that the objects being discussed must exist simultaneously. If you don't specify that factor, your description includes a great big hole, just as I show above. > You will have to produce: > > (id(x) == id(y)) == (x is y) > > False I don't have to produce anything of the sort. All I need to do is show a case where two distinct objects have the same ID. That is quite easy in CPython, since IDs can be re-used after objects are garbage-collected. >> (This is *implementation dependent* so your mileage my vary.) >> >>> Does that cover it? >> >> No. Your definition describes some properties of identity-equivalence, >> but doesn't explain what identity actually means. > > That's the point. I don't think id() and "is" have any abstract meaning > on top of the formal axioms. Who is talking about "abstract meaning"? They have concrete meaning in Python, and extremely simple meaning at that. * id() is a function which returns an abstract implementation- dependent identity number which is unique for each object during the object's lifetime. * The "is" operator compares the two operands for identity, returning True if, and only if, they are the same object, otherwise returning False. Object identity is simple and well-defined in Python. I don't know why you are so resistant to this. Read the documentation. -- Steven From __peter__ at web.de Sat Feb 15 09:50:34 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Feb 2014 15:50:34 +0100 Subject: ipython References: Message-ID: greymausg wrote: > using IPython, is there any way of recording the commands I have entered? Did you ever enter ? in ipython? In [1]: a = float(raw_input("a? ")) a? 1 In [2]: b = float(raw_input("b? ")) b? 2 In [3]: ab = a + b In [4]: c = ab*ab In [5]: print c 9.0 In [6]: In[1:3] Out[6]: u'a = float(raw_input("a? "))\nb = float(raw_input("b? "))\n' In [7]: %macro abc 1:6 Macro `abc` created. To execute, type its name (without quotes). Macro contents: a = float(raw_input("a? ")) b = float(raw_input("b? ")) ab = a + b c = ab*ab print c In [8]: abc ------> abc() a? 2 b? 2 16.0 In [14]: From laurent.pointal at free.fr Sat Feb 15 09:52:14 2014 From: laurent.pointal at free.fr (Laurent Pointal) Date: Sat, 15 Feb 2014 15:52:14 +0100 Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: <52ff7f1f$0$2128$426a74cc@news.free.fr> luke.geelen at gmail.com wrote: > hello, > i have been working on a python resistor calculator to let my class show > what you can do with python. now i have a script that makes the more > speekable value of the resistance (res) > > #if len(str(res)) > 9: > # res2 = res / 1000000000 > # print "de weerstand is %s,%s giga ohms" % (res2) > #elif len(str(res)) > 6: > # res2 = res / 1000000 > # print "de weerstand is %s,%s Mega ohm" % (res2) > #elif len(str(res)) > 3: > # res2 = res / 1000 > # print "de weerstand is", res2,"kilo ohm" > #elif len(str(res)) < 4: > # res2 = res > # print "de weerstand is", res2,"ohm" > > i commented it because it doesn't work (yet), when i have a resistance of > 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural > number, anyway of using decimals insted so that it says : the resistance > is 9.9 Giga Ohms instead of 9 ? Seem you are using Python2, if res is an integer the division by an integer values produce an integer result (changed in Python3), so you loose the decimal part. Try dividing by floating point numbers, like res2 = res / 1000. Note: should take a lok at the log10() function from math module. (with Python3) In [1]: from math import log10 In [2]: r = 132828378723 In [3]: int(log10(r)) Out[3]: 11 In [4]: r / 10**int(log10(r)) Out[4]: 1.32828378723 A+ Laurent. From greymaus at mail.com Sat Feb 15 09:55:16 2014 From: greymaus at mail.com (greymausg) Date: 15 Feb 2014 14:55:16 GMT Subject: ipython References: Message-ID: On 2014-02-15, greymausg wrote: > On 2014-02-15, Mark Lawrence wrote: >> On 15/02/2014 11:55, greymausg wrote: >>> using IPython, is there any way of recording the commands I have entered? >>> >> >> I believe ipython automatically stores the commands you enter. >> Searching for ipython+command+history should get you more detail than I >> can offer :) >> > > What I was thinking of is like a perl Module WWW::Mechanize::Shell, > which has a script included, "wwwshell.pl", which allows you to > enter commands to explore web sites, then enter "source x", Sorry "script x" > and it will save the commands you have used to a script, 'x'. > This can be run straight to do what you want, say scraping a > web site. > > -- maus . . ... From roy at panix.com Sat Feb 15 10:06:21 2014 From: roy at panix.com (Roy Smith) Date: Sat, 15 Feb 2014 10:06:21 -0500 Subject: Absolute imports? Message-ID: http://docs.python.org/2/whatsnew/2.5.html says: "Once absolute imports are the default, import string will always find the standard library?s version." Experimentally, it appears that modules in site-packages are also found by absolute imports. I wouldn't consider site-packages to be part of the "standard library". Can somebody give me a more precise description of what absolute import does? It also says, "This absolute-import behaviour will become the default in a future version (probably Python 2.7)", but it appears that 2.7.6 is still doing relative by default. From rosuav at gmail.com Sat Feb 15 10:26:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 02:26:13 +1100 Subject: Absolute imports? In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 2:06 AM, Roy Smith wrote: > It also says, "This absolute-import behaviour will become the default in > a future version (probably Python 2.7)", but it appears that 2.7.6 is > still doing relative by default. > Since absolute imports can be controlled with a future directive, you can check it out via that module: >>> import __future__ >>> __future__.absolute_import _Feature((2, 5, 0, 'alpha', 1), (3, 0, 0, 'alpha', 0), 16384) Looks like it was held over for 3.0 rather than potentially breaking stuff across 2.6->2.7. ChrisA From kjakupak at gmail.com Sat Feb 15 10:27:24 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Sat, 15 Feb 2014 07:27:24 -0800 (PST) Subject: Quick Help Message-ID: <7eefdfb9-527c-4712-a111-4ea662051f43@googlegroups.com> Just need a bit of help understanding this so I can actually start it. The input to a program will come from a file called "asdf.in". This file will have all the info needed for the course. The formatting of the input file is described as follows, with denoting # of white spaces and denoting n white spaces. Title: Title: etc.. Is it asking me to make an input file with all of that info (like it is above), or to have an info file actually filled with all that information filled out? Because I then need to have the program be able to output info in certain formats that come from that input file. From steve+comp.lang.python at pearwood.info Sat Feb 15 10:27:29 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 15:27:29 GMT Subject: Question on using FP numbers in python 2 References: <52feec65$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <52ff8760$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 00:07:49 -0500, Gene Heskett wrote: >> Can you extract the float calculations and show us, together with some >> sample data, expected result, and actual result? > > Not extract, but let you get & look at the code, its the top entry on > this page: > > Code_Generators#Counterbore_Software> Here is the direct link to the Python code: http://wiki.linuxcnc.org/uploads/counterbore.py > Assume no bolt size is clicked on, but a wanted diameter is entered in > the lower left pair of boxes, and its to carve .700" deep in the other > box. The cutting tool is .250 in diameter, its to do a stepover of 25% > of the tool diameter, while carving an additional .015" out of the .850" > hole with the tool bit turning 2000 rpm as it spirals down. If I've understood the purpose of this program correctly, it generates code in some language called "G-code", presumably to control some sort of actual physical cutting machine. So the first thing you ought to do is have a G-code expert look at the generated code and tell you it does what it is supposed to do. Or perhaps your cutting machine is buggy. > But the hole it will cut will only be .650" in diameter, And the > backplot, shown in the axis interface, shows no spiral, its doing what > it thinks is full diameter in one circular plunge cut. Scroll to the GeneratePath method, and read the comments at the top of the method. They tell you that the *intention* is: * If the tool diameter equals the hole diameter, then just Plunge down to the hole depth. * If the tool diameter is less than 80% of the hole diameter, then Plunge to each Level and Spiral out. * If the tool diameter is greater than 80% of the hole diameter, then Spiral to each Level and Spiral out. But a little later, we see this code: # Figure out what kind of entry into the hole if (self.ToolDiameter * 1.25 <= self.HoleDiameter): self.CutType = 'Spiral Down to Depth of each Pass and Spiral Out' else: if (self.ToolDiameter < self.HoleDiameter): self.CutType = 'Plunge Down to Depth of each Pass and Spiral Out' else: self.CutType = 'Plunge Down to Hole Depth' Assuming that the comments are correct, the CutType is wrong. It looks like a simple logic error, and should be something like this: # Figure out what kind of entry into the hole if (self.ToolDiameter * 1.25 <= self.HoleDiameter): self.CutType = 'Plunge down and spiral out' elif (self.ToolDiameter * 1.25 > self.HoleDiameter): self.CutType = 'Spiral down and spiral out' else: self.CutType = 'Plunge down' CutType is, I believe, merely a comment, but it leads me to believe that there are probably similar logic errors in the rest of the GeneratePath method. In fact, the description states: "At this time there is a bug if you have a path that does not require a spiral... working on it" -- Steven From __peter__ at web.de Sat Feb 15 10:46:31 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Feb 2014 16:46:31 +0100 Subject: Absolute imports? References: Message-ID: Roy Smith wrote: > http://docs.python.org/2/whatsnew/2.5.html says: > > "Once absolute imports are the default, import string will always find > the standard library?s version." > > Experimentally, it appears that modules in site-packages are also found > by absolute imports. I wouldn't consider site-packages to be part of > the "standard library". Can somebody give me a more precise description > of what absolute import does? Basically, if module foo.bar contains an `import baz` with relative imports python will look for foo.baz before searching for baz in sys.path; with absolute imports `from . import baz` will only look for baz in the current package while `import baz` will only search sys.path. > It also says, "This absolute-import behaviour will become the default in > a future version (probably Python 2.7)", but it appears that 2.7.6 is > still doing relative by default. $ tree . ??? baz.py ??? foo ??? bar.py ??? baz.py ??? __init__.py 1 directory, 4 files $ cat baz.py print("import is absolute") $ cat foo/baz.py print("import is relative") $ cat foo/bar.py import baz $ python -c 'import foo.bar' import is relative $ python3 -c 'import foo.bar' import is absolute From marko at pacujo.net Sat Feb 15 11:29:59 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 18:29:59 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wqgwl4oo.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sat, 15 Feb 2014 14:07:35 +0200, Marko Rauhamaa wrote: >> Steven D'Aprano : >>> On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: >>>> 5. id(x) == id(y) iff x is y >>> >>> # Counter-example >>> py> x = 230000 >>> py> idx = id(x) >>> py> del x >>> py> y = 420000 >>> py> idy = id(y) >>> py> idx == idy >>> True >> >> I don't accept that as a counterexample. > Why? Nowhere do I see the violating "x is y". > All I need to do is show a case where two distinct objects have the > same ID. How do you know objects are "distinct"? Myself, I would use the "is" test. >> That's the point. I don't think id() and "is" have any abstract >> meaning on top of the formal axioms. > > Who is talking about "abstract meaning"? I am. I mean, "implementation-independent". > Object identity is simple and well-defined in Python. I don't know why > you are so resistant to this. Read the documentation. It is not defined at all: Every object has an identity, a type and a value. An object?s identity never changes once it has been created; you may think of it as the object?s address in memory. The ?is? operator compares the identity of two objects; the id() function returns an integer representing its identity. Thus "x and y are identical" *means* "x is y" and nothing else. Marko From gary.herron at islandtraining.com Sat Feb 15 11:41:37 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Sat, 15 Feb 2014 08:41:37 -0800 Subject: Quick Help In-Reply-To: <7eefdfb9-527c-4712-a111-4ea662051f43@googlegroups.com> References: <7eefdfb9-527c-4712-a111-4ea662051f43@googlegroups.com> Message-ID: <52FF98C1.1090408@islandtraining.com> On 02/15/2014 07:27 AM, kjakupak at gmail.com wrote: > Just need a bit of help understanding this so I can actually start it. > > The input to a program will come from a file called "asdf.in". This file will have all the info needed for the course. The formatting of the input file is described as follows, with denoting # of white spaces and denoting n white spaces. > > Title: > Title: > etc.. > > Is it asking me to make an input file with all of that info (like it is above), or to have an info file actually filled with all that information filled out? Because I then need to have the program be able to output info in certain formats that come from that input file. It makes no sense to ask us to guess what your teacher wants. Please ask the teacher. Once you know what the assignment expects, you may ask us Python questions, because we can answer those without guessing. (But don't ask us to write the program for you.) Gary Herron From roy at panix.com Sat Feb 15 12:02:39 2014 From: roy at panix.com (Roy Smith) Date: Sat, 15 Feb 2014 12:02:39 -0500 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: Steven D'Aprano : > > Object identity is simple and well-defined in Python. I don't know why > > you are so resistant to this. Read the documentation. Marko Rauhamaa : > It is not defined at all: > > Every object has an identity, a type and a value. An object???s > identity never changes once it has been created; you may think of it > as the object???s address in memory. The ???is??? operator compares the > identity of two objects; the id() function returns an integer > representing its identity. The "you may think of it as the object's address in memory" part is misleading, and should be removed from the docs. While it's true that you may think of it that way, such thinking just leads you to make assumptions which are not universally true. I agree with Marko that this is not a definition. It's a collection of random statements about ids, their use, and some misleading philosophy. Even the part about "... compares the identify of two objects" is kind of funky, since it implies that you do indeed have two objects! A definition would be: "The identity of an object is an integer which never changes during the lifetime of the object, and which is guaranteed to be distinct from the identities of all other objects with overlapping lifetimes. A given identity may be reused for objects with disjoint lifetimes". That (I think) says everything is which is guaranteed about identities, and nothing more. Once you've defined what an identity is, then you can go on to describe some fun things you can do with it: "The id() function returns the identity of an object. The 'is' operator compares the identities of its two operands and returns True if they are the same." From rmorgan466 at gmail.com Sat Feb 15 12:10:33 2014 From: rmorgan466 at gmail.com (Rita) Date: Sat, 15 Feb 2014 12:10:33 -0500 Subject: inheriting a large python code base Message-ID: hi all, i just inherited a large python code base and I would like to optimize the code (run faster). The application is a scientific application so I really don't understand the internal logic. Here is what I have done so far, profile (cProfile) and was able to see where the code was taking the longest time. I was wondering if anyone else experienced something like this and how they overcame a problem such a this...what techniques have you used to "optimize" the code. -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Sat Feb 15 12:11:46 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 10:11:46 -0700 Subject: Explanation of list reference In-Reply-To: <87wqgwl4oo.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 9:29 AM, Marko Rauhamaa wrote: > Steven D'Aprano : >> On Sat, 15 Feb 2014 14:07:35 +0200, Marko Rauhamaa wrote: >>> Steven D'Aprano : >>>> On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: >>>>> 5. id(x) == id(y) iff x is y >>>> >>>> # Counter-example >>>> py> x = 230000 >>>> py> idx = id(x) >>>> py> del x >>>> py> y = 420000 >>>> py> idy = id(y) >>>> py> idx == idy >>>> True >>> >>> I don't accept that as a counterexample. > >> Why? > > Nowhere do I see the violating "x is y". You formulated your rule as a rule of inference. The logical inference from the above is that x is y, which is false even if it can't be directly tested in Python. >> All I need to do is show a case where two distinct objects have the >> same ID. > > How do you know objects are "distinct"? Myself, I would use the "is" > test. Eliding over details of how one knows that both of the literals above create objects, if the objects are separately created, then they are distinct objects. >>> That's the point. I don't think id() and "is" have any abstract >>> meaning on top of the formal axioms. >> >> Who is talking about "abstract meaning"? > > I am. I mean, "implementation-independent". > >> Object identity is simple and well-defined in Python. I don't know why >> you are so resistant to this. Read the documentation. > > It is not defined at all: > > Every object has an identity, a type and a value. An object's > identity never changes once it has been created; you may think of it > as the object's address in memory. The 'is' operator compares the > identity of two objects; the id() function returns an integer > representing its identity. > > Thus "x and y are identical" *means* "x is y" and nothing else. This notion of identity sounds useless, and if that is the way you prefer to understand it then you can safely ignore that it exists. I think that most users though inherently understand the concept of objects being distinct or identical and see the value in being able to test for this. From luke.geelen at gmail.com Sat Feb 15 12:17:52 2014 From: luke.geelen at gmail.com (Luke Geelen) Date: Sat, 15 Feb 2014 09:17:52 -0800 (PST) Subject: decimal numbers In-Reply-To: References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: If i do set form thing in my script i get Invalide syntax pointing at the last word of the form rule From ian.g.kelly at gmail.com Sat Feb 15 12:20:35 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 10:20:35 -0700 Subject: decimal numbers In-Reply-To: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 2:18 AM, wrote: > hello, > i have been working on a python resistor calculator to let my class show what you can do with python. > now i have a script that makes the more speekable value of the resistance (res) > > #if len(str(res)) > 9: > # res2 = res / 1000000000 > # print "de weerstand is %s,%s giga ohms" % (res2) > #elif len(str(res)) > 6: > # res2 = res / 1000000 > # print "de weerstand is %s,%s Mega ohm" % (res2) > #elif len(str(res)) > 3: > # res2 = res / 1000 > # print "de weerstand is", res2,"kilo ohm" > #elif len(str(res)) < 4: > # res2 = res > # print "de weerstand is", res2,"ohm" > > i commented it because it doesn't work (yet), when i have a resistance of > 9.9 Giga ohms it says it is 9 giga ohms. it seems to work with natural number, anyway of using decimals insted so that it says : the resistance is 9.9 Giga Ohms instead of 9 ? Others have already explained how to do floating-point rather than integer division. I'm curious to know why you're basing the if tests on the length of the number as a string rather than on the magnitude of the number. Consider for example an input of 0.01. Converted to a string, that is "0.01" which has a length of 4. So the output would be "de weerstand is 0.00001 kilo ohm", which is probably not what you would desire. From ian.g.kelly at gmail.com Sat Feb 15 12:23:20 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 10:23:20 -0700 Subject: decimal numbers In-Reply-To: References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen wrote: > If i do set form thing in my script i get > Invalide syntax pointing at the last word of the form rule Please copy and paste the exact code you ran along with the full text of the exception into your post. Paraphrasing it like this doesn't help us help you. From gheskett at wdtv.com Sat Feb 15 12:27:38 2014 From: gheskett at wdtv.com (Gene Heskett) Date: Sat, 15 Feb 2014 12:27:38 -0500 Subject: Question on using FP numbers in python 2 In-Reply-To: <52ff8760$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <52ff8760$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <201402151227.38288.gheskett@wdtv.com> On Saturday 15 February 2014 12:13:42 Steven D'Aprano did opine: > On Sat, 15 Feb 2014 00:07:49 -0500, Gene Heskett wrote: > >> Can you extract the float calculations and show us, together with > >> some sample data, expected result, and actual result? > > > > Not extract, but let you get & look at the code, its the top entry on > > this page: > > > > > Code_Generators#Counterbore_Software> > > Here is the direct link to the Python code: > > http://wiki.linuxcnc.org/uploads/counterbore.py > > > Assume no bolt size is clicked on, but a wanted diameter is entered in > > the lower left pair of boxes, and its to carve .700" deep in the other > > box. The cutting tool is .250 in diameter, its to do a stepover of 25% > > of the tool diameter, while carving an additional .015" out of the > > .850" hole with the tool bit turning 2000 rpm as it spirals down. > > If I've understood the purpose of this program correctly, it generates > code in some language called "G-code", presumably to control some sort > of actual physical cutting machine. More or less standard cNC machine control language. > So the first thing you ought to do > is have a G-code expert look at the generated code and tell you it does > what it is supposed to do. I think I might qualify for that expert label. Looking at the output code, take the maximum X values it outputs plus and minus, add, then add the tool diameter to get the size of the pocket it will cut. I don't need a graphical backplot to check that. > Or perhaps your cutting machine is buggy. Not impossible, but that part of the scaling code is 20+ years mature. It knows exactly how many times to step the motor to move the tables 20 feet with micron accuracy if there is no mechanical backlash between the motor and the table. Unfortunately there is in my toy mill, which is whats driving me to install ball screws in the table drives, which can have backlashes well under .0001" if properly made. > > But the hole it will cut will only be .650" in diameter, And the > > backplot, shown in the axis interface, shows no spiral, its doing what > > it thinks is full diameter in one circular plunge cut. > > Scroll to the GeneratePath method, and read the comments at the top of > the method. They tell you that the *intention* is: > > * If the tool diameter equals the hole diameter, then just Plunge > down to the hole depth. > > * If the tool diameter is less than 80% of the hole diameter, > then Plunge to each Level and Spiral out. > > * If the tool diameter is greater than 80% of the hole diameter, > then Spiral to each Level and Spiral out. > > But a little later, we see this code: > > # Figure out what kind of entry into the hole > if (self.ToolDiameter * 1.25 <= self.HoleDiameter): > self.CutType = 'Spiral Down to Depth of each Pass and Spiral > Out' else: > if (self.ToolDiameter < self.HoleDiameter): > self.CutType = 'Plunge Down to Depth of each Pass and Spiral > Out' > else: > self.CutType = 'Plunge Down to Hole Depth' > > > Assuming that the comments are correct, the CutType is wrong. It looks > like a simple logic error, and should be something like this: > > # Figure out what kind of entry into the hole > if (self.ToolDiameter * 1.25 <= self.HoleDiameter): > self.CutType = 'Plunge down and spiral out' > elif (self.ToolDiameter * 1.25 > self.HoleDiameter): > self.CutType = 'Spiral down and spiral out' > else: > self.CutType = 'Plunge down' > > CutType is, I believe, merely a comment, but it leads me to believe that > there are probably similar logic errors in the rest of the GeneratePath > method. In fact, the description states: > > "At this time there is a bug if you have a path that does not require a > spiral... working on it" And I just heard back, he is looking at it again. Thanks Steven. 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) Genes Web page NOTICE: Will pay 100 USD for an HP-4815A defective but complete probe assembly. From rustompmody at gmail.com Sat Feb 15 12:30:52 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 15 Feb 2014 09:30:52 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: On Saturday, February 15, 2014 10:32:39 PM UTC+5:30, Roy Smith wrote: > Steven D'Aprano : > > > Object identity is simple and well-defined in Python. I don't know why > > > you are so resistant to this. Read the documentation. > Marko Rauhamaa > > It is not defined at all: > > Every object has an identity, a type and a value. An object?s > > identity never changes once it has been created; you may think of it > > as the object?s address in memory. The ?is? operator compares the > > identity of two objects; the id() function returns an integer > > representing its identity. > The "you may think of it as the object's address in memory" part is > misleading, and should be removed from the docs. While it's true that > you may think of it that way, such thinking just leads you to make > assumptions which are not universally true. > I agree with Marko that this is not a definition. It's a collection of > random statements about ids, their use, and some misleading philosophy. > Even the part about "... compares the identify of two objects" is kind > of funky, since it implies that you do indeed have two objects! > A definition would be: > "The identity of an object is an integer which never changes during the > lifetime of the object, and which is guaranteed to be distinct from the > identities of all other objects with overlapping lifetimes. A given > identity may be reused for objects with disjoint lifetimes". > That (I think) says everything is which is guaranteed about identities, > and nothing more. Once you've defined what an identity is, then you can > go on to describe some fun things you can do with it: Thanks! -- Nice to hear slightly more philosophically astute attempt than the naivete going around: "Object?! We all know whats an object! Everyone knows whats an object!!" However I am betting that the problem remains. Youve transfered the identity question into the lifetime. Now define object-lifetime without reference to identity :-) [Incidentally same applies to Ian's attempt at reducing identity to creation] Just staying with 'lifetime' and the original meaning from which this word was analogized. (Allegorized?) I am supposed to be about 50 years old. What exactly does that mean? The cells in my body recycle every few months -- couple of years if we add bones The molecules that make up those cells are as old as the universe. What exactly does that 50 refer to? > "The id() function returns the identity of an object. The 'is' operator > compares the identities of its two operands and returns True if they are > the same." Thats good -- 'is' in terms of 'id' -- better than the obfuscation and prevarication of the other way round. Only the name id is misleading -- it should be machine-id or some such. Consider these examples: Two graphs are the same if they have the same no of vertices and there is a mapping f from one vertex set to the other such that vw is edge in graph1 iff f(v)f(w) is edge in graph2. For a mathematician such an identity is unexceptionable The only catch is that implementing such an identity requires finding the f and that is NP complete. Even worse... Two functions f and g are the same (from a math pov) if ? x y . f(x) = g(y) Now I define def f(x) : return x+x def g(x) : return 2*x If a python (or any such) implementation could 'solve' f==g ? f,g, it could also 'solve' f == h where h is def h(x) : return h(x) which is the halting problem Moral? The meaning of identity is very dependent on framing and has no 'single' 'obvious' 'most natural' answer. Given that we are (hopefully!) programmers, a machine-oriented framing seems appropriate From luke.geelen at gmail.com Sat Feb 15 12:42:51 2014 From: luke.geelen at gmail.com (Luke Geelen) Date: Sat, 15 Feb 2014 09:42:51 -0800 (PST) Subject: decimal numbers In-Reply-To: References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian: > On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen wrote: > > > If i do set form thing in my script i get > > > Invalide syntax pointing at the last word of the form rule > > > > Please copy and paste the exact code you ran along with the full text > > of the exception into your post. Paraphrasing it like this doesn't > > help us help you. sorry i made a typo its fixed, thanks a lot From rustompmody at gmail.com Sat Feb 15 12:47:08 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 15 Feb 2014 09:47:08 -0800 (PST) Subject: Explanation of list reference In-Reply-To: <87wqgwl4oo.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: <26997873-8f75-4df7-8f08-565d89d1d10f@googlegroups.com> On Saturday, February 15, 2014 9:59:59 PM UTC+5:30, Marko Rauhamaa wrote: > Steven D'Aprano: > > Object identity is simple and well-defined in Python. I don't know why > > you are so resistant to this. Read the documentation. > It is not defined at all: In a certain way thats what I am saying. But you are saying it stronger than I would... See below > Every object has an identity, a type and a value. An object's > identity never changes once it has been created; you may think of it > as the object's address in memory. The 'is' operator compares the > identity of two objects; the id() function returns an integer > representing its identity. > Thus "x and y are identical" *means* "x is y" and nothing else. Formally yes. But in practice, we (where we means experienced programmers and presumably excludes persons like the OP) understand identity 'somehow-or-other' What does that 'somehow-or-other' consist of? I would argue that we do that comprehending-act by translating to a kind of C. Maybe an informal, pidgin C but close enough that we get (something of) the semantics. From breamoreboy at yahoo.co.uk Sat Feb 15 13:10:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 18:10:20 +0000 Subject: inheriting a large python code base In-Reply-To: References: Message-ID: On 15/02/2014 17:10, Rita wrote: > hi all, > > i just inherited a large python code base and I would like to optimize > the code (run faster). The application is a scientific application so I > really don't understand the internal logic. > > Here is what I have done so far, profile (cProfile) and was able to see > where the code was taking the longest time. > > I was wondering if anyone else experienced something like this and how > they overcame a problem such a this?what techniques have you used to > "optimize" the code. > https://wiki.python.org/moin/PythonSpeed/PerformanceTips -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rgacote at appropriatesolutions.com Sat Feb 15 13:04:43 2014 From: rgacote at appropriatesolutions.com (Ray Cote) Date: Sat, 15 Feb 2014 13:04:43 -0500 (EST) Subject: inheriting a large python code base In-Reply-To: Message-ID: <25489394.698.1392487482685.JavaMail.rgacote@Rays-Home-iMac.local> Hi Rita: Some personal thoughts on how I've approached similar situations: Step 0: Put all that code under version control immediately. Being able to track and back-out changes is extremely useful -- even in a small, single-coder app. With something this big, you'll find "things suddenly stopped working" as you make changes, and being able to back-track your changes is invaluatable. Step 2: Ask, "Why do you want to optimize the code (run faster)?" - what is slow? - starting? - loading data? - solving specific problem? - running specific functionality? - specific calculations? - network access? - database access? - small data sets? - large data sets? - who says it is slow? and what is their definition of sufficiently quick? 3: You state you do not understand the internal logic. I've also inherited applications where the internal logic was unclear. Writing unit and functional tests (if they do not exist) will help to ensure you do not change the behavior of the application. You may find that understanding the internal logic is the best way to speed-up the application. You'll likely find that the biggest speed improvements come from optimizing the logic -- not the Python. 4: This is a personal prefernce when inheriting large code chunks -- and I'm sure some will counter it is not optimum. Go through the code and run pep8 and pyflakes (or flake8) on all the code and address the issues that come up. Aside from bringing the code into styling conformance, I find that this helps me to familiarize myself with the code. As you're making style changes, review individual functions and add documentation if it is missing. If you're not clear what a function does, mark it as such so you know to look at it carefully in the future. 5: Now you have a clean set of code -- most of which you've at least visually scanned -- and you're ready to create some timing tests and dig into specifics. --Ray ----- Original Message ----- From: "Rita" To: python-list at python.org Sent: Saturday, February 15, 2014 12:10:33 PM Subject: inheriting a large python code base hi all, i just inherited a large python code base and I would like to optimize the code (run faster). The application is a scientific application so I really don't understand the internal logic. Here is what I have done so far, profile (cProfile) and was able to see where the code was taking the longest time. I was wondering if anyone else experienced something like this and how they overcame a problem such a this?what techniques have you used to "optimize" the code. -- --- Get your facts first, then you can distort them as you please. -- -- https://mail.python.org/mailman/listinfo/python-list -- Ray Cote, President Appropriate Solutions, Inc. We Build Software 603.924.6079 From fabiofz at gmail.com Sat Feb 15 13:25:15 2014 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 15 Feb 2014 16:25:15 -0200 Subject: Problem importing libraries installed with PIP in Eclipse In-Reply-To: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> References: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Message-ID: On Fri, Feb 14, 2014 at 1:30 AM, Renato wrote: > Hi guys, I'm using Python 2.7.5 64 bits and I have a problem when > importing libraries that were installed via PIP when importing them inside > Eclipse (version 4.3.1). Outside Eclipse (directly in Python's shell) > everything works fine, here is an example: > > >>> import numpy # installed from repositories > >>> from numpy import array > >>> import pybrain # installed via PIP > >>> from pybrain import Network > >>> > > Everything works outside Eclipse. But inside Eclipse I can't import > libraries installed via PIP using "from x import y" format, it will give an > error. The only way I can import libraries installed via PIP is using > "import x" format. Here is an example: > > import numpy # no errors (installed > from repositories) > from numpy import array # no errors > import pybrain # no errors (installed > via PIP) > from pybrain import Network # gives the error below > > Traceback (most recent call last): > File "/media/arquivos/pybrain_import_test.py", line 4, in > from pybrain import Network > ImportError: cannot import name Network > > I suspected it could be related to virtualenv, but here is a print screen ( > http://imageshack.com/a/img534/4307/3x0m.png) of my Python's PATH. The > directory /usr/lib/python2.7/site-packages where PyBrain is installed is > already in Python's PATH inside Eclipse. Could someone help me, please? > -- > https://mail.python.org/mailman/listinfo/python-list > Hi Renato, Can you do the following: Create a new script with: import sys print '\n'.join(sorted(sys.path)) And let me know if the paths you have listed in both are equal... Also, which version of PyDev are you using? Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Sat Feb 15 13:37:35 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 11:37:35 -0700 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 10:30 AM, Rustom Mody wrote: > Thanks! -- Nice to hear slightly more philosophically astute attempt than > the naivete going around: "Object?! We all know whats an object! > Everyone knows whats an object!!" > > However I am betting that the problem remains. Youve transfered the identity > question into the lifetime. > > Now define object-lifetime without reference to identity :-) Fundamentally that's what definitions do. They transfer the question of "what is X" to "okay, so what is this thing that defines X". All definitions must ultimately be circular, simply because we have only finitely many words and concepts to work with. >> "The id() function returns the identity of an object. The 'is' operator >> compares the identities of its two operands and returns True if they are >> the same." > > Thats good -- 'is' in terms of 'id' -- better than the obfuscation and > prevarication of the other way round. Only the name id is misleading -- it > should be machine-id or some such. > > Consider these examples: > > Two graphs are the same if they have the same no of vertices and > there is a mapping f from one vertex set to the other such that > vw is edge in graph1 iff f(v)f(w) is edge in graph2. > > For a mathematician such an identity is unexceptionable Is it though? If we were to play the same game with it, I could point out that you haven't defined graph. So I'll retrieve a definition from Wikipedia: """ a graph is an ordered pair G = (V, E) comprising a set V of vertices or nodes together with a set E of edges or lines, which are 2-element subsets of V """ Well, that's great, but it just transfers the definition of graph into the definition of an ordered pair. Ordered pairs can be defined in terms of sets: """ In 1921 Kazimierz Kuratowski offered the now-accepted definition of the ordered pair (a, b): (a, b) := {{a}, {a, b}} """ But what is a set? Cantor offers this definition: """ A set is a gathering together into a whole of definite, distinct objects of our perception [Anschauung] or of our thought - which are called elements of the set. """ But what precisely are "objects" and how are we to determine their distinctness? Cantor above relates them to perception or thought, but surely my own perception and thought differ from Cantor's. If mathematics or philosophy offer us any absolute answer to this question, I'm unable to find it. From ian.g.kelly at gmail.com Sat Feb 15 13:45:52 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 11:45:52 -0700 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 11:37 AM, Ian Kelly wrote: > But what is a set? Cantor offers this definition: > > """ > A set is a gathering together into a whole of definite, distinct > objects of our perception [Anschauung] or of our thought - which are > called elements of the set. > """ > > But what precisely are "objects" and how are we to determine their > distinctness? Cantor above relates them to perception or thought, but > surely my own perception and thought differ from Cantor's. If > mathematics or philosophy offer us any absolute answer to this > question, I'm unable to find it. I sent the last message a little too early. To continue: the above definition of set is an informal one. In axiomatic set theory, it turns out that "set" is simply taken as an undefined primitive. In other words: "Set?! We all know what's a set! Everyone knows what's a set!!" At some level we have to have primitives, and while we can at some level delve into the machine in order to define an object in terms of memory location and layout and lifetime and even physical considerations such as "which memory?"; at the level of the Python abstraction I suggest that an object is simply an undefined primitive. From luke.geelen at gmail.com Sat Feb 15 13:57:20 2014 From: luke.geelen at gmail.com (Luke Geelen) Date: Sat, 15 Feb 2014 10:57:20 -0800 (PST) Subject: decimal numbers In-Reply-To: <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> Message-ID: <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> Op zaterdag 15 februari 2014 18:42:51 UTC+1 schreef Luke Geelen: > Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian: > > > On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen wrote: > > > > > > > If i do set form thing in my script i get > > > > > > > Invalide syntax pointing at the last word of the form rule > > > > > > > > > > > > Please copy and paste the exact code you ran along with the full text > > > > > > of the exception into your post. Paraphrasing it like this doesn't > > > > > > help us help you. > > > > sorry i made a typo its fixed, thanks a lot hey, is it possible to remove the .0 if it is a valua without something behind the poit (like 5.0 gets 5 but 9.9 stays 9.9 From invalid at invalid.invalid Sat Feb 15 14:02:35 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Feb 2014 19:02:35 +0000 (UTC) Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On 2014-02-15, Chris Angelico wrote: > On Sat, Feb 15, 2014 at 4:20 PM, Ian Kelly wrote: >> On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: >>> To start with we say two objects are identical if they have the same >>> memory address. >> >> This is false. It happens to hold for CPython, but that's an >> implementation detail. The definition of object identity does not >> depend on memory address. It also doesn't have anything to do with >> space-time coordinates. The concept of object identity is an >> abstraction, not an analogy from physics. > > With the restrictions of computer memory, I suspect that two objects > with the same address must be identical, That's true if they have the same address _at_the_exact_same_time_. [AND IF the two chunks of code evaluating the addresses of the objects share a machine-level address space -- which I doubt is actually required by the Python language definition. It would be difficult (but not impossible) to implement a Python where that wasn't true.] However, it's possible for object 1 to have address XYZ at one point in time and object 2 to have address XYZ at a different point in time even though object 1 and object 2 are different objects. The tricky bit is that those two points in time may occur at adjacent "lines" when your program is executing. They may even occur at two different points within the same line of code. IOW, there's just no reason to assume that: address_of(object1) == address_of(ojbect2) is equivalent to object1 is object2 Garbage collection could kick in after the evaluation of address_of(object1) and before the evaluation of address_of(object2) with the result that the two objects would appear to have the same address in memory. So, unless you're working on the guts of a Python implementation you've got to just plain stop thinking about memory addresses. Period. -- Grant From breamoreboy at yahoo.co.uk Sat Feb 15 14:06:27 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Feb 2014 19:06:27 +0000 Subject: decimal numbers In-Reply-To: <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> Message-ID: On 15/02/2014 18:57, Luke Geelen wrote: > Op zaterdag 15 februari 2014 18:42:51 UTC+1 schreef Luke Geelen: >> Op zaterdag 15 februari 2014 18:23:20 UTC+1 schreef Ian: >> >>> On Sat, Feb 15, 2014 at 10:17 AM, Luke Geelen wrote: >> >>> >> >>>> If i do set form thing in my script i get >> >>> >> >>>> Invalide syntax pointing at the last word of the form rule >> >>> >> >>> >> >>> >> >>> Please copy and paste the exact code you ran along with the full text >> >>> >> >>> of the exception into your post. Paraphrasing it like this doesn't >> >>> >> >>> help us help you. >> >> >> >> sorry i made a typo its fixed, thanks a lot > > hey, is it possible to remove the .0 if it is a valua without something behind the poit (like 5.0 gets 5 but 9.9 stays 9.9 > Thanks for yet more double line spacing and single line paragraphs. Is it too much to ask for you to follow the instructions that you've already been given or better yet to use a decent tool? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From steve+comp.lang.python at pearwood.info Sat Feb 15 14:05:03 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 19:05:03 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: <52ffba5f$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 12:02:39 -0500, Roy Smith wrote: > Steven D'Aprano : >> > Object identity is simple and well-defined in Python. I don't know >> > why you are so resistant to this. Read the documentation. > > Marko Rauhamaa : >> It is not defined at all: >> >> Every object has an identity, a type and a value. An object?s >> identity never changes once it has been created; you may think of it >> as the object?s address in memory. The ?is? operator compares the >> identity of two objects; the id() function returns an integer >> representing its identity. > > The "you may think of it as the object's address in memory" part is > misleading, and should be removed from the docs. While it's true that > you may think of it that way, such thinking just leads you to make > assumptions which are not universally true. > > I agree with Marko that this is not a definition. It's a collection of > random statements about ids, their use, and some misleading philosophy. > Even the part about "... compares the identify of two objects" is kind > of funky, since it implies that you do indeed have two objects! Correct, it should say "two operands" to be pedantic. But in regular English, it is quite normal to say things like "the two people actually turned out to be same person" (say, Superman and Clark Kent) and I see no reason not to allow the similar, technically sloppy but easily understandable idea that the `is` operator tests whether two objects are in fact the same object. This concept isn't really that hard to understand. In the expression `a is b`, you have an object bound to the name "a", an object bound to the name "b", hence *two objects*, and you want to know if they are the same object or not. > A definition would be: > > "The identity of an object is an integer which never changes during the > lifetime of the object, and which is guaranteed to be distinct from the > identities of all other objects with overlapping lifetimes. A given > identity may be reused for objects with disjoint lifetimes". You then go on to say: > "The id() function returns the identity of an object. ..." This definition is wrong. An object's identity and its ID are not the same. Objects in Python have an identity the instant they are created, but they may not have an ID assigned to them until much later, if at all. Both IronPython and Jython lazily assign IDs on request, not on creation. Here's an example from Jython: >>> x = "first" >>> y = "second" >>> id(y) # created second, but ID assigned first 1 >>> id(x) # created first, but ID assigned second 2 IronPython is similar, although the specific IDs may not be the same. The problem here is that you are wrongly identifying an object's identity with its identification number. That doesn't apply to people (if you are American, your identity is not the same as your Social Security number); it doesn't apply to rocks, or pencils, or kitchen spoons. Why should it apply to Python objects? The identity of an object is an inherent, fundamental aspect of the object's existence, not some label stuck to it. In Jython, the `is` operator can distinguish objects without assigning them an ID number: >>> a = 230000 >>> b = 230000 >>> a is b # compare two ID-less objects for identity False >>> id("fe") 4 >>> id("fi") 5 >>> id(a) # finally assign a an ID 6 >>> id("fo") 7 >>> id(b) # and the same for b 8 In plain English, "identity" has various definitions, but the one needed here is this: The state or quality of being identical, or the same; sameness. [Webster 1913] where "identical" is understood in the strong sense of: being the exact same one; not any other [Wordnet 2006] rather than the weak sense of merely looking the same, as in "identical houses". These are common, ordinary words, and no more need specialist definitions in the Python documentation than do the other common, ordinary words used, such as "never", "changes" or "created". An object's identity is that quality which distinguishes it from every other object. The nature of that quality is not important. Not withstanding such interesting but irrelevant philosophical questions as the Paradox Of My Grandfather's Axe, the intuitive, common, plain-English meaning of identity is all we need to understand object identity, because it's the same meaning. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 14:17:13 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 19:17:13 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: <52ffbd39$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 18:29:59 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : >> On Sat, 15 Feb 2014 14:07:35 +0200, Marko Rauhamaa wrote: >>> Steven D'Aprano : >>>> On Sat, 15 Feb 2014 12:13:54 +0200, Marko Rauhamaa wrote: >>>>> 5. id(x) == id(y) iff x is y >>>> >>>> # Counter-example >>>> py> x = 230000 >>>> py> idx = id(x) >>>> py> del x >>>> py> y = 420000 >>>> py> idy = id(y) >>>> py> idx == idy >>>> True >>> >>> I don't accept that as a counterexample. > >> Why? > > Nowhere do I see the violating "x is y". Do you truly think that there is even the tiniest, most microscopic chance that the int 230000 which has been garbage-collected and no longer exists, and the int 420000, are the same object? >> All I need to do is show a case where two distinct objects have the >> same ID. > > How do you know objects are "distinct"? Myself, I would use the "is" > test. I know objects are distinct if they are objects with different values, such as 230000 and 420000, due to the fundamental fact that ints cannot have the value 230000 and 420000 at the same time. I leverage my knowledge that ints are intended to model the mathematical integers, and while that model is not perfect, it is not so bad as to have 230000 and 420000 be the same number. I also know that objects are distinct if one of them has been garbage collected, on the account of it no longer existing. >>> That's the point. I don't think id() and "is" have any abstract >>> meaning on top of the formal axioms. >> >> Who is talking about "abstract meaning"? > > I am. I mean, "implementation-independent". "Abstract meaning" does not mean "implementation independent". The definition of identity given in the documentation is both implementation independent and concrete: identity is tied concretely to the creation of the object, while still leaving implementations free to choose exactly how they tie identity to creation. >> Object identity is simple and well-defined in Python. I don't know why >> you are so resistant to this. Read the documentation. > > It is not defined at all: > > Every object has an identity, a type and a value. An object?s > identity never changes once it has been created; you may think of it > as the object?s address in memory. The ?is? operator compares the > identity of two objects; the id() function returns an integer > representing its identity. > > Thus "x and y are identical" *means* "x is y" and nothing else. You are correct, "x and y are identical" does mean that "x is y". That is exactly the point. However, the `is` operator is not necessarily the same as the English word "is". Is some languages, the `is` operator is a synonym for the equals operator. That is not the case in Python. In Python, the *expression* `x is y` has the same meaning as the English sentence "x is y" in the strong sense of testing identity, rather than the weak sense of merely testing similarities (or metaphor). So the Python docs don't merely give a circular definition, they distinguish between two different and competing possibilities: (1) The `is` operator means the same as the == operator. (NO) (2) The `is` operator tests for object identity. (YES) Please also see my response to Roy Smith's message. Every object has a unique (during the lifetime of the object) identity. The specific nature of that identity is implementation-dependent, and strictly irrelevant. The `is` operator tests whether the two operands are the same object, that is, whether they have the same identity. That's all it does. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 14:43:33 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 15 Feb 2014 19:43:33 GMT Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> Message-ID: <52ffc365$0$29973$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 10:57:20 -0800, Luke Geelen wrote: > hey, is it possible to remove the .0 if it is a valua without something > behind the poit (like 5.0 gets 5 but 9.9 stays 9.9 Yes, but not easily. First, check the number's fractional part, and if it is zero, convert it to an int: # Here, your value is x if x % 1 == 0: # Exact whole number. x = int(x) But be warned that really big floats are always ints, even if they have a decimal point in them! For example: x = 1.1e20 has a decimal point, but its value is: 110000000000000000000.0 which is a whole number. So perhaps a better way to do this is to operate on the number as a string, not as a numeric value: s = "%s" % x if s.endswith(".0"): s = s[:-2] If there is anything you don't understand about this code snippet, please feel free to ask. By the way, I see that you are using GoogleGroups to post. GoogleGroups has an extremely obnoxious and annoying habit of throwing in blank lines between every line of your reply. Could you please read and follow the instructions here: https://wiki.python.org/moin/GoogleGroupsPython otherwise you are likely to annoy people and may find we stop answering your questions. We are volunteers, and aren't being paid to answer your questions. If you make it difficult for us, we may just stop. Thank you in advance. Any questions, please don't hesitate to ask. -- Steven From marko at pacujo.net Sat Feb 15 15:20:33 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 22:20:33 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> Message-ID: <87mwhsku0e.fsf@elektro.pacujo.net> Ian Kelly : > On Sat, Feb 15, 2014 at 9:29 AM, Marko Rauhamaa wrote: >> Thus "x and y are identical" *means* "x is y" and nothing else. > > This notion of identity sounds useless, and if that is the way you > prefer to understand it then you can safely ignore that it exists. I > think that most users though inherently understand the concept of > objects being distinct or identical and see the value in being able to > test for this. It is not useless to identify your fundamental definitions and axioms instead of resorting to circular reasoning. The original question was how a beginning programmer could "get" lists. We very quickly descended into the murky waters of "objects" of an underlying machine and CPython's way of implementing things. I was wondering if there was a way to "get" integers, lists, references etc without hauling the poor student under the keel. In a word, could Python be your first programming language? Marko From tjreedy at udel.edu Sat Feb 15 15:40:54 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Feb 2014 15:40:54 -0500 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: On 2/15/2014 1:07 AM, Rustom Mody wrote: > On Saturday, February 15, 2014 10:50:35 AM UTC+5:30, Ian wrote: >> On Fri, Feb 14, 2014 at 9:24 PM, Rustom Mody wrote: >>> In the case of physical objects like dice there is a fairly >>> unquestionable framing that makes identity straightforward -- >>> 4-dimensional space-time coordiantes. If the space-time coordinates of >>> 2 objects are all equal then the objects are identical, else not. >>> Now we analogize the space-time identity of physical objects to >>> computer identity of computer objects (so-called) and all sorts of >>> problems ensue. >>> To start with we say two objects are identical if they have the same >>> memory address. > >> This is false. It happens to hold for CPython, but that's an >> implementation detail. The definition of object identity does not >> depend on memory address. It also doesn't have anything to do with >> space-time coordinates. The concept of object identity is an >> abstraction, not an analogy from physics. > >> The language reference states, "Every object has an identity, a type >> and a value. An object's identity never changes once it has been >> created; you may think of it as the object's address in memory." >> Okay, so that quote does bring up memory address, but in my >> interpretation that's just an analogy to introduce the concept. The >> more important part of that sentence is the first part, which ties an >> object's identity to its creation. If two objects share the same >> creation, then they're the same object. > > Whats the notion of object identity is the question. > Ok so you reject the memory addr as an 'implementation detail' > Then you are obliged to provide some other way of understanding object-identity 'Identity' is an abstraction. For immutable objects, it is essentially irrelevant. For mutable objects, it is essential in the following sense. A and B are the same object if mutating A necessarily mutates B and different if they can be independently mutated. The id() of an object is a fixed integer that is temporally unique. An implementation might use the id to access objects. When one executes Python mentally, one might skip implementing id(). Its main use is to test an implementation. Most beginners should ignore it. -- Terry Jan Reedy From joshua at landau.ws Sat Feb 15 15:44:31 2014 From: joshua at landau.ws (Joshua Landau) Date: Sat, 15 Feb 2014 20:44:31 +0000 Subject: Explanation of list reference In-Reply-To: <858utc790v.fsf@benfinney.id.au> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <858utc790v.fsf@benfinney.id.au> Message-ID: On 15 February 2014 14:20, Ben Finney wrote: > Joshua Landau writes: > >> Here, I give you a pdf. Hopefully this isn't anti >> mailing-list-etiquette. > > This forum is read in many different contexts, and attachments aren't > appropriate. You should simply put the text directly into your message, > if it's short enough. > > If it's long, then put it online somewhere and send a link with a > description; or, better, make it shorter so it is reasonable to put the > text in a message :-) A PDF seemed like a better use of my time than ASCII art. Nevertheless, I agree that I can always give a link; I was just wondering if there was an environment under which this was actively harmful. From marko at pacujo.net Sat Feb 15 16:01:53 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 15 Feb 2014 23:01:53 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> <52ffbd39$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87fvnkks3i.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sat, 15 Feb 2014 18:29:59 +0200, Marko Rauhamaa wrote: >> Nowhere do I see the violating "x is y". > > Do you truly think that there is even the tiniest, most microscopic > chance that the int 230000 which has been garbage-collected and no > longer exists, and the int 420000, are the same object? What were we talking about again? Marko From stutzman at cat2.kjsl.com Sat Feb 15 16:18:38 2014 From: stutzman at cat2.kjsl.com (Frank Stutzman) Date: Sat, 15 Feb 2014 21:18:38 +0000 (UTC) Subject: Emacs python-mode.el bug #1207470 References: Message-ID: This has been resolved and I want to publically thank Andreas for finding and fixing this bug so quick. I'm fairly new to open source development and the rapidity that this was fix was gratifying. -- Frank Stutzman From ian.g.kelly at gmail.com Sat Feb 15 16:20:07 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 14:20:07 -0700 Subject: Explanation of list reference In-Reply-To: <87mwhsku0e.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> <87mwhsku0e.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 15, 2014 at 1:20 PM, Marko Rauhamaa wrote: > Ian Kelly : > >> On Sat, Feb 15, 2014 at 9:29 AM, Marko Rauhamaa wrote: >>> Thus "x and y are identical" *means* "x is y" and nothing else. >> >> This notion of identity sounds useless, and if that is the way you >> prefer to understand it then you can safely ignore that it exists. I >> think that most users though inherently understand the concept of >> objects being distinct or identical and see the value in being able to >> test for this. > > It is not useless to identify your fundamental definitions and axioms > instead of resorting to circular reasoning. > > The original question was how a beginning programmer could "get" lists. > We very quickly descended into the murky waters of "objects" of an > underlying machine and CPython's way of implementing things. I was > wondering if there was a way to "get" integers, lists, references etc > without hauling the poor student under the keel. > > In a word, could Python be your first programming language? Absolutely, many people learn Python as their first language. Even MIT famously uses it for their introductory computer science class. And I think that most of them do it without getting into internal details like memory addresses and the heap. From ian.g.kelly at gmail.com Sat Feb 15 16:34:45 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 15 Feb 2014 14:34:45 -0700 Subject: decimal numbers In-Reply-To: <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 11:57 AM, Luke Geelen wrote: > hey, is it possible to remove the .0 if it is a valua without something behind the poit (like 5.0 gets 5 but 9.9 stays 9.9 The ':g' format specifier will trim off trailing zeroes, e.g.: >>> '{:g}'.format(5.0) '5' It also switches to exponential notation if the scale of the number is greater than the specified precision (default 6): >>> '{:g}'.format(5000000.0) '5e+06' You can read up on string formatting for more details: http://docs.python.org/3/library/string.html#formatstrings From roy at panix.com Sat Feb 15 17:01:41 2014 From: roy at panix.com (Roy Smith) Date: Sat, 15 Feb 2014 17:01:41 -0500 Subject: How to turn a package into something pip can install References: Message-ID: In article , Chris ???Kwpolska??? Warrick wrote: > On Sat, Feb 15, 2014 at 3:26 AM, Roy Smith wrote: > > In article , > > Ryan Gonzalez wrote: > > > >> python setup.py sdist > > > > OK, I run that and I get a metar-1.4.0.tar.gz under dist. If I move > > that tarfile to my packages directory, and run pip, I get: > > > > $ pip install --no-index --quiet --find-links packages metar==1.4.0 > [snip] > > ValueError: unknown url type: packages > > The path to your cache directory is incorrect. I suggest using > absolute paths (eg. /home/user/packages) instead of relative paths, > which is likely what caused this issue. No, that's not it. It doesn't work with an absolute path either. ----------------------------- $ pip install -v --no-index --find-links /home/roy/deploy/current/code/deploy/python/packages metar==1.4.0 Ignoring indexes: http://pypi.python.org/simple/ Downloading/unpacking metar==1.4.0 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 504, in run self.__target(*self.__args, **self.__kwargs) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/index.py", line 245, in _get_queued_page page = self._get_page(location, req) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/index.py", line 335, in _get_page return HTMLPage.get_page(link, req, cache=self.cache) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/index.py", line 452, in get_page resp = urlopen(url) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/download.py", line 85, in __call__ response = urllib2.urlopen(self.get_request(url)) File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 392, in open protocol = req.get_type() File "/usr/lib/python2.7/urllib2.py", line 254, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: /home/roy/deploy/current/code/deploy/python/packages Could not find any downloads that satisfy the requirement metar==1.4.0 No distributions at all found for metar==1.4.0 Exception information: Traceback (most recent call last): File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main status = self.run(options, args) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 245, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 978, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "/home/roy/deploy/current/python/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/index.py", line 157, in find_requirement raise DistributionNotFound('No distributions at all found for %s' % req) DistributionNotFound: No distributions at all found for metar==1.4.0 Storing complete log in /home/roy/.pip/pip.log ----------------------------- The tar file is there: $ ls -l /home/roy/deploy/current/code/deploy/python/packages/metar-1.4.0.tar.gz -rw-rw-r-- 1 roy roy 28542 Feb 15 16:55 /home/roy/deploy/current/code/deploy/python/packages/metar-1.4.0.tar.gz From rosuav at gmail.com Sat Feb 15 17:27:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 09:27:05 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <858utc790v.fsf@benfinney.id.au> Message-ID: On Sun, Feb 16, 2014 at 7:44 AM, Joshua Landau wrote: > On 15 February 2014 14:20, Ben Finney wrote: >> Joshua Landau writes: >> >>> Here, I give you a pdf. Hopefully this isn't anti >>> mailing-list-etiquette. >> >> This forum is read in many different contexts, and attachments aren't >> appropriate. You should simply put the text directly into your message, >> if it's short enough. >> >> If it's long, then put it online somewhere and send a link with a >> description; or, better, make it shorter so it is reasonable to put the >> text in a message :-) > > A PDF seemed like a better use of my time than ASCII art. > Nevertheless, I agree that I can always give a link; I was just > wondering if there was an environment under which this was actively > harmful. A PDF is fine. An attachment is problematic, and won't get to everyone. Hence the suggestion to put it online somewhere and post a link. (But be sure the host will be up for the next hundred years, ish.) ChrisA From jabba.laci at gmail.com Sat Feb 15 17:32:53 2014 From: jabba.laci at gmail.com (Jabba Laci) Date: Sat, 15 Feb 2014 23:32:53 +0100 Subject: passing an option to the python interpreter Message-ID: Hi, The first line in my scripts looks like this: #!/usr/bin/env python I would like to use unbuffered output in a script, which can be done with the -u option, thus I tried this: #!/usr/bin/env python -u But if I want to run it from the command line ($ ./unbuffered.py), I get this error: /usr/bin/env: python -u: No such file or directory env is looking for "python -u" but such a command doesn't exist. How to overcome this problem? I could write #!/usr/bin/python -u but I prefer to call python through env. For instance if I put this last one in a virtualenv, that would call the system-wide interpreter not the one in the virtualenv. Thanks, Laszlo From roy at panix.com Sat Feb 15 17:35:37 2014 From: roy at panix.com (Roy Smith) Date: Sat, 15 Feb 2014 17:35:37 -0500 Subject: How to turn a package into something pip can install References: Message-ID: In article , Roy Smith wrote: > > > $ pip install --no-index --quiet --find-links packages metar==1.4.0 > > [snip] > > > ValueError: unknown url type: packages > > > > The path to your cache directory is incorrect. I suggest using > > absolute paths (eg. /home/user/packages) instead of relative paths, > > which is likely what caused this issue. > > No, that's not it. It doesn't work with an absolute path either. OK, I figured this out. The on-line docs (http://www.pip-installer.org/en/latest/reference/pip_wheel.html) say you can give --find-links a path, but it looks like it insists on it being a valid URL. If I prepend "file:" to the absolute path, it works. Maybe this is something which has changed in newer versions of pip? I've got 1.1 (and python 2.7.3). I'm pretty sure both of these are what came with Ubuntu Precise. From marko at pacujo.net Sat Feb 15 17:47:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 00:47:58 +0200 Subject: passing an option to the python interpreter References: Message-ID: <871tz4kn6p.fsf@elektro.pacujo.net> Jabba Laci : > I tried this: > > #!/usr/bin/env python -u The hash-bang notation is quite rigid; it only accepts a single argument ("python") to the command ("/usr/bin/env"). I don't know if there is a simple workaround. Marko From rosuav at gmail.com Sat Feb 15 17:50:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 09:50:36 +1100 Subject: passing an option to the python interpreter In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 9:32 AM, Jabba Laci wrote: > #!/usr/bin/env python -u > > But if I want to run it from the command line ($ ./unbuffered.py), I > get this error: > > /usr/bin/env: python -u: No such file or directory > > env is looking for "python -u" but such a command doesn't exist. > > How to overcome this problem? I could write > > #!/usr/bin/python -u That's a fundamental limitation with the shebang syntax: you can pass exactly one argument. Passing more than one is platform-dependent - some Unixes will pass multiple args, some will pass the whole string as a single arg (which is what you're seeing here), and I think some will discard everything from the space onward. What you could do is add a wrapper called 'pythonu'.which invokes 'env python -u %*'. Be aware, though, that shebanging to a shell script isn't safe either; modern Linuxes support it, but to be truly cross-platform, you'd have to write pythonu in a compiled language and make a binary. ChrisA From cs at zip.com.au Sat Feb 15 17:32:16 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 16 Feb 2014 09:32:16 +1100 Subject: inheriting a large python code base In-Reply-To: References: Message-ID: <20140215223216.GA74503@cskk.homeip.net> On 15Feb2014 12:10, Rita wrote: > i just inherited a large python code base and I would like to optimize the > code (run faster). The application is a scientific application so I really > don't understand the internal logic. [...] One thing I would keep in mind is that scientific applications generally involve floating point math. That is subject to loss of precision if done the wrong way. If you are fiddling with a numeric algorithm (as opposed to plain old data structure manipulations) I would want to be sure the code you're changing is not done that way for a specific reason. Make unit tests to check for correctness if possible. Make regression tests to compare the results of your modified code against the results from the original code on the same data. Cheers, -- Cameron Simpson Plague, Famine, Pestilence, and C++ stalk the land. We're doomed! Doomed! - Simon E Spero From nad at acm.org Sat Feb 15 18:00:37 2014 From: nad at acm.org (Ned Deily) Date: Sat, 15 Feb 2014 15:00:37 -0800 Subject: [RELEASED] Python 3.3.4 References: <52F93CCC.70304@python.org> Message-ID: In article , Makoto Kuwata wrote: > By the way, I can't find Python-3.3.4.tar.bz2 in: > http://www.python.org/ftp/python/3.3.4/ > > Python-3.3.{1,2,3}.tar.bz2 and Python-3.4.0.tar.bz2 are provided, > but Python-3.3.4.tar.bz2 is not. Why? > # I hope that Python-3.3.4.tar.bz2 is also provided. The release managers decided that having three different source release formats was not necessary so, as of recent Python releases, the bz2 format is no longer provided. The newer xz compression format provides generally smaller files than bz2 and the gz format is provided because of its wide support. (BTW, Python 3.4.0 is not released yet; some early alphas of 3.4.0 still provided .bz2 tarballs but the most recent ones, including the current rc1, do not.) -- Ned Deily, nad at acm.org From cs at zip.com.au Sat Feb 15 17:41:02 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 16 Feb 2014 09:41:02 +1100 Subject: Quick Help In-Reply-To: <7eefdfb9-527c-4712-a111-4ea662051f43@googlegroups.com> References: <7eefdfb9-527c-4712-a111-4ea662051f43@googlegroups.com> Message-ID: <20140215224102.GA84676@cskk.homeip.net> On 15Feb2014 07:27, kjakupak at gmail.com wrote: > Just need a bit of help understanding this so I can actually start it. > > The input to a program will come from a file called "asdf.in". This file will have all the info needed for the course. The formatting of the input file is described as follows, with denoting # of white spaces and denoting n white spaces. > > Title: > Title: > etc.. > > Is it asking me to make an input file with all of that info (like it is above), or to have an info file actually filled with all that information filled out? Because I then need to have the program be able to output info in certain formats that come from that input file. I would read this as saying that the your program must understand an input file of the format described above. If your teacher has not given you some example file, you will need to hand-make some files to use as input files to test your program. BTW, your subject: line is not very good. All questions want "help". Don't change the subject line for this discussion, but in future, try to make it more descriptive. For example: "what does this task specification mean?" Maybe. Cheers, -- Cameron Simpson Copies of ACM publications are filling library self space so rapidly that shelf boundaries will soon be expanding faster that the speed of light. But Special Relativity is not violated, as no information is being propagated. - Howard E. Motteler, From roy at panix.com Sat Feb 15 18:15:04 2014 From: roy at panix.com (Roy Smith) Date: Sat, 15 Feb 2014 18:15:04 -0500 Subject: inheriting a large python code base References: Message-ID: In article , Cameron Simpson wrote: > On 15Feb2014 12:10, Rita wrote: > > i just inherited a large python code base and I would like to optimize the > > code (run faster). The application is a scientific application so I really > > don't understand the internal logic. > [...] > > One thing I would keep in mind is that scientific applications > generally involve floating point math. That is subject to loss of > precision if done the wrong way. Another thing to keep in mind is that scientific applications are often written by {physicists, chemists, astronomers, etc} who have no clue about how floating point math, or indeed much of anything about computers, works :-) From rosuav at gmail.com Sat Feb 15 19:18:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 11:18:51 +1100 Subject: Operator precedence table questions Message-ID: http://docs.python.org/3.3/reference/expressions.html#operator-precedence """ Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right...) """ Comparisons, including tests, are all in the same box. Grammatically, this wording puzzles me. Everything groups L->R except these, which group L->R? Also, the if/else operator presumably groups left to right, since it's not mentioned. My understanding of that is that it's like addition and multiplication: >>> class X: def __add__(self,other): print("X() +",other) return self >>> X() + 2 + 3 X() + 2 X() + 3 <__main__.X object at 0x0190DFD0> So "(X() + 2 + 3)" is the same as "(X() + 2) + 3" and *not* the same as "X() + (2 + 3)". This is the correct understanding, yes? Okay. >>> [(1 if x else 2) if y else 3 for x in range(2) for y in range(2)] [3, 2, 3, 1] >>> [1 if x else (2 if y else 3) for x in range(2) for y in range(2)] [3, 2, 1, 1] >>> [(1 if x else 2 if y else 3) for x in range(2) for y in range(2)] [3, 2, 1, 1] This makes it appear that if/else groups right to left, which contradicts the docs. What have I missed here? ChrisA From ned at nedbatchelder.com Sat Feb 15 19:30:06 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 15 Feb 2014 19:30:06 -0500 Subject: Operator precedence table questions In-Reply-To: References: Message-ID: On 2/15/14 7:18 PM, Chris Angelico wrote: > http://docs.python.org/3.3/reference/expressions.html#operator-precedence > > """ > Operators in the same box group left to right (except for comparisons, > including tests, which all have the same precedence and chain from > left to right...) > """ > > Comparisons, including tests, are all in the same box. Grammatically, > this wording puzzles me. Everything groups L->R except these, which > group L->R? I think the "except" is referring to "group" vs. "chain". Comparison operators don't group left to right, they chain left to right: a + b + c is the same as: (a + b) + c but: a < b < c is not the same as: (a < b) < c -- Ned Batchelder, http://nedbatchelder.com From rosuav at gmail.com Sat Feb 15 19:43:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 11:43:11 +1100 Subject: Operator precedence table questions In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 11:30 AM, Ned Batchelder wrote: > On 2/15/14 7:18 PM, Chris Angelico wrote: >> >> http://docs.python.org/3.3/reference/expressions.html#operator-precedence >> >> """ >> Operators in the same box group left to right (except for comparisons, >> including tests, which all have the same precedence and chain from >> left to right...) >> """ >> >> Comparisons, including tests, are all in the same box. Grammatically, >> this wording puzzles me. Everything groups L->R except these, which >> group L->R? > > > I think the "except" is referring to "group" vs. "chain". Comparison > operators don't group left to right, they chain left to right: Oh, right... duh. Somehow my eye glossed right over that as though the two words were synonymous. Thanks. ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 15 21:25:54 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Feb 2014 02:25:54 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> <52ffbd39$0$29973$c3e8da3$5496439d@news.astraweb.com> <87fvnkks3i.fsf@elektro.pacujo.net> Message-ID: <530021b1$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 23:01:53 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> On Sat, 15 Feb 2014 18:29:59 +0200, Marko Rauhamaa wrote: >>> Nowhere do I see the violating "x is y". >> >> Do you truly think that there is even the tiniest, most microscopic >> chance that the int 230000 which has been garbage-collected and no >> longer exists, and the int 420000, are the same object? > > What were we talking about again? Two distinct objects with the same id(). I demonstrated a situation where your claim: id(x) == id(y) implies x is y fails. I explained *twice* how to rescue your claim. In each case you deleted my explanation, apparently unread. I can only conclude that you are not actually engaging in this discussion in good faith. For anyone else reading, id(x) == id(y) implies that x is y only if x and y exist at the same time, in the same process. Python can re-use IDs, and you cannot compare IDs from multiple processes. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 21:27:41 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Feb 2014 02:27:41 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> Message-ID: <5300221c$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 15:40:54 -0500, Terry Reedy wrote: > 'Identity' is an abstraction. For immutable objects, it is essentially > irrelevant. For mutable objects, it is essential in the following sense. > A and B are the same object if mutating A necessarily mutates B and > different if they can be independently mutated. That's not quite right. See the earlier example in this thread about numpy arrays. Since mutator methods can have side-effects, and objects can act as proxies or views to other methods, we can't make any conclusion about identity from the fact that mutation affects two or more objects. [Aside: I think the numpy array API is poor, since it doesn't make clear the distinction between arrays which are being used as views to another array, and arrays which are being used as independent arrays.] -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 15 21:30:13 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Feb 2014 02:30:13 GMT Subject: decimal numbers References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> Message-ID: <530022b5$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Feb 2014 14:34:45 -0700, Ian Kelly wrote: > On Sat, Feb 15, 2014 at 11:57 AM, Luke Geelen > wrote: >> hey, is it possible to remove the .0 if it is a valua without something >> behind the poit (like 5.0 gets 5 but 9.9 stays 9.9 > > The ':g' format specifier will trim off trailing zeroes, e.g.: > >>>> '{:g}'.format(5.0) > '5' Oh! That's much nicer than my solution. And it even works with %-style string interpolation too! py> "%g" % 23.0 '23' py> "%g" % 23.1 '23.1' Even though I didn't ask the question, I learned something from the answer. Thank you. -- Steven From rosuav at gmail.com Sat Feb 15 21:36:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 13:36:58 +1100 Subject: decimal numbers In-Reply-To: <530022b5$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> <9c1b03cb-c607-4784-aaec-78616988c302@googlegroups.com> <877d1ddd-39d8-4ede-8dff-addade1c57cd@googlegroups.com> <530022b5$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 16, 2014 at 1:30 PM, Steven D'Aprano wrote: > Even though I didn't ask the question, I learned something from the > answer. Thank you. Reason #1443694 for mailing lists rather than personal tutoring :) I love this aspect of them. ChrisA From eglowstein.h at gmail.com Sat Feb 15 21:49:17 2014 From: eglowstein.h at gmail.com (eglowstein.h at gmail.com) Date: Sat, 15 Feb 2014 18:49:17 -0800 (PST) Subject: Pyserial for Python3 in OSX? Message-ID: <4a0eb13f-a5f1-49bb-acc7-f59a68dafc46@googlegroups.com> I need to do some serial I/O on a Mac running OSX Mavericks. I followed the instructions at http://stackoverflow.com/questions/20082935/how-to-install-pip-for-python3-on-mac-os-x to install pyserial. OSX already had Python 2.7 and pyserial seems to work okay in 2.7, but I can't figure out how to get to run in 3.3.3 or 3.3.4. After I install pyserial, in python 2.7 I can get this: Python 2.7.5 (default, Sep 12 2013, 21:33:34) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from serial.tools import list_ports >>> list_ports.comports() [['/dev/cu.Bluetooth-Incoming-Port', 'n/a', 'n/a'], ['/dev/cu.Bluetooth-Modem', 'n/a', 'n/a'], ['/dev/cu.usbserial-AH012QEW', 'FT232R USB UART', 'USB VID:PID=403:6001 SNR=AH012QEW']] >>> quit() In Python 3, I get this: Python 3.3.4 (default, Feb 15 2014, 21:28:44) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from serial.tools import list_ports >>> list_ports.comports() [] >>> quit() I see all sorts of messages around the web suggesting similar problems getting Python 3 on a Mac to talk to serial ports but I can't find any fixes. Is there a trick I haven't found yet? Many thanks in advance for a cure. Howard From rustompmody at gmail.com Sat Feb 15 22:06:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 15 Feb 2014 19:06:39 -0800 (PST) Subject: inheriting a large python code base In-Reply-To: References: Message-ID: On Sunday, February 16, 2014 4:45:04 AM UTC+5:30, Roy Smith wrote: > In article Cameron Simpson wrote: > > On 15Feb2014 12:10, Rita wrote: > > > i just inherited a large python code base and I would like to optimize the > > > code (run faster). The application is a scientific application so I really > > > don't understand the internal logic. > > [...] > > One thing I would keep in mind is that scientific applications > > generally involve floating point math. That is subject to loss of > > precision if done the wrong way. > Another thing to keep in mind is that scientific applications are often > written by {physicists, chemists, astronomers, etc} who have no clue > about how floating point math, or indeed much of anything about > computers, works :-) Not exactly my experience. Most of the {physicists, chemists, astronomers, etc}s I know grok floating point better than Ive been able to do in 30 years. They dont get much else though! -- Usually called 'Fortran programmers'. The guy who taught me numerical analysis -- a brilliant chemist -- could never understand why anyone should want to use anything other than Fortran. And it was a self-evident God's truth that a variable starting with I-N was integer Rest real. Declarations?? Pshaw! Sissy stuff! "I *IS* an integer and no hanky-panky about it" From python.list at tim.thechases.com Sat Feb 15 23:41:45 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 15 Feb 2014 22:41:45 -0600 Subject: random.sample with large weighted sample-sets? Message-ID: <20140215224145.68c82eb4@bigbox.christie.dr> I'm not coming up with the right keywords to find what I'm hunting. I'd like to randomly sample a modestly compact list with weighted distributions, so I might have data = ( ("apple", 20), ("orange", 50), ("grape", 30), ) and I'd like to random.sample() it as if it was a 100-element list. However, ideally, this could be done in O(size-of-data) storage rather than requiring the build-out of the entire set just for sampling purposes, as the actual data can get a bit large. For this small toy data-set, I can use sample_me = sum(([s]*n for s,n in data, []) random.sample(sample_me, k) but for large counts, the list returned from sum() grinds my system because I start swapping. What am I missing? (links to relevant keywords/searches/algorithms welcome in lieu of actually answering in-line) Thanks, -tkc . From lightaiyee at gmail.com Sat Feb 15 23:45:58 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 15 Feb 2014 20:45:58 -0800 (PST) Subject: Can one use Python to learn and even apply Functional Programming? Message-ID: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> I would like to learn and try out functional programming (FP). I love Python and would like to use it to try FP. Some have advised me to use Haskell instead because Python is not a good language for FP. I am sort of confused at the moment. Is Python a dysfunctional programming language to apply FP? Can the more experienced Python users advise? From ben+python at benfinney.id.au Sun Feb 16 00:08:27 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Feb 2014 16:08:27 +1100 Subject: random.sample with large weighted sample-sets? References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: <8538jj7igk.fsf@benfinney.id.au> Tim Chase writes: > I'm not coming up with the right keywords to find what I'm hunting. > I'd like to randomly sample a modestly compact list with weighted > distributions, so I might have > > data = ( > ("apple", 20), > ("orange", 50), > ("grape", 30), > ) That's not a list, it's a tuple. I think you want a list. When you want a sequence where each position has a semantic meaning, use a tuple (such as ?("apple", 20)?). Each item has a meaning *because of* the position it's in; if the items were in a different order, they'd mean different things. When you want a sequence where the positions don't have a special meaning ? each item means exactly the same no matter if you change the order ? that's sometimes called a ?homogeneous? sequence, and you want a list. So a ?record? should be represented as a tuple, and a ?table? of records should be represented as a list of tuples: records = [ ("apple", 20), ("orange", 50), ("grape", 30), ] > and I'd like to random.sample() it as if it was a 100-element list. The implication being, I suppose, that you'd like the number in each tuple to be a weighting for the probability of choosing that item. For probability weightings, you should arrange for the weightings to sum to 1 (instead of 100 in your example). Then each weighting is simply the desired probability of that item, and those values will work with various libraries that deal with probability. > What am I missing? (links to relevant keywords/searches/algorithms > welcome in lieu of actually answering in-line) You're looking for a ?probability distribution? and ?weighted choice?. Hope that helps! -- \ ?This world in arms is not spending money alone. It is spending | `\ the sweat of its laborers, the genius of its scientists, the | _o__) hopes of its children.? ?Dwight Eisenhower, 1953-04-16 | Ben Finney From rosuav at gmail.com Sun Feb 16 00:34:09 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 16:34:09 +1100 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On Sun, Feb 16, 2014 at 3:45 PM, Sam wrote: > I would like to learn and try out functional programming (FP). I love Python and would like to use it to try FP. Some have advised me to use Haskell instead because Python is not a good language for FP. I am sort of confused at the moment. Is Python a dysfunctional programming language to apply FP? Can the more experienced Python users advise? > Functional programming is a particular style. Python supports some of that style, but it certainly doesn't enforce it; if you want to learn how to work within a functional style, you'd do better with a language that won't let you do anything else. Python does have a number of extremely handy notations, borrowed from more functional languages. But it's not a functional language, primarily. It's what you might call "multi-paradigm" [1], but primarily imperative and object-oriented (everything's an object). ChrisA [1] My buzzword limiter is starting to smoke From ben+python at benfinney.id.au Sun Feb 16 00:42:34 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Feb 2014 16:42:34 +1100 Subject: Can one use Python to learn and even apply Functional Programming? References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: <85y51b62b9.fsf@benfinney.id.au> Sam writes: > Some have advised me to use Haskell instead because Python is not a > good language for FP. There are some features of functional programming which are not a good fit with Python. By attempting to learn functional programming in Python, you will necessarily compromise your Python code *and* your understanding of functional programming. > I am sort of confused at the moment. Is Python a dysfunctional > programming language to apply FP? Can the more experienced Python > users advise? I think if you want to learn functional programming you should have a good reason for doing so, and you should learn something like Common Lisp or Scheme or another purely-functional language. You will definitely learn a lot about programming that you didn't know before, and be able to think about problems with an expanded mental toolkit. Similarly, I encourage anyone working with databases to learn correct relational database techniques ? even though SQL is a deeply-flawed and rather incomplete tool for working with relational databases, nevertheless learning relational theory gives one an expanded mental toolkit for thinking about database design and access when working in SQL. Much of the functional programming toolkit will apply to your Python programming, but you will need to be aware of what tru functional programming is, and then bring that toolkit back to Python. -- \ ?If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea? ?Thomas Jefferson | Ben Finney From jeanpierreda at gmail.com Sun Feb 16 01:38:56 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 15 Feb 2014 22:38:56 -0800 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On Sat, Feb 15, 2014 at 8:45 PM, Sam wrote: > I would like to learn and try out functional programming (FP). I love Python and would like to use it to try FP. Some have advised me to use Haskell instead because Python is not a good language for FP. I am sort of confused at the moment. Is Python a dysfunctional programming language to apply FP? Can the more experienced Python users advise? Everything about FP that can be done in, say, Scheme, can be done in Python, with the exception of tail recursion (but that isn't important for "real" FP). But Scheme is old, and people keep thinking of new things and more interesting variations on the lambda calculus. Haskell is kind of the core of modern functional programming, and involves heavy use of concepts that do not exist or are visibly alien in Python. If you want to learn FP properly, you should learn Haskell. Otherwise you will likely be confused when you overhear functional programmers talking, whether it's about Hindley-Milner or sum types or eta conversion. -- Devin From rosuav at gmail.com Sun Feb 16 02:04:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 18:04:43 +1100 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On Sun, Feb 16, 2014 at 5:38 PM, Devin Jeanpierre wrote: > Otherwise you will likely be confused when you overhear functional > programmers talking, whether it's about Hindley-Milner or sum types or > eta conversion. ETA conversion? I know what that is. That's when a programmer says something'll take six months, and the marketing guys start selling it for delivery in three. *dives for cover* ChrisA From p.johnson125 at gmail.com Sun Feb 16 03:00:58 2014 From: p.johnson125 at gmail.com (Pat Johnson) Date: Sun, 16 Feb 2014 00:00:58 -0800 (PST) Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: This made me grin. ;) From marko at pacujo.net Sun Feb 16 03:08:22 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 10:08:22 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> Message-ID: <8761ofiio9.fsf@elektro.pacujo.net> Marko Rauhamaa : > Conceptually, the "everything is a reference" and the "small"/"big" > distinction are equivalent (produce the same outcomes). The question > is, which model is easier for a beginner to grasp. Case in point, if everything is a reference, how come: >>> "hello".__str__() 'hello' >>> 1.__str__() SyntaxError: invalid syntax Marko From gandalf at shopzeus.com Sun Feb 16 03:13:14 2014 From: gandalf at shopzeus.com (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Sun, 16 Feb 2014 09:13:14 +0100 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: References: <52FCB228.5040301@shopzeus.com> Message-ID: <5300731A.7010001@shopzeus.com> > I should emphasize that this is with the /same/ x.y version... > Installing 3.3 when the previous was 3.2 won't overlay. > > Though I don't see anything in the ActiveState builds (which are all > I've ever used) to handle the #! type selection of the desired version. > Just got done updating my 2.7, replacing 3.2 with 3.3, and then having to > edit my path to make 2.7 primary... No "py.exe" I need both 2.7 and 3.3. And apparently, py.exe does not work the way it should be. I would happily reinstall 3.3 to solve the problem, but before I do that I would like to check all other related settings. So that after I reinstall 3.3, I will exactly know what was happening. It might be a good idea to change the installer of the 2.x series to detect if 3.x is already installed, and handle assignments of py and pyw files gracefully. From ian.g.kelly at gmail.com Sun Feb 16 03:28:34 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Feb 2014 01:28:34 -0700 Subject: Explanation of list reference In-Reply-To: <8761ofiio9.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: On Feb 16, 2014 1:11 AM, "Marko Rauhamaa" wrote: > > Marko Rauhamaa : > > > Conceptually, the "everything is a reference" and the "small"/"big" > > distinction are equivalent (produce the same outcomes). The question > > is, which model is easier for a beginner to grasp. > > Case in point, if everything is a reference, how come: > > >>> "hello".__str__() > 'hello' > >>> 1.__str__() > SyntaxError: invalid syntax You need parentheses around the 1. Otherwise you confuse the lexer, which thinks you're starting a float literal. >>> (1).__str__() '1' -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Sun Feb 16 03:35:37 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Feb 2014 01:35:37 -0700 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: On Sun, Feb 16, 2014 at 1:28 AM, Ian Kelly wrote: > > On Feb 16, 2014 1:11 AM, "Marko Rauhamaa" wrote: >> Case in point, if everything is a reference, how come: >> >> >>> "hello".__str__() >> 'hello' >> >>> 1.__str__() >> SyntaxError: invalid syntax > > You need parentheses around the 1. Otherwise you confuse the lexer, which > thinks you're starting a float literal. > >>>> (1).__str__() > '1' Or if the parentheses bother you, you can also just toss in some whitespace: >>> 1 .__str__() '1' From jpiitula at ling.helsinki.fi Sun Feb 16 03:35:20 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 16 Feb 2014 10:35:20 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Marko Rauhamaa : > > > Conceptually, the "everything is a reference" and the "small"/"big" > > distinction are equivalent (produce the same outcomes). The question > > is, which model is easier for a beginner to grasp. > > Case in point, if everything is a reference, how come: > > >>> "hello".__str__() > 'hello' > >>> 1.__str__() > SyntaxError: invalid syntax That's just a clash with number syntax. Once succesfully parsed, there is no such difference: >>> (1).__str__() '1' >>> 1 .__str__() '1' (I'm not saying anything about anything being a reference, just that your example didn't get analyzed to a level where there are things.) From alan at scooby-doo.csail.mit.edu Sun Feb 16 03:38:55 2014 From: alan at scooby-doo.csail.mit.edu (Alan Bawden) Date: Sun, 16 Feb 2014 03:38:55 -0500 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Case in point, if everything is a reference, how come: > > >>> "hello".__str__() > 'hello' > >>> 1.__str__() > SyntaxError: invalid syntax >>> (1).__str__() '1' >>> 1..__str__() '1.0' -- Alan Bawden From tjreedy at udel.edu Sun Feb 16 03:40:24 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Feb 2014 03:40:24 -0500 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On 2/16/2014 1:38 AM, Devin Jeanpierre wrote: > On Sat, Feb 15, 2014 at 8:45 PM, Sam wrote: >> I would like to learn and try out functional programming (FP). I love Python and would like to use it to try FP. Some have advised me to use Haskell instead because Python is not a good language for FP. I am sort of confused at the moment. Is Python a dysfunctional programming language to apply FP? Can the more experienced Python users advise? > > Everything about FP that can be done in, say, Scheme, can be done in > Python, with the exception of tail recursion (but that isn't important You can do tail recursion in Python, but it will not be noticed and optimized in the way it is is some functional languages. > for "real" FP). But Scheme is old, and people keep thinking of new > things and more interesting variations on the lambda calculus. > > Haskell is kind of the core of modern functional programming, and > involves heavy use of concepts that do not exist or are visibly alien > in Python. If you want to learn FP properly, you should learn Haskell. > Otherwise you will likely be confused when you overhear functional > programmers talking, whether it's about Hindley-Milner or sum types or > eta conversion. In some ways, Haskell is more different from Python than Scheme is, so it may stretch your brain more. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Sun Feb 16 03:40:29 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Feb 2014 08:40:29 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: <5300797c$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Feb 2014 10:08:22 +0200, Marko Rauhamaa wrote: > Case in point, if everything is a reference, how come: > > >>> "hello".__str__() > 'hello' > >>> 1.__str__() > SyntaxError: invalid syntax Because it is a syntax error, just like the parser tells you. When the parser sees "1." it expects a floating point number, and "1.__str__()" is not a legal float. There are three simple ways to get the effect that you want: py> x = 1; x.__str__() # don't use a literal '1' py> (1).__str__() # parenthesize the literal '1' py> 1 .__str__() # offset it from the dot with a space '1' -- Steven From tjreedy at udel.edu Sun Feb 16 04:12:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Feb 2014 04:12:22 -0500 Subject: random.sample with large weighted sample-sets? In-Reply-To: <20140215224145.68c82eb4@bigbox.christie.dr> References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: On 2/15/2014 11:41 PM, Tim Chase wrote: > I'm not coming up with the right keywords to find what I'm hunting. > I'd like to randomly sample a modestly compact list with weighted > distributions, so I might have > > data = ( > ("apple", 20), > ("orange", 50), > ("grape", 30), > ) If you actually start with date in this form, write the few lines needed to produce the form below. import bisect import random data = [ (0, 'apple'), (20, 'orange'), (70, 'grape'), ] for i in range(10): r = random.randrange(0, 100) i = bisect.bisect(data, (r, 'zzzzz')) - 1 print(data[i][1]) >>> apple orange orange grape orange apple grape orange grape orange It is just coincidence that the sample has exactly the expected distribution. -- Terry Jan Reedy From rosuav at gmail.com Sun Feb 16 05:18:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 21:18:17 +1100 Subject: Explanation of list reference In-Reply-To: <5300797c$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> <5300797c$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 16, 2014 at 7:40 PM, Steven D'Aprano wrote: > There are three simple ways to get the effect that you want: > > py> x = 1; x.__str__() # don't use a literal > '1' > py> (1).__str__() # parenthesize the literal > '1' > py> 1 .__str__() # offset it from the dot with a space > '1' Four: >>> 0o1.__str__() # use a literal notation that doesn't allow floats '1' ChrisA From marko at pacujo.net Sun Feb 16 05:52:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 12:52:58 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> Message-ID: <87wqgvgwhh.fsf@elektro.pacujo.net> Ian Kelly : >>>> (1).__str__() > '1' Fair enough. The syntactic awkwardness, then, explains why numbers don't have an evolved set of methods (unlike strings). Marko From marko at pacujo.net Sun Feb 16 06:18:51 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 13:18:51 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <87y51cn2m9.fsf@elektro.pacujo.net> <87mwhsn0nx.fsf@elektro.pacujo.net> <52ff4ce4$0$29973$c3e8da3$5496439d@news.astraweb.com> <87iosgmveg.fsf@elektro.pacujo.net> <52ff7cac$0$29973$c3e8da3$5496439d@news.astraweb.com> <87wqgwl4oo.fsf@elektro.pacujo.net> <52ffbd39$0$29973$c3e8da3$5496439d@news.astraweb.com> <87fvnkks3i.fsf@elektro.pacujo.net> <530021b1$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87sirjgvac.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sat, 15 Feb 2014 23:01:53 +0200, Marko Rauhamaa wrote: > I demonstrated a situation where your claim: > > id(x) == id(y) implies x is y > > fails. My from-the-hip formulation can obviously be inaccurate, but I was hoping the point was clear. The Python language specification feels the need to introduce the nebulous concept of "object lifetime." I believe that concept can be more confusing than useful. Compare that with Common Lisp, whose objects are by definition eternal; there's no garbage collection. Practical implementations do collect garbage, but that's an optimization that doesn't affect the observed output of a program. It is possible to define id() without making any references to the object lifetime. Let's, then, make a more satisfactory attempt at specifying id(): 1. For any argument, the function id returns an integer. 2. For any pair of arguments, the function lambda x, y: (id(x) == id(y)) == (x is y) returns True. That should cover all valid implementations and uses of id(). Marko From rosuav at gmail.com Sun Feb 16 06:24:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Feb 2014 22:24:42 +1100 Subject: Explanation of list reference In-Reply-To: <87wqgvgwhh.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> <87wqgvgwhh.fsf@elektro.pacujo.net> Message-ID: On Sun, Feb 16, 2014 at 9:52 PM, Marko Rauhamaa wrote: > Ian Kelly : > >>>>> (1).__str__() >> '1' > > Fair enough. > > The syntactic awkwardness, then, explains why numbers don't have an > evolved set of methods (unlike strings). No; it's more that numbers are more often used with either operators or polymorphic functions. Yes, you can add strings together with +, but with numbers, you also subtract them, multiply them (okay, you can multiply a string by a number, but that kinda counts one to each), and divide them (some languages let you divide a string by a string, but Python does that with the .split() method). There are only two types of string, and arguably one of them is more an array of bytes than it is a string; but with numbers, you have int/float/complex/Fraction/Decimal, and rather than create methods that have to be implemented by each, there are stand-alone functions instead. Strings get methods: >>> "a b c d".count(" ") 3 >>> "asdf".capitalize() 'Asdf' >>> "asdf".center(20) ' asdf ' Numbers get functions: >>> math.sqrt(100) 10.0 >>> math.sqrt(100.0) 10.0 >>> math.log(1234) 7.1180162044653335 Sometimes the line is blurred: >>> help(math.trunc) Help on built-in function trunc in module math: trunc(x) Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method. Which could have been done as x.trunc() instead: >>> 0o1.__trunc__ >>> 1.0.__trunc__ >>> (1+0j).__trunc__ Traceback (most recent call last): File "", line 1, in (1+0j).__trunc__ AttributeError: 'complex' object has no attribute '__trunc__' >>> math.trunc(1+0j) Traceback (most recent call last): File "", line 1, in math.trunc(1+0j) TypeError: type complex doesn't define __trunc__ method But in a lot of cases, it makes good sense to have a single function that can take many types of number (since, after all, it's possible to define a lot of functions in terms of the basic operators), whereas doing them as methods would entail duplicating code. Partly it's just a matter of expectations. People expect strings to have more methods and numbers to use more operators, so a string method is discoverable and an int method is less so. (When was the last time *you* checked to see what methods an int has?) ChrisA From steve+comp.lang.python at pearwood.info Sun Feb 16 07:04:27 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Feb 2014 12:04:27 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> <87wqgvgwhh.fsf@elektro.pacujo.net> Message-ID: <5300a94b$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Feb 2014 12:52:58 +0200, Marko Rauhamaa wrote: > Ian Kelly : > >>>>> (1).__str__() >> '1' > > Fair enough. > > The syntactic awkwardness, then, explains why numbers don't have an > evolved set of methods (unlike strings). But numbers do have an evolved set of methods. py> [name for name in vars(int) if not name.startswith("_")] ['numerator', 'imag', 'to_bytes', 'from_bytes', 'bit_length', 'real', 'conjugate', 'denominator'] py> [name for name in vars(float) if not name.startswith("_")] ['fromhex', 'imag', 'as_integer_ratio', 'is_integer', 'hex', 'real', 'conjugate'] py> [name for name in vars(complex) if not name.startswith("_")] ['imag', 'real', 'conjugate'] To say nothing of these numbers: py> from decimal import Decimal py> [name for name in vars(Decimal) if not name.startswith("_")] ['canonical', 'exp', 'to_integral_value', 'logical_xor', 'imag', 'same_quantum', 'log10', 'max_mag', 'is_snan', 'to_eng_string', 'ln', 'is_normal', 'min', 'is_subnormal', 'to_integral_exact', 'is_nan', 'logb', 'is_qnan', 'logical_or', 'radix', 'real', 'max', 'normalize', 'as_tuple', 'is_canonical', 'is_zero', 'copy_negate', 'min_mag', 'next_plus', 'is_finite', 'number_class', 'scaleb', 'is_signed', 'compare_total', 'next_toward', 'adjusted', 'fma', 'rotate', 'logical_and', 'from_float', 'to_integral', 'next_minus', 'remainder_near', 'compare_signal', 'quantize', 'is_infinite', 'copy_sign', 'shift', 'compare_total_mag', 'copy_abs', 'compare', 'conjugate', 'logical_invert', 'sqrt'] That's more methods than strings have: py> len([name for name in vars(Decimal) if not name.startswith("_")]) 54 py> len([name for name in vars(str) if not name.startswith("_")]) 44 -- Steven From kwpolska at gmail.com Sun Feb 16 07:18:12 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Feb 2014 13:18:12 +0100 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: On Sat, Feb 15, 2014 at 11:35 PM, Roy Smith wrote: > In article , > Roy Smith wrote: > >> > > $ pip install --no-index --quiet --find-links packages metar==1.4.0 >> > [snip] >> > > ValueError: unknown url type: packages >> > >> > The path to your cache directory is incorrect. I suggest using >> > absolute paths (eg. /home/user/packages) instead of relative paths, >> > which is likely what caused this issue. >> >> No, that's not it. It doesn't work with an absolute path either. > > OK, I figured this out. The on-line docs > (http://www.pip-installer.org/en/latest/reference/pip_wheel.html) say > you can give --find-links a path, but it looks like it insists on it > being a valid URL. If I prepend "file:" to the absolute path, it works. > > Maybe this is something which has changed in newer versions of pip? > I've got 1.1 (and python 2.7.3). I'm pretty sure both of these are what > came with Ubuntu Precise. > -- > https://mail.python.org/mailman/listinfo/python-list It?s heavily outdated, and that IS the cause of your problem. pip 1.5 accepts such paths just fine. Please upgrade your pip. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From wxjmfauth at gmail.com Sun Feb 16 07:19:55 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 16 Feb 2014 04:19:55 -0800 (PST) Subject: decimal numbers In-Reply-To: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> References: <833583c7-c307-4ebf-9a60-3be146a565b5@googlegroups.com> Message-ID: <827289f9-9220-4501-addb-009618a017af@googlegroups.com> Without any warranty. >>> def z(r): ... # r: int > 0 ... t = log10(r) ... if t >= 12.0: ... prefix = '' ... prefix2 = '' ... elif t >= 9.0: ... prefix = 'giga' ... prefix2 = 'G' ... r = r / 1.0e9 ... elif t >= 6.0: ... prefix = 'mega' ... prefix2 = 'M' ... r = r / 1.0e6 ... elif t >= 3.0: ... prefix = 'kilo-' # Netherlands std? ... prefix2 = 'k' ... r = r / 1.0e3 ... else: ... prefix = '' ... prefix2 = '' ... ... # correct for this language (Dutch?) ? ... # kept as illustrative example ... if r >= 2: ... suffix = 's' ... else: ... suffix = '' ... ... # '.13g' to "cover the ranges" while "keeping precision" ... num = format(r, '.13g') ... s = 'de weerstand is ' + num + ' ' + prefix + 'ohm' + suffix ... s = s + ' , R = ' + num + ' ' + prefix2 + '?' ... return s ... >>> a = [1, 2, 9, 20, 300, 1000 - 1, 1000, 1000 + 1, 2000, \ ... 1000000 - 1, 1000000, 1000000 + 1, \ ... 1000000000 - 1, 1000000000, 1000000000 + 1, 11123456789] >>> >>> for e in a: ... print(e, '-', z(e)) ... 1 - de weerstand is 1 ohm , R = 1 ? 2 - de weerstand is 2 ohms , R = 2 ? 9 - de weerstand is 9 ohms , R = 9 ? 20 - de weerstand is 20 ohms , R = 20 ? 300 - de weerstand is 300 ohms , R = 300 ? 999 - de weerstand is 999 ohms , R = 999 ? 1000 - de weerstand is 1 kilo-ohm , R = 1 k? 1001 - de weerstand is 1.001 kilo-ohm , R = 1.001 k? 2000 - de weerstand is 2 kilo-ohms , R = 2 k? 999999 - de weerstand is 999.999 kilo-ohms , R = 999.999 k? 1000000 - de weerstand is 1 megaohm , R = 1 M? 1000001 - de weerstand is 1.000001 megaohm , R = 1.000001 M? 999999999 - de weerstand is 999.999999 megaohms , R = 999.999999 M? 1000000000 - de weerstand is 1 gigaohm , R = 1 G? 1000000001 - de weerstand is 1.000000001 gigaohm , R = 1.000000001 G? 11123456789 - de weerstand is 11.123456789 gigaohms , R = 11.123456789 G? jmf From rmorgan466 at gmail.com Sun Feb 16 07:59:43 2014 From: rmorgan466 at gmail.com (Rita) Date: Sun, 16 Feb 2014 07:59:43 -0500 Subject: inheriting a large python code base In-Reply-To: References: Message-ID: when I do profiling is it possible to find out if I am spending a lot of time in type conversion? it seems I am not. Also, is it possible to predeclare a type in python? Similar to C: int i=0; On Sat, Feb 15, 2014 at 10:06 PM, Rustom Mody wrote: > On Sunday, February 16, 2014 4:45:04 AM UTC+5:30, Roy Smith wrote: > > In article Cameron Simpson wrote: > > > > On 15Feb2014 12:10, Rita wrote: > > > > i just inherited a large python code base and I would like to > optimize the > > > > code (run faster). The application is a scientific application so I > really > > > > don't understand the internal logic. > > > [...] > > > One thing I would keep in mind is that scientific applications > > > generally involve floating point math. That is subject to loss of > > > precision if done the wrong way. > > > Another thing to keep in mind is that scientific applications are often > > written by {physicists, chemists, astronomers, etc} who have no clue > > about how floating point math, or indeed much of anything about > > computers, works :-) > > Not exactly my experience. > Most of the {physicists, chemists, astronomers, etc}s I know grok > floating point better than Ive been able to do in 30 years. > They dont get much else though! -- Usually called 'Fortran programmers'. > > The guy who taught me numerical analysis -- a brilliant chemist -- could > never understand why anyone should want to use anything other than Fortran. > And it was a self-evident God's truth that a variable starting with > I-N was integer Rest real. > Declarations?? Pshaw! Sissy stuff! > "I *IS* an integer and no hanky-panky about it" > -- > https://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 rvernucio at gmail.com Sun Feb 16 07:59:32 2014 From: rvernucio at gmail.com (Renato) Date: Sun, 16 Feb 2014 04:59:32 -0800 (PST) Subject: Problem importing libraries installed with PIP in Eclipse In-Reply-To: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> References: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Message-ID: Em sexta-feira, 14 de fevereiro de 2014 01h30min05s UTC-2, Renato escreveu: > Hi guys, I'm using Python 2.7.5 64 bits and I have a problem when importing libraries that were installed via PIP when importing them inside Eclipse (version 4.3.1). Outside Eclipse (directly in Python's shell) everything works fine, here is an example: > > > > >>> import numpy # installed from repositories > > >>> from numpy import array > > >>> import pybrain # installed via PIP > > >>> from pybrain import Network > > >>> > > > > Everything works outside Eclipse. But inside Eclipse I can't import libraries installed via PIP using "from x import y" format, it will give an error. The only way I can import libraries installed via PIP is using "import x" format. Here is an example: > > > > import numpy # no errors (installed from repositories) > > from numpy import array # no errors > > import pybrain # no errors (installed via PIP) > > from pybrain import Network # gives the error below > > > > Traceback (most recent call last): > > File "/media/arquivos/pybrain_import_test.py", line 4, in > > from pybrain import Network > > ImportError: cannot import name Network > > > > I suspected it could be related to virtualenv, but here is a print screen (http://imageshack.com/a/img534/4307/3x0m.png) of my Python's PATH. The directory /usr/lib/python2.7/site-packages where PyBrain is installed is already in Python's PATH inside Eclipse. Could someone help me, please? Fabio, thanks for your reply. I'm using PyDev version 2.7.0.2013032300, the one who comes with Aptana Studio plugin for Eclipse. Here is Eclipse output: /media/arquivos/Documentos/Programacao/Source/workspace_linux/Testes em Python/src /media/arquivos/Documentos/Programacao/Source/workspace_linux/Testes em Python/src/pip_eclipse /usr/lib/python2.7/site-packages /usr/lib/python27.zip /usr/lib64/python2.7 /usr/lib64/python2.7/lib-dynload /usr/lib64/python2.7/lib-old /usr/lib64/python2.7/lib-tk /usr/lib64/python2.7/plat-linux2 /usr/lib64/python2.7/site-packages /usr/lib64/python2.7/site-packages/PIL /usr/lib64/python2.7/site-packages/gtk-2.0 /usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode /usr/local/lib/python2.7/site-packages /usr/local/lib/python2.7/site-packages /usr/local/lib64/python2.7/site-packages /usr/local/lib64/python2.7/site-packages And here is Python shell output: /usr/lib/python2.7/site-packages /usr/lib/python27.zip /usr/lib64/python2.7 /usr/lib64/python2.7/lib-dynload /usr/lib64/python2.7/lib-old /usr/lib64/python2.7/lib-tk /usr/lib64/python2.7/plat-linux2 /usr/lib64/python2.7/site-packages /usr/lib64/python2.7/site-packages/PIL /usr/lib64/python2.7/site-packages/gtk-2.0 /usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode /usr/local/lib/python2.7/site-packages /usr/local/lib64/python2.7/site-packages They are almost exactly the same, the only difference is that Eclipse includes the directory I'm running the script and print twice the last 2 directories. From breamoreboy at yahoo.co.uk Sun Feb 16 08:20:47 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Feb 2014 13:20:47 +0000 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On 16/02/2014 08:00, Pat Johnson wrote: > This made me grin. ;) > What did, using google groups? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rosuav at gmail.com Sun Feb 16 08:23:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 00:23:24 +1100 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 11:18 PM, Chris ?Kwpolska? Warrick wrote: > On Sat, Feb 15, 2014 at 11:35 PM, Roy Smith wrote: >> Maybe this is something which has changed in newer versions of pip? >> I've got 1.1 (and python 2.7.3). I'm pretty sure both of these are what >> came with Ubuntu Precise. > > It?s heavily outdated, and that IS the cause of your problem. pip 1.5 > accepts such paths just fine. Please upgrade your pip. http://packages.ubuntu.com/precise/python-pip says it's shipping 1.0.1, even older. You get 1.1 with Quantal: http://packages.ubuntu.com/quantal/python-pip and (unsurprisingly) newer versions with newer Ubuntus. Debian's just as bad, incidentally. On Wheezy (current stable), Debian ships 1.1, though Jessie (current testing) has 1.4.1. But neither Ubuntu Trusty nor Debian Sid (unreleased versions of each) ships 1.5. ChrisA From rosuav at gmail.com Sun Feb 16 08:26:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 00:26:55 +1100 Subject: inheriting a large python code base In-Reply-To: References: Message-ID: On Sun, Feb 16, 2014 at 11:59 PM, Rita wrote: > when I do profiling is it possible to find out if I am spending a lot of > time in type conversion? > it seems I am not. I would guess that you don't. But in Python, type conversion is like any other function call: value = int("12345") So you can test for it the same way you would any other. > Also, is it possible to predeclare a type in python? > Similar to C: int i=0; > No, because in Python, variables/names don't have types - only objects/values do. You can simply initialize i to 0, in the obvious way: i = 0 And if you never put anything but an integer into i, it'll always be an integer. That's about as close as you'll get to an "integer variable" like C has. (Python's idea of an integer is rather better than C's, of course; C's 'int' type is a machine word, so it can't store values greater than 2**32 or 2**64 or whatever the limit is, but Python's int can store any integer you have RAM enough to store.) ChrisA From rosuav at gmail.com Sun Feb 16 08:28:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 00:28:12 +1100 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On Mon, Feb 17, 2014 at 12:20 AM, Mark Lawrence wrote: > On 16/02/2014 08:00, Pat Johnson wrote: >> >> This made me grin. ;) >> > > What did, using google groups? :) "Well! I've often seen context without a grin," thought Alice; "but a grin without context! It's the most curious thing I ever saw in my life!" ChrisA From rustompmody at gmail.com Sun Feb 16 08:52:07 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 05:52:07 -0800 (PST) Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: <7cff3812-2bc6-410e-9e6a-f849d39f801d@googlegroups.com> On Sunday, February 16, 2014 10:15:58 AM UTC+5:30, Sam wrote: > I would like to learn and try out functional programming (FP). I love Python and would like to use it to try FP. Some have advised me to use Haskell instead because Python is not a good language for FP. I am sort of confused at the moment. Is Python a dysfunctional programming language to apply FP? Can the more experienced Python users advise? For many years I taught programming in which a pure functional language was the 'mother-tongue' and was followed by a multi-paradigm language. In the 90s the pair was Miranda + Scheme; after 2001 it was a haskell (wee-subset) + python. Two of the bedrock items for a FP education is 1. Getting Hindley-Milner* 2. Lambda Calculus 1 python does not have at all and 2 is ok but not great. Once Hindley-Milner is in your bones -- yeah its radioactive and harmless -- you can happily think in pseudo-Haskell and code in(to) python (or C++ or whatever) The syllabus I made and used (well kindof :-) ) http://www.the-magus.in/Publications/ip.pdf I must say I am not personally too happy with haskell's direction today -- its 'progress' looks quite like how C++ 'progresses' C. [Yeah this does not amount to a very helpful direction :-( ] In more abstract, here is a blog-post of mine http://blog.languager.org/2012/10/functional-programming-lost-booty.html which lists out (in very brief) concepts/features that originated from FP and would benefit programmers irrespective of language/paradigm/technology they are currently into. From anthra.norell at bluewin.ch Sun Feb 16 09:00:00 2014 From: anthra.norell at bluewin.ch (F.R.) Date: Sun, 16 Feb 2014 15:00:00 +0100 Subject: Puzzling PDF Message-ID: <5300C460.8000702@bluewin.ch> Hi all, Struggling to parse bank statements unavailable in sensible data-transfer formats, I use pdftotext, which solves part of the problem. The other day I encountered a strange thing, when one single figure out of many erroneously converted into letters. Adobe Reader displays the figure 50'000 correctly, but pdftotext makes it into "SO'OOO" (The letters "S" as in Susan and "O" as in Otto). One would expect such a mistake from an OCR. However, the statement is not a scan, but is made up of text. Because malfunctions like this put a damper on the hope to ever have a reliable reader that doesn't require time-consuming manual verification, I played around a bit and ended up even more confused: When I lift the figure off the Adobe display (mark, copy) and paste it into a Python IDLE window, it is again letters (ascii 83 and 79), when on the Adobe display it shows correctly as digits. How can that be? Frederic From rustompmody at gmail.com Sun Feb 16 09:00:30 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 06:00:30 -0800 (PST) Subject: Explanation of list reference In-Reply-To: <878utcmqwo.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> Message-ID: <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> On Saturday, February 15, 2014 7:14:39 PM UTC+5:30, Marko Rauhamaa wrote: > Mark Lawrence: > > I have no interest in understanding object identity, I can write code > > quite happily without it. > Luckily, what we are now debating is mostly terminology and points of > view where the outcomes are unaffected. > However, as an example, it is important to know if you should write: > if x is not None: > ... > or if > if x != None: > ... > is more robust. Yes This is my main beef: Not that both are possible but that the first is *recommended* and the second not. Something like a C compiler manual advising: You can write x*8 but its better to drop out into asm and write shl $3, %eax From python.list at tim.thechases.com Sun Feb 16 09:22:50 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 16 Feb 2014 08:22:50 -0600 Subject: random.sample with large weighted sample-sets? In-Reply-To: References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: <20140216082250.7aecebb4@bigbox.christie.dr> On 2014-02-16 04:12, Terry Reedy wrote: > On 2/15/2014 11:41 PM, Tim Chase wrote: > > data = ( > > ("apple", 20), > > ("orange", 50), > > ("grape", 30), > > ) To Ben, yes, this was just some sample data; the original gets built from an external (i.e., client-supplied, thus the need to gracefully support crazy-large numbers) data source and is indeed actually a list rather than a tuple. When entering static data like this, I often default to an outer tuple (rather than list) just as a hint/reminder to myself that I don't expect this to change at runtime (and have Python yell at me if I accidentally try). > If you actually start with date in this form, write the few lines > needed to produce the form below. > > import bisect > import random > > data = [ > (0, 'apple'), > (20, 'orange'), > (70, 'grape'), > ] > > for i in range(10): > r = random.randrange(0, 100) > i = bisect.bisect(data, (r, 'zzzzz')) - 1 > print(data[i][1]) Trying to read what may be implicit assumptions in your code: 1) your code calculates "100" as sum(item[0] for item in data) 2) the data has to be sorted for bisect to work 3) you meant to write "(10, 'apple')" rather than 0. With my original example code, a 0-probability shouldn't ever show up in the sampling, where it looks like it might when using this sample code. In my particular use case, I can limit/ensure that 0-probability items never appear in the list, filtering them upon loading. 4) that "zzzzzz" is some arbitrary value that should come after any string that could appear in the data; perhaps using some custom "InfinityString" class where everything compared to it is always less than it. So it would be class InfinityString: def __gt__(self, other): True __ge__ = __gt__ def __lt__(self, other): False __eq__ = __le__ = __ne__ = __lt__ infinity_string = InfinityString() data = load_data() # list of (quantity, value) tuples data.sort() total = sum(qty for qty, value in data) for i in range(num_to_sample): r = random.randrange(0, total) i = bisect.bisect(data, (r, infinity_string)) - 1 use(data[i][1]) Some long-running testing on this code seems to show that if two items have the same probability, bisect only appears to find the last one. Tested with data = [ (10, "apple"), (20, "banana"), # I never get any bananas, even after thousands of iterations (20, "grape"), (50, "orange"), ] Thanks, -tkc From roy at panix.com Sun Feb 16 09:25:07 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 09:25:07 -0500 Subject: How to turn a package into something pip can install References: Message-ID: In article , Chris Angelico wrote: > On Sun, Feb 16, 2014 at 11:18 PM, Chris ???Kwpolska??? Warrick > wrote: > > On Sat, Feb 15, 2014 at 11:35 PM, Roy Smith wrote: > >> Maybe this is something which has changed in newer versions of pip? > >> I've got 1.1 (and python 2.7.3). I'm pretty sure both of these are what > >> came with Ubuntu Precise. > > > > It???s heavily outdated, and that IS the cause of your problem. pip 1.5 > > accepts such paths just fine. Please upgrade your pip. > > http://packages.ubuntu.com/precise/python-pip > says it's shipping 1.0.1, even older. You get 1.1 with Quantal: > http://packages.ubuntu.com/quantal/python-pip > and (unsurprisingly) newer versions with newer Ubuntus. > > Debian's just as bad, incidentally. On Wheezy (current stable), Debian > ships 1.1, though Jessie (current testing) has 1.4.1. But neither > Ubuntu Trusty nor Debian Sid (unreleased versions of each) ships 1.5. > > ChrisA Yup. I just checked around. My dev machine (which is Ubuntu Precise, plus some random upgrade history) has 1.1. Our production boxes (which are much cleaner Precise installs) have 1.0 in /usr/bin; that's only used for bootstrapping deployments. We have 1.4.1 in the virtualenv we run out of. Oh, yeah, we've still got a few Lucid boxes floating around on some back-end machines. They're running: pip 0.3.1 from /usr/lib/python2.6/dist-packages (python 2.6) We tend not to upgrade stuff unless there's a good reason to. You never know what will break (looking furtively in the direction of the Python 3.x mafiosi). From ned at nedbatchelder.com Sun Feb 16 09:32:54 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 16 Feb 2014 09:32:54 -0500 Subject: random.sample with large weighted sample-sets? In-Reply-To: <20140216082250.7aecebb4@bigbox.christie.dr> References: <20140215224145.68c82eb4@bigbox.christie.dr> <20140216082250.7aecebb4@bigbox.christie.dr> Message-ID: On 2/16/14 9:22 AM, Tim Chase wrote: > 3) you meant to write "(10, 'apple')" rather than 0. With my original > example code, a 0-probability shouldn't ever show up in the sampling, > where it looks like it might when using this sample code. In my > particular use case, I can limit/ensure that 0-probability items never > appear in the list, filtering them upon loading. Terry didn't state this explicitly, but he restructured your data to have cumulative probabilities. You had: data = ( ("apple", 20), ("orange", 50), ("grape", 30), ) He turned it into: data = [ (0, 'apple'), (0+20, 'orange'), (0+20+50, 'grape'), ] Each number is the cumulative probability up to but not including the item. -- Ned Batchelder, http://nedbatchelder.com From rvernucio at gmail.com Sun Feb 16 09:52:12 2014 From: rvernucio at gmail.com (Renato) Date: Sun, 16 Feb 2014 06:52:12 -0800 (PST) Subject: Problem importing libraries installed with PIP in Eclipse In-Reply-To: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> References: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Message-ID: It's solved now, oh my god I was so stupid! I created a package named "pybrain" for testing PyBrain module, so obviously when I tryed to import something from PyBrain library, Python would import all modules from this personal package I created. The problem was not being reproduced outside Eclipse because only within Eclipse my personal workstation directory (which contained the personal package "pybrain") was visible. The solution was simple: I just deleted the personal package named "pybrain" and now everything is working. Thank you very much for your help! From breamoreboy at yahoo.co.uk Sun Feb 16 10:06:41 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Feb 2014 15:06:41 +0000 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: On 16/02/2014 14:25, Roy Smith wrote: > > We tend not to upgrade stuff unless there's a good reason to. You never > know what will break (looking furtively in the direction of the Python > 3.x mafiosi). > Yeah, those really unpleasant, nasty, horrible mafiosi who have the audacity to point out that people have only been given seven (ish) years so far to plan and implement their upgrades. Then the mafiosi further complain when people ask if they can have a Python 2.8 to help plan and implement their upgrades. Yep, this mafiosi mob really do have a lot to answer for. Not. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rymg19 at gmail.com Sun Feb 16 10:11:42 2014 From: rymg19 at gmail.com (Ryan) Date: Sun, 16 Feb 2014 09:11:42 -0600 Subject: Can one use Python to learn and even apply Functional Programming? In-Reply-To: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: <784e8979-7a09-4b6a-a0f9-95f378b6bebd@email.android.com> Python*can* do functional programming, but, for learning, Haskell will work better. Sam wrote: >I would like to learn and try out functional programming (FP). I love >Python and would like to use it to try FP. Some have advised me to use >Haskell instead because Python is not a good language for FP. I am sort >of confused at the moment. Is Python a dysfunctional programming >language to apply FP? Can the more experienced Python users advise? >-- >https://mail.python.org/mailman/listinfo/python-list -- Sent from my Android phone with K-9 Mail. Please excuse my brevity. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Feb 16 10:20:20 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 16 Feb 2014 15:20:20 +0000 Subject: How to turn a package into something pip can install In-Reply-To: References: Message-ID: <5300D734.702@mrabarnett.plus.com> On 2014-02-16 15:06, Mark Lawrence wrote: > On 16/02/2014 14:25, Roy Smith wrote: >> >> We tend not to upgrade stuff unless there's a good reason to. You never >> know what will break (looking furtively in the direction of the Python >> 3.x mafiosi). >> > > Yeah, those really unpleasant, nasty, horrible mafiosi who have the > audacity to point out that people have only been given seven (ish) years > so far to plan and implement their upgrades. Then the mafiosi further > complain when people ask if they can have a Python 2.8 to help plan and > implement their upgrades. Yep, this mafiosi mob really do have a lot to > answer for. Not. > And, what's more, this mafiosi mob cruelly continues to provide the previous releases on its website free of charge, including all the source code. From roy at panix.com Sun Feb 16 10:23:47 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 10:23:47 -0500 Subject: How to answer questions from newbies Message-ID: We get a lot of newbie questions on this list. People are eager to jump in and answer them (which is wonderful), but sometimes we get off on tangents about trivia and lose sight of the real question, and our audience. The particular one that set me off just now (I'm leaving off the names because it's a generic problem) was somebody asking a basic, "how do I code an algorithm to manipulate this data" question. They presented some sample data as a tuple of tuples. One of the (otherwise well-written and informative) responses started out with a 20-line treatise on the difference between lists and tuples, and why the OP should have used a list of tuples. Nothing they said was wrong, but it wasn't essential to explaining the algorithm. What I'm asking is that when people answer questions, try to figure out what the core question really is, and answer that first. If there's other suggestions you can make for how things might be further improved, add those later. Also, try to figure out what the experience level of the OP is, and scale your answer to fit their ability. I've seen people who are obviously struggling with basic concepts in an introductory programming class get responses that include list comprehensions, lambdas, map/reduce, etc. These are things people should learn along the road to Python guru-ness, but if you haven't figured out what a for loop is yet, those things are just going to confuse you even more. From roy at panix.com Sun Feb 16 10:33:39 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 10:33:39 -0500 Subject: Puzzling PDF References: Message-ID: In article , "F.R." wrote: > Hi all, > > Struggling to parse bank statements unavailable in sensible > data-transfer formats, I use pdftotext, which solves part of the > problem. The other day I encountered a strange thing, when one single > figure out of many erroneously converted into letters. Adobe Reader > displays the figure 50'000 correctly, but pdftotext makes it into > "SO'OOO" (The letters "S" as in Susan and "O" as in Otto). One would > expect such a mistake from an OCR. However, the statement is not a scan, > but is made up of text. Because malfunctions like this put a damper on > the hope to ever have a reliable reader that doesn't require > time-consuming manual verification, I played around a bit and ended up > even more confused: When I lift the figure off the Adobe display (mark, > copy) and paste it into a Python IDLE window, it is again letters (ascii > 83 and 79), when on the Adobe display it shows correctly as digits. How > can that be? > > Frederic Maybe it's an intentional effort to keep people from screen-scraping data out of the PDFs (or perhaps trace when they do). Is it possible the document includes a font where those codepoints are drawn exactly the same as the digits they resemble? Keep in mind that PDF is not a data transmission format, it's a document format. When you try to scape data out of a PDF, you've made a pact with the devil. Unclear what any of this has to do with Python. Maybe the tie-in is that in the old Snake video game, the snake was drawn as Soooooo? Anyway, it's S as in Sierra, and O as in Oscar. From breamoreboy at yahoo.co.uk Sun Feb 16 10:47:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Feb 2014 15:47:43 +0000 Subject: How to turn a package into something pip can install In-Reply-To: <5300D734.702@mrabarnett.plus.com> References: <5300D734.702@mrabarnett.plus.com> Message-ID: On 16/02/2014 15:20, MRAB wrote: > On 2014-02-16 15:06, Mark Lawrence wrote: >> On 16/02/2014 14:25, Roy Smith wrote: >>> >>> We tend not to upgrade stuff unless there's a good reason to. You never >>> know what will break (looking furtively in the direction of the Python >>> 3.x mafiosi). >>> >> >> Yeah, those really unpleasant, nasty, horrible mafiosi who have the >> audacity to point out that people have only been given seven (ish) years >> so far to plan and implement their upgrades. Then the mafiosi further >> complain when people ask if they can have a Python 2.8 to help plan and >> implement their upgrades. Yep, this mafiosi mob really do have a lot to >> answer for. Not. >> > And, what's more, this mafiosi mob cruelly continues to provide the > previous releases on its website free of charge, including all the > source code. The obligatory "And apart from that, what have the mafiosi ..." :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From rustompmody at gmail.com Sun Feb 16 10:53:47 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 07:53:47 -0800 (PST) Subject: How to answer questions from newbies In-Reply-To: References: Message-ID: On Sunday, February 16, 2014 8:53:47 PM UTC+5:30, Roy Smith wrote: > We get a lot of newbie questions on this list. People are eager to jump > in and answer them (which is wonderful), but sometimes we get off on > tangents about trivia and lose sight of the real question, and our > audience. > The particular one that set me off just now (I'm leaving off the names > because it's a generic problem) was somebody asking a basic, "how do I > code an algorithm to manipulate this data" question. They presented > some sample data as a tuple of tuples. > One of the (otherwise well-written and informative) responses started > out with a 20-line treatise on the difference between lists and tuples, > and why the OP should have used a list of tuples. Nothing they said was > wrong, but it wasn't essential to explaining the algorithm. > What I'm asking is that when people answer questions, try to figure out > what the core question really is, and answer that first. If there's > other suggestions you can make for how things might be further improved, > add those later. > Also, try to figure out what the experience level of the OP is, and > scale your answer to fit their ability. I've seen people who are > obviously struggling with basic concepts in an introductory programming > class get responses that include list comprehensions, lambdas, > map/reduce, etc. These are things people should learn along the road to > Python guru-ness, but if you haven't figured out what a for loop is yet, > those things are just going to confuse you even more. Agreed! Just one WARNING! If you include comprehensions I shall include re's From buzzard at invalid.invalid Sun Feb 16 11:01:53 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sun, 16 Feb 2014 16:01:53 +0000 Subject: random.sample with large weighted sample-sets? In-Reply-To: References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: <5300e118$0$28923$862e30e2@ngroups.net> On 16/02/14 05:08, Ben Finney wrote: > Tim Chase writes: > >> I'm not coming up with the right keywords to find what I'm hunting. >> I'd like to randomly sample a modestly compact list with weighted >> distributions, so I might have >> >> data = ( >> ("apple", 20), >> ("orange", 50), >> ("grape", 30), >> ) > > That's not a list, it's a tuple. I think you want a list. > > When you want a sequence where each position has a semantic meaning, use > a tuple (such as ?("apple", 20)?). Each item has a meaning *because of* > the position it's in; if the items were in a different order, they'd > mean different things. > > When you want a sequence where the positions don't have a special > meaning ? each item means exactly the same no matter if you change the > order ? that's sometimes called a ?homogeneous? sequence, and you want a > list. > > So a ?record? should be represented as a tuple, and a ?table? of records > should be represented as a list of tuples: > > records = [ > ("apple", 20), > ("orange", 50), > ("grape", 30), > ] > >> and I'd like to random.sample() it as if it was a 100-element list. > [snip] That's a description of sampling without replacement. The probabilities change as items are sampled. e.g. The probability of the first item being "apple"is 20/100. But the probability that the second sampled item is "apple" is either 19/99 or 20/99, depending on the value of the first sampled item. The following (due to Knuth) will generate indices into a notional list of items. def indices(n, pop): # generates indices into a # population list containing # items with frequencies in pop # [("apple", 10), ("orange", 50), ...] N = sum(tup[1] for tup in pop) i = m = 0 while m < n: u = random.random() if (N-i)*u >= n-m: i += 1 else: yield i i += 1 m += 1 >>> list(indices(3, [("apple", 20),("orange", 50),("grape", 30)])) [8, 27, 78] >>> The indices are generated in order, so it could easily be extended to generate items or item count pairs. There might be something more efficient based on the hypergeometric distribution (generate a number of apples, then a number of oranges given the number of sampled apples, then a number of grapes given the number of sampled apples and oranges, etc.). Duncan From __peter__ at web.de Sun Feb 16 11:12:57 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Feb 2014 17:12:57 +0100 Subject: random.sample with large weighted sample-sets? References: <20140215224145.68c82eb4@bigbox.christie.dr> <20140216082250.7aecebb4@bigbox.christie.dr> Message-ID: Tim Chase wrote: > On 2014-02-16 04:12, Terry Reedy wrote: >> On 2/15/2014 11:41 PM, Tim Chase wrote: >> > data = ( >> > ("apple", 20), >> > ("orange", 50), >> > ("grape", 30), >> > ) > > To Ben, yes, this was just some sample data; the original gets built > from an external (i.e., client-supplied, thus the need to gracefully > support crazy-large numbers) data source and is indeed actually a list > rather than a tuple. When entering static data like this, I often > default to an outer tuple (rather than list) just as a hint/reminder > to myself that I don't expect this to change at runtime (and have > Python yell at me if I accidentally try). > >> If you actually start with date in this form, write the few lines >> needed to produce the form below. >> >> import bisect >> import random >> >> data = [ >> (0, 'apple'), >> (20, 'orange'), >> (70, 'grape'), >> ] >> >> for i in range(10): >> r = random.randrange(0, 100) >> i = bisect.bisect(data, (r, 'zzzzz')) - 1 >> print(data[i][1]) > > Trying to read what may be implicit assumptions in your code: > > 1) your code calculates "100" as sum(item[0] for item in data) > > 2) the data has to be sorted for bisect to work > > 3) you meant to write "(10, 'apple')" rather than 0. With my original > example code, a 0-probability shouldn't ever show up in the sampling, > where it looks like it might when using this sample code. In my > particular use case, I can limit/ensure that 0-probability items never > appear in the list, filtering them upon loading. > > 4) that "zzzzzz" is some arbitrary value that should come after any > string that could appear in the data; perhaps using some custom > "InfinityString" class where everything compared to it is always less > than it. > > So it would be > > class InfinityString: > def __gt__(self, other): True > __ge__ = __gt__ > def __lt__(self, other): False > __eq__ = __le__ = __ne__ = __lt__ > infinity_string = InfinityString() > data = load_data() # list of (quantity, value) tuples > data.sort() > total = sum(qty for qty, value in data) > for i in range(num_to_sample): > r = random.randrange(0, total) > i = bisect.bisect(data, (r, infinity_string)) - 1 > use(data[i][1]) > > Some long-running testing on this code seems to show that if two > items have the same probability, bisect only appears to find the last > one. Tested with > > data = [ > (10, "apple"), > (20, "banana"), # I never get any bananas, even after thousands of > iterations (20, "grape"), > (50, "orange"), > ] I think it becomes simpler if you make an intermediate list with the cumulated probabilities. You can then avoid the InfinityString gymnastics: import random, bisect def cumulated(probs): sigma = 0 cumprobs = [] for p in probs: sigma += p cumprobs.append(sigma) return cumprobs def pick(cumprobs): return bisect.bisect(cumprobs, random.randrange(cumprobs[-1])) data = [ (10, "apple"), (20, "banana"), (20, "grape"), (50, "orange"), ] cumprobs = cumulated(p for p, k in data) # check for off-by-one bugs bins = [0] * len(cumprobs) for i in range(cumprobs[-1]): bins[bisect.bisect(cumprobs, i)] += 1 assert bins == [p for p, k in data] # use it bins = [0] * len(cumprobs) for i in range(10000): bins[pick(cumprobs)] += 1 for item, bin in zip(data, bins): print("{} --> {}".format(item, bin)) From roy at panix.com Sun Feb 16 11:14:00 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 11:14:00 -0500 Subject: How to answer questions from newbies References: Message-ID: In article , Rustom Mody wrote: > On Sunday, February 16, 2014 8:53:47 PM UTC+5:30, Roy Smith wrote: > > We get a lot of newbie questions on this list. People are eager to jump > > in and answer them (which is wonderful), but sometimes we get off on > > tangents about trivia and lose sight of the real question, and our > > audience. > > > The particular one that set me off just now (I'm leaving off the names > > because it's a generic problem) was somebody asking a basic, "how do I > > code an algorithm to manipulate this data" question. They presented > > some sample data as a tuple of tuples. > > > One of the (otherwise well-written and informative) responses started > > out with a 20-line treatise on the difference between lists and tuples, > > and why the OP should have used a list of tuples. Nothing they said was > > wrong, but it wasn't essential to explaining the algorithm. > > > What I'm asking is that when people answer questions, try to figure out > > what the core question really is, and answer that first. If there's > > other suggestions you can make for how things might be further improved, > > add those later. > > > Also, try to figure out what the experience level of the OP is, and > > scale your answer to fit their ability. I've seen people who are > > obviously struggling with basic concepts in an introductory programming > > class get responses that include list comprehensions, lambdas, > > map/reduce, etc. These are things people should learn along the road to > > Python guru-ness, but if you haven't figured out what a for loop is yet, > > those things are just going to confuse you even more. > > Agreed! > > Just one WARNING! > If you include comprehensions I shall include re's Moi? From marko at pacujo.net Sun Feb 16 11:17:01 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 18:17:01 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <8761ofiio9.fsf@elektro.pacujo.net> <87wqgvgwhh.fsf@elektro.pacujo.net> <5300a94b$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87lhxbghhe.fsf@elektro.pacujo.net> Steven D'Aprano : > On Sun, 16 Feb 2014 12:52:58 +0200, Marko Rauhamaa wrote: >> The syntactic awkwardness, then, explains why numbers don't have an >> evolved set of methods (unlike strings). > > But numbers do have an evolved set of methods. > [...] > py> from decimal import Decimal > py> [name for name in vars(Decimal) if not name.startswith("_")] > ['canonical', 'exp', 'to_integral_value', 'logical_xor', 'imag', > 'same_quantum', 'log10', 'max_mag', 'is_snan', 'to_eng_string', 'ln', > 'is_normal', 'min', 'is_subnormal', 'to_integral_exact', 'is_nan', > 'logb', 'is_qnan', 'logical_or', 'radix', 'real', 'max', 'normalize', > 'as_tuple', 'is_canonical', 'is_zero', 'copy_negate', 'min_mag', > 'next_plus', 'is_finite', 'number_class', 'scaleb', 'is_signed', > 'compare_total', 'next_toward', 'adjusted', 'fma', 'rotate', > 'logical_and', 'from_float', 'to_integral', 'next_minus', > 'remainder_near', 'compare_signal', 'quantize', 'is_infinite', > 'copy_sign', 'shift', 'compare_total_mag', 'copy_abs', 'compare', > 'conjugate', 'logical_invert', 'sqrt'] That's more like it! Alas: >>> (2).sqrt() AttributeError: 'int' object has no attribute 'sqrt' >>> (2.0).sqrt() AttributeError: 'float' object has no attribute 'sqrt' >>> import math >>> math.sqrt(2) 1.4142135623730951 Also, unfortunately: >>> (2.0).hex() '0x1.0000000000000p+1' >>> (2).hex() AttributeError: 'int' object has no attribute 'hex' There's still some evolving to do. The "smallness" of numbers is still shining through. Marko From emile at fenx.com Sun Feb 16 11:29:11 2014 From: emile at fenx.com (Emile van Sebille) Date: Sun, 16 Feb 2014 08:29:11 -0800 Subject: Puzzling PDF In-Reply-To: <5300C460.8000702@bluewin.ch> References: <5300C460.8000702@bluewin.ch> Message-ID: You On 2/16/2014 6:00 AM, F.R. wrote: > Hi all, > > Struggling to parse bank statements unavailable in sensible > data-transfer formats, I use pdftotext, which solves part of the > problem. The other day I encountered a strange thing, when one single > figure out of many erroneously converted into letters. Adobe Reader > displays the figure 50'000 correctly, but pdftotext makes it into > "SO'OOO" (The letters "S" as in Susan and "O" as in Otto). One would > expect such a mistake from an OCR. However, the statement is not a scan, > but is made up of text. Because malfunctions like this put a damper on > the hope to ever have a reliable reader that doesn't require > time-consuming manual verification, I played around a bit and ended up > even more confused: When I lift the figure off the Adobe display (mark, > copy) and paste it into a Python IDLE window, it is again letters (ascii > 83 and 79), when on the Adobe display it shows correctly as digits. How > can that be? > I've also gotten inconsistent results using various pdf to text converters[1], but getting an explanation for pdf2totext's failings here isn't likely to happen. I'd first try google doc's on-line conversion tool to see if you get better results. If you're lucky it'll do the job and you'll have confirmation that better tools exist. Otherwise, I'd look for an alternate way of getting the bank info than working from the pdf statement. At one site I've scripted firefox to access the bank's web based inquiry to retrieve the new activity overnight and use that to complete a daily bank reconciliation. HTH, Emile [1] I wrote my own once to get data out of a particularly gnarly EDI specification pdf. From ned at nedbatchelder.com Sun Feb 16 11:29:53 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 16 Feb 2014 11:29:53 -0500 Subject: Explanation of list reference In-Reply-To: <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> Message-ID: On 2/16/14 9:00 AM, Rustom Mody wrote: > On Saturday, February 15, 2014 7:14:39 PM UTC+5:30, Marko Rauhamaa wrote: >> Mark Lawrence: > >>> I have no interest in understanding object identity, I can write code >>> quite happily without it. > >> Luckily, what we are now debating is mostly terminology and points of >> view where the outcomes are unaffected. > >> However, as an example, it is important to know if you should write: > >> if x is not None: >> ... > >> or if > >> if x != None: >> ... > >> is more robust. > > Yes This is my main beef: > Not that both are possible but that the first is *recommended* and the second not. > I'm not sure why you don't like the recommendation, or if you just want people to be more explicit about why it is recommended. My main reason for preferring "x is not None" is that if x's class defines __ne__ incorrectly, "x != None" can come out wrong. And yes, I have actually debugged problems where that was the root cause. If you use "x is not None", nothing about x's class can interfere with the correct operation. > Something like a C compiler manual advising: > You can write x*8 but its better to drop out into asm and write > shl $3, %eax > -- Ned Batchelder, http://nedbatchelder.com From ca137tmp at earthlink.net Sun Feb 16 11:35:58 2014 From: ca137tmp at earthlink.net (Charles Allen) Date: Sun, 16 Feb 2014 10:35:58 -0600 Subject: random.sample with large weighted sample-sets? References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: How efficient does this thing need to be? You can always just turn it into a two-dimensional sampling problem by thinking of the data as a function f(x=item), generating a random x=xr in [0,x], then generating a random y in [0,max(f(x))]. The xr is accepted if 0 < y <= max(f(xr)), or rejected (and another attempt made) if y > max(f(xr)). From rustompmody at gmail.com Sun Feb 16 11:50:45 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 08:50:45 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> Message-ID: On Sunday, February 16, 2014 9:59:53 PM UTC+5:30, Ned Batchelder wrote: > On 2/16/14 9:00 AM, Rustom Mody wrote: > > On Saturday, February 15, 2014 7:14:39 PM UTC+5:30, Marko Rauhamaa wrote: > >> Mark Lawrence: > >>> I have no interest in understanding object identity, I can write code > >>> quite happily without it. > >> Luckily, what we are now debating is mostly terminology and points of > >> view where the outcomes are unaffected. > >> However, as an example, it is important to know if you should write: > >> if x is not None: > >> ... > >> or if > >> if x != None: > >> ... > >> is more robust. > > Yes This is my main beef: > > Not that both are possible but that the first is *recommended* and the second not. > I'm not sure why you don't like the recommendation, or if you just want > people to be more explicit about why it is recommended. My main reason > for preferring "x is not None" is that if x's class defines __ne__ > incorrectly, "x != None" can come out wrong. And yes, I have actually > debugged problems where that was the root cause. > If you use "x is not None", nothing about x's class can interfere with > the correct operation. Ok But for that Ive to use is And as a teacher Ive to explain is Might as well use C and get on with pointers To me 'is' is a can of worms Mostly I dont need to open that can In the few instances when I need to open it, I am allowed (I hope!) to say "Ugh!" From buzzard at invalid.invalid Sun Feb 16 12:38:38 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sun, 16 Feb 2014 17:38:38 +0000 Subject: random.sample with large weighted sample-sets? In-Reply-To: References: <20140215224145.68c82eb4@bigbox.christie.dr> Message-ID: <5300f7c5$0$29259$862e30e2@ngroups.net> On 16/02/14 16:35, Charles Allen wrote: > How efficient does this thing need to be? > > You can always just turn it into a two-dimensional sampling problem by > thinking of the data as a function f(x=item), generating a random x=xr > in [0,x], then generating a random y in [0,max(f(x))]. The xr is > accepted if 0 < y <= max(f(xr)), or rejected (and another attempt made) if > y > max(f(xr)). > You can avoid rejection by constructing an alias table. A list can be constructed such that each list element contains a pair of values and a cutoff. e.g. [("apple", 20), ("orange", 50), ("grape", 30)] would become (using one particular algorithm) [(("apple", "orange"), 0.6), (("orange", "apple"), 1.0), (("grape", "orange"), 0.9)] Generate a random index, then select one of the values on the basis of the cutoff. For short enough lists you can generate a single 0-1 random variate, u, and use int(n*u) for the index and compare n*u - int(n*u) to the cutoff, where n is the length of the list. It's still sampling with replacement though. Duncan From marko at pacujo.net Sun Feb 16 13:01:46 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 16 Feb 2014 20:01:46 +0200 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <87mwhtnzdu.fsf@elektro.pacujo.net> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> Message-ID: <87eh33gcmt.fsf@elektro.pacujo.net> Rustom Mody : > But for that Ive to use is > And as a teacher Ive to explain is > Might as well use C and get on with pointers > > To me 'is' is a can of worms I'm not against "is," but it must be carefully defined and taught. As far as "x is None" is concerned, a key piece of information is presented on : None The sole value of the type NoneType. Unfortunately the page is a bit confusing. It says: A small number of constants live in the built-in namespace. So an essential characteristic of the None object (uniqueness) is mentioned in the middle of the discussion on the built-in namespace. The index doesn't contain an entry on NoneType. Thus, there might still be a nagging concern that a second NoneType object x such that x == None and x is not None could crop up (from native code, perhaps). Marko From breamoreboy at yahoo.co.uk Sun Feb 16 13:36:44 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Feb 2014 18:36:44 +0000 Subject: Explanation of list reference In-Reply-To: <87eh33gcmt.fsf@elektro.pacujo.net> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> <87eh33gcmt.fsf@elektro.pacujo.net> Message-ID: On 16/02/2014 18:01, Marko Rauhamaa wrote: > Rustom Mody : > >> But for that Ive to use is >> And as a teacher Ive to explain is >> Might as well use C and get on with pointers >> >> To me 'is' is a can of worms > > I'm not against "is," but it must be carefully defined and taught. > > As far as "x is None" is concerned, a key piece of information is > presented on : > > None > The sole value of the type NoneType. > > Unfortunately the page is a bit confusing. It says: > > A small number of constants live in the built-in namespace. > > So an essential characteristic of the None object (uniqueness) is > mentioned in the middle of the discussion on the built-in namespace. The > index doesn't contain an entry on NoneType. > > Thus, there might still be a nagging concern that a second NoneType > object x such that > > x == None and x is not None > > could crop up (from native code, perhaps). > > > Marko > Patches are always welcome :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From alister.ware at ntlworld.com Sun Feb 16 13:59:37 2014 From: alister.ware at ntlworld.com (Alister) Date: Sun, 16 Feb 2014 18:59:37 GMT Subject: Puzzling PDF References: Message-ID: On Sun, 16 Feb 2014 10:33:39 -0500, Roy Smith wrote: > In article , > "F.R." wrote: > >> Hi all, >> >> Struggling to parse bank statements unavailable in sensible >> data-transfer formats, I use pdftotext, which solves part of the >> problem. The other day I encountered a strange thing, when one single >> figure out of many erroneously converted into letters. Adobe Reader >> displays the figure 50'000 correctly, but pdftotext makes it into >> "SO'OOO" (The letters "S" as in Susan and "O" as in Otto). One would >> expect such a mistake from an OCR. However, the statement is not a >> scan, >> but is made up of text. Because malfunctions like this put a damper on >> the hope to ever have a reliable reader that doesn't require >> time-consuming manual verification, I played around a bit and ended up >> even more confused: When I lift the figure off the Adobe display (mark, >> copy) and paste it into a Python IDLE window, it is again letters >> (ascii 83 and 79), when on the Adobe display it shows correctly as >> digits. How can that be? >> >> Frederic > > Maybe it's an intentional effort to keep people from screen-scraping > data out of the PDFs (or perhaps trace when they do). Is it possible > the document includes a font where those codepoints are drawn exactly > the same as the digits they resemble? This seems to be the most likely explanation to me although I would like to know why. Assuming these are your bank statements I would change bank Mine are available in a variety of formats (QIF & CSV) so that they can be used in my own accounting programs if i desire. I see no reason why the bank would want to prevent me accessing this data -- Without life, Biology itself would be impossible. From alister.ware at ntlworld.com Sun Feb 16 14:16:29 2014 From: alister.ware at ntlworld.com (Alister) Date: Sun, 16 Feb 2014 19:16:29 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> Message-ID: On Sat, 15 Feb 2014 10:44:39 +0100, Christian Gollwitzer wrote: > Am 15.02.14 01:57, schrieb Chris Angelico: >> Can you give an example of an ambiguous case? Fundamentally, the 'is' >> operator tells you whether its two operands are exactly the same >> object, nothing more and nothing less, so I assume your "ambiguous >> cases" are ones where it's possible for two things to be either the >> same object or two indistinguishable ones. > > What about the thing I posted down in this thread? > > >>> import numpy as np a=np.array([1, 2, 3, 4]) > >>> b=a[:] > >>> id(a) > 140267900969344 > >>> id(b) > 140267901045920 > > So, a and b are different things, right? > > >>> b[1]=37 b > array([ 1, 37, 3, 4]) > >>> a > array([ 1, 37, 3, 4]) > > Still they are connected. I can imagin that id() is just a debugging > tool for extensions. What useful applications does it have outside of > this? > > Christian try id(a[0]) and id(b[0]) the two tupples are different but they both contain the same list -- If God wanted us to be brave, why did he give us legs? -- Marvin Kitman From tjreedy at udel.edu Sun Feb 16 14:47:56 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Feb 2014 14:47:56 -0500 Subject: random.sample with large weighted sample-sets? In-Reply-To: <20140216082250.7aecebb4@bigbox.christie.dr> References: <20140215224145.68c82eb4@bigbox.christie.dr> <20140216082250.7aecebb4@bigbox.christie.dr> Message-ID: On 2/16/2014 9:22 AM, Tim Chase wrote: > On 2014-02-16 04:12, Terry Reedy wrote: >> On 2/15/2014 11:41 PM, Tim Chase wrote: >>> data = ( >>> ("apple", 20), >>> ("orange", 50), >>> ("grape", 30), >>> ) >> If you actually start with date in this form, write the few lines >> needed to produce the form below. >> >> import bisect >> import random >> >> data = [ >> (0, 'apple'), >> (20, 'orange'), >> (70, 'grape'), >> ] >> >> for i in range(10): >> r = random.randrange(0, 100) >> i = bisect.bisect(data, (r, 'zzzzz')) - 1 >> print(data[i][1]) > > Trying to read what may be implicit assumptions in your code: 0) The frequencies are relative, not absolute, and the selection is with replacement (== selection without replacement from an 'infinite' population) > 1) your code calculates "100" as sum(item[0] for item in data) yes > 2) the data has to be sorted for bisect to work cumulative sums are automatically sorted. > > 3) you meant to write "(10, 'apple')" rather than 0. No (as Ned explained). There are 20 integers in [0, 20), so 20 chances out of 100 to select an apple. > 4) that "zzzzzz" is some arbitrary value that should come after any > string that could appear in the data; Right. Use "\U000FFFFF" if not using ascii only. > perhaps using some custom "InfinityString" class where everything > compared to it is always less than it. Why bother when a good-enough 'top' string is available? Up to you. The issue can be avoided by transposing the n x 2 array into a 2 x n array with separate subarrays of cumulative sums and objects. Do the bisect search in the subarray of cusums and use the returned index to retrieve the object from the object array. > > Some long-running testing on this code seems to show that if two > items have the same probability, bisect only appears to find the last > one. Tested with > > data = [ > (10, "apple"), > (20, "banana"), # I never get any bananas, even after thousands of iterations because 20 - 20 == 0 > (20, "grape"), > (50, "orange"), > ] -- Terry Jan Reedy From python.list at tim.thechases.com Sun Feb 16 14:58:04 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 16 Feb 2014 13:58:04 -0600 Subject: random.sample with large weighted sample-sets? [SOLVED] In-Reply-To: References: <20140215224145.68c82eb4@bigbox.christie.dr> <20140216082250.7aecebb4@bigbox.christie.dr> Message-ID: <20140216135804.2641a249@bigbox.christie.dr> On 2014-02-16 14:47, Terry Reedy wrote: > > 2) the data has to be sorted for bisect to work > > cumulative sums are automatically sorted. Ah, that they were *cumulative* was the key that I missed in my understanding. It makes sense now and works like a charm. Thanks to all who offered a hand in this thread. -tkc From anthra.norell at bluewin.ch Sun Feb 16 17:38:44 2014 From: anthra.norell at bluewin.ch (F.R.) Date: Sun, 16 Feb 2014 23:38:44 +0100 Subject: Puzzling PDF In-Reply-To: References: <5300C460.8000702@bluewin.ch> Message-ID: <53013DF4.5000905@bluewin.ch> On 02/16/2014 05:29 PM, Emile van Sebille wrote: > You > On 2/16/2014 6:00 AM, F.R. wrote: >> Hi all, >> >> Struggling to parse bank statements unavailable in sensible >> data-transfer formats, I use pdftotext, which solves part of the >> problem. The other day I encountered a strange thing, when one single >> figure out of many erroneously converted into letters. Adobe Reader >> displays the figure 50'000 correctly, but pdftotext makes it into >> "SO'OOO" (The letters "S" as in Susan and "O" as in Otto). One would >> expect such a mistake from an OCR. However, the statement is not a scan, >> but is made up of text. Because malfunctions like this put a damper on >> the hope to ever have a reliable reader that doesn't require >> time-consuming manual verification, I played around a bit and ended up >> even more confused: When I lift the figure off the Adobe display (mark, >> copy) and paste it into a Python IDLE window, it is again letters (ascii >> 83 and 79), when on the Adobe display it shows correctly as digits. How >> can that be? >> > > > I've also gotten inconsistent results using various pdf to text > converters[1], but getting an explanation for pdf2totext's failings > here isn't likely to happen. I'd first try google doc's on-line > conversion tool to see if you get better results. If you're lucky > it'll do the job and you'll have confirmation that better tools > exist. Otherwise, I'd look for an alternate way of getting the bank > info than working from the pdf statement. At one site I've scripted > firefox to access the bank's web based inquiry to retrieve the new > activity overnight and use that to complete a daily bank reconciliation. > > HTH, > > Emile > > > [1] I wrote my own once to get data out of a particularly gnarly EDI > specification pdf. > > Emile, thanks for your response. Thanks to Roy Smith and Alister, too. pdftotext has been working just fine. So much so that this freak incident is all the more puzzling. It smacks of an OCR error, but where does OCR come in, I wonder. I certainly suspected that the font I was looking at had fives and zeroes identical to esses and ohs, respectively, but the suspicion didn't hold up to scrutiny. I attach a little screen shot: At the top, the way it looks on the statement. Next, two words marked with the mouse. (One single marking, doesn't color the space.) Ctl-c puts both words to the clip board. Ctl-v drops them into the python IDLE window between the quotation marks. Lo and behold: they're clearly different! A little bit of code around displays the ascii numbers. Isn't that interesting? Frederic No matter. You're both right. There are alternatives. The best would be to get the data in a CSV format. Alas, I am so lightweight a client that banks don't even bother to find out what I am talking about. I know how to access web pages programmatically, but haven't gotten around to dealing with password-protected log-ins and to sending such data as one writes into templates interactively. Frederic -------------- next part -------------- A non-text attachment was scrubbed... Name: pdf-weirdness.gif Type: image/gif Size: 10726 bytes Desc: not available URL: From greg.ewing at canterbury.ac.nz Sun Feb 16 17:40:57 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 17 Feb 2014 11:40:57 +1300 Subject: Explanation of list reference In-Reply-To: <52ff473b$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <52ff473b$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > And indeed numpy arrays do share state. Why? No idea. Somebody thought > that it was a good idea. (Not me though...) Probably because they're often large and people don't want to incur the overhead of copying them any more than necessary. So slices are defined to return views rather than independent objects. -- Greg From greg.ewing at canterbury.ac.nz Sun Feb 16 17:54:45 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 17 Feb 2014 11:54:45 +1300 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico wrote: > Because everything in Python is an object, and objects always are > handled by their references. So, we have objects... and we have references to objects... but everything is an object... so does that mean references are objects too? This is the kind of trouble you get into when you make a statement of the form "everything is an X"[1]. When we say "everything is an object", we don't literally mean everything, only... well, those things that *are* objects. Which doesn't really help the beginner much. [1] Mathematicians tried this. "Everything is a set!" Yeah, right... -- Greg From rosuav at gmail.com Sun Feb 16 18:02:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 10:02:26 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 17, 2014 at 9:54 AM, Gregory Ewing wrote: > Chris Angelico wrote: >> >> Because everything in Python is an object, and objects always are >> handled by their references. > > > So, we have objects... and we have > references to objects... but everything is an object... > so does that mean references are objects too? > References aren't themselves objects. Names, attributes, etc, etc, etc, all refer to objects. Is it clearer to use the verb "refer" rather than the noun "reference"? ChrisA From ben+python at benfinney.id.au Sun Feb 16 18:05:46 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Feb 2014 10:05:46 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85ppmm64l1.fsf@benfinney.id.au> Gregory Ewing writes: > Chris Angelico wrote: > > Because everything in Python is an object, and objects always are > > handled by their references. > > So, we have objects... and we have > references to objects... but everything is an object... > so does that mean references are objects too? > My response: No, because references are not things :-) I've never known a programming beginner to express such a question. Have you? Were they beginners at programming, or experienced programmers who were coming to Python with the data models of other languages already in their head? -- \ ?Computer perspective on Moore's Law: Human effort becomes | `\ twice as expensive roughly every two years.? ?anonymous | _o__) | Ben Finney From roy at panix.com Sun Feb 16 18:43:15 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 18:43:15 -0500 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Ben Finney wrote: > Gregory Ewing writes: > > > Chris Angelico wrote: > > > Because everything in Python is an object, and objects always are > > > handled by their references. > > > > So, we have objects... and we have > > references to objects... but everything is an object... > > so does that mean references are objects too? > > > > My response: No, because references are not things :-) > > I've never known a programming beginner to express such a question. Have > you? You make light of Gregory's point, but he's right. That's exactly the kind of thing a beginner would get confused about. From roy at panix.com Sun Feb 16 18:46:10 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 18:46:10 -0500 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > On Mon, Feb 17, 2014 at 9:54 AM, Gregory Ewing > wrote: > > Chris Angelico wrote: > >> > >> Because everything in Python is an object, and objects always are > >> handled by their references. > > > > > > So, we have objects... and we have > > references to objects... but everything is an object... > > so does that mean references are objects too? > > > > References aren't themselves objects. Names, attributes, etc, etc, > etc, all refer to objects. Is it clearer to use the verb "refer" > rather than the noun "reference"? > > ChrisA I know functions are objects, but what about statements? Is the body of a for loop an object? It is in some languages. From ben+python at benfinney.id.au Sun Feb 16 19:04:46 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Feb 2014 11:04:46 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85lhxa61up.fsf@benfinney.id.au> Roy Smith writes: > In article , > Ben Finney wrote: > > > Gregory Ewing writes: > > > So, we have objects... and we have references > > > to objects... but everything is an object... so does that mean > > > references are objects too? > > > > My response: No, because references are not things :-) > > > > I've never known a programming beginner to express such a question. Have > > you? > > You make light of Gregory's point, but he's right. That's exactly the > kind of thing a beginner would get confused about. That's exactly what I'm asking: What beginners actually do get confused about this? What category of beginner are they, and how di different categories of beginner approach this differently? In other words, rather than asserting based on anecdotes, what *actually* happens? Let's examine what leads them to this confusion, as a starting point for what can be done. -- \ ?Odious ideas are not entitled to hide from criticism behind | `\ the human shield of their believers' feelings.? ?Richard | _o__) Stallman | Ben Finney From rosuav at gmail.com Sun Feb 16 20:26:38 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 12:26:38 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 17, 2014 at 10:46 AM, Roy Smith wrote: >> References aren't themselves objects. Names, attributes, etc, etc, >> etc, all refer to objects. Is it clearer to use the verb "refer" >> rather than the noun "reference"? >> >> ChrisA > > I know functions are objects, but what about statements? Is the body of > a for loop an object? It is in some languages. And *that* is an extremely fair question. The best explanation I can come up with is somewhat circular: If it can be named in the code, it's an object. What that really means is that every object is first-class (contrast, for instance, C's arrays and functions), but it doesn't answer the actual question of what's an object and what's not. But my advice would be to try things in the interactive interpreter. ChrisA From rustompmody at gmail.com Sun Feb 16 20:39:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 17:39:39 -0800 (PST) Subject: How to answer questions from newbies In-Reply-To: References: Message-ID: On Sunday, February 16, 2014 9:44:00 PM UTC+5:30, Roy Smith wrote: > Moi? See thats the problem with re's -- just 3 letters and completely incomprehensible! It even resembles our resident unicode-troll Oui? From ned at nedbatchelder.com Sun Feb 16 20:43:46 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 16 Feb 2014 20:43:46 -0500 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2/16/14 5:54 PM, Gregory Ewing wrote: > Chris Angelico wrote: >> Because everything in Python is an object, and objects always are >> handled by their references. > > So, we have objects... and we have > references to objects... but everything is an object... > so does that mean references are objects too? > > > This is the kind of trouble you get into when you make > a statement of the form "everything is an X"[1]. When > we say "everything is an object", we don't literally > mean everything, only... well, those things that *are* > objects. Which doesn't really help the beginner much. > > [1] Mathematicians tried this. "Everything is a set!" > Yeah, right... > The correct statement is "all values are objects", or "all data is objects". When people mistakenly say "everything is an object", they are implicitly only thinking about data. That said, "all data is objects" is really mostly useful in contrast to other languages where some data is objects and some is not. I think Ben Finney's point from nearby in this thread is spot on: there's a huge difference between a beginning programmer and an experienced programmer new to Python. The latter category is sometimes the harder to teach, because you have to undo the things they learned about their earlier language X, but which they mistakenly believe to be true about all programming languages. -- Ned Batchelder, http://nedbatchelder.com From ben+python at benfinney.id.au Sun Feb 16 20:46:16 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Feb 2014 12:46:16 +1100 Subject: How to answer questions from newbies References: Message-ID: <85bny65x5j.fsf@benfinney.id.au> Rustom Mody writes: > On Sunday, February 16, 2014 9:44:00 PM UTC+5:30, Roy Smith wrote: > > Moi? > > See thats the problem with re's -- just 3 letters and completely > incomprehensible! Actually, that's a regexp pattern that matches two *or* three letters. -- \ ?If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea? ?Thomas Jefferson | Ben Finney From rosuav at gmail.com Sun Feb 16 20:59:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 12:59:25 +1100 Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 17, 2014 at 12:43 PM, Ned Batchelder wrote: > The correct statement is "all values are objects", or "all data is objects". > When people mistakenly say "everything is an object", they are implicitly > only thinking about data. > > That said, "all data is objects" is really mostly useful in contrast to > other languages where some data is objects and some is not. Part of the trouble is that some code is (represented by) objects. A function is an object, ergo it's data; a module is an object (though that's different); a class is an object; but no other block of code is. You can't give a name to a while loop, then pick it up and use it somewhere else. x = while input("Guess my number: ")!="42": print("Wrong number, try again.") So a while loop isn't data. But wrap it in a function and suddenly it is: def x(): while input("Guess my number: ")!="42": print("Wrong number, try again.") y = x func(x) etc So when does code become data? When it's represented by an object. What's an object and what's not? Data is objects, non-data is not. And we're back to being circular again. (Does this mean we're having a circular discussion about circular definitions?) ChrisA From rosuav at gmail.com Sun Feb 16 21:02:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 13:02:06 +1100 Subject: How to answer questions from newbies In-Reply-To: <85bny65x5j.fsf@benfinney.id.au> References: <85bny65x5j.fsf@benfinney.id.au> Message-ID: On Mon, Feb 17, 2014 at 12:46 PM, Ben Finney wrote: > Rustom Mody writes: > >> On Sunday, February 16, 2014 9:44:00 PM UTC+5:30, Roy Smith wrote: >> > Moi? >> >> See thats the problem with re's -- just 3 letters and completely >> incomprehensible! > > Actually, that's a regexp pattern that matches two *or* three letters. It's worse if you emphasize it. Did you say *re*? But let's not be greedy, here. ChrisA From anish198519851985 at gmail.com Sun Feb 16 22:27:43 2014 From: anish198519851985 at gmail.com (anish198519851985 at gmail.com) Date: Sun, 16 Feb 2014 19:27:43 -0800 (PST) Subject: Possibly better stringobject allocator In-Reply-To: <199702081907.OAA21749@monty> References: <199702081830.NAA27193@dolphin.automatrix.com> <199702081907.OAA21749@monty> Message-ID: On Saturday, February 8, 1997 12:00:00 AM UTC-8, Guido van Rossum wrote: > > I installed modified versions of stringobject.c and stropmodule.c on our web > > server. They are accessible via > > > > http://www.automatrix.com/~skip/python/ > > Cool. I read your description and am very pleased with your > approach. Did you benchmark it with pystone yet? (I'm still waiting > for a better benchmark, but nobody has given me one yet... ;-) > > > Warning: This is just a first attempt. I've done some testing, but not a > > bunch. Use this on an experimental basis only. The code isn't yet properly > > packaged, and there are some definite warts on it. Feedback is welcome. > > I immediately went to resizestring (to check that you'd taken care of > it properly -- you have) and noticed that there's one easy > optimization there: when the new and old sizes fall in the same > bucket, you don't need to do anything except change the ob_size field. > > > One thing I haven't yet figured out is this: Given an arbitrary number, n, > > return the power of two that is equal to or greater than n *without writing > > a loop*. I can clearly do something like: > > > > for (i = 1; i < n; i <<= 1); > > > > Can it be done using a single bit-twiddling expression though? > > For numbers < 256 you can do it with a single table lookup, if you can > spare 256 bytes for the table. For larger numbers you can quickly > find the highest byte in the number that's non-zero and use that to > index the table and add 8* the byte number (if you count from the > right end ;_) Below is the code for this idea. #include int log[256]; int next_power_of_two(int no) { int t, tt, r; if(tt = no>> 16) { r = (t = tt >> 8)?24+log[tt]:16+log[t]; } else { r = (t = no >> 8)?8+log[t]:log[no]; } return r; } void make_table() { int i; log[0] = 0; log[1] = 1; for(i=2;i<256;i++) { log[i] = 1 + log[i/2]; } } int main() { int no = 512; make_table(); printf ("%d\n", next_power_of_two(no)); } > > --Guido van Rossum (home page: http://www.python.org/~guido/) From roy at panix.com Sun Feb 16 22:28:23 2014 From: roy at panix.com (Roy Smith) Date: Sun, 16 Feb 2014 22:28:23 -0500 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > On Mon, Feb 17, 2014 at 12:43 PM, Ned Batchelder > wrote: > > The correct statement is "all values are objects", or "all data is > > objects". > > When people mistakenly say "everything is an object", they are implicitly > > only thinking about data. > > > > That said, "all data is objects" is really mostly useful in contrast to > > other languages where some data is objects and some is not. > > Part of the trouble is that some code is (represented by) objects. A > function is an object, ergo it's data; a module is an object (though > that's different); a class is an object; but no other block of code > is. Lambda? > So when does code become data? When it's represented by an object. OK, now take somebody who knows lisp and try to explain to him or her why Python's eval() doesn't mean data is code. Yeah, I know that's pushing things a bit, but I'm trying to point out that people come into things with pre-conceived notions that are hard to shake (the psychology of learning people would call this the Law of Primacy). From ben+python at benfinney.id.au Sun Feb 16 22:52:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Feb 2014 14:52:38 +1100 Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8561oe5rax.fsf@benfinney.id.au> Roy Smith writes: > Chris Angelico wrote: > > Part of the trouble is that some code is (represented by) objects. A > > function is an object, ergo it's data; a module is an object (though > > that's different); a class is an object; but no other block of code > > is. > > Lambda? The ?lambda? syntax creates a function. It doesn't create ?a lambda?; there's no distinction between functions that were created with a ?def? statement versus a ?lambda? expression. -- \ ?Generally speaking, the errors in religion are dangerous; | `\ those in philosophy only ridiculous.? ?David Hume, _A Treatise | _o__) of Human Nature_, 1739 | Ben Finney From rustompmody at gmail.com Sun Feb 16 23:35:08 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 16 Feb 2014 20:35:08 -0800 (PST) Subject: Explanation of list reference In-Reply-To: References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Monday, February 17, 2014 8:58:23 AM UTC+5:30, Roy Smith wrote: > Chris Angelico wrote: > > > The correct statement is "all values are objects", or "all data is > > > objects". > > > When people mistakenly say "everything is an object", they are implicitly > > > only thinking about data. > > > That said, "all data is objects" is really mostly useful in contrast to > > > other languages where some data is objects and some is not. > > Part of the trouble is that some code is (represented by) objects. A > > function is an object, ergo it's data; a module is an object (though > > that's different); a class is an object; but no other block of code > > is. > Lambda? > > So when does code become data? When it's represented by an object. > OK, now take somebody who knows lisp and try to explain to him or her > why Python's eval() doesn't mean data is code. Yeah, I know that's > pushing things a bit, but I'm trying to point out that people come into > things with pre-conceived notions that are hard to shake (the psychology > of learning people would call this the Law of Primacy). More true than you (probably) know. No Ive not seen a newcomer to python who is an old hand at lisp* What Ive seen is: 25 years ago a 'newcomer' -- like all python objects are objects -- was a newcomer. One of the things I learnt early was that kids were terrified of a beastie that has two modes -- one in which it beeps and the other in which it corrupts the file -- also called 'vi.' Add to that C and pointers and all that and it was just too much. So my first assignment was not programming but just to type a poem. Nowadays the 'newcomers' come with half a dozen computers -- including the phones in their pockets. They know all sorts of technologies that I dont -- Whats a raspberry-pi or an xbox? I frankly dont know more than the names All of them seem to use their phones more savvily than I do! So I cannot even effectively evaluate what percentage of their knowledge is ok, what confused and what balderdash. No -- a clean slate is not a realistic luxury in 2014. * with the exception of yours truly 12 years ago From steve+comp.lang.python at pearwood.info Mon Feb 17 00:52:21 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 05:52:21 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <59c876d3-02f5-4f5a-8728-a5098472e03d@googlegroups.com> <6e96ba97-8ad0-4dad-9d11-b27bf9b237d0@googlegroups.com> <878utcmqwo.fsf@elektro.pacujo.net> <8ca61d1a-b4f6-4677-9cd6-ba15c251f173@googlegroups.com> <87eh33gcmt.fsf@elektro.pacujo.net> Message-ID: <5301a395$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Feb 2014 20:01:46 +0200, Marko Rauhamaa wrote: > As far as "x is None" is concerned, a key piece of information is > presented on : > > None > The sole value of the type NoneType. ^^^^ Sole, adj. "being the only one; single and isolated from others", e.g. "the sole heir", "the sole example". In plain English, None is the sole (only, single) instance of its type. In computer science jargon, None is a singleton. > Thus, there might still be a nagging concern that a second NoneType > object x such that > > x == None and x is not None > > could crop up (from native code, perhaps). If that were possible, then None would not be the sole instance of its type. Since None is documented as being a singleton, that would be a bad bug. -- Steven From steve+comp.lang.python at pearwood.info Mon Feb 17 00:57:13 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 05:57:13 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <917ede6d-db7c-4a8c-8203-27677283776b@googlegroups.com> <871tz5piy0.fsf@elektro.pacujo.net> <87vbwho1i0.fsf@elektro.pacujo.net> <87mwhtnzdu.fsf@elektro.pacujo.net> <52ff473b$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5301a4b9$0$29985$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Feb 2014 11:40:57 +1300, Gregory Ewing wrote: > Steven D'Aprano wrote: >> And indeed numpy arrays do share state. Why? No idea. Somebody thought >> that it was a good idea. (Not me though...) > > Probably because they're often large and people don't want to incur the > overhead of copying them any more than necessary. So slices are defined > to return views rather than independent objects. I don't have a problem with slices returning views. But they should claim to be views, not claim to be arrays: py> from numpy import array py> a = array([1, 2, 3, 4]) py> b = a[:] py> type(a) is type(b) True py> b[1] = 99 py> a array([ 1, 99, 3, 4]) You can do this to distinguish the two cases: py> a.base py> b.base is a True but I think a dedicated array_view type would have be better. -- Steven From anjutiwari5 at gmail.com Mon Feb 17 01:00:57 2014 From: anjutiwari5 at gmail.com (anju tiwari) Date: Mon, 17 Feb 2014 11:30:57 +0530 Subject: Python version problem for rpm Message-ID: Hi all, I have two version of python 2.4 and 2.7. By default python version is 2.4 . I want to install need to install some rpm which needs python 2.7 interpreter. how can I enable 2.7 interpreter for only those packages which are requiring python 2.7, I don't want to change my default python version(2.4). -- ANJU TIWARI... -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Mon Feb 17 01:21:23 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 06:21:23 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5301aa63$0$29985$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Feb 2014 11:54:45 +1300, Gregory Ewing wrote: > Chris Angelico wrote: >> Because everything in Python is an object, and objects always are >> handled by their references. > > So, we have objects... and we have references to > objects... but everything is an object... so does that mean references > are objects too? Every *thing* is an object. References aren't *things*. An analogy: there is no thing "Greg Ewing" which is independent of you, there is you, the thing with an independent existence, and then there is the reference (or name), "Greg Ewing", a label for you. But perhaps it is better to say that all *values* are objects. > This is the kind of trouble you get into when you make a statement of > the form "everything is an X"[1]. When we say "everything is an object", > we don't literally mean everything, only... well, those things that > *are* objects. Which doesn't really help the beginner much. I don't believe that in Python there are any *things* (values) which aren't objects. Even classes and exceptions are values. That's not the case in all languages. In Java, you have objects, and you have unboxed (native) types, and you have classes which aren't values at all. (Or at least, not first-class values.) So before you ask: for-loops aren't things (values). Neither are while- loops, try...except blocks, pass statements, del statements, etc. Nor are names and other references -- I believe that there is a practice in certain areas of computer science to call them "l-values", which despite the name are not values at all -- at least not in Python. Apart from binding and unbinding: ref = something() del ref which are somewhat special, you can't perform computations on *references*, only on the things (values) which references refer to. Contrast this to a hypothetical language which allowed you do perform computations on references, say using a special ! operator: # given x = 23 XY = 42 # then print (!x+"Y") would print 42. The expression !x+"Y" operates on the reference itself, and then print operates on the value referred to by that new reference. > [1] Mathematicians tried this. "Everything is a set!" Yeah, right... No, that's okay. You only get into trouble when you have self-referential sets, like "the set of all sets that don't contain themselves". -- Steven From steve+comp.lang.python at pearwood.info Mon Feb 17 01:31:18 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 06:31:18 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5301acb6$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Feb 2014 18:43:15 -0500, Roy Smith wrote: > In article , > Ben Finney wrote: > >> Gregory Ewing writes: >> >> > Chris Angelico wrote: >> > > Because everything in Python is an object, and objects always are >> > > handled by their references. >> > >> > So, we have objects... and we have references to >> > objects... but everything is an object... so does that mean >> > references are objects too? >> >> My response: No, because references are not things :-) >> >> I've never known a programming beginner to express such a question. >> Have you? > > You make light of Gregory's point, but he's right. That's exactly the > kind of thing a beginner would get confused about. I take it that you haven't spent much time around beginners? Perhaps you should spend some time on the "tutor" mailing list. If you do, you will see very few abstract or philosophical questions such as whether references are themselves things or what identity means. But you will find plenty of questions about: - "Will you do my homework for me?" - "What's this syntax error mean?" (very rarely with the syntax error actually shown) - confusion about the fundamentals of sequential algorithms, e.g. asking why this loop always prints the same value forever: var = random.randint(1, 10) while var != 10: print(var) and similar sorts of *concrete* problems. Just about the only abstract question that I've seen from beginners is the question "What's object oriented programming?" In my experience, people don't start asking abstract questions until they've been programming for a few years. -- Steven From Nikolaus at rath.org Mon Feb 17 01:35:22 2014 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sun, 16 Feb 2014 22:35:22 -0800 Subject: select(sock) indicates not-ready, but sock.recv does not block Message-ID: <87a9dq9rh1.fsf@vostro.rath.org> Hello, I have a problem with using select. I can reliably reproduce a situation where select.select((sock.fileno(),), (), (), 0) returns ((),(),()) (i.e., no data ready for reading), but an immediately following sock.recv() returns data without blocking. I am pretty sure that this is not a race condition. The behavor is 100% reproducible, the program is single threaded, and even waiting for 10 seconds before the select() call does not change the result. I'm running Python 3.3.3 under Linux 3.12. Has anyone an idea what might be going wrong here? Thanks, -Nikolaus -- Encrypted emails preferred. PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C ?Time flies like an arrow, fruit flies like a Banana.? From rosuav at gmail.com Mon Feb 17 02:11:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 18:11:27 +1100 Subject: Explanation of list reference In-Reply-To: <5301aa63$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> <5301aa63$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Feb 17, 2014 at 5:21 PM, Steven D'Aprano wrote: > So before you ask: for-loops aren't things (values). Neither are while- > loops, try...except blocks, pass statements, del statements, etc. Nor are > names and other references -- I believe that there is a practice in > certain areas of computer science to call them "l-values", which despite > the name are not values at all -- at least not in Python. Usually an l-value is something that can go on the left side of assignment, and an r-value is something that can go on the right side of assignment. (In most languages, every l-value is also an r-value, by definition.) In C, for instance, any simple variable is an l-value, except for those that are constants (you can't assign to an array). A dereferenced pointer is also an l-value, as is a structure element reference. An expression usually isn't (unless it results in a dereferenced pointer). C++ adds references. You can always assign to those (the assignment "happens" to the referred-to "thing"). Python says that these things can be assigned to: names, attributes (with dot), and items (with square brackets); I think that's it. Those are Python's l-values. Anything that evaluates to an object reference is an r-value, with the possible exception of function-local names that haven't been assigned to (does it count as "not an r-value" if trying to read it raises an exception?). Python's statements aren't values at all, and can't be referred to. (Though some of them, like class and def, do result in values or name bindings. But you can't refer to the def statement, only to the function object that it creates.) ChrisA From rosuav at gmail.com Mon Feb 17 02:14:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Feb 2014 18:14:36 +1100 Subject: select(sock) indicates not-ready, but sock.recv does not block In-Reply-To: <87a9dq9rh1.fsf@vostro.rath.org> References: <87a9dq9rh1.fsf@vostro.rath.org> Message-ID: On Mon, Feb 17, 2014 at 5:35 PM, Nikolaus Rath wrote: > Hello, > > I have a problem with using select. I can reliably reproduce a situation ... Can you reproduce it with a reasonably short amount of code? If so, please post it. > I'm running Python 3.3.3 under Linux 3.12. Do you mean Linux kernel 3.12 (in which case, which distro?), or is this the version number of a distribution (and if so, which?)? ChrisA From arun.achutha at gmail.com Mon Feb 17 02:37:43 2014 From: arun.achutha at gmail.com (kumar) Date: Sun, 16 Feb 2014 23:37:43 -0800 (PST) Subject: How to use logging Message-ID: <5a53c1ca-1104-40f2-9401-a6d3b3673ede@googlegroups.com> Hi folks, i'm new to python i understood the logging mechanism but unable to understand how these are applied in real time examples can any body help me out From steve+comp.lang.python at pearwood.info Mon Feb 17 03:03:04 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 08:03:04 GMT Subject: Explanation of list reference References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5301c238$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Feb 2014 22:28:23 -0500, Roy Smith wrote: >> So when does code become data? When it's represented by an object. > > OK, now take somebody who knows lisp and try to explain to him or her > why Python's eval() doesn't mean data is code. Yeah, I know that's > pushing things a bit, but I'm trying to point out that people come into > things with pre-conceived notions that are hard to shake (the psychology > of learning people would call this the Law of Primacy). There are ways to treat code as values: - you can use a string (an object/value) representing source code; - you can create a code object using compile(), passing it a string; - you can eval or exec on a string or a code object; - you can extract bits and pieces of function objects; and possibly others. But, and I think this is critical, you can't evaluate source code directly in Python. You can only do so indirectly, after creating some sort of object: a string, a code object, a function, etc. There is always an intermediate step: first, create a string object, then treat it as code. There's no functionality in Python for taking source code directly *as source code* and treating it as a value: function(import this) doesn't work, because `import this` is not a value that can be passed to the function. You have to make it a string first: function("import this") The Python compiler can check the syntax of actual source code at compile time, but it can't do anything about mock source code until runtime when you pass it to exec, eval or compile. That's because until that moment, it's just a string of characters, not source code. -- Steven From laxmikant.general at gmail.com Mon Feb 17 03:24:25 2014 From: laxmikant.general at gmail.com (Laxmikant Chitare) Date: Mon, 17 Feb 2014 13:54:25 +0530 Subject: Does CPython already has Peephole optimizations? Message-ID: Hello All, I read about this article: http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/montanaro.html Just wanted to clarify whether CPython already includes these kind of byte code optimizations? Are all the temporary variables removed when byte code is generated? Regards, Laxmikant -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 17 03:45:47 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Feb 2014 09:45:47 +0100 Subject: Does CPython already has Peephole optimizations? References: Message-ID: Laxmikant Chitare wrote: > Hello All, > > I read about this article: > http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/montanaro.html > > Just wanted to clarify whether CPython already includes these kind of byte > code optimizations? Are all the temporary variables removed when byte code > is generated? You can find out for yourself: Python 3.4.0rc1+ (default:2ba583191550+, Feb 12 2014, 00:08:44) [GCC 4.6.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> def f(): ... a, b, c = 1, 2, 3 ... >>> dis.dis(f) 2 0 LOAD_CONST 4 ((1, 2, 3)) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 12 STORE_FAST 2 (c) 15 LOAD_CONST 0 (None) 18 RETURN_VALUE >>> def g(): ... q = 2 + 3j ... >>> dis.dis(g) 2 0 LOAD_CONST 3 ((2+3j)) 3 STORE_FAST 0 (q) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE If you can read C there is also http://hg.python.org/cpython/file/180e4b678003/Python/peephole.c From steve+comp.lang.python at pearwood.info Mon Feb 17 03:59:46 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Feb 2014 08:59:46 GMT Subject: Does CPython already has Peephole optimizations? References: Message-ID: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Feb 2014 13:54:25 +0530, Laxmikant Chitare wrote: > I read about this article: > http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/ montanaro.html > > Just wanted to clarify whether CPython already includes these kind of > byte code optimizations? Are all the temporary variables removed when > byte code is generated? You can check these things for yourself: import dis dis.dis(function) will show you the byte code. But in general, I would expect not. CPython (that's the Python you probably use) doesn't do a lot of optimization apart from some simple constant folding. If you're interested in optimizing Python, you should look at the JIT optimizing Python compiler, PyPy. -- Steven From breamoreboy at yahoo.co.uk Mon Feb 17 04:14:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 09:14:20 +0000 Subject: Python version problem for rpm In-Reply-To: References: Message-ID: On 17/02/2014 06:00, anju tiwari wrote: > > Hi all, > > I have two version of python 2.4 and 2.7. > > By default python version is 2.4 . I want to install need to install > some rpm > which needs python 2.7 interpreter. how can I enable 2.7 interpreter for > only those > packages which are requiring python 2.7, I don?t want to change my > default python version(2.4). > -- > ANJU TIWARI... > > Please refer to the answer Dave Angel gave you to the same question you posed three days ago. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Mon Feb 17 04:21:40 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 09:21:40 +0000 Subject: How to use logging In-Reply-To: <5a53c1ca-1104-40f2-9401-a6d3b3673ede@googlegroups.com> References: <5a53c1ca-1104-40f2-9401-a6d3b3673ede@googlegroups.com> Message-ID: On 17/02/2014 07:37, kumar wrote: > Hi folks, > > i'm new to python i understood the logging mechanism but unable to understand how these are applied in real time examples can any body help me out > Start here http://docs.python.org/3/howto/logging.html, if that's not good enough please come back with a more detailed question, I'm certain that someone will be able to help you. Slight aside you appear to be using google groups. If that is the case would you read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent the problems that gg causes. if not sorry about the noise :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Mon Feb 17 04:28:12 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 09:28:12 +0000 Subject: [OT]Internet Trolls Really Are Horrible People Message-ID: http://www.slate.com/articles/health_and_science/climate_desk/2014/02/internet_troll_personality_study_machiavellianism_narcissism_psychopathy.html Dedicated to all trolls everywhere. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ned at nedbatchelder.com Mon Feb 17 07:48:00 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 17 Feb 2014 07:48:00 -0500 Subject: Does CPython already has Peephole optimizations? In-Reply-To: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2/17/14 3:59 AM, Steven D'Aprano wrote: > On Mon, 17 Feb 2014 13:54:25 +0530, Laxmikant Chitare wrote: > >> I read about this article: >> http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/ > montanaro.html >> >> Just wanted to clarify whether CPython already includes these kind of >> byte code optimizations? Are all the temporary variables removed when >> byte code is generated? > > > You can check these things for yourself: > > import dis > dis.dis(function) > > > will show you the byte code. > > But in general, I would expect not. CPython (that's the Python you > probably use) doesn't do a lot of optimization apart from some simple > constant folding. If you're interested in optimizing Python, you should > look at the JIT optimizing Python compiler, PyPy. > > CPython does some constant folding, and also jump optimizations. In my role as coverage.py maintainer, I would love to see a way to disable all those optimizations. I tried filing a bug about it (http://bugs.python.org/issue2506), but it did not win the popular support I had hoped for. -- Ned Batchelder, http://nedbatchelder.com From gandalf at shopzeus.com Mon Feb 17 08:01:55 2014 From: gandalf at shopzeus.com (=?ISO-8859-2?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Mon, 17 Feb 2014 14:01:55 +0100 Subject: Import order question Message-ID: <53020843.5010804@shopzeus.com> I have a class hierarchy like this: Widget <- VisualWidget <- BsWidget and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc. Widgets can have children. They are stored in a tree. In order to manage the order of widgets, I need methods to append children. (And later: insert or prepend because they also have an order). So I would like to have methods like this: BsWidget.AppendNavbar(....) BsWidget.AppendRow(...) Here is the problem: these methods should create instances of Row, Column and Navbar. But this leads to circular imports. Here is code for BsWidget: from shopzeus.yaaf.ui.visualwidget import VisualWidget from shopzeus.yaaf.ui.bootstrap.row import Row from shopzeus.yaaf.ui.bootstrap.column import Column from shopzeus.yaaf.ui.bootstrap.navbar import Navbar class BsWidget(VisualWidget): """Visual widget for bootstrap. Adds extra methods for adding/removing content like rows columnsetc.""" def __init__(self,parent): def AppendRow(self): return Row(self) def AppendColumn(self): return Row(self) def PrependRow(self): return Row(self,position=-1) Here is code for ClassX (where ClassX can be: Row, Column, Desktop, Navbar etc.): from shopzeus.yaaf.ui.bootstrap.bswidget import BsWidget class ClassX(BsWidget): The circular import is as follows: * I want to create a Desktop instance * I try to import shopzeus.yaaf.ui.bootstrap.desktop * That tries to import BsWidget * That tries to import Row * That tries to import BsWidget, which is importing -> I get an "ImportError: cannot import name BsWidger" Of course, instead of "AppendRow()" method I could just use this pattern: from shopzeus.yaaf.ui.bootstrap.desktop import Desktop from shopzeus.yaaf.ui.bootstrap.row import Row desktop = Desktop(None) row = Row(desktop) However, I really want to avoid this, because there will be at least 100 different widget classes. For a usual UI, I would have to use many of them and then I would have to start any UI builder code like this: from shopzeus.yaaf.ui.bootstrap.class1 import Class1 from shopzeus.yaaf.ui.bootstrap.class2 import Class2 ... from shopzeus.yaaf.ui.bootstrap.class100 import Class100 Most of the UI building code should look like this instead: with self.desktop.AddRow() as row: with row.AddColumn() as col1: .... with row.AddColumn() as col2: .... The child can only be created with its parent anyway, and UI building code will have to focus of the strucutre of the UI. So to me, it seems logical to create children using methods of the parent. But how do I avoid circular imports and achieve my goal at the same time? Here are my expectations: * I want to put different widget classes into their corresponding different source files * I want to have a base class (BsWidget) with methods that can prepend/append/insert all kinds of other subclasses * I do NOT want to import all classes of all used widgets in UI building code, just use the above methods This might be a bad idea, but then please tell me why it is bad, and what would be the right code pattern for this task. Thanks, Laszlo -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Mon Feb 17 08:04:13 2014 From: roy at panix.com (Roy Smith) Date: Mon, 17 Feb 2014 08:04:13 -0500 Subject: select(sock) indicates not-ready, but sock.recv does not block References: Message-ID: In article , Nikolaus Rath wrote: > Hello, > > I have a problem with using select. I can reliably reproduce a situation > where select.select((sock.fileno(),), (), (), 0) returns ((),(),()) > (i.e., no data ready for reading), but an immediately following > sock.recv() returns data without blocking. > > I am pretty sure that this is not a race condition. The behavor is 100% > reproducible, the program is single threaded, and even waiting for 10 > seconds before the select() call does not change the result. > > I'm running Python 3.3.3 under Linux 3.12. > > Has anyone an idea what might be going wrong here? > > Thanks, > -Nikolaus Can you post the code which demonstrates this? Also, with any kind of networking problem, tcpdump is your fried. When you run your code, use tcpdump to watch all the network traffic on whatever port your socket is bound to. That might give you some clues what's going on. Likewise, I would also strace the process and watch all the network system calls. The problem you're describing might be unexpected behavior in Python, or it might be in the kernel. Watching the actual system calls that are generated will narrow it down to which. From ben+python at benfinney.id.au Mon Feb 17 08:11:34 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Feb 2014 00:11:34 +1100 Subject: Import order question References: <53020843.5010804@shopzeus.com> Message-ID: <851tz16fzt.fsf@benfinney.id.au> Nagy L?szl? Zsolt writes: > I have a class hierarchy like this: > > Widget <- VisualWidget <- BsWidget > > and then BsWidget has many descendants: Desktop, Row, Column, Navbar > etc. None of this implies anything about which modules you place these in; Python is not Java, and you should be putting your class definitions wherever makes the most sense for reading and access. > Here is the problem: these methods should create instances of Row, > Column and Navbar. But this leads to circular imports. It should not; Python is not Java. Use modules to group your class definitions conceptually. There is no need whatever to separate every class into a different module. > * I want to put different widget classes into their corresponding > different source files Please, don't. > This might be a bad idea, but then please tell me why it is bad, and > what would be the right code pattern for this task. Not only does it lead to the problem you've described, it makes the code needlessly difficult to read. Pyth is not Java . -- \ ?I do not believe in forgiveness as it is preached by the | `\ church. We do not need the forgiveness of God, but of each | _o__) other and of ourselves.? ?Robert G. Ingersoll | Ben Finney From __peter__ at web.de Mon Feb 17 08:29:07 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Feb 2014 14:29:07 +0100 Subject: Import order question References: <53020843.5010804@shopzeus.com> Message-ID: Nagy L?szl? Zsolt wrote: > I have a class hierarchy like this: > > Widget <- VisualWidget <- BsWidget > > and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc. > > Widgets can have children. They are stored in a tree. In order to manage > the order of widgets, I need methods to append children. (And later: > insert or prepend because they also have an order). So I would like to > have methods like this: > > BsWidget.AppendNavbar(....) > BsWidget.AppendRow(...) > > Here is the problem: these methods should create instances of Row, > Column and Navbar. But this leads to circular imports. > > Here is code for BsWidget: > > from shopzeus.yaaf.ui.visualwidget import VisualWidget > > from shopzeus.yaaf.ui.bootstrap.row import Row > from shopzeus.yaaf.ui.bootstrap.column import Column > from shopzeus.yaaf.ui.bootstrap.navbar import Navbar > > class BsWidget(VisualWidget): > """Visual widget for bootstrap. > > Adds extra methods for adding/removing content like rows > columnsetc.""" def __init__(self,parent): > > > def AppendRow(self): > return Row(self) > > def AppendColumn(self): > return Row(self) > > def PrependRow(self): > return Row(self,position=-1) > > > > > Here is code for ClassX (where ClassX can be: Row, Column, Desktop, > Navbar etc.): > > from shopzeus.yaaf.ui.bootstrap.bswidget import BsWidget > > > class ClassX(BsWidget): > > > The circular import is as follows: > > * I want to create a Desktop instance > * I try to import shopzeus.yaaf.ui.bootstrap.desktop > * That tries to import BsWidget > * That tries to import Row > * That tries to import BsWidget, which is importing -> I get an > "ImportError: cannot import name BsWidger" Hm, is that cut-and-paste? If so fix the name. If that doesn't work use qualified names: from shopzeus.yaaf.ui.bootstrap import row [...] def AppendRow(self): return row.Row(self) If that still doesn't work follow Ben's advice and be enlightened... From rustompmody at gmail.com Mon Feb 17 08:43:11 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 17 Feb 2014 05:43:11 -0800 (PST) Subject: Explanation of list reference In-Reply-To: <5301acb6$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> <5301acb6$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Monday, February 17, 2014 12:01:18 PM UTC+5:30, Steven D'Aprano wrote: > I take it that you haven't spent much time around beginners? Perhaps you > should spend some time on the "tutor" mailing list. If you do, you will > see very few abstract or philosophical questions such as whether > references are themselves things or what identity means. But you will > find plenty of questions about: > - "Will you do my homework for me?" Right And what that 'homework' consists of is determined by the educational context of the questioner. 'Teacher' is of course a big but hardly exclusive part of that 'Syllabus-setters' (who can be more clueless than teachers) are another 'Other attendant factors' big one being programming language. Hang out on a Haskell list and you will get questions about - category theory - typesystems - structural induction and so on and so forth Does that mean Haskell is better than Python? That depends on which side of the balance-sheet is plus for you. For some getting the job done with a minimum of heavy-duty concepts is a plus For some lots of profound concepts is wonderful Basic to python philosophy is to get people off to a running start quickly. If NOT starting until you/your ward have mulled on some profundity is your thing then python is not for you From tjreedy at udel.edu Mon Feb 17 08:51:16 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Feb 2014 08:51:16 -0500 Subject: Does CPython already has Peephole optimizations? In-Reply-To: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2/17/2014 3:59 AM, Steven D'Aprano wrote: > On Mon, 17 Feb 2014 13:54:25 +0530, Laxmikant Chitare wrote: > >> I read about this article: >> http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/ > montanaro.html >> >> Just wanted to clarify whether CPython already includes these kind of >> byte code optimizations? Most of the easily seen and obviously safe low-hanging fruits for the compile step have been plucked. Note that the effect of the peephole process would only save a few percent, if any, for real apps*. Improving the C code invoked by bytecode has resulted in much larger gains. * We now have a much better benchmark suite with some real apps. This is thanks in part to the pypy project. >> Are all the temporary variables removed when byte code is generated? > > You can check these things for yourself: > > import dis > dis.dis(function) > > will show you the byte code. > > But in general, I would expect not. CPython (that's the Python you > probably use) doesn't do a lot of optimization apart from some simple > constant folding. If you're interested in optimizing Python, you should > look at the JIT optimizing Python compiler, PyPy. For CPython, new optimization has mostly moved to AST tranformations prior to compilation. (Python ASTs are new since Skip started the peephole work.) I believe there are some open issues on the tracker. Once optimization constraint Skip did not mention is the correspondence between source lines and blocks of bytecode, which is used by profiling, tracing, and tracebacks. Effectively transforming if type(a) == types.ComplexType: x = cmath.sin(a) foo(x) else: x = math.sin(a) foo(x) into if type(a) == types.ComplexType: x = cmath.sin(a) else: x = math.sin(a) foo(x) breaks the correspondence. If foo(x) raises, which original line should be reported as the source of the exception? -- Terry Jan Reedy From tjreedy at udel.edu Mon Feb 17 10:35:07 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Feb 2014 10:35:07 -0500 Subject: Import order question In-Reply-To: <53020843.5010804@shopzeus.com> References: <53020843.5010804@shopzeus.com> Message-ID: On 2/17/2014 8:01 AM, Nagy L?szl? Zsolt wrote: > I have a class hierarchy like this: > > Widget <- VisualWidget <- BsWidget > > and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc. > > Widgets can have children. They are stored in a tree. In order to manage > the order of widgets, I need methods to append children. (And later: > insert or prepend because they also have an order). So I would like to > have methods like this: > > BsWidget.AppendNavbar(....) > BsWidget.AppendRow(...) I would write one prepend/insert/append method that prepends/inserts/appends the widget passed. > Here is the problem: these methods should create instances of Row, > Column and Navbar. I disagree, without strong justification. Create the instances by directly calling the classes and do with them as you want. -- Terry Jan Reedy From nirchernia at gmail.com Mon Feb 17 12:00:49 2014 From: nirchernia at gmail.com (Nir) Date: Mon, 17 Feb 2014 09:00:49 -0800 (PST) Subject: Why is the interpreter is returning a 'reference'? Message-ID: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> >>> k = ['hi','boss'] >>> >>> k ['hi', 'boss'] >>> k= [s.upper for s in k] >>> k [, ] Why doesn't the python interpreter just return ['HI, 'BOSS'] ? This isn't a big deal, but I am just curious as to why it does this. From joel.goldstick at gmail.com Mon Feb 17 12:08:37 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 17 Feb 2014 12:08:37 -0500 Subject: Why is the interpreter is returning a 'reference'? In-Reply-To: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: On Feb 17, 2014 12:05 PM, "Nir" wrote: > > >>> k = ['hi','boss'] > >>> > >>> k > ['hi', 'boss'] > >>> k= [s.upper for s in k S.upper() > >>> k > [, ] > > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? > > This isn't a big deal, but I am just curious as to why it does this. > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ned at nedbatchelder.com Mon Feb 17 12:08:34 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 17 Feb 2014 12:08:34 -0500 Subject: Why is the interpreter is returning a 'reference'? In-Reply-To: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: On 2/17/14 12:00 PM, Nir wrote: >>>> k = ['hi','boss'] >>>> >>>> k > ['hi', 'boss'] >>>> k= [s.upper for s in k] >>>> k > [, ] > > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? > > This isn't a big deal, but I am just curious as to why it does this. > You have to invoke s.upper, with parens: k = [s.upper() for s in k] In Python, a function or method is a first-class object, so "s.upper" is a reference to the method, "s.upper()" is the result of calling the method. -- Ned Batchelder, http://nedbatchelder.com From emile at fenx.com Mon Feb 17 12:08:33 2014 From: emile at fenx.com (emile) Date: Mon, 17 Feb 2014 09:08:33 -0800 Subject: Why is the interpreter is returning a 'reference'? In-Reply-To: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: On 02/17/2014 09:00 AM, Nir wrote: >>>> k = ['hi','boss'] >>>> >>>> k > ['hi', 'boss'] >>>> k= [s.upper for s in k] s.upper is a reference to the method upper of s -- to execute the method add parens -- s.upper() Emile >>>> k > [, ] > > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? > > This isn't a big deal, but I am just curious as to why it does this. > From marko at pacujo.net Mon Feb 17 12:09:52 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 17 Feb 2014 19:09:52 +0200 Subject: Why is the interpreter is returning a 'reference'? References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: <87ob2564yn.fsf@elektro.pacujo.net> Nir : >>>> k= [s.upper for s in k] >>>> k > [, ] > > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? Try: k = [ s.upper() for s in k ] Marko From zachary.ware+pylist at gmail.com Mon Feb 17 12:14:10 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Mon, 17 Feb 2014 11:14:10 -0600 Subject: Why is the interpreter is returning a 'reference'? In-Reply-To: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: On Mon, Feb 17, 2014 at 11:00 AM, Nir wrote: >>>> k = ['hi','boss'] >>>> >>>> k > ['hi', 'boss'] >>>> k= [s.upper for s in k] >>>> k > [, ] > > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? It's just doing exactly what you are telling it to :). Your list comprehension is constructing a list consisting of the 'upper' method (which are themselves objects, able to be passed around just like any other value) for each string object in list 'k'. Consider this: >>> k = ['hi', 'boss'] >>> s = k[0] >>> s 'hi' >>> s.upper # this just accesses the 'upper' attribute of 's', which turns out to be its 'upper' method >>> s.upper() # this actually calls the 'upper' method on 's' 'HI' Change your comprehension to actually call the upper method like so: "k = [s.upper() for s in k]". It will do what you expected with that change. Hope this helps, -- Zach From bobifle at gmail.com Mon Feb 17 08:21:31 2014 From: bobifle at gmail.com (P J) Date: Mon, 17 Feb 2014 14:21:31 +0100 Subject: Getting a stable virtual env Message-ID: Hi ppl, I'm trying to figure out the whole virtualenv story. Right now I'm using it to creating an environment for our upcoming debian upgrade to squeeze. I'm doing some tests in our current distrib (python 2.5). I have come to realize that a lot of packages in the version I'm interested in are not available anymore on pypi. The pip installer fails a lot. Squeeze features python 2.7 so I'm pretty sure that everything will work fine. I've actually tested it. The question is, how do I protect myself from future package removal ? Do I absolutely need to run a local pypi server (I've seen some python package doing this), and mirror all the packages I'm interested in ? cheers, JM -------------- next part -------------- An HTML attachment was scrubbed... URL: From bobifle at gmail.com Mon Feb 17 12:26:08 2014 From: bobifle at gmail.com (JM) Date: Mon, 17 Feb 2014 18:26:08 +0100 Subject: Getting a stable virtual env In-Reply-To: References: Message-ID: This one should be in plain text, sorry guys I'm trying to get used to this new mail address and client. Hi ppl, I'm trying to figure out the whole virtualenv story. Right now I'm using it to creating an environment for our upcoming debian upgrade to squeeze. I'm doing some tests in our current distrib (python 2.5). I have come to realize that a lot of packages in the version I'm interested in are not available anymore on pypi. The pip installer fails a lot. Squeeze features python 2.7 so I'm pretty sure that everything will work fine. I've actually tested it. The question is, how do I protect myself from future package removal ? Do I absolutely need to run a local pypi server (I've seen some python package doing this), and mirror all the packages I'm interested in ? cheers, JM 2014-02-17 14:21 GMT+01:00 P J : > Hi ppl, > > I'm trying to figure out the whole virtualenv story. > Right now I'm using it to creating an environment for our upcoming debian > upgrade to squeeze. > > I'm doing some tests in our current distrib (python 2.5). > I have come to realize that a lot of packages in the version I'm interested > in are not available anymore on pypi. The pip installer fails a lot. > > Squeeze features python 2.7 so I'm pretty sure that everything will work > fine. I've actually tested it. The question is, how do I protect myself from > future package removal ? > Do I absolutely need to run a local pypi server (I've seen some python > package doing this), and mirror all the packages I'm interested in ? > > cheers, > > JM From gandalf at shopzeus.com Mon Feb 17 13:14:48 2014 From: gandalf at shopzeus.com (=?UTF-8?B?TmFneSBMw6FzemzDsyBac29sdA==?=) Date: Mon, 17 Feb 2014 19:14:48 +0100 Subject: Import order question In-Reply-To: <851tz16fzt.fsf@benfinney.id.au> References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> Message-ID: <53025198.1060000@shopzeus.com> >> Here is the problem: these methods should create instances of Row, >> Column and Navbar. But this leads to circular imports. > It should not; Python is not Java. > > Use modules to group your class definitions conceptually. There is no > need whatever to separate every class into a different module. If there is a consensus, and it is really desireable to put all these related classes into the same module, then this is what I'm going to do. > >> This might be a bad idea, but then please tell me why it is bad, and >> what would be the right code pattern for this task. > Not only does it lead to the problem you've described, it makes the code > needlessly difficult to read. > > Pyth is not Java > . This is funny, because I was working for wxPython for years and this article is making an example with wxPython. It is one of the best toolkits around. Some years ago I wondered why did they not follow PEP8 and used lower case method names. Then I found out that these are C++ wrapper classes, many of them automatically generated from C++ code. So that is why. But by that time I was using captialized method names for UI widgets everywhere, and I guess this is my bad habit now. Probably when it comes to UI widgets I do not think the Pythonic way for the same reason. I never know when to put classes in different modules. I usually draw an UML diagram and group classes into packages. Wich makes sense because there can be sub-groups with subpackages. But I'm always confused with modules, I don't know why. Thanks for the help. From sg552 at hotmail.co.uk Mon Feb 17 13:24:35 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Mon, 17 Feb 2014 18:24:35 +0000 Subject: Explanation of list reference In-Reply-To: <5301aa63$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <13208de8-0f85-4e60-b059-dc087c8fda41@googlegroups.com> <52fefccc$0$29973$c3e8da3$5496439d@news.astraweb.com> <52ff0dc5$0$29973$c3e8da3$5496439d@news.astraweb.com> <5301aa63$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 17/02/2014 06:21, Steven D'Aprano wrote: > On Mon, 17 Feb 2014 11:54:45 +1300, Gregory Ewing wrote: >> [...] >> >> [1] Mathematicians tried this. "Everything is a set!" Yeah, right... > > No, that's okay. You only get into trouble when you have self-referential > sets, like "the set of all sets that don't contain themselves". Actually there's nothing wrong with self-referential sets per se. For example set theory with Aczel's anti-foundation axiom instead of the axiom of foundation is consistent if ZF is; see e.g. http://en.wikipedia.org/wiki/Non-well-founded_set_theory The trouble comes not with self-reference, but with unrestricted comprehension. From davea at davea.name Mon Feb 17 13:33:10 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 13:33:10 -0500 (EST) Subject: Import order question References: <53020843.5010804@shopzeus.com> Message-ID: Terry Reedy Wrote in message: > On 2/17/2014 8:01 AM, Nagy L??szl?? Zsolt wrote: >> I have a class hierarchy like this: >> >> Widget <- VisualWidget <- BsWidget >> >> and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc. >> >> Widgets can have children. They are stored in a tree. In order to manage >> the order of widgets, I need methods to append children. (And later: >> insert or prepend because they also have an order). So I would like to >> have methods like this: >> >> BsWidget.AppendNavbar(....) >> BsWidget.AppendRow(...) > > I would write one prepend/insert/append method that > prepends/inserts/appends the widget passed. > >> Here is the problem: these methods should create instances of Row, >> Column and Navbar. > > I disagree, without strong justification. Create the instances by > directly calling the classes and do with them as you want. > I agree with Terry, and will try to justify it. Whenever you have a large group of modules recursively importing each other, you need to look hard at the reason. (And saying ' because java does it that way' isn't a good enough one). Chances are things are too coupled. Your reason is because you have a base class instantiating child classes, for most if not all its children. Problem with that is you then need to modify that base class in about 4 places each time you add a child class. Very messy. So how do you avoid modifying the base class? Have an instance passed in, instead, as Terry implied. Now you say you don't want the application code to have to import all of those child classes? There are several solutions to that, depending. You can make a module which imports each of those, and stores a reference to each class. That becomes the only place to modify as new ones are added. Or you can have each of these extra modules add its factory function to a common list or dict, either at import time or in a once-called function. That common list could be defined (with only the base class in it initially) in the module with the base class. You could even add these methods you're trying to define to the base class, by defining them as ordinary functions in the corresponding module, and adding the appropriate attribute to the base. Or you could have each new class add itself as a top level module attribute to the module you plan for your users to import. Many more choices with various tradeoffs, and the best depends on a number of factors not yet discussed. For example, do all these classes take the same arguments to __init__? If so, then a single factory that takes the class reference as a parameter might be useful. -- DaveA From fabiofz at gmail.com Mon Feb 17 14:07:22 2014 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 17 Feb 2014 16:07:22 -0300 Subject: Problem importing libraries installed with PIP in Eclipse In-Reply-To: References: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Message-ID: On Sun, Feb 16, 2014 at 11:52 AM, Renato wrote: > It's solved now, oh my god I was so stupid! I created a package named > "pybrain" for testing PyBrain module, so obviously when I tryed to import > something from PyBrain library, Python would import all modules from this > personal package I created. The problem was not being reproduced outside > Eclipse because only within Eclipse my personal workstation directory > (which contained the personal package "pybrain") was visible. The solution > was simple: I just deleted the personal package named "pybrain" and now > everything is working. Thank you very much for your help! > Hi Renato, Nice that you got it working... Now, just as a heads up, that version of PyDev is quite old (the latest PyDev release: 3.3.3 is in many ways improved when comparing to older PyDev versions). I know Aptana Studio still has the older version, so, if you use mostly Python and you don't need the other features that Aptana Studio adds, it might be worth going to pure Eclipse + PyDev (or using LiClipse which also adds support for other languages -- besides being better configured out of the box, although it's a commercial counterpart of PyDev -- whose funds help to keep PyDev development going forward). Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From gordon at panix.com Mon Feb 17 14:16:13 2014 From: gordon at panix.com (John Gordon) Date: Mon, 17 Feb 2014 19:16:13 +0000 (UTC) Subject: How to use logging References: <5a53c1ca-1104-40f2-9401-a6d3b3673ede@googlegroups.com> Message-ID: In <5a53c1ca-1104-40f2-9401-a6d3b3673ede at googlegroups.com> kumar writes: > Hi folks, > i'm new to python i understood the logging mechanism but unable to > understand how these are applied in real time examples can any body help > me out Here are some very simple examples: import logging logging.info('This message will be logged at the INFO level.') logging.error('This message will be logged at the ERROR level.') logging.debug('This message will be logged at the DEBUG level.') Did you need help with some specific aspect of logging, like sending the output to a file instead of the default destination? -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From gordon at panix.com Mon Feb 17 14:17:07 2014 From: gordon at panix.com (John Gordon) Date: Mon, 17 Feb 2014 19:17:07 +0000 (UTC) Subject: Why is the interpreter is returning a 'reference'? References: <9b80c233-ad31-44c8-8a6e-9002ab11bd0d@googlegroups.com> Message-ID: In <9b80c233-ad31-44c8-8a6e-9002ab11bd0d at googlegroups.com> Nir writes: > >>> k = ['hi','boss'] > >>> > >>> k > ['hi', 'boss'] > >>> k= [s.upper for s in k] > >>> k > [, ] > Why doesn't the python interpreter just return > ['HI, 'BOSS'] ? > This isn't a big deal, but I am just curious as to why it does this. Because you typed 'str.upper' instead of 'str.upper()'. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From rvernucio at gmail.com Mon Feb 17 14:20:10 2014 From: rvernucio at gmail.com (Renato Vernucio) Date: Mon, 17 Feb 2014 16:20:10 -0300 Subject: Problem importing libraries installed with PIP in Eclipse In-Reply-To: References: <3a3acbf3-a7a5-4a5f-9e6c-10b4640be17f@googlegroups.com> Message-ID: Hi Fabio, I wish I could use the latest PyDev, unfortunately I need Aptana studio. It's a pity they won't let us install individual packages from their bundle. If they did, I could install only the other packages and install PyDev separately. Thanks for your help once again. Yours, Renato 2014-02-17 16:07 GMT-03:00 Fabio Zadrozny : > > On Sun, Feb 16, 2014 at 11:52 AM, Renato wrote: > >> It's solved now, oh my god I was so stupid! I created a package named >> "pybrain" for testing PyBrain module, so obviously when I tryed to import >> something from PyBrain library, Python would import all modules from this >> personal package I created. The problem was not being reproduced outside >> Eclipse because only within Eclipse my personal workstation directory >> (which contained the personal package "pybrain") was visible. The solution >> was simple: I just deleted the personal package named "pybrain" and now >> everything is working. Thank you very much for your help! >> > > > Hi Renato, > > Nice that you got it working... > > Now, just as a heads up, that version of PyDev is quite old (the latest > PyDev release: 3.3.3 is in many ways improved when comparing to older PyDev > versions). I know Aptana Studio still has the older version, so, if you use > mostly Python and you don't need the other features that Aptana Studio > adds, it might be worth going to pure Eclipse + PyDev (or using LiClipse > which also adds support for other languages -- besides being better > configured out of the box, although it's a commercial counterpart of PyDev > -- whose funds help to keep PyDev development going forward). > > Cheers, > > Fabio > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Mon Feb 17 14:40:41 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Feb 2014 06:40:41 +1100 Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <85vbwd4jeu.fsf@benfinney.id.au> Nagy L?szl? Zsolt writes: > > Use modules to group your class definitions conceptually. There is > > no need whatever to separate every class into a different module. > If there is a consensus, and it is really desireable to put all these > related classes into the same module, then this is what I'm going to > do. You should use multiple modules to separate the code where it makes sense, along *conceptual* lines. Make separate modules that each represent a conceptually-separate area of functionality in your application, and put the classes which implement that functionality in that module. > I never know when to put classes in different modules. I usually draw > an UML diagram and group classes into packages. Wich makes sense > because there can be sub-groups with subpackages. But I'm always > confused with modules, I don't know why. You can start by making one module for each of those groupings. (The term ?package? already has a specific technical meaning in Python, and I'm not sure whether that's what you meant here.) > Thanks for the help. Welcome to Python! -- \ ?If sharing a thing in no way diminishes it, it is not rightly | `\ owned if it is not shared.? ?Augustine of Hippo | _o__) | Ben Finney From maoist at the.peoples.republic.of.thrinaxodon.co.uk Mon Feb 17 19:44:20 2014 From: maoist at the.peoples.republic.of.thrinaxodon.co.uk (MAOIST) Date: Mon, 17 Feb 2014 19:44:20 -0500 Subject: NEW INFORMATION ON HUMAN DEVONIAN ORIGINS Message-ID: http://thrinaxodon.wordpress.com/faq/ -- Thrinaxodon, the ultimate defender of USENET. From eliasbylarsen at gmail.com Mon Feb 17 19:57:34 2014 From: eliasbylarsen at gmail.com (Physics) Date: Mon, 17 Feb 2014 16:57:34 -0800 (PST) Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: Message-ID: Does ANYONE have a clue how to do this? I understand that it is hard but geez... From eliasbylarsen at gmail.com Mon Feb 17 19:58:53 2014 From: eliasbylarsen at gmail.com (Physics) Date: Mon, 17 Feb 2014 16:58:53 -0800 (PST) Subject: NEW INFORMATION ON HUMAN DEVONIAN ORIGINS In-Reply-To: References: Message-ID: <44af36b0-31f5-428a-95c5-33663e4d0df6@googlegroups.com> On Monday, February 17, 2014 7:44:20 PM UTC-5, MAOIST wrote: > http://thrinaxodon.wordpress.com/faq/ > -- > Thrinaxodon, the ultimate defender of USENET. What The HELL? From rosuav at gmail.com Mon Feb 17 20:03:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 18 Feb 2014 12:03:45 +1100 Subject: NEW INFORMATION ON HUMAN DEVONIAN ORIGINS In-Reply-To: <44af36b0-31f5-428a-95c5-33663e4d0df6@googlegroups.com> References: <44af36b0-31f5-428a-95c5-33663e4d0df6@googlegroups.com> Message-ID: On Tue, Feb 18, 2014 at 11:58 AM, Physics wrote: > On Monday, February 17, 2014 7:44:20 PM UTC-5, MAOIST wrote: >> [ link deleted ] >> -- >> Thrinaxodon, the ultimate defender of USENET. > > What > The > HELL? These are just spam. Ignore them. And if you must respond, please remove the link :) ChrisA From Nikolaus at rath.org Mon Feb 17 20:29:42 2014 From: Nikolaus at rath.org (Nikolaus Rath) Date: Mon, 17 Feb 2014 17:29:42 -0800 Subject: select(sock) indicates not-ready, but sock.recv does not block In-Reply-To: <87a9dq9rh1.fsf@vostro.rath.org> (Nikolaus Rath's message of "Sun, 16 Feb 2014 22:35:22 -0800") References: <87a9dq9rh1.fsf@vostro.rath.org> Message-ID: <878ut9ky2h.fsf@vostro.rath.org> Nikolaus Rath writes: > Hello, > > I have a problem with using select. I can reliably reproduce a situation > where select.select((sock.fileno(),), (), (), 0) returns ((),(),()) > (i.e., no data ready for reading), but an immediately following > sock.recv() returns data without blocking. [...] Turns out that I fell into the well-known (except to me) ssl-socket trap: http://docs.python.org/3/library/ssl.html#notes-on-non-blocking-sockets TL;DR: Relying on select() on an SSL socket is not a good idea because some internal buffering is done. Better put the socket in non-blocking mode and try to read something, catching the ssl.Want* exception if nothing is ready. Best, -Nikolaus -- Encrypted emails preferred. PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C ?Time flies like an arrow, fruit flies like a Banana.? From steve at pearwood.info Mon Feb 17 21:52:10 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 18 Feb 2014 02:52:10 GMT Subject: Google Cloud Platform and GlassSolver Project References: Message-ID: <5302cada$0$2788$c3e8da3$76491128@news.astraweb.com> On Mon, 17 Feb 2014 16:57:34 -0800, Physics wrote: > Does ANYONE have a clue how to do this? I understand that it is hard but > geez... Absolutely no clue what your question is. You seem to assume that: - we know what "God's algorithm" is; - we know what "God's Number" is; - we understand what you mean by 3x3s, 2x2s, 4x4s and 5x5s (five what by five what?). and then to add insult to injury, you're asking us to write your program for you! Quote: "I am asking for a Python (2.7 please!) script for each cube." So, we don't fully understand the problem you are trying to solve, we don't understand the terminology you are using, and we're not really inclined to do all the work doing the hard part -- the part you apparently don't know how to solve -- just so that you can mention our name somewhere in a Read Me file and then claim the program as your own work. Especially since the problem you are trying to solve appears to be impossible, according to the link you posted earlier: http://www.speedsolving.com/forum/showthread.php?46268-Introducing-GlassSolver-back-and-better-than-ever!&p=951473 tl;dr: you've announced a project that never existed as "back and better than ever", and asked others to write the code for you. -- Steven From rosuav at gmail.com Mon Feb 17 22:09:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 18 Feb 2014 14:09:51 +1100 Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: <5302cada$0$2788$c3e8da3$76491128@news.astraweb.com> References: <5302cada$0$2788$c3e8da3$76491128@news.astraweb.com> Message-ID: On Tue, Feb 18, 2014 at 1:52 PM, Steven D'Aprano wrote: > On Mon, 17 Feb 2014 16:57:34 -0800, Physics wrote: > >> Does ANYONE have a clue how to do this? I understand that it is hard but >> geez... > > > Absolutely no clue what your question is. You seem to assume that: > > - we know what "God's algorithm" is; > > - we know what "God's Number" is; > > - we understand what you mean by 3x3s, 2x2s, 4x4s and 5x5s (five > what by five what?). They'll be Rubik's Cubes, as Dave said earlier in the thread. God's Number is the theoretical fewest-moves-to-solve, called that because you would need to be the omniscient Deity to know which moves to actually do. But I agree that it should have been said. Not everyone knows what your research is :) ChrisA From tjreedy at udel.edu Mon Feb 17 23:41:26 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Feb 2014 23:41:26 -0500 Subject: Re In-Reply-To: <44af36b0-31f5-428a-95c5-33663e4d0df6@googlegroups.com> References: <44af36b0-31f5-428a-95c5-33663e4d0df6@googlegroups.com> Message-ID: On 2/17/2014 7:58 PM, Physics wrote: A response to a spammer who changed email to avoid filters. If you want to do anything, forward the message with headers to Original-X-Complaints-To: abuse at aioe.org asking them to try harder to block the person. -- Terry Jan Reedy From laxmikant.general at gmail.com Tue Feb 18 00:11:05 2014 From: laxmikant.general at gmail.com (Laxmikant Chitare) Date: Tue, 18 Feb 2014 10:41:05 +0530 Subject: Does CPython already has Peephole optimizations? In-Reply-To: References: <5301cf82$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Thank you all for the enlightening inputs. I have learnt a lot just with this one question. Great to know about dis library. Ned, from explanation I now realize how important it is to do impact analysis. Things are not always rosy :). I have always appreciated everyone over this list. This is just another opportunity. Best regards, Laxmikant On Mon, Feb 17, 2014 at 7:21 PM, Terry Reedy wrote: > On 2/17/2014 3:59 AM, Steven D'Aprano wrote: > >> On Mon, 17 Feb 2014 13:54:25 +0530, Laxmikant Chitare wrote: >> >> I read about this article: >>> http://www.python.org/workshops/1998-11/proceedings/papers/montanaro/ >>> >> montanaro.html >> >>> >>> Just wanted to clarify whether CPython already includes these kind of >>> byte code optimizations? >>> >> > Most of the easily seen and obviously safe low-hanging fruits for the > compile step have been plucked. Note that the effect of the peephole > process would only save a few percent, if any, for real apps*. Improving > the C code invoked by bytecode has resulted in much larger gains. > > * We now have a much better benchmark suite with some real apps. This is > thanks in part to the pypy project. > > > Are all the temporary variables removed when byte code is generated? >>> >> >> You can check these things for yourself: >> >> import dis >> dis.dis(function) >> >> will show you the byte code. >> >> But in general, I would expect not. CPython (that's the Python you >> probably use) doesn't do a lot of optimization apart from some simple >> constant folding. If you're interested in optimizing Python, you should >> look at the JIT optimizing Python compiler, PyPy. >> > > For CPython, new optimization has mostly moved to AST tranformations prior > to compilation. (Python ASTs are new since Skip started the peephole work.) > I believe there are some open issues on the tracker. > > Once optimization constraint Skip did not mention is the correspondence > between source lines and blocks of bytecode, which is used by profiling, > tracing, and tracebacks. Effectively transforming > > if type(a) == types.ComplexType: > x = cmath.sin(a) > foo(x) > else: > x = math.sin(a) > foo(x) > > into > > if type(a) == types.ComplexType: > x = cmath.sin(a) > else: > x = math.sin(a) > foo(x) > > breaks the correspondence. If foo(x) raises, which original line should be > reported as the source of the exception? > > -- > Terry Jan Reedy > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Feb 18 07:35:05 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 18 Feb 2014 12:35:05 +0000 Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: References: <5302cada$0$2788$c3e8da3$76491128@news.astraweb.com> Message-ID: <53035379.90103@mrabarnett.plus.com> On 2014-02-18 03:09, Chris Angelico wrote: > On Tue, Feb 18, 2014 at 1:52 PM, Steven D'Aprano wrote: >> On Mon, 17 Feb 2014 16:57:34 -0800, Physics wrote: >> >>> Does ANYONE have a clue how to do this? I understand that it is hard but >>> geez... >> >> >> Absolutely no clue what your question is. You seem to assume that: >> >> - we know what "God's algorithm" is; >> >> - we know what "God's Number" is; >> >> - we understand what you mean by 3x3s, 2x2s, 4x4s and 5x5s (five >> what by five what?). > > They'll be Rubik's Cubes, as Dave said earlier in the thread. God's > Number is the theoretical fewest-moves-to-solve, called that because > you would need to be the omniscient Deity to know which moves to > actually do. But I agree that it should have been said. Not everyone > knows what your research is :) > Where I'm from, Rubik's Cubes are, well, cubes, thus 3x3x3, etc. From eglowstein.h at gmail.com Tue Feb 18 09:56:51 2014 From: eglowstein.h at gmail.com (eglowstein.h at gmail.com) Date: Tue, 18 Feb 2014 06:56:51 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows Message-ID: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> The next adventure in Python was to install Python 3 into a Windows XP machine. I had a previous 2.7 installation that I uninstalled and carefully removed all traces of from the directory and the registry. I got the 'python-3.3.3.msi' from Python.org and installed it. From a command window I can run 'python' and I get the Python prompt. I have several Python programs on the machine. If I right click o one, I have the option of 'Edit in IDLE'. If I do that, the disk light blinks briefly, and then nothing. So I went into the \python33\lib\idlelib directory and from a CMD window, ran 'python idle.py'. That loads IDLE. but when I ask IDLE to load a file, it navigates to a FileOpen dialog and then closes everything when I actually open the file. I then tried the same thing but used 'pythonw' instead. Same deal. I also saw some other threads here about how Python can get befuddled by firewalls, so I disabled that with no effect. Any suggestions? Thanks in advance! Howard From behrooz.abbasy at gmail.com Tue Feb 18 10:47:57 2014 From: behrooz.abbasy at gmail.com (behrooz.abbasy at gmail.com) Date: Tue, 18 Feb 2014 07:47:57 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> Message-ID: <884d8b13-6bcf-409d-b270-ceda7f9f5c16@googlegroups.com> On Tuesday, February 18, 2014 6:26:51 PM UTC+3:30, eglows... at gmail.com wrote: > The next adventure in Python was to install Python 3 into a Windows XP machine. I had a previous 2.7 installation that I uninstalled and carefully removed all traces of from the directory and the registry. > > > > I got the 'python-3.3.3.msi' from Python.org and installed it. From a command window I can run 'python' and I get the Python prompt. I have several Python programs on the machine. If I right click o one, I have the option of 'Edit in IDLE'. If I do that, the disk light blinks briefly, and then nothing. So I went into the \python33\lib\idlelib directory and from a CMD window, ran 'python idle.py'. That loads IDLE. but when I ask IDLE to load a file, it navigates to a FileOpen dialog and then closes everything when I actually open the file. I then tried the same thing but used 'pythonw' instead. Same deal. > > > > I also saw some other threads here about how Python can get befuddled by firewalls, so I disabled that with no effect. > > > > Any suggestions? Thanks in advance! > > > > Howard From neilc at norwich.edu Tue Feb 18 11:39:43 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Tue, 18 Feb 2014 16:39:43 +0000 (UTC) Subject: Can one use Python to learn and even apply Functional Programming? References: <3fd33e3a-7774-4988-b725-4fed5472ac94@googlegroups.com> Message-ID: On 2014-02-16, Sam wrote: > I would like to learn and try out functional programming (FP). > I love Python and would like to use it to try FP. Some have > advised me to use Haskell instead because Python is not a good > language for FP. I am sort of confused at the moment. Is Python > a dysfunctional programming language to apply FP? Can the more > experienced Python users advise? I recommend Scheme to learn functional programming style. There's a short scheme tutorial that was entered in the Interactive Fiction competition in 1998 or so. You can play it online here, and try out functional programming on a scheme interepreter implemented in Inform and running on a Z-machine interpreter written in javascript. It was *my* first introduction to functional programming. http://www.eblong.com/zarf/if.html#lists I purchased and really enjoyed Simply Scheme as a followup to that mind-bending experience. http://www.eecs.berkeley.edu/~bh/ss-toc2.html I wouldn't recommend trying to learn anything at the same time as learning Haskell. ;) -- Neil Cerutti From rosuav at gmail.com Tue Feb 18 11:47:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 03:47:15 +1100 Subject: Bad Code Snippet of the Day Message-ID: I call this "Russian Exception Roulette". It came about because of some discussions on python-ideas regarding the new PEP 463 and exception handling. try: exc = getattr(__builtins__,random.choice(list(filter(lambda x: x.endswith("Error"),dir(__builtins__))))) f() except exc: print("You win!") Given a function f(), defined elsewhere, what will this do? Note that this was developed on Python 3.4, and some of the details may be different on other versions (especially 2.x). ChrisA From kjakupak at gmail.com Tue Feb 18 13:30:34 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Tue, 18 Feb 2014 10:30:34 -0800 (PST) Subject: Dictionary help Message-ID: So let's say I have a file and it looks like this: Title 1: item Title 2: item etc Is it possible to use a dictionary for something like the input above? Because I want to be able to use the input above to delete the "Title 1" and "Title 2" but still show the items (on separate lines). Basically I want it to just show: item item etc.. What I've got is dict(item.split(":") for item in cInfo.split(" ")) Where cInfo is a function that extracts the first 5 lines of a file From python.list at tim.thechases.com Tue Feb 18 13:46:26 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 Feb 2014 12:46:26 -0600 Subject: Dictionary help In-Reply-To: References: Message-ID: <20140218124626.684ffa9b@bigbox.christie.dr> On 2014-02-18 10:30, kjakupak at gmail.com wrote: > So let's say I have a file and it looks like this: > Title 1: item > Title 2: item > etc > > Is it possible to use a dictionary for something like the input > above? Because I want to be able to use the input above to delete > the "Title 1" and "Title 2" but still show the items (on separate > lines). Basically I want it to just show: item item > etc.. > > What I've got is > dict(item.split(":") for item in cInfo.split(" ")) > > Where cInfo is a function that extracts the first 5 lines of a file It sounds like all you need is some basic string functions, not a dictionary: for line in file('input.txt'): title, _, item = line.partition(':') print(item.strip()) -tkc From jonnojohnson at gmail.com Tue Feb 18 15:34:51 2014 From: jonnojohnson at gmail.com (Jonno) Date: Tue, 18 Feb 2014 14:34:51 -0600 Subject: Help creating new module which inherits existing class from another module. Message-ID: I'm not sure if this list is a suitable place to ask for this kind of help so if it's not please just suggest another forum which might be more suitable. I'm looking for help/suggestions how to architect a module (perhaps just a class). There is an existing module I want to use which has a class we'll call *Existing Class*. I want to create a python module which allows me to create *new_objects* with the following properties: - The new_objects have all the attributes of the Existing_Class (simply create a class that inherits from Existing_Class) - I then want to create a nested structure under the new_objects something like: new_object.foo new_object.foo.bar new_object.foo.bar.baz Where foo, bar, baz have the following properties: - All have *docstrings* - All are available for *tab completion* tools upon new_object creation. - Some of which will have *new methods* which act in the following way: - new_object.foo.bar() calls - new_object.existing_method("foo.bar", *args) I believe I'll need to use metaclasses and have an idea that types.MethodType will help but I keep getting stuck. Any pointers would be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Feb 18 15:41:53 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Feb 2014 15:41:53 -0500 Subject: Bad Code Snippet of the Day In-Reply-To: References: Message-ID: On 2/18/2014 11:47 AM, Chris Angelico wrote: > I call this "Russian Exception Roulette". It came about because of > some discussions on python-ideas regarding the new PEP 463 and > exception handling. > > try: > exc = getattr(__builtins__,random.choice(list(filter(lambda x: > x.endswith("Error"),dir(__builtins__))))) > f() > except exc: > print("You win!") > > Given a function f(), defined elsewhere, what will this do? I am not sure what you are asking or what your point is. If f happens to raise the randomly selected exception, it prints 'You win!', otherwise it does nothing. > Note that this was developed on Python 3.4, and some of the details > may be different on other versions (especially 2.x). -- Terry Jan Reedy From rantingrickjohnson at gmail.com Tue Feb 18 15:41:20 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 18 Feb 2014 12:41:20 -0800 (PST) Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On Monday, February 17, 2014 1:40:41 PM UTC-6, Ben Finney wrote: > Nagy L?szl? Zsolt ... writes: > > > Use modules to group your class definitions conceptually. There is > > > no need whatever to separate every class into a different module. > > If there is a consensus, and it is really desireable to put all these > > related classes into the same module, then this is what I'm going to > > do. It is not desirable to me, and i would argue truthfully, to many others either. > You should use multiple modules to separate the code where it makes > sense, along *conceptual* lines. Make separate modules that each > represent a conceptually-separate area of functionality in your > application, and put the classes which implement that functionality in > that module. Classes with an "s"? As in many classes in one source file? Are you insane man? Why oh why would you torture yourself and others with such advice? Are you some sort of hard disc neat freak? Do you fear cluttering your hard-drive with too many files will overwork it? What of yourself? I'm continually amazed by you "Java haters" who will willingly place burdens on yourself just to spite that "mean old Java". Splitting code into small source files is wise, whereas, creating single monolithic monstrosities like Tkinter should be a sin! A sin that should be punishable by the Exception! As the lines of code increase, so does the complexity of navigating and maintaining large modules. Classes should naturally exist in their own module with the exception of small utility or special use classes that are not exposed publicly. Then you go and intermix the areas of "module source code" and "module API". These are two distinct areas that need not follow the same patterns. You can have 20 classes contained in 20 different source files and then combine them transparently at run-time so that as far as the client is concerned, all the classes exist under one namespace. # ui_mod1.py class One():pass # ui_mod2.py class Two():pass # ui_mod3.py class Three():pass # ui_mod4.py class Four():pass # ui_main.py from ui_mod1 import * from ui_mod2 import * from ui_mod3 import * from ui_mod4 import * At least by this method i can maintain the code base without wearing-out my scroll finger and eventually loosing my mind. THE MORAL: With very few exceptions, please put EVERY class in it's own module. From ben+python at benfinney.id.au Tue Feb 18 15:47:52 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Feb 2014 07:47:52 +1100 Subject: Help creating new module which inherits existing class from another module. References: Message-ID: <85fvng407b.fsf@benfinney.id.au> Jonno writes: > I'm not sure if this list is a suitable place to ask for this kind of > help so if it's not please just suggest another forum which might be > more suitable. Welcome! Asking for help with writing Python code is definitely suitable here. > I'm looking for help/suggestions how to architect a module (perhaps > just a class). Right, I don't see anything in your request that indicates why a new module would be needed. > There is an existing module I want to use which has a class we'll call > *Existing Class*. > > I want to create a python module which allows me to create > *new_objects* This is all rather abstract. Can you explain what the existing class is for? What the new class is for? > with the following properties: > > - The new_objects have all the attributes of the Existing_Class (simply > create a class that inherits from Existing_Class) The syntax for that is:: class Bar(Foo): ? where ?Foo? is the existing class, ?Bar? is the class you're defining. It's not strictly true to say that Bar will thereby ?have all the attributes of? the existing class. Rather, the resolution chain will mean that accessing attributes on Bar will fall-back to looking at Foo for attributes not found in Bar. > - I then want to create a nested structure under the new_objects > something like: > > new_object.foo > new_object.foo.bar > new_object.foo.bar.baz Again, it's not clear why you're doing this. What are these attributes for? > Where foo, bar, baz have the following properties: > > - All have *docstrings* Docstrings are only for code objects: modules, classes, functions. Will each of those attributes be one of those? > - All are available for *tab completion* tools upon new_object creation. Tab completion is up to the interactive tool you're using. Which tool is that? > - > Some of which will have *new methods* which act in the following way: > - new_object.foo.bar() > > calls > - new_object.existing_method("foo.bar", *args) This would be an unusual semantic. Why not call the existing method? > Any pointers would be greatly appreciated. I am smelling the likelihood that you have a strange design that needs to be examined and changed. Can you describe what your purpose is that you think needs this strange architecture? -- \ ?Anyone can do any amount of work provided it isn't the work he | `\ is supposed to be doing at the moment.? ?Robert Benchley | _o__) | Ben Finney From rosuav at gmail.com Tue Feb 18 16:02:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 08:02:26 +1100 Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On Wed, Feb 19, 2014 at 7:41 AM, Rick Johnson wrote: > # ui_main.py > from ui_mod1 import * > from ui_mod2 import * > from ui_mod3 import * > from ui_mod4 import * > > At least by this method i can maintain the code base without > wearing-out my scroll finger and eventually loosing my mind. > THE MORAL: With very few exceptions, please put EVERY class > in it's own module. Absolutely definitely not. If you're going to import * into every module, just write it all in a single source file. Otherwise, when someone tries to find the source code for some particular class or function, s/he has to go digging through all five source files - first the utterly useless merge-point, then the four others, because there's no way to know which one has it. Python could make this easier for us, by retaining the origin of every function and class. And maybe it's already there, but I don't know about it. But even if it did exist (by the way, it would be useful for other things than just taming a mad layout like this), it'd still be better to keep everything combined, because the origin of a function/class could just as easily go to the exact line as to the file. A module is a namespace. It should be used as such. If you want a package, use a package. There's no point putting each class out separate unless you really need that. ChrisA From rosuav at gmail.com Tue Feb 18 16:14:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 08:14:37 +1100 Subject: Bad Code Snippet of the Day In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 7:41 AM, Terry Reedy wrote: > On 2/18/2014 11:47 AM, Chris Angelico wrote: >> >> I call this "Russian Exception Roulette". It came about because of >> some discussions on python-ideas regarding the new PEP 463 and >> exception handling. >> >> try: >> exc = getattr(__builtins__,random.choice(list(filter(lambda x: >> x.endswith("Error"),dir(__builtins__))))) >> f() >> except exc: >> print("You win!") >> >> Given a function f(), defined elsewhere, what will this do? > > > I am not sure what you are asking or what your point is. If f happens to > raise the randomly selected exception, it prints 'You win!', otherwise it > does nothing. My point is that this is a piece of obscure code: the try block affects the interpretation of the except that's associated with it. Just playing around with obfuscated Python, for amusement value. The rules of Python are so simple that they allow stupidity like this, and the interpreter just goes, "So? Of course that's how it is!". I like it. :) ChrisA From rantingrickjohnson at gmail.com Tue Feb 18 16:10:22 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 18 Feb 2014 13:10:22 -0800 (PST) Subject: Bad Code Snippet of the Day In-Reply-To: References: Message-ID: <5f3e508e-d4d6-4573-b562-e393f7183f5a@googlegroups.com> On Tuesday, February 18, 2014 10:47:15 AM UTC-6, Chris Angelico wrote: > I call this "Russian Exception Roulette". It came about because of > some discussions on python-ideas regarding the new PEP 463 and > exception handling. > try: > > exc = getattr(__builtins__,random.choice(list(filter(lambda x: > x.endswith("Error"),dir(__builtins__))))) > f() > except exc: > print("You win!") > Given a function f(), defined elsewhere, what will this do? For get about "f()", it will throw a NameError since "random" was not imported. Beyond that this code (either conscientiously or unconsciously) exposes the onerous and obfuscation of a language design that coddles a global function nightmare paradigm over the elegance of true OOP -- talk about cutting off your nose just to spite your face! From rosuav at gmail.com Tue Feb 18 16:18:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 08:18:41 +1100 Subject: Google Cloud Platform and GlassSolver Project In-Reply-To: <53035379.90103@mrabarnett.plus.com> References: <5302cada$0$2788$c3e8da3$76491128@news.astraweb.com> <53035379.90103@mrabarnett.plus.com> Message-ID: On Tue, Feb 18, 2014 at 11:35 PM, MRAB wrote: > Where I'm from, Rubik's Cubes are, well, cubes, thus 3x3x3, > etc. For some reason, they're often referred to in just two dimensions. I have no idea why. A so-called "3x3" cube is standard, and has 3x3x3 small cubes (well, actually, the standard engineering form of it has eight corner cubes, twelve edge cubes, and six center cubes, not one of which is actually a cube, so that's 26 non-cubes and nothing in the middle), and analogously the others. I suppose calling it a "Three Cube" or a "Four Cube" isn't clear, and certainly "3x3x3" is redundant. ChrisA From rosuav at gmail.com Tue Feb 18 16:21:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 08:21:25 +1100 Subject: Bad Code Snippet of the Day In-Reply-To: <5f3e508e-d4d6-4573-b562-e393f7183f5a@googlegroups.com> References: <5f3e508e-d4d6-4573-b562-e393f7183f5a@googlegroups.com> Message-ID: On Wed, Feb 19, 2014 at 8:10 AM, Rick Johnson wrote: > Beyond that this code (either conscientiously or unconsciously) > exposes the onerous and obfuscation of a language design > that coddles a global function nightmare paradigm over the > elegance of true OOP -- talk about cutting off your nose > just to spite your face! Humour me, Rick. Pretend I've been awake for 22 hours straight, am wired on sleep-deprivation and energy drinks, and have no idea what you're talking about. How exactly does the ability to dynamically determine which exception to catch coddle a functional paradigm, and how is it not object oriented? Also, my face doesn't much care for my nose. It gets in the way. If I cut my nose off, my face would be happy with me. ChrisA From rantingrickjohnson at gmail.com Tue Feb 18 16:44:47 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 18 Feb 2014 13:44:47 -0800 (PST) Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On Tuesday, February 18, 2014 3:02:26 PM UTC-6, Chris Angelico wrote: > On Wed, Feb 19, 2014 at 7:41 AM, Rick Johnson wrote: > > # ui_main.py > > from ui_mod1 import * > > from ui_mod2 import * > > from ui_mod3 import * > > from ui_mod4 import * > > At least by this method i can maintain the code base without > > wearing-out my scroll finger and eventually loosing my mind. > > THE MORAL: With very few exceptions, please put EVERY class > > in it's own module. > Absolutely definitely not. If you're going to import * into every > module, just write it all in a single source file. Writing multiple individual classes in multiple individual modules, and then importing those individual classes under a single namespace at run-time is key to exposing a monolithic API to a client without storing all the source code in a monolithic file. The "Tkinter" folks would be wise to follow my advise! But I'm not suggesting this is the solution to EVERY problem, or even that this is the solution to the OP's current problem, what i am suggesting is that source files should be kept as short as possible so as to accommodate easy maintenance. You see, unlike other languages, Python does not give us a choice of the start and end of a Python module, there is no keyword or delimiting chars that we can use to EXPLICITLY define the start and end of a Python module. No, EVERY Python script IS a module by default, and that is the law of the land. > Otherwise, when > someone tries to find the source code for some particular class or > function, s/he has to go digging through all five source files - first > the utterly useless merge-point, then the four others, because there's > no way to know which one has it. Only if you're blind, or your source code was written by people lacking even a modicum of common sense about how to name a module. Most modules can simply be the name of the containing class. Heck, even an idiot can manage that! > Python could make this easier for us, by retaining the origin of every > function and class. And maybe it's already there, but I don't know > about it. Google "inspect" and be enlightened. But Chris, if you have to use the inspect module to find a class then sir, you need lack: simple search tools, and/or motivation. Are you telling me you're willing to search through a single file containing 3,734 lines of code (yes, Tkinter) looking for a method named "destroy" of a class named "OptionMenu" (of which three other classes contain a method of the same exact name!), when all you needed to do was open one single module named "tk_optionmenu.py" and do a single search for "def destroy"? You must be trolling! > But even if it did exist (by the way, it would be useful for > other things than just taming a mad layout like this), it'd still be > better to keep everything combined, because the origin of a > function/class could just as easily go to the exact line as to the > file. > A module is a namespace. It should be used as such. If you want a > package, use a package. There's no point putting each class out > separate unless you really need that. But in many cases you do! Chris, i think you missed the entire crux of this thread. The OP is not writing a single monolithic program where the code will ONLY be investigated by the developers, no, he's creating an API, and API's require structure. But even if this were not an API, breaking large chunks of code up and spreading them across individual files is the key to managing code bases. From rosuav at gmail.com Tue Feb 18 16:49:22 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 08:49:22 +1100 Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On Wed, Feb 19, 2014 at 8:44 AM, Rick Johnson wrote: > Are you telling me you're willing to search through a single > file containing 3,734 lines of code (yes, Tkinter) looking > for a method named "destroy" of a class named "OptionMenu" Yeah, actually I am. At my last job, I had a single C++ file of roughly 5K lines, and it wasn't at all unmanageable. Probably wouldn't have been a problem to have another order of magnitude on that. What sort of wimpy text editor are you using that you can't find what you're looking for in a single large file? Less steps to get to the file, more searching within the file. Much easier. ChrisA From torriem at gmail.com Tue Feb 18 17:06:39 2014 From: torriem at gmail.com (Michael Torrie) Date: Tue, 18 Feb 2014 15:06:39 -0700 Subject: Import order question In-Reply-To: <53020843.5010804@shopzeus.com> References: <53020843.5010804@shopzeus.com> Message-ID: <5303D96F.7050802@gmail.com> On 02/17/2014 06:01 AM, Nagy L?szl? Zsolt wrote: > I have a class hierarchy like this: > > Widget <- VisualWidget <- BsWidget > > and then BsWidget has many descendants: Desktop, Row, Column, Navbar etc. > > Widgets can have children. They are stored in a tree. In order to manage > the order of widgets, I need methods to append children. (And later: > insert or prepend because they also have an order). So I would like to > have methods like this: > > BsWidget.AppendNavbar(....) > BsWidget.AppendRow(...) Why not just take advantage of duck typing and have a generic append() method that takes any kind of widget. As long as the widget supports the method calls that BsWidget needs to make on it, you have zero need of imports in BsWidget. There's really no need to import other parts of your widget hierarchy. That is only necessary for the module that instantiates the objects. This is one feature of Python I really like and use a lot. The ability to completely decouple code units. Of course you can do similar things in Java and C++ by using abstract base classes and interfaces. From python.list at tim.thechases.com Tue Feb 18 17:17:48 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 Feb 2014 16:17:48 -0600 Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <20140218161748.4485e647@bigbox.christie.dr> On 2014-02-19 08:49, Chris Angelico wrote: > > Are you telling me you're willing to search through a single > > file containing 3,734 lines of code (yes, Tkinter) looking > > for a method named "destroy" of a class named "OptionMenu" > > At my last job, I had a single C++ file of roughly 5K lines, and > it wasn't at all unmanageable. Probably wouldn't have been a > problem to have another order of magnitude on that. What sort of > wimpy text editor are you using that you can't find what you're > looking for in a single large file? Even the venerable "ed" handles files of those sizes without batting an eye. I just opened a 2MB XML file (50k lines) in ed and jumped all around in it with no trouble at all. It's as simple as 1;/class OptionMenu/;/def destroy/ in most cases. If your editor can't help you do simple things like that, I recommend you find an editor that is at least as good as ed. :-) -tkc From invalid at invalid.invalid Tue Feb 18 17:44:44 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 18 Feb 2014 22:44:44 +0000 (UTC) Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On 2014-02-18, Chris Angelico wrote: > On Wed, Feb 19, 2014 at 8:44 AM, Rick Johnson > wrote: >> Are you telling me you're willing to search through a single >> file containing 3,734 lines of code (yes, Tkinter) looking >> for a method named "destroy" of a class named "OptionMenu" > > Yeah, actually I am. Yup. And there are new-fangled tools like grep and vi/emacs that even make it easy! > At my last job, I had a single C++ file of roughly 5K lines, and it > wasn't at all unmanageable. Probably wouldn't have been a problem to > have another order of magnitude on that. What sort of wimpy text > editor are you using that you can't find what you're looking for in a > single large file? Less steps to get to the file, more searching > within the file. Much easier. Definitely. I've worked on a number C projects where the source code was pointlessly split up into a whole slew of files. AFAICT, it wasn't done to provide separate namespaces or for information hiding or code reuse. It was just done to piss me off when I'm trying to find something... -- Grant Edwards grant.b.edwards Yow! Maybe I should have at asked for my Neutron Bomb gmail.com in PAISLEY -- From invalid at invalid.invalid Tue Feb 18 17:45:19 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 18 Feb 2014 22:45:19 +0000 (UTC) Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On 2014-02-18, Tim Chase wrote: > On 2014-02-19 08:49, Chris Angelico wrote: >> > Are you telling me you're willing to search through a single >> > file containing 3,734 lines of code (yes, Tkinter) looking >> > for a method named "destroy" of a class named "OptionMenu" >> >> At my last job, I had a single C++ file of roughly 5K lines, and >> it wasn't at all unmanageable. Probably wouldn't have been a >> problem to have another order of magnitude on that. What sort of >> wimpy text editor are you using that you can't find what you're >> looking for in a single large file? > > Even the venerable "ed" handles files of those sizes without batting > an eye. I just opened a 2MB XML file (50k lines) in ed and jumped > all around in it with no trouble at all. It's as simple as > > 1;/class OptionMenu/;/def destroy/ > > in most cases. If your editor can't help you do simple things like > that, I recommend you find an editor that is at least as good as > ed. :-) You think you're joking, but there are lot of editors that aren't. -- Grant Edwards grant.b.edwards Yow! RELATIVES!! at gmail.com From rantingrickjohnson at gmail.com Tue Feb 18 17:49:39 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 18 Feb 2014 14:49:39 -0800 (PST) Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <65e656f1-acc6-470a-b39e-cf6fb035cbbc@googlegroups.com> On Tuesday, February 18, 2014 4:17:48 PM UTC-6, Tim Chase wrote: > On 2014-02-19 08:49, Chris Angelico wrote: > > At my last job, I had a single C++ file of roughly 5K lines, and > > it wasn't at all unmanageable. Probably wouldn't have been a > > problem to have another order of magnitude on that. What sort of > > wimpy text editor are you using that you can't find what you're > > looking for in a single large file? > Even the venerable "ed" handles files of those sizes without batting > an eye. I just opened a 2MB XML file (50k lines) in ed and jumped > all around in it with no trouble at all. It's as simple as > 1;/class OptionMenu/;/def destroy/ > in most cases. If your editor can't help you do simple things like > that, I recommend you find an editor that is at least as good as > ed. :-) SarcasticSam: Who needs directories anyway when the hard-drive is already one gigantic directory... THOSE IDIOTS! Yes Sam, it seems this thread has degenerated into a testosterone induced contest to determine who can open the largest file, climb inside, and then jump around the fastest -- MAY THE BEST MEAT-HEAD WIN! For the rest of us --of which who respect brains over brawn-- we'll swallow our foolish pride and wield the technology of sane structures. From sg552 at hotmail.co.uk Tue Feb 18 18:28:21 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Tue, 18 Feb 2014 23:28:21 +0000 Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On 18/02/2014 21:44, Rick Johnson wrote: > [...] > > Are you telling me you're willing to search through a single > file containing 3,734 lines of code (yes, Tkinter) looking > for a method named "destroy" of a class named "OptionMenu" > (of which three other classes contain a method of the same > exact name!), when all you needed to do was open one single > module named "tk_optionmenu.py" and do a single search for > "def destroy"? > > You must be trolling! I have music software that's a single 9K-line Python module, which I edit using Notepad++ or gedit. If I wish to find e.g. the method "edit" of class "sequence" I can type class seqdef edit( From rantingrickjohnson at gmail.com Tue Feb 18 18:41:32 2014 From: rantingrickjohnson at gmail.com (Rick Johnson) Date: Tue, 18 Feb 2014 15:41:32 -0800 (PST) Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On Tuesday, February 18, 2014 5:28:21 PM UTC-6, Rotwang wrote: > I have music software that's a single 9K-line Python module, which I > edit using Notepad++ or gedit. If I wish to find e.g. the method "edit" > of class "sequence" I can type > class seqdef edit( References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <5303F854.90205@mrabarnett.plus.com> On 2014-02-18 23:28, Rotwang wrote: > On 18/02/2014 21:44, Rick Johnson wrote: >> [...] >> >> Are you telling me you're willing to search through a single >> file containing 3,734 lines of code (yes, Tkinter) looking >> for a method named "destroy" of a class named "OptionMenu" >> (of which three other classes contain a method of the same >> exact name!), when all you needed to do was open one single >> module named "tk_optionmenu.py" and do a single search for >> "def destroy"? >> >> You must be trolling! > > I have music software that's a single 9K-line Python module, which I > edit using Notepad++ or gedit. If I wish to find e.g. the method "edit" > of class "sequence" I can type > > class seqdef edit( > I use EditPad Pro. It has a File Navigator, which gives a hierarchical view of functions, classes and methods. From sg552 at hotmail.co.uk Tue Feb 18 20:09:27 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Wed, 19 Feb 2014 01:09:27 +0000 Subject: Import order question In-Reply-To: References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: On 18/02/2014 23:41, Rick Johnson wrote: > On Tuesday, February 18, 2014 5:28:21 PM UTC-6, Rotwang wrote: [snipped material restored for context] >> On 18/02/2014 21:44, Rick Johnson wrote: >>> [...] >>> >>> Are you telling me you're willing to search through a single >>> file containing 3,734 lines of code (yes, Tkinter) looking >>> for a method named "destroy" of a class named "OptionMenu" >>> (of which three other classes contain a method of the same >>> exact name!), when all you needed to do was open one single >>> module named "tk_optionmenu.py" and do a single search for >>> "def destroy"? >>> >>> You must be trolling! >> >> I have music software that's a single 9K-line Python module, which I >> edit using Notepad++ or gedit. If I wish to find e.g. the method "edit" >> of class "sequence" I can type >> class seqdef edit( > This is not about "how to use a search function" No, it's about your incredulity that someone would search for a method in a large file that contains several methods of the same name. However, the existence of search functions makes this completely trivial. From roy at panix.com Tue Feb 18 20:13:05 2014 From: roy at panix.com (Roy Smith) Date: Tue, 18 Feb 2014 20:13:05 -0500 Subject: Bad Code Snippet of the Day References: Message-ID: In article , Terry Reedy wrote: > On 2/18/2014 11:47 AM, Chris Angelico wrote: > > I call this "Russian Exception Roulette". It came about because of > > some discussions on python-ideas regarding the new PEP 463 and > > exception handling. > > > > try: > > exc = getattr(__builtins__,random.choice(list(filter(lambda x: > > x.endswith("Error"),dir(__builtins__))))) > > f() > > except exc: > > print("You win!") > > > > Given a function f(), defined elsewhere, what will this do? > > I am not sure what you are asking or what your point is. If f happens to > raise the randomly selected exception, it prints 'You win!', otherwise > it does nothing. def f(): print("You win!") problem solved :-) From rosuav at gmail.com Tue Feb 18 20:57:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 12:57:34 +1100 Subject: Import order question In-Reply-To: <20140218161748.4485e647@bigbox.christie.dr> References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> <20140218161748.4485e647@bigbox.christie.dr> Message-ID: On Wed, Feb 19, 2014 at 9:17 AM, Tim Chase wrote: > On 2014-02-19 08:49, Chris Angelico wrote: >> > Are you telling me you're willing to search through a single >> > file containing 3,734 lines of code (yes, Tkinter) looking >> > for a method named "destroy" of a class named "OptionMenu" >> >> At my last job, I had a single C++ file of roughly 5K lines, and >> it wasn't at all unmanageable. Probably wouldn't have been a >> problem to have another order of magnitude on that. What sort of >> wimpy text editor are you using that you can't find what you're >> looking for in a single large file? > > Even the venerable "ed" handles files of those sizes without batting > an eye. I just opened a 2MB XML file (50k lines) in ed and jumped > all around in it with no trouble at all. It's not just about whether your editor can handle a file of that size, of course [1], but how well they help you find your way around the codebase. But ultimately, you're going to have those KLOC somewhere. Whether they're in one file, a small handful of files, or eight hundred separate tiny .PHP files (UGH UGH UGH UGH! and yes that was a real thing and yes I had to search through it wince wince!), you somehow need to find the one line you want out of, let's say, 50K. That's a fairly small project by a lot of standards. Somehow, you need to find one particular function. It might be named beautifully, in which case a grep-across-files will do the job, or it might not. Maybe you can see, as a human, that one of the subbranches MUST contain what you're looking for (one file, or one directory, or something); but that often requires knowledge of the codebase, which you mightn't have. So splitting into files doesn't solve anything, and it introduces its own set of problems. Just for reference, here are a few line counts. They're based on "find -name \*.FILE_EXT|xargs wc -l" in the base directories of several projects (using an appropriate extension, as listed). Small projects: Proprietary project at my last job, *.cpp: 4782 (one file) Same project, *.pike: 6559 Gypsum (open source MUD client), *.pike: 5083 Medium size projects: CPython/Python, *.c: 55329 alsa-lib, *.c: 91131 SciTE, *.cxx: 114785 (34876 + Scintilla's 79909) Pike, *.pike: 138705 Large projects: Pike, *.c: 298773 CPython/Lib, *.py: 318232 (See how much of Python is written in Python? Although I can't help feeling that my figures are wrong somehow. And that figure is ignoring the test/ subdirectory with another 267872 lines for a total of 586104.) I've done "search across files" in all of these, bar alsa-lib which I line-counted just because it happened to be there. (Incidentally, I'm fully aware that some of those figures are unfair. overall, I'd say Pike and Python are comparable-sized projects, but Python's more heavily written in Python and Pike's more heavily written in C, partly by using a precompiler that's somewhat along the lines of Cython. Scintilla includes a whole bunch of individual language lexers, and it's usually pretty clear that you don't need to look in any of those. Etc, etc.) It's usually been easy enough to find what I want; in fact, the few times when it _hasn't_ have generally turned out to be because of bugs (something had "desrtuct" instead of "destruct" in its name and I of course couldn't find it). SciTE's search-across-files isn't the best, but it covers 99%+ of my use cases. For anything else, well, there's always popping up a terminal and using primitives like grep, find, and so on. ChrisA [1] But as Grant hinted, some do have issues. From biolord9 at gmail.com Tue Feb 18 20:58:21 2014 From: biolord9 at gmail.com (SAINT THRINAXODON) Date: Tue, 18 Feb 2014 17:58:21 -0800 (PST) Subject: SMITHSONIAN DOWN AND BLEEDING -- THE THRINAXODON TIMES Message-ID: ============== >BREAKING NEWS ============== > SMITHSONIAN FINALLY SHUT DOWN AFTER YEARS OF CENSORSHIP, SCAMS AND CON ARTISTRY. > THRINAXODON BLEW DOWN THE BUILDINGS, LIT IT ON FIRE AND HAD THE ASSHOLES ARRESTED. > R. DAWKINS WAS THROWN IN THE DOGHOUSE, ONLY TO GET KILLED BY ANGRY FELONS WHO WANTED PAYBACK FOR FRAMING THEM. > THRINAXODON DANCED ON DAWKINS' GRAVE, AND BURNED A FEW SMITHSONIAN MAGAZINES. > ================================= EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER. ====================================== > THRINAXODON WAS AWARDED US$100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 DOLLARS FOR HIS BRAVE EFFORTS IN SHUTTING DOWN THE EVOLUTIONARY SCAMS. From plicatibu at gmail.com Tue Feb 18 18:48:26 2014 From: plicatibu at gmail.com (Marcio Andrey Oliveira) Date: Tue, 18 Feb 2014 20:48:26 -0300 Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: Hi. I stumbled upon Wheezy.web and I got interested into learn more about it. After googling I didn't find that many information about it: only docs and samples from its web site. I didn't find a mailing list nor user groups and no tutorials from its users. Is Wheezy.web been actively developed? Does it have any user base community that I could get in touch with? Or should I forget about it and stick to say flask or pyramid? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Feb 18 22:58:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 14:58:30 +1100 Subject: Turning an AST node / subnodes into something human-readable Message-ID: I'm working with the ast module to do some analysis on Python codebases, and once I've found what I'm looking for, I want to print something out. The file name I'm hanging onto externally, so that works; and the nodes all have a lineno. So far so good. But how do I "reconstitute" a subtree into something fit for human consumption? Take this cut-down example: module = ast.parse("x[1] = 345+456") assign = list(ast.walk(module))[1] destination = assign.targets[0] At this point, destination is the subtree representing what's being assigned to. I can get a verbose dump of that: >>> print(ast.dump(destination)) Subscript(value=Name(id='x', ctx=Load()), slice=Index(value=Num(n=1)), ctx=Store()) but what I'd really like to do is get something that looks approximately like "x[1]". Is there an easy way to do that? Its str and repr aren't useful, and I can't see a "reconstitute" method on the node, nor a function in ast itself for the job. In theory I could write one, but it'd need to understand every node type, so it seems the most logical place would be on the node itself - maybe in __str__. Is there anything nice and easy? I don't care if it's not perfect, as long as it's more readable than ast.dump(). :) ChrisA From jonnojohnson at gmail.com Tue Feb 18 23:16:40 2014 From: jonnojohnson at gmail.com (Jonno) Date: Tue, 18 Feb 2014 22:16:40 -0600 Subject: Help creating new module which inherits existing class from another module. In-Reply-To: <85fvng407b.fsf@benfinney.id.au> References: <85fvng407b.fsf@benfinney.id.au> Message-ID: Ben, Thanks for your reply. I'll try to ellaborate a little more in the comments below. On Tue, Feb 18, 2014 at 2:47 PM, Ben Finney wrote: > Jonno writes: > > > I'm not sure if this list is a suitable place to ask for this kind of > > help so if it's not please just suggest another forum which might be > > more suitable. > > Welcome! Asking for help with writing Python code is definitely suitable > here. > > > I'm looking for help/suggestions how to architect a module (perhaps > > just a class). > > Right, I don't see anything in your request that indicates why a new > module would be needed. > Only that eventually I might want to distribute this and include some other features. > > > There is an existing module I want to use which has a class we'll call > > *Existing Class*. > > > > I want to create a python module which allows me to create > > *new_objects* > > This is all rather abstract. Can you explain what the existing class is > for? What the new class is for? > > Well I was trying to keep it as generic as possible and only introduce the necessary features. It's possible I've left out something important though. > > with the following properties: > > > > - The new_objects have all the attributes of the Existing_Class > (simply > > create a class that inherits from Existing_Class) > > The syntax for that is:: > > class Bar(Foo): > ... > > where "Foo" is the existing class, "Bar" is the class you're defining. > > It's not strictly true to say that Bar will thereby "have all the > attributes of" the existing class. Rather, the resolution chain will > mean that accessing attributes on Bar will fall-back to looking at Foo > for attributes not found in Bar. > > Point taken. > > - I then want to create a nested structure under the new_objects > > something like: > > > > new_object.foo > > new_object.foo.bar > > new_object.foo.bar.baz > > Again, it's not clear why you're doing this. What are these attributes for? > I tried to explain the necessary properties in the requirements below. Really the main function of creating this new module is to add the docstring & tab completion capabilities. Essentially it's a way to create an explorable structure of elements with documentation. If you have other suggestions how to achieve that I'd be interested. . > > > Where foo, bar, baz have the following properties: > > > > - All have *docstrings* > > Docstrings are only for code objects: modules, classes, functions. Will > each of those attributes be one of those? > > Only because I'd like them to have docstring attributes. > > - All are available for *tab completion* tools upon new_object > creation. > > Tab completion is up to the interactive tool you're using. Which tool is > that? > > For me ipython but I'd like it to work in other tools so the more general the better. > > - > > Some of which will have *new methods* which act in the following way: > > - new_object.foo.bar() > > > > calls > > - new_object.existing_method("foo.bar", *args) > > This would be an unusual semantic. Why not call the existing method? > > Basically right now the user has to look up external documentation to figure out which arguments (foo, bar etc) are necessary and there are many of them in a nested structure. I'd like to create a module that they can explore within an enhanced python editor/interpreter. > > Any pointers would be greatly appreciated. > > I am smelling the likelihood that you have a strange design that needs > to be examined and changed. Can you describe what your purpose is that > you think needs this strange architecture? > > Hopefully my comments help some. I'm definitely not opposed to changing the architecture but the main objectives of documentation & explorability (yes I know that's not a real word) are top priority. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Wed Feb 19 00:48:34 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Feb 2014 16:48:34 +1100 Subject: Help creating new module which inherits existing class from another module. References: <85fvng407b.fsf@benfinney.id.au> Message-ID: <85bny34pql.fsf@benfinney.id.au> Jonno writes: > I tried to explain the necessary properties in the requirements below. What you've described is a bunch of abstract behaviour. But as I said, I'm suspecting this is a poor design; and I can't know better until you explain what all this is *for*. What is the purpose of the code you're writing? What is special about it that makes you think it needs the specific properties you've described? I ask all this because I suspect there are better and/or simpler ways to achieve your *actual* goals. Maybe not; but to rule that out, I'd need to know more about the purpose. -- \ ?It is the integrity of each individual human that is in final | `\ examination. On personal integrity hangs humanity's fate.? | _o__) ?Richard Buckminster Fuller, _Critical Path_, 1981 | Ben Finney From research at johnohagan.com Wed Feb 19 02:14:25 2014 From: research at johnohagan.com (John O'Hagan) Date: Wed, 19 Feb 2014 18:14:25 +1100 Subject: a question about list as an element in a tuple In-Reply-To: References: Message-ID: <20140219181425.3ea44f0f@mini.home> On Mon, 16 Dec 2013 11:30:13 +0800 liuerfire Wang wrote: > Just like below: > > In [1]: a = ([], []) > > In [2]: a[0].append(1) > > In [3]: a > Out[3]: ([1], []) > > In [4]: a[0] += [1] > --------------------------------------------------------------------------- > TypeError Traceback (most recent call > last) in () > ----> 1 a[0] += [1] > > TypeError: 'tuple' object does not support item assignment > > In [5]: a > Out[5]: ([1, 1], []) > > no problem, there is an exception. But a is still changed. > > is this a bug, or could anyone explain it? > > thanks. > This thread from two years ago deals with this in some detail: https://mail.python.org/pipermail/python-list/2012-February/619265.html It's one of those things that is hard to resolve in a way that makes sense in every situation. The weirdest part for me is this: >>> t = ([],) >>> l = t[0] >>> l is t[0] True >>> l += [1] >>> t[0] += [1] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Whether there is an error or not depends on the name used for the object! -- John From andriy.kornatskyy at live.com Wed Feb 19 02:18:17 2014 From: andriy.kornatskyy at live.com (Andriy Kornatskyy) Date: Wed, 19 Feb 2014 09:18:17 +0200 Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: Marcio, The wheezy.web framework (http://bitbucket.org/akorn/wheezy.web) supplies documentation, tutorials, quick starts and benchmark for you. Due to modular architecture, it is being developed in several independent loosely coupled libraries under wheezy.*. The source code is easy to read, there is 100% test coverage. No bells and whistles. I believe the web framework should not be something cryptic (requiring community to exchange ideas about workarounds) nor something that involves infinitive development cycle. If you have any questions I will be happy to answer in this mailing list or personally. Thanks. Andriy Kornatskyy On Feb 19, 2014, at 1:48 AM, Marcio Andrey Oliveira wrote: > Hi. > > I stumbled upon Wheezy.web and I got interested into learn more about it. > > After googling I didn't find that many information about it: only docs and samples from its web site. > > I didn't find a mailing list nor user groups and no tutorials from its users. > > Is Wheezy.web been actively developed? Does it have any user base community that I could get in touch with? Or should I forget about it and stick to say flask or pyramid? > > Thank you. > > -- > https://mail.python.org/mailman/listinfo/python-list From steve at pearwood.info Wed Feb 19 02:32:02 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 19 Feb 2014 07:32:02 GMT Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <53045df2$0$2788$c3e8da3$76491128@news.astraweb.com> On Tue, 18 Feb 2014 13:44:47 -0800, Rick Johnson wrote: > Are you telling me you're willing to search through a single file > containing 3,734 lines of code (yes, Tkinter) looking for a method named > "destroy" of a class named "OptionMenu" (of which three other classes > contain a method of the same exact name!), when all you needed to do was > open one single module named "tk_optionmenu.py" and do a single search > for "def destroy"? How do you know that the module tk_optionmenu.py contains the class OptionMenu? Perhaps it contains the function optionmenu. Or the class TK_OptionMenu. For a mere 4000 lines of code, yes, I'd rather have it all in the one file, presuming that they are all related pieces of code. Much, much, much easier to search, edit and maintain; avoids circular imports and other dependency problems. If there are parts of that module that stand alone, then arguably they ought to be extracted out into a separate module. But other than that, 4000 lines of code isn't so big that we should be splitting the file apart merely for the size. [...] > But even if this were not an API, breaking large chunks of code up and > spreading them across individual files is the key to managing code > bases. You left out the word "badly". -- Steven From steve at pearwood.info Wed Feb 19 02:32:57 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 19 Feb 2014 07:32:57 GMT Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> Message-ID: <53045e29$0$2788$c3e8da3$76491128@news.astraweb.com> On Tue, 18 Feb 2014 15:41:32 -0800, Rick Johnson wrote: > Heck, when a class gets too big i even export some of the methods to > outside modules and load the methods dynamically at run-time just to cut > down on the length. I suppose my detractors would find that surprising > also! Not in the least bit surprising. I expected nothing less from you. -- Steven From steve at pearwood.info Wed Feb 19 02:52:08 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 19 Feb 2014 07:52:08 GMT Subject: Help creating new module which inherits existing class from another module. References: Message-ID: <530462a8$0$2788$c3e8da3$76491128@news.astraweb.com> On Tue, 18 Feb 2014 14:34:51 -0600, Jonno wrote: > There is an existing module I want to use which has a class we'll call > *Existing Class*. > > I want to create a python module which allows me to create *new_objects* > with the following properties: > > - The new_objects have all the attributes of the Existing_Class > (simply create a class that inherits from Existing_Class) That part is easy: from some_module import ExistingClass class NewClass(ExistingClass): pass newobject = NewClass() > - I then > want to create a nested structure under the new_objects something > like: > > new_object.foo > > new_object.foo.bar > > new_object.foo.bar.baz > > Where foo, bar, baz have the following properties: > > - All have *docstrings* > - All are available for *tab completion* tools upon new_object > creation. Well, that depends on the tab completion tools you are using. > - Some of which will have *new methods* which act in the following > way: > - new_object.foo.bar() > > calls > - new_object.existing_method("foo.bar", *args) Seems awfully complicated, and I don't understand what you would do with these strange things, but okay. Start by ignoring the "existing class" and concentrated on these foo, foo.bar, foo.bar.baz things. It isn't clear to me what they are, but I think that you want foo to be an object which is callable, as well as having an attribute bar (which itself is callable, etc.). The way to do that is with a class: class FooClass: def __init__(self, parent): self.parent = parent def __call__(self): return self.parent.existing_method("something") Add your foo, bar and baz methods as needed, and we'll look for a way to calculate "something" on the fly later. Now remember your NewClass definition above? What we'd like to do is this: class NewClass(ExistingClass): foo = FooClass(self) but of course you can't, because self doesn't exist until the class is instantiated! So what we need if for foo to be a descriptor. I don't quite remember the descriptor syntax, so this may be wrong, but I think you want something like this: # This is probably wrong. class FooDescriptor(object): def __get__(self, cls, obj): return FooClass(obj) and then in NewClass you put in: foo = FooDescriptor() The idea is that when you have a NewClass instance, calling "newobject.foo" will automatically call the descriptor's __getmethod__, passing it the class and instance. That descriptor will create and populate the FooClass instance, which does the real work. Descriptors are how methods, classmethods, staticmethods and properties work, so they are a fundamental, powerful way of implementing things like this. -- Steven From rosuav at gmail.com Wed Feb 19 02:59:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 18:59:43 +1100 Subject: Import order question In-Reply-To: <53045df2$0$2788$c3e8da3$76491128@news.astraweb.com> References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> <53045df2$0$2788$c3e8da3$76491128@news.astraweb.com> Message-ID: On Wed, Feb 19, 2014 at 6:32 PM, Steven D'Aprano wrote: > On Tue, 18 Feb 2014 13:44:47 -0800, Rick Johnson wrote: > >> Are you telling me you're willing to search through a single file >> containing 3,734 lines of code (yes, Tkinter) ... > > For a mere 4000 lines of code, yes, I'd rather have it all in the one > file, presuming that they are all related pieces of code. If Tkinter were horribly unreadable, I would figure it as being because of the multiple languages involved. But I just pulled up tkinter/__init__.py to try to find OptionMenu, and it's 35 lines of easy-to-read code. And there's a destroy method. Not at all hard to find. ChrisA From irmen.NOSPAM at xs4all.nl Wed Feb 19 03:05:18 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 19 Feb 2014 09:05:18 +0100 Subject: Turning an AST node / subnodes into something human-readable In-Reply-To: References: Message-ID: <530465bd$0$2971$e4fe514c@news.xs4all.nl> On 19-2-2014 4:58, Chris Angelico wrote: > but what I'd really like to do is get something that looks > approximately like "x[1]". Is there an easy way to do that? Its str > and repr aren't useful, and I can't see a "reconstitute" method on the > node, nor a function in ast itself for the job. In theory I could > write one, but it'd need to understand every node type, so it seems > the most logical place would be on the node itself - maybe in __str__. > > Is there anything nice and easy? I don't care if it's not perfect, as > long as it's more readable than ast.dump(). :) > Maybe this https://pypi.python.org/pypi/astor can do what you want? (found it by following a few links starting from http://stackoverflow.com/questions/768634/python-parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified) Irmen From sujiths80 at gmail.com Wed Feb 19 03:14:40 2014 From: sujiths80 at gmail.com (Sujith S) Date: Wed, 19 Feb 2014 00:14:40 -0800 (PST) Subject: SSH/Telnet program to Router/switch Message-ID: Hi, I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. Do we have expect available in python as well or need to use some other method ? Regards Sujith From rosuav at gmail.com Wed Feb 19 03:44:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 19:44:48 +1100 Subject: Turning an AST node / subnodes into something human-readable In-Reply-To: <530465bd$0$2971$e4fe514c@news.xs4all.nl> References: <530465bd$0$2971$e4fe514c@news.xs4all.nl> Message-ID: On Wed, Feb 19, 2014 at 7:05 PM, Irmen de Jong wrote: > On 19-2-2014 4:58, Chris Angelico wrote: > >> but what I'd really like to do is get something that looks >> approximately like "x[1]". Is there an easy way to do that? Its str >> and repr aren't useful, and I can't see a "reconstitute" method on the >> node, nor a function in ast itself for the job. In theory I could >> write one, but it'd need to understand every node type, so it seems >> the most logical place would be on the node itself - maybe in __str__. >> >> Is there anything nice and easy? I don't care if it's not perfect, as >> long as it's more readable than ast.dump(). :) >> > > Maybe this https://pypi.python.org/pypi/astor can do what you want? > (found it by following a few links starting from > http://stackoverflow.com/questions/768634/python-parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified) > Hmm. I saw a few (things like codegen), but was hoping to stick to the standard library - introducing a dependency in a small script just for the sake of tidy output is a bit messy. Oh well. Some things just aren't as ideal as I'd like. Thanks Irmen! ChrisA From rosuav at gmail.com Wed Feb 19 03:45:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 19 Feb 2014 19:45:59 +1100 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 7:14 PM, Sujith S wrote: > Hi, > > I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. > > Do we have expect available in python as well or need to use some other method ? > Yep! Look up the socket module. Straight-forward TCP sockets are usually easy enough to work. ChrisA From wojciech.lysiak at hotmail.com Wed Feb 19 03:45:53 2014 From: wojciech.lysiak at hotmail.com (=?UTF-8?B?V29qY2llY2ggxYF5c2lhaw==?=) Date: Wed, 19 Feb 2014 09:45:53 +0100 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: On 19.02.2014 09:14, Sujith S wrote: > Hi, > > I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. > > Do we have expect available in python as well or need to use some other method ? Hello, If you are looking for a way to connect to your netdevices and then execute some shell commands (with output) via ssh then google for paramiko module for python. It works on windows and linux. -- BR, Wojtek From marko at pacujo.net Wed Feb 19 03:51:22 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 19 Feb 2014 10:51:22 +0200 Subject: a question about list as an element in a tuple References: Message-ID: <87bny38oz9.fsf@elektro.pacujo.net> John O'Hagan : > The weirdest part for me is this: > >>>> t = ([],) >>>> l = t[0] >>>> l is t[0] > True >>>> l += [1] >>>> t[0] += [1] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > Whether there is an error or not depends on the name used for the > object! Nice catch! The += operator rebinds the reference even if the object wouldn't change: >>> t = 1, >>> t[0] = t[0] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment See also: >>> a = [] >>> b = a >>> a = a + [1] >>> a is b False >>> a = [] >>> b = a >>> a += [1] >>> a is b True This behavior is not a bug, though. : for example, the statement x += y is equivalent to x = operator.iadd(x, y) operator.iadd(x, y) modifies x in place and returns x. However, () x + y is dealt with by operator.add(x, y), which leaves x and y intact and must return a new object. Marko From marko at pacujo.net Wed Feb 19 03:54:39 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 19 Feb 2014 10:54:39 +0200 Subject: a question about list as an element in a tuple References: <87bny38oz9.fsf@elektro.pacujo.net> Message-ID: <877g8r8ots.fsf@elektro.pacujo.net> Marko Rauhamaa : > operator.add(x, y) [...] leaves x and y intact and must return a new > object. Well, if the addition doesn't modify x, the method can of course return x. Marko From johannes.schneider at galileo-press.de Wed Feb 19 05:36:56 2014 From: johannes.schneider at galileo-press.de (Johannes Schneider) Date: Wed, 19 Feb 2014 11:36:56 +0100 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: <53048948.9040709@galileo-press.de> On 19.02.2014 09:14, Sujith S wrote: > Hi, > > I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. > > Do we have expect available in python as well or need to use some other method ? > > Regards > Sujith > I'm using paramiko to access some routers and firewalls from python and it works very well. bg, Johannes -- Johannes Schneider Webentwicklung johannes.schneider at galileo-press.de Tel.: +49.228.42150.xxx Galileo Press GmbH Rheinwerkallee 4 - 53227 Bonn - Germany Tel.: +49.228.42.150.0 (Zentrale) .77 (Fax) http://www.galileo-press.de/ Gesch?ftsf?hrer: Tomas Wehren, Ralf Kaulisch, Rainer Kaltenecker HRB 8363 Amtsgericht Bonn From hugocoolens at gmail.com Wed Feb 19 06:02:52 2014 From: hugocoolens at gmail.com (hugocoolens) Date: Wed, 19 Feb 2014 03:02:52 -0800 (PST) Subject: how to install automatically missing modules on a debian-system Message-ID: <7841a394-46ff-4f63-8afc-12b396bb8695@googlegroups.com> It often happens I start a python-script I wrote some time ago on another system and get messages like "module_x is missing". I then perform an apt-cache search module_x, followed by an apt-get install name_of_missing_module.deb I was wondering whether someone here has a kind of method which automatically looks for the missing modules as debian-packages and offers to install them? hugo From plicatibu at gmail.com Wed Feb 19 06:31:11 2014 From: plicatibu at gmail.com (Marcio Andrey Oliveira) Date: Wed, 19 Feb 2014 08:31:11 -0300 Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: Hi. Thanks for replying. I navigated in its site. I just feel strange that no one wrote tutorials of it (not counting some speed testing) and that there is no Wheezy.web community (yet). I'll give it a try and for sure I'll get in touch in case of problems. Thank you. 2014-02-19 4:18 GMT-03:00 Andriy Kornatskyy : > Marcio, > > The wheezy.web framework (http://bitbucket.org/akorn/wheezy.web) supplies > documentation, tutorials, quick starts and benchmark for you. Due to > modular architecture, it is being developed in several independent loosely > coupled libraries under wheezy.*. The source code is easy to read, there is > 100% test coverage. > > No bells and whistles. > > I believe the web framework should not be something cryptic (requiring > community to exchange ideas about workarounds) nor something that involves > infinitive development cycle. > > If you have any questions I will be happy to answer in this mailing list > or personally. > > Thanks. > > Andriy Kornatskyy > > On Feb 19, 2014, at 1:48 AM, Marcio Andrey Oliveira > wrote: > > > Hi. > > > > I stumbled upon Wheezy.web and I got interested into learn more about it. > > > > After googling I didn't find that many information about it: only docs > and samples from its web site. > > > > I didn't find a mailing list nor user groups and no tutorials from its > users. > > > > Is Wheezy.web been actively developed? Does it have any user base > community that I could get in touch with? Or should I forget about it and > stick to say flask or pyramid? > > > > Thank you. > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > -- > https://mail.python.org/mailman/listinfo/python-list > -- *Do you have an arcade site? I do 1:1 Game Exchange * *Play free on-line games * *Get free games for* -------------- next part -------------- An HTML attachment was scrubbed... URL: From ttdhead at gmail.com Wed Feb 19 06:46:31 2014 From: ttdhead at gmail.com (Leo) Date: Wed, 19 Feb 2014 22:46:31 +1100 Subject: Python Requests script to login to a phpbb forum Message-ID: Hi there, I have decided to jump in at the deep end to try and learn python. I have been able to get requests to pull the login page off the server and I think send the login request. I don't get logged in though. Please let me know if I would be better off asking in a phpBB related group or forum. Here is my code without username and password included: import requests payload = {'username': 'username', 'password': 'password'} r = requests.post("http://www.tt-forums.net/ucp.php?mode=login",data=payload) sidStart = r.text.find("sid")+4 sid = r.text[sidStart:sidStart+32] parameters = {'mode': 'login', 'sid': sid} r = requests.post("http://www.tt-forums.net/ucp.php",params=parameters,data=payload) if "Logout" in r.text: print("We are in") Thank you -- ClassicVB Users Regroup! comp.lang.basic.visual.misc Free usenet access at http://www.eternal-september.org From kwpolska at gmail.com Wed Feb 19 06:50:01 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 19 Feb 2014 12:50:01 +0100 Subject: Python Requests script to login to a phpbb forum In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 12:46 PM, Leo wrote: > Hi there, > > I have decided to jump in at the deep end to try and learn python. I have > been able to get requests to pull the login page off the server and I think > send the login request. I don't get logged in though. Please let me know if > I would be better off asking in a phpBB related group or forum. > Here is my code without username and password included: You need cookies. In order to do it, simply use sessions instead of the ?global? API. Code: import requests payload = {'username': 'username', 'password': 'password'} session = requests.Session() r = session.post("http://www.tt-forums.net/ucp.php?mode=login",data=payload) sidStart = r.text.find("sid")+4 sid = r.text[sidStart:sidStart+32] parameters = {'mode': 'login', 'sid': sid} r = session.post("http://www.tt-forums.net/ucp.php",params=parameters,data=payload) if "Logout" in r.text: print("We are in") (for the record, I added the session creation line and replaced requests. with session. so it uses your session. This code was not tested on a real phpBB forum; if everything you coded is correct, it will work.) -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From kwpolska at gmail.com Wed Feb 19 07:01:21 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 19 Feb 2014 13:01:21 +0100 Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 8:18 AM, Andriy Kornatskyy wrote: > I believe the web framework should not be something cryptic (requiring community to exchange ideas about workarounds) nor something that involves infinitive development cycle. Having lots of humans give support is much better when you have problems. You are more likely to get a quick response from a big group of humans than from one developer. On Wed, Feb 19, 2014 at 12:31 PM, Marcio Andrey Oliveira wrote: > I navigated in its site. I just feel strange that no one wrote tutorials of it (not counting some speed testing) and that there is no Wheezy.web community (yet). I personally suggest trying something more popular, like Flask, Bottle, Pyramid, or Django (though it?s quite big and complicated). Lots of tutorials exist for those. There are big, vivid communities offering help and support. You can often find good solutions for popular problems (like user accounts) without reinventing wheels. Flask is the easiest option, and it?s very popular. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From plicatibu at gmail.com Wed Feb 19 08:00:37 2014 From: plicatibu at gmail.com (Marcio Andrey Oliveira) Date: Wed, 19 Feb 2014 10:00:37 -0300 Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: To say the truth right now I'm studying some frameworks (not only in Python) to get one I feel more comfortable with. I'm learning Flask too and it seems a very nice project. And I completely agree with you that the bigger the community the easier is to get support. Regards. 2014-02-19 9:01 GMT-03:00 Chris "Kwpolska" Warrick : > On Wed, Feb 19, 2014 at 8:18 AM, Andriy Kornatskyy > wrote: > > I believe the web framework should not be something cryptic (requiring > community to exchange ideas about workarounds) nor something that involves > infinitive development cycle. > > Having lots of humans give support is much better when you have > problems. You are more likely to get a quick response from a big > group of humans than from one developer. > > On Wed, Feb 19, 2014 at 12:31 PM, Marcio Andrey Oliveira > wrote: > > I navigated in its site. I just feel strange that no one wrote tutorials > of it (not counting some speed testing) and that there is no Wheezy.web > community (yet). > > I personally suggest trying something more popular, like Flask, > Bottle, Pyramid, or Django (though it's quite big and complicated). > Lots of tutorials exist for those. There are big, vivid communities > offering help and support. You can often find good solutions for > popular problems (like user accounts) without reinventing wheels. > Flask is the easiest option, and it's very popular. > > -- > Chris "Kwpolska" Warrick > PGP: 5EAAEA16 > stop html mail | always bottom-post | only UTF-8 makes sense > -- *Do you have an arcade site? I do 1:1 Game Exchange * *Play free on-line games * *Get free games for* -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Wed Feb 19 08:28:50 2014 From: roy at panix.com (Roy Smith) Date: Wed, 19 Feb 2014 08:28:50 -0500 Subject: Import order question References: <53020843.5010804@shopzeus.com> <851tz16fzt.fsf@benfinney.id.au> <53025198.1060000@shopzeus.com> <53045df2$0$2788$c3e8da3$76491128@news.astraweb.com> Message-ID: In article <53045df2$0$2788$c3e8da3$76491128 at news.astraweb.com>, Steven D'Aprano wrote: > How do you know that the module tk_optionmenu.py contains the class > OptionMenu? Perhaps it contains the function optionmenu. Or the class > TK_OptionMenu. Stuff like this is a really important issue once a codebase gets large enough that nobody has it all memorized. If I'm looking at a piece of code: foo = Frobnicator() foo.flamozilate() and I want to get a better understanding of what flamozilation involves, it saves me a bunch of time if I can look at the class name and guess where it lives. Otherwise, I'm reduced to: $ cd $BASE_DIR; find . -name '*.py' | xargs grep "class Frobnicator" In the Songza codebase, we often deal with triples of related names. A class FooBar should live in a file models/foo_bar.py, and the name of the related database collection (think: SQL table name) should be "foo_bar". When any of those assumptions are broken (and, sadly, sometimes they are), the cost of maintenance goes up. Sometimes we'll put a small collection of very closely related classes in one file. So, FrobnicatorIndexHelper would probably be in the same file as Frobnicator. I once worked on a huge C++ project that had thousands of classes spread out over about 50 modules. They had adopted the convention that *every* class name was something like CI_Frobnicator; the prefix told you where the class lived. From khanta at gmail.com Wed Feb 19 07:42:02 2014 From: khanta at gmail.com (khanta) Date: Wed, 19 Feb 2014 07:42:02 -0500 Subject: Win32 Write RAW Physical Disk Python 3.3.2 Message-ID: Hello, I am trying to write to the raw physical disk on Windows 8.1 but I get an error: PermissionError: [Errno 13] Permission denied: '\\\\.\\PHYSICALDRIVE2\\\\' OS: Windows 8.1 Python: 3.3.2 Drive is a USB drive Running as administrator Code Snippet: with open(r"\\.\PHYSICALDRIVE2\\", "rb+") as f: #Writing Binary! f.seek(unallocatedoffset + 0) f.write(t1) or with open('\\\\.\\PHYSICALDRIVE2\\', "rb+") as f: #Writing Binary! f.seek(unallocatedoffset + 0) f.write(t1) or f = os.fdopen(os.open('\\\\.\\PHYSICALDRIVE2\\' os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_EXCL)) Any suggestions? Is it possible? From roy at panix.com Wed Feb 19 08:35:00 2014 From: roy at panix.com (Roy Smith) Date: Wed, 19 Feb 2014 08:35:00 -0500 Subject: SSH/Telnet program to Router/switch References: Message-ID: In article , Sujith S wrote: > Hi, > > I am new to programming and python. I am looking for a python script to do > ssh/telnet to a network equipment ? I know tcl/perl does this using > expect/send. > > Do we have expect available in python as well or need to use some other > method ? You want two libraries. First, the low-level paramiko (http://www.lag.net/paramiko/) which handles all the basic ssh connection stuff. Next, fabric (http://docs.fabfile.org/en/1.8/), which layers a very easy to use application layer on top of paramiko. Fabric is most commonly used in conjunction with a near command-line driver tool called fab, but you can also work directly with the library layer (http://docs.fabfile.org/en/1.8/usage/library.html). Fabric rocks. Don't waste your time with anything else (but see the next paragraph). As far as I know, fabric only works with ssh. If you are forced to use telnet to talk to legacy equipment, that's another problem. From rosuav at gmail.com Wed Feb 19 08:58:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 00:58:33 +1100 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 12:35 AM, Roy Smith wrote: > As far as I know, fabric only works with ssh. If you are forced to use > telnet to talk to legacy equipment, that's another problem. If it's telnet, it's likely to be a pretty simple protocol. All you really need is the socket module, build it all yourself. Networking's easy enough to handle; it's the crypto on top of it (SSH, in your case) that's not worth doing manually. ChrisA From roy at panix.com Wed Feb 19 09:13:23 2014 From: roy at panix.com (Roy Smith) Date: Wed, 19 Feb 2014 09:13:23 -0500 Subject: SSH/Telnet program to Router/switch References: Message-ID: In article , Roy Smith wrote: > in conjunction with a near command-line driver tool called fab Typo there: "near" should have been "neat". [this is why I love wikis] From wrw at mac.com Wed Feb 19 09:27:53 2014 From: wrw at mac.com (William Ray Wing) Date: Wed, 19 Feb 2014 09:27:53 -0500 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: <9F41D954-3415-4C18-AEE7-8241590EA5A5@mac.com> On Feb 19, 2014, at 3:14 AM, Sujith S wrote: > Hi, > > I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. > > Do we have expect available in python as well or need to use some other method ? > > Regards > Sujith > -- > https://mail.python.org/mailman/listinfo/python-list In addition to the other answers you've received (and noting that you are familiar with "expect"), you might want to investigate the pexpect module. Google will give you quite a long list of references to it, but you could start here: http://pexpect.readthedocs.org/en/latest/ -Bill From breamoreboy at yahoo.co.uk Wed Feb 19 10:04:29 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Feb 2014 15:04:29 +0000 Subject: Turning an AST node / subnodes into something human-readable In-Reply-To: References: Message-ID: On 19/02/2014 03:58, Chris Angelico wrote: > I'm working with the ast module to do some analysis on Python > codebases, and once I've found what I'm looking for, I want to print > something out. The file name I'm hanging onto externally, so that > works; and the nodes all have a lineno. So far so good. But how do I > "reconstitute" a subtree into something fit for human consumption? > > Take this cut-down example: > > module = ast.parse("x[1] = 345+456") > assign = list(ast.walk(module))[1] > destination = assign.targets[0] > > At this point, destination is the subtree representing what's being > assigned to. I can get a verbose dump of that: > >>>> print(ast.dump(destination)) > Subscript(value=Name(id='x', ctx=Load()), slice=Index(value=Num(n=1)), > ctx=Store()) > > but what I'd really like to do is get something that looks > approximately like "x[1]". Is there an easy way to do that? Its str > and repr aren't useful, and I can't see a "reconstitute" method on the > node, nor a function in ast itself for the job. In theory I could > write one, but it'd need to understand every node type, so it seems > the most logical place would be on the node itself - maybe in __str__. > > Is there anything nice and easy? I don't care if it's not perfect, as > long as it's more readable than ast.dump(). :) > > ChrisA > http://alexleone.blogspot.co.uk/2010/01/python-ast-pretty-printer.html ? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From harrismh777 at gmail.com Wed Feb 19 10:30:19 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Wed, 19 Feb 2014 07:30:19 -0800 (PST) Subject: extend methods of decimal module Message-ID: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> Would it be possible to extend the methods of the decimal module just a bit to include atan(), sin(), cos(), and exp() ? The module has methods for ln() and sqrt(); and that's great! I have done some rudimentary searching of the pep history and I'm not finding any pep related to extending the decimal module with other scientific functions. It is easy to write them in pure python, of course, but I am interested in having the same performance boost with atan(), sin(), cos(), and exp() as I see with the rest of the decimal module on 3.3/ Is it possible anytime sooner than later? By-the-by, my hat is off to the person(s) who did the 3.3 work on the decimal module --- the performance boost is astounding. My agm routine for pi100k (which runs on 3.2.3 2Ghz in 10.5 minutes) runs on the same processor in 42 seconds on 3.3.4/ very nice. From rosuav at gmail.com Wed Feb 19 10:35:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 02:35:42 +1100 Subject: Turning an AST node / subnodes into something human-readable In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 2:04 AM, Mark Lawrence wrote: >> but what I'd really like to do is get something that looks >> approximately like "x[1]". > > http://alexleone.blogspot.co.uk/2010/01/python-ast-pretty-printer.html ? That's still based on ast.dump(), so it's still highly verbose. I've stuck with just dumping to screen for the present. This really does seem like a useful feature addition, though, if anyone wants to push it through. ChrisA From rosuav at gmail.com Wed Feb 19 10:44:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 02:44:56 +1100 Subject: Win32 Write RAW Physical Disk Python 3.3.2 In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 11:42 PM, khanta wrote: > PermissionError: [Errno 13] Permission denied: '\\\\.\\PHYSICALDRIVE2\\\\' Have you tried running your script as administrator? Raw writing to a disk quite possibly is (and definitely should be) a restricted action. ChrisA From rosuav at gmail.com Wed Feb 19 10:45:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 02:45:30 +1100 Subject: Win32 Write RAW Physical Disk Python 3.3.2 In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 2:44 AM, Chris Angelico wrote: > On Wed, Feb 19, 2014 at 11:42 PM, khanta wrote: >> PermissionError: [Errno 13] Permission denied: '\\\\.\\PHYSICALDRIVE2\\\\' > > Have you tried running your script as administrator? Raw writing to a > disk quite possibly is (and definitely should be) a restricted action. Whoops! I missed seeing that somehow. You already are. Sorry about that! ChrisA From jonnojohnson at gmail.com Wed Feb 19 10:56:22 2014 From: jonnojohnson at gmail.com (Jonno) Date: Wed, 19 Feb 2014 09:56:22 -0600 Subject: Help creating new module which inherits existing class from another module. In-Reply-To: <85bny34pql.fsf@benfinney.id.au> References: <85fvng407b.fsf@benfinney.id.au> <85bny34pql.fsf@benfinney.id.au> Message-ID: On Tue, Feb 18, 2014 at 11:48 PM, Ben Finney wrote: > Jonno writes: > > > I tried to explain the necessary properties in the requirements below. > > What you've described is a bunch of abstract behaviour. > > But as I said, I'm suspecting this is a poor design; and I can't know > better until you explain what all this is *for*. > > What is the purpose of the code you're writing? What is special about it > that makes you think it needs the specific properties you've described? > > I ask all this because I suspect there are better and/or simpler ways to > achieve your *actual* goals. Maybe not; but to rule that out, I'd need > to know more about the purpose. > > Let me try to give an example then. Let's say the existing module provides a class RoboCom() which allows the user to communicate with robots (it doesn't). It handles all the communication hooks to send commands to & receive updates from many kinds of robots. RoboCom has attributes like: send_cmd() receive_cmd() as well as other attributes like robot_name etc which are created when an instance of RoboCom is created. But a RoboCom object doesn't have any attributes specific to the type of robot it will be communicating with. Let's say the robots can be humanoid or canine. A command that can be sent to the humanoid robot might look like: 1. send_cmd("left_leg.knee.raise 1.1") # 1.1 being a height in units of m A command that can be sent to the canine robot might look like: 2. send_cmd("tail.wag 3") # where 3 = number of times to wag. To be able to use RoboCom the user must currently look up the documentation for the kind of robot they want to communicate with which is stored somewhere in a text file and then enter it into the arguments of the RoboCom methods which is a pain. What I want to do is create a RoboCom-like object, specific to the type of robot it will communicate with, which allows the user of that object to discover which commands can & can't be sent to that type of robot. The actual code executed to send the commands should be 1. & 2. above but it would be more convenient to the user if they could type something like: 1A. humanoid_robocom1.left_leg.knee.raise.send(1.1) 2A. canine_robocom1.tail.wag.send(3) Does that help explain things better? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonnojohnson at gmail.com Wed Feb 19 11:11:16 2014 From: jonnojohnson at gmail.com (Jonno) Date: Wed, 19 Feb 2014 10:11:16 -0600 Subject: Help creating new module which inherits existing class from another module. In-Reply-To: <530462a8$0$2788$c3e8da3$76491128@news.astraweb.com> References: <530462a8$0$2788$c3e8da3$76491128@news.astraweb.com> Message-ID: > > > > The idea is that when you have a NewClass instance, calling > "newobject.foo" will automatically call the descriptor's __getmethod__, > passing it the class and instance. That descriptor will create and > populate the FooClass instance, which does the real work. > > Descriptors are how methods, classmethods, staticmethods and properties > work, so they are a fundamental, powerful way of implementing things like > this. > Thanks for the suggestion Steven. Hopefully my last email on the subject helped explain the intention a little better. I'll look into descriptors some more. I had the feeling I needed to use one (or more) of the following: descriptors decorators metaclasses None of which I know much about yet. I will do some reading & test out your suggestion. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From biolord9 at gmail.com Wed Feb 19 11:28:33 2014 From: biolord9 at gmail.com (THRINAXODON OF THRINAXODON) Date: Wed, 19 Feb 2014 08:28:33 -0800 (PST) Subject: NEW STUNNING RESEARCH SHOWS THAT HUMANS HAVE ORIGINS IN THE DEVONIAN Message-ID: =============== >BREAKING NEWS! =============== NEW YORK TIMES, THRINAXODON, OHIO ===================== > THRINAXODON RECENTLY FOUND 3 HUMAN FOSSILS FROM DEVONIAN STRATA FROM GREENLAND, THE EVOLUTIONISTS HAVE NO BONES ABOUT. > ONE EVIL EVOLUTIONIST, BOB CASANOVA HAS ADMITTED THAT HUMAN EVOLUTION IS IN FREE-FALL. > RICHARD LEAKEY HAS DIED FROM A HEART ATTACK DUE TO THIS GROUND-BREAKING FIND THAT CONCLUSIVELY SHOWS THAT HUMANS HAVE ORIGINS IN THE DEVONIAN. > NOW, IF YOU PLEASE, I HAVE TO SUE THE SMITHSONIAN FOR YEARS OF CENSORSHIP. > ====================================== EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# From biolord9 at gmail.com Wed Feb 19 11:29:07 2014 From: biolord9 at gmail.com (THRINAXODON'S CREATION STUDIES) Date: Wed, 19 Feb 2014 08:29:07 -0800 (PST) Subject: NEW RESEARCH DISPROVES EVOLUTION Message-ID: <87fadd89-081d-44f0-b742-686c826eda22@googlegroups.com> =============== >BREAKING NEWS! =============== NEW YORK TIMES, THRINAXODON, OHIO ===================== > THRINAXODON RECENTLY FOUND 3 HUMAN FOSSILS FROM DEVONIAN STRATA FROM GREENLAND, THE EVOLUTIONISTS HAVE NO BONES ABOUT. > ONE EVIL EVOLUTIONIST, BOB CASANOVA HAS ADMITTED THAT HUMAN EVOLUTION IS IN FREE-FALL. > RICHARD LEAKEY HAS DIED FROM A HEART ATTACK DUE TO THIS GROUND-BREAKING FIND THAT CONCLUSIVELY SHOWS THAT HUMANS HAVE ORIGINS IN THE DEVONIAN. > NOW, IF YOU PLEASE, I HAVE TO SUE THE SMITHSONIAN FOR YEARS OF CENSORSHIP. > ====================================== EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# From biolord9 at gmail.com Wed Feb 19 11:29:32 2014 From: biolord9 at gmail.com (biolord9 at gmail.com) Date: Wed, 19 Feb 2014 08:29:32 -0800 (PST) Subject: Help creating new module which inherits existing class from another module. In-Reply-To: References: Message-ID: On Tuesday, February 18, 2014 3:34:51 PM UTC-5, Jonno wrote: > I'm not sure if this list is a suitable place to ask for this kind of help so if it's not please just suggest another forum which might be more suitable. > > > > > I'm looking for help/suggestions how to architect a module (perhaps just a class). > > There is an existing module I want to use which has a class we'll call?Existing Class. > > I want to create a python module which allows me to create?new_objects?with the following properties: > The new_objects have all the attributes of the Existing_Class (simply create a class that inherits from Existing_Class) > I then want to create a nested structure under the new_objects something like: > > new_object.foo > > > new_object.foo.bar > > > new_object.foo.bar.baz > > > Where foo, bar, baz have the following properties: > All have?docstrings > All are available for?tab completion?tools upon new_object creation. > > Some of which will have?new methods?which act in the following way: > > new_object.foo.bar() > > calls > new_object.existing_method("foo.bar", *args) > > > I believe I'll need to use metaclasses and have an idea that types.MethodType will help but I keep getting stuck. Any pointers would be greatly appreciated. =============== >BREAKING NEWS! =============== NEW YORK TIMES, THRINAXODON, OHIO ===================== > THRINAXODON RECENTLY FOUND 3 HUMAN FOSSILS FROM DEVONIAN STRATA FROM GREENLAND, THE EVOLUTIONISTS HAVE NO BONES ABOUT. > ONE EVIL EVOLUTIONIST, BOB CASANOVA HAS ADMITTED THAT HUMAN EVOLUTION IS IN FREE-FALL. > RICHARD LEAKEY HAS DIED FROM A HEART ATTACK DUE TO THIS GROUND-BREAKING FIND THAT CONCLUSIVELY SHOWS THAT HUMANS HAVE ORIGINS IN THE DEVONIAN. > NOW, IF YOU PLEASE, I HAVE TO SUE THE SMITHSONIAN FOR YEARS OF CENSORSHIP. > ====================================== EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# From biolord9 at gmail.com Wed Feb 19 11:30:06 2014 From: biolord9 at gmail.com (THRINAXODON) Date: Wed, 19 Feb 2014 08:30:06 -0800 (PST) Subject: NEW STUNNING RESEARCH DISPROVES EVOLUTIONARY FAIRY-TALES Message-ID: <91b6d247-0c53-4c90-bf44-2818b098f73e@googlegroups.com> =============== >BREAKING NEWS! =============== NEW YORK TIMES, THRINAXODON, OHIO ===================== > THRINAXODON RECENTLY FOUND 3 HUMAN FOSSILS FROM DEVONIAN STRATA FROM GREENLAND, THE EVOLUTIONISTS HAVE NO BONES ABOUT. > ONE EVIL EVOLUTIONIST, BOB CASANOVA HAS ADMITTED THAT HUMAN EVOLUTION IS IN FREE-FALL. > RICHARD LEAKEY HAS DIED FROM A HEART ATTACK DUE TO THIS GROUND-BREAKING FIND THAT CONCLUSIVELY SHOWS THAT HUMANS HAVE ORIGINS IN THE DEVONIAN. > NOW, IF YOU PLEASE, I HAVE TO SUE THE SMITHSONIAN FOR YEARS OF CENSORSHIP. > ====================================== EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# From harrismh777 at gmail.com Wed Feb 19 11:56:53 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Wed, 19 Feb 2014 08:56:53 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> Message-ID: <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> > > Any suggestions? Thanks in advance! > > Switch to Gnu/Linux. Which version of tcl/tk is installed. I would guess that tkinter is honked up somehow... did you clear up the old tkinter stuff? From breamoreboy at yahoo.co.uk Wed Feb 19 12:11:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Feb 2014 17:11:01 +0000 Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> Message-ID: On 19/02/2014 16:56, Mark H. Harris wrote: > >> >> Any suggestions? Thanks in advance! >> > Switch to Gnu/Linux. > > Which version of tcl/tk is installed. I would guess that tkinter is honked up somehow... did you clear up the old tkinter stuff? > The version of tcl/tk is completely irrelevant as it comes bundled in the Python msi installer. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From harrismh777 at gmail.com Wed Feb 19 12:30:11 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Wed, 19 Feb 2014 09:30:11 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> Message-ID: <3b3e6a3c-acd6-40e4-a9a3-f8f6b8b914cc@googlegroups.com> > > The version of tcl/tk is completely irrelevant as it comes bundled in > > the Python msi installer. > Does the previous version put stuff into the registry that keeps the new version from running correctly? From dg.gmane at thesamovar.net Wed Feb 19 12:40:14 2014 From: dg.gmane at thesamovar.net (Dan Goodman) Date: Wed, 19 Feb 2014 17:40:14 +0000 (UTC) Subject: Turning an AST node / subnodes into something human-readable References: Message-ID: Chris Angelico gmail.com> writes: > I'm working with the ast module to do some analysis on Python > codebases, and once I've found what I'm looking for, I want to print > something out. The file name I'm hanging onto externally, so that > works; and the nodes all have a lineno. So far so good. But how do I > "reconstitute" a subtree into something fit for human consumption? I did something like this, feel free to use my code: https://github.com/brian-team/brian2/blob/master/brian2/parsing/rendering.py At the moment, it only works for series of mathematical statements (no control conditions, loops, array notation, etc.), but it would be pretty easy to add those. It also puts too many parentheses in outputted expressions, e.g. 1+2+3 would come back as (1+2)+3, etc. Dan From breamoreboy at yahoo.co.uk Wed Feb 19 12:50:37 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Feb 2014 17:50:37 +0000 Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <3b3e6a3c-acd6-40e4-a9a3-f8f6b8b914cc@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> <3b3e6a3c-acd6-40e4-a9a3-f8f6b8b914cc@googlegroups.com> Message-ID: On 19/02/2014 17:30, Mark H. Harris wrote: > >> >> The version of tcl/tk is completely irrelevant as it comes bundled in >> >> the Python msi installer. >> > > > Does the previous version put stuff into the registry that keeps the new version from running correctly? > Not that I'm aware of. But then again if people knew the answer it would have been posted by now. Where is Terry Reedy when you need him? Or possibly rr for that matter? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From iamalimuhammad at gmail.com Wed Feb 19 13:28:07 2014 From: iamalimuhammad at gmail.com (iamalimuhammad at gmail.com) Date: Wed, 19 Feb 2014 10:28:07 -0800 (PST) Subject: "JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com "JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com "JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com "JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com "JOBS IN PAKISTAN" In-Reply-To: References: Message-ID: On Tuesday, August 4, 2009 3:06:59 PM UTC+5, Riaz Ahmad wrote: > "JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com " > > > JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com " > > > JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com " > > JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com " > > > JOBS IN PAKISTAN" www.pakjobs2008.blogspot.com " for more http://pak.doortojobs.com From tjreedy at udel.edu Wed Feb 19 13:59:02 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Feb 2014 13:59:02 -0500 Subject: extend methods of decimal module In-Reply-To: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> Message-ID: On 2/19/2014 10:30 AM, Mark H. Harris wrote: > Would it be possible to extend the methods of the decimal module just > a bit to include atan(), sin(), cos(), and exp() ? The decimal module implements IEEE 854 > The module has methods for ln() and sqrt(); and that's great! that includes just these. I am not sure if we have an ironclad policy against adding things not in the standard. > By-the-by, my hat is off to the person(s) who did the 3.3 work on the > decimal module --- the performance boost is astounding. Stephen (?) Krah. -- Terry Jan Reedy From bv8bv8bv8 at gmail.com Wed Feb 19 13:55:45 2014 From: bv8bv8bv8 at gmail.com (BV BV) Date: Wed, 19 Feb 2014 10:55:45 -0800 (PST) Subject: A Brief Introduction to Islam Message-ID: <3510ade3-8270-42e0-aeeb-ce36c0df0997@googlegroups.com> A Brief Introduction to Islam A brief introduction to the meaning of Islam, the notion of God in Islam, and His basic message to humanity through the Prophets. http://www.islamhouse.com/426146/en/en/articles/A_Brief_Introduction_to_Islam Thank you From tjreedy at udel.edu Wed Feb 19 14:00:52 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Feb 2014 14:00:52 -0500 Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> <3b3e6a3c-acd6-40e4-a9a3-f8f6b8b914cc@googlegroups.com> Message-ID: On 2/19/2014 12:50 PM, Mark Lawrence wrote: > On 19/02/2014 17:30, Mark H. Harris wrote: >> Does the previous version put stuff into the registry that keeps the >> new version from running correctly? > Not that I'm aware of. But then again if people knew the answer it > would have been posted by now. Where is Terry Reedy when you need him? Puzzled as to what the problem is. -- Terry Jan Reedy From kevingloveruk at gmail.com Wed Feb 19 14:39:54 2014 From: kevingloveruk at gmail.com (Kevin Glover) Date: Wed, 19 Feb 2014 11:39:54 -0800 (PST) Subject: Insert variable into text search string Message-ID: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> These two lines are from a program that carries out a phrase search of Wikipedia and returns the total number of times that the specific phrase occurs. It is essential that the search contains an apostrophe: results = w.search("\"of the cat's\"", type=ALL, start=1, count=1) print results.total I want to replace the word "cat" with a variable, e.g. q = "cat" so that I can generate the same search format for a list of different words. How do I format the search string to include the variable, please? I am using Python 2.7. From python at mrabarnett.plus.com Wed Feb 19 14:46:50 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 19 Feb 2014 19:46:50 +0000 Subject: Insert variable into text search string In-Reply-To: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> References: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> Message-ID: <53050A2A.6000106@mrabarnett.plus.com> On 2014-02-19 19:39, Kevin Glover wrote: > These two lines are from a program that carries out a phrase search of Wikipedia and returns the total number of times that the specific phrase occurs. It is essential that the search contains an apostrophe: > > results = w.search("\"of the cat's\"", type=ALL, start=1, count=1) > print results.total > > I want to replace the word "cat" with a variable, e.g. > > q = "cat" > > so that I can generate the same search format for a list of different words. How do I format the search string to include the variable, please? I am using Python 2.7. > Try string concatenation: results = w.search("\"of the " + q + "'s\"", type=ALL, start=1, count=1) From jpiitula at ling.helsinki.fi Wed Feb 19 14:59:39 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 19 Feb 2014 21:59:39 +0200 Subject: Insert variable into text search string References: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> Message-ID: Kevin Glover writes: > These two lines are from a program that carries out a phrase search > of Wikipedia and returns the total number of times that the specific > phrase occurs. It is essential that the search contains an > apostrophe: > > results = w.search("\"of the cat's\"", type=ALL, start=1, count=1) > print results.total > > I want to replace the word "cat" with a variable, e.g. > > q = "cat" > > so that I can generate the same search format for a list of > different words. How do I format the search string to include the > variable, please? I am using Python 2.7. Format is the right word: look up the .format method of strings. >>> '''"of the {q}'s"'''.format(q='kangaroo') '"of the kangaroo\'s"' That's with Python 2.7.3. An older mechanism uses the percent sign for place holders and as an operator. From kevingloveruk at gmail.com Wed Feb 19 15:15:49 2014 From: kevingloveruk at gmail.com (Kevin Glover) Date: Wed, 19 Feb 2014 12:15:49 -0800 (PST) Subject: Insert variable into text search string In-Reply-To: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> References: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> Message-ID: <6e8fa7a0-f943-4802-aedd-4672ad18c352@googlegroups.com> Thank you both so much. I had tried % but not successfully. From breamoreboy at yahoo.co.uk Wed Feb 19 15:40:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 19 Feb 2014 20:40:02 +0000 Subject: Can I use Python 3 - script on github Message-ID: https://github.com/brettcannon/caniusepython3 may be of interest to some of you fine folks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From harrismh777 at gmail.com Wed Feb 19 16:30:13 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Wed, 19 Feb 2014 13:30:13 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> Message-ID: <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> > > The decimal module implements IEEE 854 > Thanks Terry... ... long time. I would like to find out if there is some iron-clad policy about extending the implementation of an IEEE standard... decimal module in this case; I'm just thinking that this particular extension really fits the python "batteries included" philosophy. I guess what I'm really asking for are the same routines found in "bc -l" math library. I've finally moved my number crunching stuff to python (from bc) because the performance of "decimal" is finally way better than bc for the moment, and wrapping python are the math routines for control and processing is so much better. Anyway, sure would be nice to have a very speedy atan() function built-in for decimal. Thanks for the answer... I hope you enjoy the day! From zachary.ware+pylist at gmail.com Wed Feb 19 16:54:04 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 19 Feb 2014 15:54:04 -0600 Subject: extend methods of decimal module In-Reply-To: <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> Message-ID: On Wed, Feb 19, 2014 at 3:30 PM, Mark H. Harris wrote: >> >> The decimal module implements IEEE 854 >> > > Thanks Terry... ... long time. > > I would like to find out if there is some iron-clad policy about extending > the implementation of an IEEE standard... decimal module in this case; I'm > just thinking that this particular extension really fits the python > "batteries included" philosophy. > > I guess what I'm really asking for are the same routines found in "bc -l" > math library. I've finally moved my number crunching stuff to python (from bc) > because the performance of "decimal" is finally way better than bc for the > moment, and wrapping python are the math routines for control and processing > is so much better. Anyway, sure would be nice to have a very speedy atan() > function built-in for decimal. You might consider suggesting a "decimal.math" module on python-ideas. -- Zach From mircescu.andrei at gmail.com Wed Feb 19 17:03:07 2014 From: mircescu.andrei at gmail.com (Mircescu Andrei) Date: Wed, 19 Feb 2014 14:03:07 -0800 (PST) Subject: Python 2.7 importing pyc files without py files Message-ID: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> Hi, I encountered a strange issue. I have an application which uses extensively python 2.7.6 (CPython). The issue that I see is the following: If there are only pyc files, the loading time of the application is much more than if I have pyc and py files. It is behind with 2 minutes more than if it had py files Do you have any idea why this is happening ? Maybe is because, python tries to search the py file in all the paths and this search is exhaustive ? This is the best guess I could figure it out but I'm not sure. Also, if this is the scenario, there is a way I can stop this, to not search for the py files ? is there an api ? or a compiling flag I should set ? From tjreedy at udel.edu Wed Feb 19 17:10:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Feb 2014 17:10:22 -0500 Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> Message-ID: On 2/19/2014 4:54 PM, Zachary Ware wrote: > On Wed, Feb 19, 2014 at 3:30 PM, Mark H. Harris wrote: >>> >>> The decimal module implements IEEE 854 >>> >> >> Thanks Terry... ... long time. >> >> I would like to find out if there is some iron-clad policy about extending >> the implementation of an IEEE standard... decimal module in this case; I'm >> just thinking that this particular extension really fits the python >> "batteries included" philosophy. >> >> I guess what I'm really asking for are the same routines found in "bc -l" >> math library. I've finally moved my number crunching stuff to python (from bc) >> because the performance of "decimal" is finally way better than bc for the >> moment, and wrapping python are the math routines for control and processing >> is so much better. Anyway, sure would be nice to have a very speedy atan() >> function built-in for decimal. > > You might consider suggesting a "decimal.math" module on python-ideas. Or just dmath. I think this is a better idea than suggesting additions to decimal itself. For one thing, anything put in decimal would be subject to change if the function were to be added to the standard. It is worth noting in such a posting that Krah's speedup make such functions really feasible. The algorithms could be similar, at least initially, to the one used for floats. -- Terry Jan Reedy From emile at fenx.com Wed Feb 19 17:25:41 2014 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Feb 2014 14:25:41 -0800 Subject: Python 2.7 importing pyc files without py files In-Reply-To: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> References: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> Message-ID: On 2/19/2014 2:03 PM, Mircescu Andrei wrote: > If there are only pyc files, the loading time of the application is > much more than if I have pyc and py files. It is behind with 2 > minutes more than if it had py files You may get some clues by starting python as /path/to/python/python2.7 -vv which will provide the details of attempts to import: [root at vsds4 log]# python2.7 -vv # installing zipimport hook import zipimport # builtin # installed zipimport hook # trying /usr/local/lib/python2.7/site.so # trying /usr/local/lib/python2.7/sitemodule.so # trying /usr/local/lib/python2.7/site.py # /usr/local/lib/python2.7/site.pyc matches /usr/local/lib/python2.7/site.py import site # precompiled from /usr/local/lib/python2.7/site.pyc # trying /usr/local/lib/python2.7/os.so # trying /usr/local/lib/python2.7/osmodule.so # trying /usr/local/lib/python2.7/os.py # /usr/local/lib/python2.7/os.pyc matches /usr/local/lib/python2.7/os.py import os # precompiled from /usr/local/lib/python2.7/os.pyc ... HTH, Emile From tjreedy at udel.edu Wed Feb 19 17:26:02 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Feb 2014 17:26:02 -0500 Subject: Python 2.7 importing pyc files without py files In-Reply-To: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> References: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> Message-ID: On 2/19/2014 5:03 PM, Mircescu Andrei wrote: > Hi, > > > I encountered a strange issue. I have an application which uses > extensively python 2.7.6 (CPython). > > > The issue that I see is the following: If there are only pyc files, > the loading time of the application is much more than if I have pyc > and py files. It is behind with 2 minutes more than if it had py > files > > Do you have any idea why this is happening ? Maybe is because, python > tries to search the py file in all the paths and this search is > exhaustive ? This is the best guess I could figure it out but I'm not > sure. It seems plausible. Once .py is found, the .pyc is in the same directory. > Also, if this is the scenario, there is a way I can stop this, to not > search for the py files ? Try reducing sys.path to the minimum needed. -- Terry Jan Reedy From zachary.ware+pylist at gmail.com Wed Feb 19 17:27:49 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 19 Feb 2014 16:27:49 -0600 Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> Message-ID: On Wed, Feb 19, 2014 at 4:10 PM, Terry Reedy wrote: > On 2/19/2014 4:54 PM, Zachary Ware wrote: >> You might consider suggesting a "decimal.math" module on python-ideas. > > > Or just dmath. The name (and location) is of course endlessly bikesheddable :) > I think this is a better idea than suggesting additions to > decimal itself. For one thing, anything put in decimal would be subject to > change if the function were to be added to the standard. It is worth noting > in such a posting that Krah's speedup make such functions really feasible. > The algorithms could be similar, at least initially, to the one used for > floats. It might be good to even go a step further, and make it "amath" (or "numbers.math", or ...), a type-agnostic math module. Such a module would likely be slower than math, cmath, or "dmath", but should end the proliferation of math modules. -- Zach From oscar.j.benjamin at gmail.com Wed Feb 19 17:29:27 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 19 Feb 2014 22:29:27 +0000 Subject: extend methods of decimal module In-Reply-To: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> Message-ID: On 19 February 2014 15:30, Mark H. Harris wrote: > Would it be possible to extend the methods of the decimal module just a bit to include atan(), sin(), cos(), and exp() ? > > The module has methods for ln() and sqrt(); and that's great! > > I have done some rudimentary searching of the pep history and I'm not finding any pep related to extending the decimal module with other scientific functions. As Terry has pointed out, the decimal module follows IEEE 854 which doesn't include those. I think the module sort of has two big use-cases. On the one hand you have people looking to do financial calculations etc. who are looking for basic arithmetic with decimal type rounding. On the other hand you have people like me who see it as a convenient multi-precision library for when double precision just isn't enough. The module doesn't fully live up to my use-case because as you say it lacks support for transcendental functions. I think, though, that there's a case for having say a "dmath" module that would export a similar interface to the math and cmath modules but with functions that work with Decimals in full precision. Someone has already created a pure Python version of this idea here: https://code.google.com/p/dmath/ > It is easy to write them in pure python, of course, but I am interested in having the same performance boost with atan(), sin(), cos(), and exp() as I see with the rest of the decimal module on 3.3/ Is it possible anytime sooner than later? Actually the performance difference isn't as big as you might think. So given the following exponential function: from decimal import Decimal, localcontext e = Decimal('2.7182818284590452353602874713527') def exp(x): ''' >>> print exp(Decimal(1)) 2.718281828459045235360287471 >>> print exp(Decimal(2)) 7.389056098930650227230427461 ''' # Work in slightly higher precision with localcontext() as ctx: ctx.prec += 2 xi, xf = divmod(x, 1) # Use integer exponentiation yi = e ** xi # Now use the Maclaurin series for the fractional part lastyf = -1 yf = 1 n = 0 fact = 1 xfn = 1 while yf != lastyf: lastyf = yf n += 1 fact *= n xfn *= xf yf += xfn / fact # Downgrade precision return yi * yf import doctest doctest.testmod() I get the following timings: $ python3.3 -m timeit -s 'from decimal import Decimal as D; d=D('0.123'); from tmp import exp' 'exp(d)' 10000 loops, best of 3: 32.3 usec per loop $ python3.3 -m timeit -s 'from decimal import Decimal as D; d=D('0.123'); from tmp import exp' 'd.exp()' 10000 loops, best of 3: 26.5 usec per loop So the pure Python exponential function (using the C-accelerated decimal module) weighs in at 32usec and the pure C version at 26usec. The intensity of software arithmetic even in C is still dominating the performance here. The difference becomes more noticeable as you approach an integer value from below e.g. something like 24.9 but not more than a factor of 2. For comparison here's how it looks on the FPU (from Python's perspective): $ python3.3 -m timeit -s 'd=0.123; from math import exp' 'exp(d)' 10000000 loops, best of 3: 0.149 usec per loop So that's 2 orders of magnitude faster. It makes sense if you think about it in terms of CPU instructions: on x87 there are about 5 instructions to call exp in (extended) double precision and takes about 20-30 cycles (with the time dominated by the F2XM1 instruction). The number of integer instructions required to compute the above with the decimal module is massive in comparison. Oscar From eglowstein.h at gmail.com Wed Feb 19 18:24:14 2014 From: eglowstein.h at gmail.com (eglowstein.h at gmail.com) Date: Wed, 19 Feb 2014 15:24:14 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> <3b8279b2-152b-4fdb-b398-0a4f96c468c4@googlegroups.com> <3b3e6a3c-acd6-40e4-a9a3-f8f6b8b914cc@googlegroups.com> Message-ID: <40a84f88-f6b5-4ef6-bf4a-129333909276@googlegroups.com> On Wednesday, February 19, 2014 2:00:52 PM UTC-5, Terry Reedy wrote: > On 2/19/2014 12:50 PM, Mark Lawrence wrote: > > > On 19/02/2014 17:30, Mark H. Harris wrote: > > > > >> Does the previous version put stuff into the registry that keeps the > > >> new version from running correctly? > > > > > Not that I'm aware of. But then again if people knew the answer it > > > would have been posted by now. Where is Terry Reedy when you need him? > > > > Puzzled as to what the problem is. > > > > -- > > Terry Jan Reedy I was extremely careful to remove any last bit of evidence in the registry that *anything* in the c:\python27 and c:\python33 directories ever existed. After the registry was purged of everything and I deleted the directories, I restarted the machine to make sure the registry was read afresh (Windows XP is wacky that way) and then did a reinstall of Python 3.3.3. Before installing anything else, I launched a program by using the 'Edit in Idle' option. Idle comes up, flashes briefly and exits. The console window never appears. If I bring up a command window and go into the lib\idlelib directory and specifically start idle with "python idle.py" or "pythons idle.py", I get Idle, but no command window. Load a file in if launched with 'python', it appears but you can't run it. If you launch with 'pythons', the whole kit & caboodle just exits when you load the file. That might not help, but that's all I saw. Is there someplace not obvious in the registry where any interesting information is kept? From rosuav at gmail.com Wed Feb 19 21:06:21 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 13:06:21 +1100 Subject: Insert variable into text search string In-Reply-To: <6e8fa7a0-f943-4802-aedd-4672ad18c352@googlegroups.com> References: <7a20fe74-e689-4261-b608-73d0f49736f3@googlegroups.com> <6e8fa7a0-f943-4802-aedd-4672ad18c352@googlegroups.com> Message-ID: On Thu, Feb 20, 2014 at 7:15 AM, Kevin Glover wrote: > Thank you both so much. I had tried % but not successfully. To do it with %, just do this: whatever = "cat" results = w.search("\"of the %s's\""%whatever, type=ALL, start=1, count=1) Use either that or .format(), whichever you like - both are fully supported, and they have different strengths. ChrisA From drobinow at gmail.com Wed Feb 19 21:11:08 2014 From: drobinow at gmail.com (David Robinow) Date: Wed, 19 Feb 2014 21:11:08 -0500 Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> Message-ID: On Tue, Feb 18, 2014 at 9:56 AM, wrote: > The next adventure in Python was to install Python 3 into a Windows XP machine. I had a previous 2.7 installation that I uninstalled and carefully removed all traces of from the directory and the registry. It is not necessary to uninstall previous versions of Python. They can live happily together. Not only does it work, it's a supported configuration. That's what the launcher is for. Mucking with the registry is generally inadvisable. It's too easy to make a mistake. If you do decide to uninstall a Python version, do it through the Control Panel. If that results in problems, submit a bug report. > I got the 'python-3.3.3.msi' from Python.org and installed it. From a command window I can run 'python' and I get the Python prompt. I have several Python programs on the machine. If I right click o one, I have the option of 'Edit in IDLE'. If I do that, the disk light blinks briefly, and then nothing. So I went into the \python33\lib\idlelib directory and from a CMD window, ran 'python idle.py'. That loads IDLE. but when I ask IDLE to load a file, it navigates to a FileOpen dialog and then closes everything when I actually open the file. I then tried the same thing but used 'pythonw' instead. Same deal. > > I also saw some other threads here about how Python can get befuddled by firewalls, so I disabled that with no effect. > > Any suggestions? Thanks in advance! I would reinstall Python2.7 and then reinstall Python3.3. That may straighten out your registry. (It may not) Let us know if that works. From ben+python at benfinney.id.au Wed Feb 19 21:34:06 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Feb 2014 13:34:06 +1100 Subject: Help creating new module which inherits existing class from another module. References: <85fvng407b.fsf@benfinney.id.au> <85bny34pql.fsf@benfinney.id.au> Message-ID: <85wqgq342p.fsf@benfinney.id.au> Jonno writes: > Let's say the existing module provides a class RoboCom() which allows > the user to communicate with robots (it doesn't). Well, can you say what it *does* do? These hypotheticals aren't very helpful; I don't know what inferences I'm safe to draw from the made-up situation. What is it you're *actually* trying to allow the user to do? > A command that can be sent to the humanoid robot might look like: > 1. send_cmd("left_leg.knee.raise 1.1") # 1.1 being a height in units of m > A command that can be sent to the canine robot might look like: > 2. send_cmd("tail.wag 3") # where 3 = number of times to wag. So, the robot (except it's not a robot, apparently) is controlled by a textual command API (or is it? is that part true, or just hypothetical?) If you're trying to wrap a command-line based API in an object-oriented API, then you're going to have considerable impedance mismatch between those APIs. Your success will depend on a number of factors, such as: how frequently can the command-line interface be expected to change; how much effective control do you have over the design of the command-line interface; how sane is the command-line interface design; etc. I can't recommend much general advice beyond: don't expect to wrap a command-line interface in an object-oriented interface without greatly distorting one or the other or both. It may be possible to get a modicum of success, but you should not expect it to be satisfactory. Of course, if I knew what you're *actually* trying to program for, I might be able to offer more specific advice. > Does that help explain things better? Not really. It's up to you if you want to be coy about your actual requirements, but the quality of assistance you can expect will be commensurately low. -- \ ?Two paradoxes are better than one; they may even suggest a | `\ solution.? ?Edward Teller | _o__) | Ben Finney From casevh at gmail.com Thu Feb 20 00:11:12 2014 From: casevh at gmail.com (casevh at gmail.com) Date: Wed, 19 Feb 2014 21:11:12 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> Message-ID: <81aa3b17-fcaf-4aea-bef7-429403ac8d27@googlegroups.com> On Wednesday, February 19, 2014 1:30:13 PM UTC-8, Mark H. Harris wrote: > > I guess what I'm really asking for are the same routines found in "bc -l" > math library. I've finally moved my number crunching stuff to python (from > bc) because the performance of "decimal" is finally way better than bc for > the moment, and wrapping python are the math routines for control and > processing is so much better. Anyway, sure would be nice to have a very > speedy atan() function built-in for decimal. > Have you looked at the gmpy2 ( https://code.google.com/p/gmpy/ ) module? It supports all the transcendental function available in the MPFR library. I did a quick performance test of sqrt() and ln() at around 1000 decimal digits. gmpy2 was about ~200 times faster than the corresponding functions in decimal. casevh From dwightdhutto at gmail.com Thu Feb 20 01:06:23 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Wed, 19 Feb 2014 22:06:23 -0800 (PST) Subject: Tanglin With Alpha Message-ID: <11242029-2a26-4bd0-bfa6-fe80fe696876@googlegroups.com> Just as a quick survey...Are individual programmers happier with tangling with the alpha code, or more comfortable with beta versions, or does it matter, dependant on the circumstances? From rosuav at gmail.com Thu Feb 20 01:59:04 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 17:59:04 +1100 Subject: Tanglin With Alpha In-Reply-To: <11242029-2a26-4bd0-bfa6-fe80fe696876@googlegroups.com> References: <11242029-2a26-4bd0-bfa6-fe80fe696876@googlegroups.com> Message-ID: On Thu, Feb 20, 2014 at 5:06 PM, David Hutto wrote: > Just as a quick survey...Are individual programmers happier with tangling with the alpha code, or more comfortable with beta versions, or does it matter, dependant on the circumstances? > Depends on the program, enormously. Or, to put it another way, depends on whether I'm trying to "just get the job done" or am prepared to put in some effort. I run a web and mail and etcetera server. For that, I use Apache, bind9, courier-imap, and a bunch of other programs, all obtained through apt-get. I also am the author of a MUD client, written in Pike. Because of the nature of what I'm doing there, I tend to push the boundaries of the language itself; that means I sometimes find bugs, submit patches, and all that. So currently, I'm running a bleeding-edge Pike that consists of the latest from upstream plus one patch of my own that hasn't yet been accepted... so it's "from __future__ import socket_nodelay" if you like. The price I pay for that is that, sometimes, stuff's broken. I try to import the bittorrent client and boom, it fails because something's half way through being edited in the SSL code and it wouldn't load. That's something I choose to accept with Pike, but I would *not* accept it with, say, gcc. With the C compiler, I expect it to just work. But alpha and beta versions? Almost never. I'm currently running Python 3.4.0b2 on Windows, because I don't have facilities to build Python from source on Windows; on my Linux boxes, I use Python 3.x straight from Mercurial (same as with Pike above), or else whatever I can apt-get. Either I'm prepared to use a development version or I'm not, with very VERY few exceptions (I think I once built a Linux kernel from a development tarball - really no point, I could have done just as well going from git). Ultimately, it comes down to how much work you want to do versus how much trust you want to place in someone else. If you'd rather trust someone else, take a published stable version (especially one that you can get from a stable OS distribution's repository - not only is it convenient to apt-get everything, you can be confident that the Debian Wheezy repo has stuff that's known to work with Debian Wheezy); if you'd rather do the work yourself, build from source, at whatever point you like. ChrisA From nirchernia at gmail.com Thu Feb 20 02:32:43 2014 From: nirchernia at gmail.com (ApathyBear) Date: Wed, 19 Feb 2014 23:32:43 -0800 (PST) Subject: Cannot figure out line of code, also not understanding error Message-ID: I have two questions that come along with the following code: ---------------------------------------------------------------------- from __future__ import print_function def sanitize(time): if '-' in time: splitter = '-' (mins,secs) = time.split(splitter, 1) return (mins+'.'+secs) elif ':' in time: splitter = ':' (mins,secs) = time.split(splitter, 1) return (mins+'.'+secs) else: return time #start class class Athlete: def __init__(self, a_name, a_dob=None, a_times=[]): self.name = a_name self.dob= a_dob self.times = a_times def top3(self): return(sorted(set([sanitize(t) for t in self.times]))[0:3]) #end class def get_coach_data(filename): try: with open(filename) as f: data = f.readline() temp1 = data.strip().split(',') return(Athlete(temp1.pop(0),temp1.pop(0), temp1) except IOError: print ('File error') return (None) james = get_coach_data('james2.txt') print (james.name + "'s fastest times are: " + str(james.top3())) ---------------------------------------------------------------------- This is the original text file data I am working with called james2.txt located on my desktop: James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16 ---------------------------------------------------------------------- 1. What does this line of code mean: return(Athlete(temp1.pop(0),temp1.pop(0), temp1) Is it making an Athlete class? if you can give examples to help explain what this is doing that would be helpful. 2. Why am I getting this error when I try to run the file? PS C:\Users\N\desktop> python gg.py File "gg.py", line 34 except IOError: ^ SyntaxError: invalid syntax PS C:\Users\N\desktop> What syntax is invalid here? From rosuav at gmail.com Thu Feb 20 03:03:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 19:03:36 +1100 Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 6:32 PM, ApathyBear wrote: > 1. What does this line of code mean: > return(Athlete(temp1.pop(0),temp1.pop(0), temp1) > > Is it making an Athlete class? if you can give examples to help explain what this is doing that would be helpful. It's supposed to be calling Athlete() with some arguments. However, due to the extra open parenthesis between the keyword "return" and the rest, it... > 2. Why am I getting this error when I try to run the file? > PS C:\Users\N\desktop> python gg.py > File "gg.py", line 34 > except IOError: > ^ > SyntaxError: invalid syntax > PS C:\Users\N\desktop> ... causes this error, which is detected at the point where a keyword comes in that makes no sense inside the return expression. The solution is to delete the first open parenthesis: return Athlete(temp1.pop(0),temp1.pop(0), temp1) Then you have properly matched parens, and it should carry on happily. Tip: Computers report errors where they find them, which isn't always where the error actually is. But with most modern programming languages, the file is read from top to bottom and left to right, so when a problem is reported, its cause is always *before* it in the file. Never after it. You could make a horrible mess of the file after that "except" and you wouldn't change the error. (Apart from things like text encoding, which are done in a separate pass.) You'll get used to scanning up a line or two from the error to find the real cause. ChrisA From vincent.vandevyvre at swing.be Thu Feb 20 02:56:57 2014 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Thu, 20 Feb 2014 08:56:57 +0100 Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: <5305B549.9060509@swing.be> Le 20/02/2014 08:32, ApathyBear a ?crit : > I have two questions that come along with the following code: > > ---------------------------------------------------------------------- > > from __future__ import print_function > > def sanitize(time): > if '-' in time: > splitter = '-' > (mins,secs) = time.split(splitter, 1) > return (mins+'.'+secs) > elif ':' in time: > splitter = ':' > (mins,secs) = time.split(splitter, 1) > return (mins+'.'+secs) > else: > return time > > > #start class > class Athlete: > def __init__(self, a_name, a_dob=None, a_times=[]): > self.name = a_name > self.dob= a_dob > self.times = a_times > > def top3(self): > return(sorted(set([sanitize(t) for t in self.times]))[0:3]) > #end class > > def get_coach_data(filename): > try: > with open(filename) as f: > data = f.readline() > temp1 = data.strip().split(',') > return(Athlete(temp1.pop(0),temp1.pop(0), temp1) > > except IOError: > print ('File error') > return (None) > > james = get_coach_data('james2.txt') > > print (james.name + "'s fastest times are: " + str(james.top3())) > > > ---------------------------------------------------------------------- > This is the original text file data I am working with called james2.txt located on my desktop: > > James Lee,2002-3-14,2-34,3:21,2.34,2.45,3.01,2:01,2:01,3:10,2-22,2-01,2.01,2:16 > > > > > ---------------------------------------------------------------------- > > > > > > 1. What does this line of code mean: > return(Athlete(temp1.pop(0),temp1.pop(0), temp1) > > Is it making an Athlete class? if you can give examples to help explain what this is doing that would be helpful. > > > > > 2. Why am I getting this error when I try to run the file? > PS C:\Users\N\desktop> python gg.py > File "gg.py", line 34 > except IOError: > ^ > SyntaxError: invalid syntax > PS C:\Users\N\desktop> > > What syntax is invalid here? One parenthesis missing here: return(Athlete(temp1.pop(0),temp1.pop(0), temp1)) -- Vincent V.V. Oqapy . Qarte . PaQager From nirchernia at gmail.com Thu Feb 20 03:26:28 2014 From: nirchernia at gmail.com (ApathyBear) Date: Thu, 20 Feb 2014 00:26:28 -0800 (PST) Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: Thanks for pointing out the missing parenthesis, it makes sense now why there was an error. I suppose my question now is (and forgive my ignorance about classes, this is my first time learning them) why is it calling Athlete with some arguments? In order to make a class object, don't you need to create an instance by assigning a class to something? like: x = Athlete(temp1.pop(0),temp1.pop(0),temp1) can a similar line look like this?: temp1.pop(0) = Athlete(temp1.pop(0),temp1) From rosuav at gmail.com Thu Feb 20 03:54:54 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 19:54:54 +1100 Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 7:26 PM, ApathyBear wrote: > Thanks for pointing out the missing parenthesis, it makes sense now why there was an error. > > I suppose my question now is (and forgive my ignorance about classes, this is my first time learning them) why is it calling Athlete with some arguments? In order to make a class object, don't you need to create an instance by assigning a class to something? > > like: > x = Athlete(temp1.pop(0),temp1.pop(0),temp1) Calling a class will create a new instance of it. [1] What you do with it afterwards is separate. The return statement takes any value and, well, returns it. You can return anything - an Athlete instance, the integer 13423523452, the floating point value NaN, anything at all. > can a similar line look like this?: > temp1.pop(0) = Athlete(temp1.pop(0),temp1) You can't assign to a function call, so no, you can't do that. I recommend you start with the Python tutorial: http://docs.python.org/3/tutorial/index.html ChrisA [1] The class might choose to do something different (when you call bool with some argument, it'll return a pre-existing True or False), but conceptually, you still get back an instance of that class. From gary.herron at islandtraining.com Thu Feb 20 04:04:50 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Thu, 20 Feb 2014 01:04:50 -0800 Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: <5305C532.8090304@islandtraining.com> On 02/20/2014 12:26 AM, ApathyBear wrote: > Thanks for pointing out the missing parenthesis, it makes sense now why there was an error. > > I suppose my question now is (and forgive my ignorance about classes, this is my first time learning them) why is it calling Athlete with some arguments? In order to make a class object, don't you need to create an instance by assigning a class to something? > > like: > x = Athlete(temp1.pop(0),temp1.pop(0),temp1) > > can a similar line look like this?: > temp1.pop(0) = Athlete(temp1.pop(0),temp1) First some notation: You are not creating a class, but rather in instance of a class. The code class Athlete: ... created the class, and now you are ready to create (many?) instances of that class. A call like Athlete(...) will create an instance of that class with whatever parameters you supply. What you do with that instance after it is created is your choice. Assignment is one possibility, but many other operation are also possible: x = Athlete(...) print( Athlete(...) ) Athlete(...)+Athlete(...) # If addition made any sense and was implemented in the class return Athlete(...) ... Gary Herron From nirchernia at gmail.com Thu Feb 20 04:22:31 2014 From: nirchernia at gmail.com (ApathyBear) Date: Thu, 20 Feb 2014 01:22:31 -0800 (PST) Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: On Thursday, February 20, 2014 12:54:54 AM UTC-8, Chris Angelico wrote: >Calling a class will create a new instance of it. [1] What you do with >it afterwards is separate. Okay. So what you are saying is that return(Athlete(temp1.pop(0),temp1.pop(0), temp1)) IS in fact creating an instance of Athlete. My problem with this is that there really is no declaration of 'self' for this instance. Usually when I do something like this. x = Athlete("Henry", "11-15-90", [1,2,3]) I can refer to things of this instance by executing x.name or whatever other attributes the class defined. If I create an instance with no 'self' how does this make any sense? How would I get an attribute for the our instance above? From rosuav at gmail.com Thu Feb 20 04:39:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 20:39:10 +1100 Subject: Commonly-used names in the Python standard library Message-ID: In working on a proposal that might result in the creation of a new keyword, I needed to ascertain what names were used extensively in existing Python code. Out of random curiosity, I asked my script what names were the most commonly used. The script responded with 21854 names and a total of 297164 references, averaging 13-14 refs per name. A good number of names are referenced just once - set and never referenced. They're there for applications to use. That takes out 6217 names. But I'm more interested in the ones that see a lot of use. By far the most common name is 'self', for obvious reasons; after that, it's a fairly steady drop-off. The most popular names in the standard library are... *drumroll* 45298 - self 3750 - os 3744 - name 3166 - i 3140 - s 2685 - value 2648 - a 2451 - len 2348 - c 2331 - sys 2255 - b 2238 - line 2132 - print 2131 - x Few surprises there. The os and sys modules are used extensively, and short variable names are reused frequently. To the print-detractors: That's two thousand uses in the standard library, more than any other single function bar 'len'! (And by the way, this is ignoring any file with /test/ in the name.) I find the pairing of 'name' and 'value' interesting. There are 40% more names than values in Python, apparently. And on that bombshell, as they say on Top Gear, it's time to end! ChrisA From rosuav at gmail.com Thu Feb 20 04:41:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 20:41:37 +1100 Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: On Thu, Feb 20, 2014 at 8:22 PM, ApathyBear wrote: > On Thursday, February 20, 2014 12:54:54 AM UTC-8, Chris Angelico wrote: > >>Calling a class will create a new instance of it. [1] What you do with >>it afterwards is separate. > > Okay. So what you are saying is that return(Athlete(temp1.pop(0),temp1.pop(0), temp1)) IS in fact creating an instance of Athlete. My problem with this is that there really is no declaration of 'self' for this instance. > > > Usually when I do something like this. > x = Athlete("Henry", "11-15-90", [1,2,3]) > I can refer to things of this instance by executing x.name or whatever other attributes the class defined. > > If I create an instance with no 'self' how does this make any sense? How would I get an attribute for the our instance above? Inside a method, including __init__, self refers to the object. Even if you never assign it to anything, that instance exists somewhere, and self can refer to it. It has an identity from the moment it begins to exist - which is before it ever gets the name 'x' pointing to it. You definitely should work through the tutorial I linked you to; it explains Python's object model quite well. ChrisA From nirchernia at gmail.com Thu Feb 20 05:13:52 2014 From: nirchernia at gmail.com (ApathyBear) Date: Thu, 20 Feb 2014 02:13:52 -0800 (PST) Subject: Cannot figure out line of code, also not understanding error In-Reply-To: References: Message-ID: <236baab2-6656-4adf-a864-76dcc7ed2c4c@googlegroups.com> Thank you Chris. And thank you to everyone else. This has tremendously helped me. This google group is definitely the best place for python questions/discussion. PS: Chris, I will be looking at that tutorial now. From marko at pacujo.net Thu Feb 20 05:22:29 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 12:22:29 +0200 Subject: Commonly-used names in the Python standard library References: Message-ID: <87mwhm6q3e.fsf@elektro.pacujo.net> Chris Angelico : > In working on a proposal that might result in the creation of a new > keyword, I'm looking forward to the day when every application can add its own keywords as is customary in Lisp. > I needed to ascertain what names were used extensively in existing > Python code One advantage of Perl is that names and keywords are in separate namespaces so introducing new keywords is easy. Should Python have something like: from py35 import * That way, you could choose between: unless x > 7: return and: py35.unless x > 7: return in case you have already made use of the name "unless" in your program. Marko From rosuav at gmail.com Thu Feb 20 05:43:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 21:43:59 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87mwhm6q3e.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 20, 2014 at 9:22 PM, Marko Rauhamaa wrote: > from py35 import * > > That way, you could choose between: > > unless x > 7: > return > > and: > > py35.unless x > 7: > return > > in case you have already made use of the name "unless" in your program. What about return? Are you allowed to namespace that? And 'from' and 'import' and '*'? In languages with keywords, they're there to signal things to the parser. There are languages that have no keywords at all, like REXX, and their grammars are usually restricted to non-alphabetic tokens (for instance, REXX has & and | instead of "and" and "or"). Python already has most of its important names in either builtins (which can be shadowed) or actual modules, so it's only actual language keywords that can't be reused; and there aren't all that many of those. But more can be created, and it's worth being careful. In this instance, various proposals included "then", "when", "use", and "raises". My script reported the following: 1 instances of the name 'use' 12 instances of the name 'when' and none of either of the others. Granted, the stdlib isn't everything, and isn't even reliably representative, but that supported my gut feeling that keywording 'when' would be likely to trip code up. If you're curious about the full proposal, it's PEP 463, an expression form of the 'except' statement. The latest draft PEP can be found here: https://raw2.github.com/Rosuav/ExceptExpr/master/pep-0463.txt and the official repo (currently out of date, but later on will be the official and maintained version) has it here: http://www.python.org/dev/peps/pep-0463/ ChrisA From marko at pacujo.net Thu Feb 20 06:28:30 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 13:28:30 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> Message-ID: <87eh2y6n1d.fsf@elektro.pacujo.net> Chris Angelico : > On Thu, Feb 20, 2014 at 9:22 PM, Marko Rauhamaa wrote: >> py35.unless x > 7: >> return > > What about return? Are you allowed to namespace that? And 'from' and > 'import' and '*'? Old keywords are guaranteed not to clash with programs. Introducing new keywords runs that risk. Hence, C had to introduce the ugly _Bool keyword. > If you're curious about the full proposal, it's PEP 463, an expression > form of the 'except' statement. The latest draft PEP can be found > here: > > https://raw2.github.com/Rosuav/ExceptExpr/master/pep-0463.txt A coworker pointed out that the gist of the PEP has already been implemented by . Marko From rosuav at gmail.com Thu Feb 20 06:37:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 22:37:20 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87eh2y6n1d.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 20, 2014 at 10:28 PM, Marko Rauhamaa wrote: > A coworker pointed out that the gist of the PEP has already been > implemented by . I love how that's categorized "Topic :: Software Development :: Quality Assurance". It certainly assures _something_ about quality... ChrisA From rosuav at gmail.com Thu Feb 20 06:47:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 22:47:29 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87eh2y6n1d.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 20, 2014 at 10:28 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> On Thu, Feb 20, 2014 at 9:22 PM, Marko Rauhamaa wrote: >>> py35.unless x > 7: >>> return >> >> What about return? Are you allowed to namespace that? And 'from' and >> 'import' and '*'? > > Old keywords are guaranteed not to clash with programs. Introducing new > keywords runs that risk. Hence, C had to introduce the ugly _Bool > keyword. Okay, so what you're saying is that there are three states: Before Python X.Y, the unless keyword simply doesn't exist. (It can't be coded in as a module, so it can't exist until someone implements the code.) >From X.Y, it can be called up by importing it from "pyAB" and used in its namespace. >From A.B onward, it always exists. Python has a facility like this. It doesn't namespace the keywords, but it does let you choose whether to have them or not. In Python 2.5, you could type "from __future__ import with_statement" to turn 'with' into a keyword. After Python 2.6, it's always a keyword. ChrisA From marko at pacujo.net Thu Feb 20 07:09:19 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 14:09:19 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> Message-ID: <87a9dm6l5c.fsf@elektro.pacujo.net> Chris Angelico : > Python has a facility like this. It doesn't namespace the keywords, > but it does let you choose whether to have them or not. In Python 2.5, > you could type "from __future__ import with_statement" to turn 'with' > into a keyword. After Python 2.6, it's always a keyword. That certainly softens the blow but might still cause unnecessary suffering when maintaining/resurrecting legacy Python code. How about blocking the introduction of new keywords for ever except if you specify: from __py35__ import syntax Eventually, every Python module would likely begin with a statement like that, and it would document the assumption more clearly than __future__. Marko From rosuav at gmail.com Thu Feb 20 07:19:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 20 Feb 2014 23:19:25 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87a9dm6l5c.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 20, 2014 at 11:09 PM, Marko Rauhamaa wrote: > How about blocking the introduction of new keywords for ever except if > you specify: > > from __py35__ import syntax > > Eventually, every Python module would likely begin with a statement like > that, and it would document the assumption more clearly than __future__. It's more self-documenting with the __future__ directive, because it says *what* syntax you're importing from the future. And at some point, the new keywords must just become standard. There's no point polluting every Python script forever with these directives, and no point maintaining two branches of code in the interpreter. ChrisA From marwa.kotb at mediu.ws Thu Feb 20 07:30:01 2014 From: marwa.kotb at mediu.ws (Marwa Kotb) Date: Thu, 20 Feb 2014 04:30:01 -0800 (PST) Subject: Al madinah international university opening apply for university colleges Message-ID: <5f112be8-fb88-4f70-93a6-f23490017dd0@googlegroups.com> MR/ Mrs * Al madinah international university which win dependence Malaysian Ministry of Higher Education Malaysia (MOHE) and also winning the adoption of all academic programs and courses, the university that are approved by the Malaysian funds and private academy, which deals with quality control and efficiency Academy, known for short as [MQA ] to congratulate you on the occasion of the new academic February year - 2014 . Its pleasure to tell you that the university opening apply for university colleges. The following colleges : * Faculty of Islamic Sciences * Faculty of languages * Faculty of Computer and Information Technology. *Faculty of education . * Faculty of Finance and Management. *Language center *Faculty of engineering The university offer : * Bachelor degree * Master degree * PHD degree Both online and on campus learning for more information you can visit http://www.mediu.edu.my/ar/admissions/requirments for more information about Bachelor degree http://www.mediu.edu.my/ar/admissions/undergraduateprograms for more information about master degree http://www.mediu.edu.my/ar/admissions/postgraduateprograms Best Regard Al madinah international university //www.mediu.edu.my/ar/ From marko at pacujo.net Thu Feb 20 07:46:35 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 14:46:35 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> Message-ID: <8738je6jf8.fsf@elektro.pacujo.net> Chris Angelico : > On Thu, Feb 20, 2014 at 11:09 PM, Marko Rauhamaa wrote: >> from __py35__ import syntax > > It's more self-documenting with the __future__ directive, because it > says *what* syntax you're importing from the future. As a developer, I will probably want to state the Python dialect that was used to write the module. Each dialect comes with hundreds of features. I don't want to list them individually (even if I could). > And at some point, the new keywords must just become standard. That's an explicit program of destroying backwards-compatibility: a war on legacy code. That may be the Python way, but it's not a necessary strategy. > There's no point polluting every Python script forever with these > directives, and no point maintaining two branches of code in the > interpreter. Two branches? I would imagine there would be dozens of "branches" in the interpreter if the latest interpreter were to support all past Python dialects (as it should, IMO). Marko From rosuav at gmail.com Thu Feb 20 08:34:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 00:34:27 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <8738je6jf8.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> Message-ID: On Thu, Feb 20, 2014 at 11:46 PM, Marko Rauhamaa wrote: >> And at some point, the new keywords must just become standard. > > That's an explicit program of destroying backwards-compatibility: a war > on legacy code. That may be the Python way, but it's not a necessary > strategy. > >> There's no point polluting every Python script forever with these >> directives, and no point maintaining two branches of code in the >> interpreter. > > Two branches? I would imagine there would be dozens of "branches" in the > interpreter if the latest interpreter were to support all past Python > dialects (as it should, IMO). Indeed. If the interpreter were to include every dialect of "old Python", then it would have a lot more than two branches. They would, in fact, increase exponentially with every Python version. Fortunately, there is an alternative. You can specify the version of Python like this: #!/usr/local/bin/python3.4 or any of several other ways. You then choose exactly which versions of Python to have installed, and continue to use them for as long as you wish. There's no reason for the 3.4 interpreter to be able to run code "as if it were" the 3.1 interpreter, when you can just have the 3.1 interpreter itself right there. ChrisA From mircescu.andrei at gmail.com Thu Feb 20 08:36:29 2014 From: mircescu.andrei at gmail.com (Mircescu Andrei) Date: Thu, 20 Feb 2014 05:36:29 -0800 (PST) Subject: Python 2.7 importing pyc files without py files In-Reply-To: References: <8a6aff2d-777a-4f80-8c26-6d1a586e6c5c@googlegroups.com> Message-ID: <8719779c-6ba4-4e72-8bcb-8c5af2864a51@googlegroups.com> joi, 20 februarie 2014, 00:25:41 UTC+2, Emile van Sebille a scris: > On 2/19/2014 2:03 PM, Mircescu Andrei wrote: > > > > > If there are only pyc files, the loading time of the application is > > > much more than if I have pyc and py files. It is behind with 2 > > > minutes more than if it had py files > > > > You may get some clues by starting python as > > > > /path/to/python/python2.7 -vv > > > > which will provide the details of attempts to import: > > > > [root at vsds4 log]# python2.7 -vv > > # installing zipimport hook > > import zipimport # builtin > > # installed zipimport hook > > # trying /usr/local/lib/python2.7/site.so > > # trying /usr/local/lib/python2.7/sitemodule.so > > # trying /usr/local/lib/python2.7/site.py > > # /usr/local/lib/python2.7/site.pyc matches /usr/local/lib/python2.7/site.py > > import site # precompiled from /usr/local/lib/python2.7/site.pyc > > # trying /usr/local/lib/python2.7/os.so > > # trying /usr/local/lib/python2.7/osmodule.so > > # trying /usr/local/lib/python2.7/os.py > > # /usr/local/lib/python2.7/os.pyc matches /usr/local/lib/python2.7/os.py > > import os # precompiled from /usr/local/lib/python2.7/os.pyc > > ... > > > > > > > > HTH, > > > > Emile I cannot start python since i'm embedding it in .net with pythonnet solution. From p at google-groups-2014.dobrogost.net Thu Feb 20 09:27:37 2014 From: p at google-groups-2014.dobrogost.net (Piotr Dobrogost) Date: Thu, 20 Feb 2014 06:27:37 -0800 (PST) Subject: Cross-platform way to get default directory for binary files like console scripts? Message-ID: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> Hi! Is there cross-platform way to get default directory for binary files (console scripts for instance) the same way one can use sys.executable to get path to the Python's interpreter in cross-platform way? Context: There's Python script which runs various tools like pip using subprocess and we would like to make sure we run tools that accompany Python's interpreter used to run this script. Please note that the script may be run from within virtualenv which had not been activated - ./venv/bin/python our_script.py Regards, Piotr Dobrogost From Hobie.Audet at comcast.net Thu Feb 20 09:53:36 2014 From: Hobie.Audet at comcast.net (Hobie Audet) Date: Thu, 20 Feb 2014 09:53:36 -0500 Subject: Error getting REMOTE_USER Environment Variable Message-ID: <3fVJjc71dFz7LjN@mail.python.org> I'm running the Abyss Web Server X1 (v 2.9.0.1) on a Windows XP Home (SP3) system and am using Python 3.3 for a scripting language. I'm having a problem getting the environment variable "REMOTE_USER". Here's the situation: 1. I have created a user under Abyss. The userid is "userxyz".. 2. I have created a directory under htdocs called "Test" and using the Abyss console I have password protected it. 3. In the "Test" directory, there is no "index.html" file but there is an "index.py" file, so that should get executed when I access the "Test" directory. 4. If I start up my web browser and point it to "localhost/Test", I get challenged for user authentication, as I should. 5. I enter the userid ("userxyz") and its password and click the "Log in" button. Authentication succeeds. So far, so good. 6. The "index.py" script is launched. It's only function (so far) is to fetch the "REMOTE_USER" environment variable and echo it back to me. 7. What it echoes back is "userxyzuserxyz". In other words, the REMOTE_USER value is repeated. In case you're interested, here is the entire "index.py" script: import os userid =os.environ["REMOTE_USER"] print("Content-type: text/html") print() print("" + userid + " From ned at nedbatchelder.com Thu Feb 20 10:11:15 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 20 Feb 2014 10:11:15 -0500 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> Message-ID: On 2/20/14 9:27 AM, Piotr Dobrogost wrote: > Hi! > > Is there cross-platform way to get default directory for binary files (console scripts for instance) the same way one can use sys.executable to get path to the Python's interpreter in cross-platform way? > > Context: > There's Python script which runs various tools like pip using subprocess and we would like to make sure we run tools that accompany Python's interpreter used to run this script. Please note that the script may be run from within virtualenv which had not been activated - ./venv/bin/python our_script.py > > > Regards, > Piotr Dobrogost > Hi Piotr, we talked about this briefly in #python this morning. I still don't quite understand why you are averse to activating the virtualenv. It is designed to solve precisely this problem: create an environment that uses the natural OS tools (including PATH) to produce a consistent environment that works the way tools expect. If you don't activate the virtualenv, then you can look for your Python executable using sys.executable, and see if the file you want to run is in that same directory. I have no idea under what conditions that is the right or wrong answer, and I don't know what to do if the file you're looking for isn't in that directory. Perhaps the shorter answer is, look in the Python executable directory, then look in the directories on PATH. -- Ned Batchelder, http://nedbatchelder.com From marko at pacujo.net Thu Feb 20 10:14:32 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 17:14:32 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> Message-ID: <87txbt6ckn.fsf@elektro.pacujo.net> Chris Angelico : > If the interpreter were to include every dialect of "old Python", then > it would have a lot more than two branches. They would, in fact, > increase exponentially with every Python version. It shouldn't be *that bad*; the linux kernel is grappling with the glut of system calls, but they are managing it reasonably well. I don't see why Python, especially at this mature stage, couldn't adopt a similar stance *going forward*. In fact, not every syntax change requires special backwards-compatibility treatment in the compiler. Constructs that used to be illegal might become legal (say, try-except-finally). They don't require any attention. Even new keywords have a very small impact on the parser; it should be a simple matter of enabling dictionary entries. > Fortunately, there is an alternative. You can specify the version of > Python like this: > > #!/usr/local/bin/python3.4 Well, * you won't be finding old Python versions on newer operating system distributions, * even isn't all that extensive and * the program may import modules that were written in different Python dialects. Marko From oscar.j.benjamin at gmail.com Thu Feb 20 10:22:53 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Feb 2014 15:22:53 +0000 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> Message-ID: On 20 February 2014 14:27, Piotr Dobrogost

wrote: > Is there cross-platform way to get default directory for binary files (console scripts for instance) the same way one can use sys.executable to get path to the Python's interpreter in cross-platform way? > > Context: > There's Python script which runs various tools like pip using subprocess and we would like to make sure we run tools that accompany Python's interpreter used to run this script. Please note that the script may be run from within virtualenv which had not been activated - ./venv/bin/python our_script.py I'm not sure if I understand the question. Are you trying to find where a script would go if it had been installed as a result of 'python setup.py install' or 'pip install ...'? If so there are different places it could go depending not only on the system but also how the packages were installed (e.g. --user). You can find the default location in this roundabout way: In [1]: from distutils.command.install import install In [2]: from distutils.dist import Distribution In [3]: c = install(Distribution()) In [4]: c.finalize_ c.finalize_options c.finalize_other c.finalize_unix In [4]: c.finalize_options() In [5]: c.insta c.install_base c.install_headers c.install_lib c.install_path_file c.install_platlib c.install_scripts c.install_usersite c.install_data c.install_layout c.install_libbase c.install_platbase c.install_purelib c.install_userbase In [5]: c.install_scripts Out[5]: '/usr/local/bin' Oscar From nikos.gr33k at gmail.com Thu Feb 20 05:59:43 2014 From: nikos.gr33k at gmail.com (Ferrous Cranus) Date: Thu, 20 Feb 2014 02:59:43 -0800 (PST) Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: ?? ???????, 19 ??????????? 2014 10:45:53 ?.?. UTC+2, ? ??????? Wojciech ?ysiak ??????: > On 19.02.2014 09:14, Sujith S wrote: > > > Hi, > > > > > > I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. > > > > > > Do we have expect available in python as well or need to use some other method ? > > > > Hello, > > If you are looking for a way to connect to your netdevices and then > > execute some shell commands (with output) via ssh then google for > > paramiko module for python. > > > > It works on windows and linux. > > > > -- > > BR, > > Wojtek Hello, What will benefit the OP to go ahead and use paramiko opposed to just use "Putty" or another perhaps even Chrome based ssh client? Is there an advantage to that? From python at mrabarnett.plus.com Thu Feb 20 10:33:58 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 Feb 2014 15:33:58 +0000 Subject: Error getting REMOTE_USER Environment Variable In-Reply-To: <3fVJjc71dFz7LjN@mail.python.org> References: <3fVJjc71dFz7LjN@mail.python.org> Message-ID: <53062066.5030402@mrabarnett.plus.com> On 2014-02-20 14:53, Hobie Audet wrote: > I'm running the Abyss Web Server X1 (v 2.9.0.1) on a Windows XP Home > (SP3) system and am using Python 3.3 for a scripting language. I'm > having a problem getting the environment variable "REMOTE_USER". Here's > the situation: > > 1. I have created a user under Abyss. The userid is "userxyz".. > 2. I have created a directory under htdocs called "Test" and using the > Abyss console I have password protected it. > 3. In the "Test" directory, there is no "index.html" file but there is > an "index.py" file, so that should get executed when I access the "Test" > directory. > 4. If I start up my web browser and point it to "localhost/Test", I get > challenged for user authentication, as I should. > 5. I enter the userid ("userxyz") and its password and click the "Log > in" button. Authentication succeeds. So far, so good. > 6. The "index.py" script is launched. It's only function (so far) is > to fetch the "REMOTE_USER" environment variable and echo it back to me. > 7. What it echoes back is "userxyzuserxyz". In other words, the > REMOTE_USER value is repeated. > > In case you're interested, here is the entire "index.py" script: > > import os > userid =os.environ["REMOTE_USER"] > print("Content-type: text/html") > print() > print("" + userid + " > That's about as simple as anything could be. The fact that the script > is displaying anything at all indicates to me that my Python cgi support > is installed correctly and that the script is being executed correctly. > By why the "REMOTE_USER" value is doubled is beyond my understanding. > Is this a bug in the os package that comes with Python 3.3? Anybody > got a fix for it? > > By the way, if I try to fetch "AUTH_USER", I get the same problem. > > Thanks in advance. > How many other environment variables are doubled? All of them? Does the problem exist when the Python script is run directly, outside Abyss, or in IDLE, for example? From p at google-groups-2014.dobrogost.net Thu Feb 20 10:34:25 2014 From: p at google-groups-2014.dobrogost.net (Piotr Dobrogost) Date: Thu, 20 Feb 2014 07:34:25 -0800 (PST) Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> Message-ID: <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> On Thursday, February 20, 2014 4:22:53 PM UTC+1, Oscar Benjamin wrote: > > I'm not sure if I understand the question. Are you trying to find > where a script would go if it had been installed as a result of > 'python setup.py install' or 'pip install ...'? > Yes. > If so there are > different places it could go depending not only on the system but also > how the packages were installed (e.g. --user). Right. > You can find the default location in this roundabout way: > > (...) > > In [5]: c.install_scripts > Out[5]: '/usr/local/bin' I think this is pretty much what I'm after, thanks. I'm wondering if there's some API to get this info as what you showed is really roundabout way to achieve the goal... Regards, Piotr From ned at nedbatchelder.com Thu Feb 20 10:42:54 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 20 Feb 2014 10:42:54 -0500 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On 2/20/14 10:34 AM, Piotr Dobrogost wrote: > On Thursday, February 20, 2014 4:22:53 PM UTC+1, Oscar Benjamin wrote: >> >> I'm not sure if I understand the question. Are you trying to find >> where a script would go if it had been installed as a result of >> 'python setup.py install' or 'pip install ...'? > >> Yes. > >> If so there are >> different places it could go depending not only on the system but also >> how the packages were installed (e.g. --user). > > Right. > >> You can find the default location in this roundabout way: >> >> (...) >> >> In [5]: c.install_scripts >> Out[5]: '/usr/local/bin' > > I think this is pretty much what I'm after, thanks. > I'm wondering if there's some API to get this info as what you showed is really roundabout way to achieve the goal... As roundabout and advanced as that code is, it doesn't give the right answer for me. It returns None. On my Mac, after activating a virtualenv: Python 2.7.2 (default, Oct 11 2012, 20:14:37) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from distutils.command.install import install >>> from distutils.dist import Distribution >>> c = install(Distribution()) >>> c.install_scripts >>> c.install_scripts is None True >>> sys.executable '/usr/local/virtualenvs/studygroup/bin/python' >>> os.listdir(os.path.dirname(sys.executable)) ['activate', 'activate.csh', 'activate.fish', 'activate_this.py', 'easy_install', 'easy_install-2.7', 'pip', 'pip-2.7', 'python', 'python2', 'python2.7'] >>> -- Ned Batchelder, http://nedbatchelder.com From oscar.j.benjamin at gmail.com Thu Feb 20 10:44:53 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Feb 2014 15:44:53 +0000 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On 20 February 2014 15:34, Piotr Dobrogost

wrote: > On Thursday, February 20, 2014 4:22:53 PM UTC+1, Oscar Benjamin wrote: > >> You can find the default location in this roundabout way: > > I'm wondering if there's some API to get this info as what you showed is really roundabout way to achieve the goal... There may be something that I don't know of. Distutils is generally pretty clunky though if you're not trying to do one of the exact things it was designed to do. Oscar From rosuav at gmail.com Thu Feb 20 10:48:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 02:48:01 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87txbt6ckn.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> <87txbt6ckn.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 21, 2014 at 2:14 AM, Marko Rauhamaa wrote: > * you won't be finding old Python versions on newer operating system > distributions, > > * even isn't all that extensive > and > > * the program may import modules that were written in different Python > dialects. You can always build your own Python, if it really matters... but more likely, if you care about old versions, you actually care about *one specific old version* which your program uses. That's why Red Hat still supports Python 2.4 and, I think, 2.3. You can't randomly pick up 2.2 or 1.5, but if you want 2.4, you can keep on using that for as long as this RHEL is supported. As to importing modules written for other versions... that can be a major problem. Often the new keywords come with new functionality. Take string exceptions, for instance. Say you import a module that was written for a version that still supported them - if it raises a string, you can't catch it. There is a limit to how far the compatibility can be taken. Also, what happens if two modules (one of which might be your script) written for different versions both import some third module? Should they get different versions, based on what version tags they use themselves? Compatibility can't be changed that easily. You either run on the new version, or run on the old. Not both. ChrisA From oscar.j.benjamin at gmail.com Thu Feb 20 10:55:41 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Feb 2014 15:55:41 +0000 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On 20 February 2014 15:42, Ned Batchelder wrote: > > As roundabout and advanced as that code is, it doesn't give the right answer > for me. It returns None. On my Mac, after activating a virtualenv: > > Python 2.7.2 (default, Oct 11 2012, 20:14:37) > [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on > darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from distutils.command.install import install > >>> from distutils.dist import Distribution > >>> c = install(Distribution()) You forgot to call c.finalize_options() here which actually sets all of these attributes. > >>> c.install_scripts > >>> c.install_scripts is None > True Oscar From p at google-groups-2014.dobrogost.net Thu Feb 20 10:55:12 2014 From: p at google-groups-2014.dobrogost.net (Piotr Dobrogost) Date: Thu, 20 Feb 2014 07:55:12 -0800 (PST) Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On Thursday, February 20, 2014 4:42:54 PM UTC+1, Ned Batchelder wrote: > > As roundabout and advanced as that code is, it doesn't give the right > answer for me. It returns None. Indeed. I tried on Linux and got None both inside and outside virtualenv :( Regards, Piotr From gordon at panix.com Thu Feb 20 11:19:03 2014 From: gordon at panix.com (John Gordon) Date: Thu, 20 Feb 2014 16:19:03 +0000 (UTC) Subject: Error getting REMOTE_USER Environment Variable References: Message-ID: In Hobie Audet writes: > 7. What it echoes back is "userxyzuserxyz". In other words, the > REMOTE_USER value is repeated. What username is recorded in the access_log file? > executed correctly. By why the "REMOTE_USER" value is doubled is > beyond my understanding. Is this a bug in the os package that comes > with Python 3.3? Anybody got a fix for it? If there is a bug, it's much more likely to be in the webserver code that sets the REMOTE_USER value. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From kjakupak at gmail.com Thu Feb 20 11:22:00 2014 From: kjakupak at gmail.com (kxjakkk) Date: Thu, 20 Feb 2014 08:22:00 -0800 (PST) Subject: The sum of numbers in a line from a file Message-ID: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Let's say I have a sample file like this: Name 1 2 3 4 5 6 7 8 ------------------------------------------------------------------------ name1 099-66-7871 A-F Y 100 67 81 59 98 name2 999-88-7766 A-F N 99 100 96 91 90 name3 000-00-0110 AUD 5 100 28 19 76 name4 398-72-3333 P/F Y 76 84 49 69 78 name5 909-37-3689 A-F Y 97 94 100 61 79 For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. All I've got is sum([int(s.strip()) for s in open('file').readlines()]) From ned at nedbatchelder.com Thu Feb 20 11:26:31 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 20 Feb 2014 11:26:31 -0500 Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On 2/20/14 10:55 AM, Oscar Benjamin wrote: > On 20 February 2014 15:42, Ned Batchelder wrote: >> >> As roundabout and advanced as that code is, it doesn't give the right answer >> for me. It returns None. On my Mac, after activating a virtualenv: >> >> Python 2.7.2 (default, Oct 11 2012, 20:14:37) >> [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on >> darwin >> Type "help", "copyright", "credits" or "license" for more information. >> >>> from distutils.command.install import install >> >>> from distutils.dist import Distribution >> >>> c = install(Distribution()) > > You forgot to call c.finalize_options() here which actually sets all > of these attributes. > Ah, good! Thanks! -- Ned Batchelder, http://nedbatchelder.com From marko at pacujo.net Thu Feb 20 11:26:00 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 20 Feb 2014 18:26:00 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> <87txbt6ckn.fsf@elektro.pacujo.net> Message-ID: <87mwhl699j.fsf@elektro.pacujo.net> Chris Angelico : > Also, what happens if two modules (one of which might be your script) > written for different versions both import some third module? Should > they get different versions, based on what version tags they use > themselves? Compatibility can't be changed that easily. You either run > on the new version, or run on the old. Not both. Shared C libraries face the exact same issue. Java seems pretty good on this front as well. When there is a will, there is a way. Marko From rosuav at gmail.com Thu Feb 20 11:36:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 03:36:14 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87mwhl699j.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> <87txbt6ckn.fsf@elektro.pacujo.net> <87mwhl699j.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 21, 2014 at 3:26 AM, Marko Rauhamaa wrote: > Chris Angelico : > >> Also, what happens if two modules (one of which might be your script) >> written for different versions both import some third module? Should >> they get different versions, based on what version tags they use >> themselves? Compatibility can't be changed that easily. You either run >> on the new version, or run on the old. Not both. > > Shared C libraries face the exact same issue. Java seems pretty good on > this front as well. When there is a will, there is a way. Shared C libraries usually do it by linking against a particular version. That's why you often need to keep multiple versions around. Once it's all binary code, there's no more compatibility question - it all runs on the same CPU. With Python code, the module's written to run on a particular interpreter, and that can't just switch around - it's like the weird and wonderful life I enjoyed as 32-bit computing started coming along, and I wanted to call on code that used the other word length... ChrisA From patelshivang82 at gmail.com Thu Feb 20 10:28:52 2014 From: patelshivang82 at gmail.com (shivang patel) Date: Thu, 20 Feb 2014 20:58:52 +0530 Subject: Just For Inquiry Message-ID: Hello, Sir I am Shivang Patel and Master of Computer Engineering Student. In this current we are studying one subject name "Principals of management " as part of syllabus. As per this subject, we have one assignment(Because of we all student think, this subject is useless for us) - *Talk with Project manager and ask them about "Role of Project Manager in Organization " * So, I kindly request to you please, give me a very brief info regarding *Role of Project Manager*. Thank u. -- # shivangpatel # http://shivangpatel1.wordpress.com/ # http://mylinuxsys.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Feb 20 11:50:10 2014 From: davea at davea.name (Dave Angel) Date: Thu, 20 Feb 2014 11:50:10 -0500 (EST) Subject: Cannot figure out line of code, also not understanding error References: Message-ID: ApathyBear Wrote in message: > > On Thursday, February 20, 2014 12:54:54 AM UTC-8, Chris Angelico wrote: > >>Calling a class will create a new instance of it. [1] What you do with >>it afterwards is separate. > > Okay. So what you are saying is that return(Athlete(temp1.pop(0),temp1.pop(0), temp1)) IS in fact creating an instance of Athlete. My problem with this is that there really is no declaration of 'self' for this instance. > > > Usually when I do something like this. > x = Athlete("Henry", "11-15-90", [1,2,3]) > I can refer to things of this instance by executing x.name or whatever other attributes the class defined. > > If I create an instance with no 'self' how does this make any sense? How would I get an attribute for the our instance above? > The code you're describing is inside a function: def get_coach_data(filename): try: with open(filename) as f: data = f.readline() temp1 = data.strip().split(',') return Athlete(temp1.pop(0),temp1.pop(0), temp1) So the caller might be doing something like x = get_coach_data ("myfile.txt") The return statement you're asking about returns a new instance of Athlete, which gets assigned to x. Then you may try x.data or equivalent if you like. -- DaveA From joel.goldstick at gmail.com Thu Feb 20 11:49:12 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 20 Feb 2014 11:49:12 -0500 Subject: The sum of numbers in a line from a file Message-ID: On Feb 20, 2014 11:25 AM, "kxjakkk" wrote: > > Let's say I have a sample file like this: > > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. > > All I've got is > sum([int(s.strip()) for s in open('file').readlines()]) > -- Use split() on each line. Do the math > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From gordon at panix.com Thu Feb 20 11:46:38 2014 From: gordon at panix.com (John Gordon) Date: Thu, 20 Feb 2014 16:46:38 +0000 (UTC) Subject: The sum of numbers in a line from a file References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: In <882091da-a499-477e-8f50-c5bdde7cdfec at googlegroups.com> kxjakkk writes: > Let's say I have a sample file like this: > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. > All I've got is > sum([int(s.strip()) for s in open('file').readlines()]) This should get you started. However, this code does not work for all your imput lines, as 'name3' is missing the third field. You'll have to to modify the code to do something smarter than simple space-delimited data. But as I said, it's a start. # open the file with open('file') as fp: # process each line for line in fp.readlines(): # split the line into a list of fields, delimited by spaces fields = line.split() # grab the name name = fields[0] # convert text values to integers and sum them sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) sum2 = int(fields[7]) + int(fields[8]) # compute the averages average1 = sum1 / 3.0 average2 = sum2 / 2.0 # display output print '%s %f %f' % (name, average1, average2) -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From davea at davea.name Thu Feb 20 11:54:09 2014 From: davea at davea.name (Dave Angel) Date: Thu, 20 Feb 2014 11:54:09 -0500 (EST) Subject: The sum of numbers in a line from a file References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: kxjakkk Wrote in message: > Let's say I have a sample file like this: > > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. > > All I've got is > sum([int(s.strip()) for s in open('file').readlines()]) > Don'ttrytodoitallinoneline.thatwayyouactuallymighthaveaplacetoinse rtsomeextralogic. -- DaveA From kjakupak at gmail.com Thu Feb 20 13:16:02 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Thu, 20 Feb 2014 10:16:02 -0800 (PST) Subject: The sum of numbers in a line from a file In-Reply-To: References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> What I've got is def stu_scores(): lines = [] with open("file.txt") as f: lines.extend(f.readlines()) return ("".join(lines[11:])) scores = stu_scores() for line in scores: fields = line.split() name = fields[0] sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) sum2 = int(fields[7]) + int(fields[8]) average1 = sum1 / 3.0 average2 = sum2 / 2.0 print ("%s %f %f %") (name, average1, average2) It says that the list index is out of range on the sum1 line. I need stu_scores because the table from above starts on line 11. From joel.goldstick at gmail.com Thu Feb 20 13:32:49 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 20 Feb 2014 13:32:49 -0500 Subject: The sum of numbers in a line from a file In-Reply-To: <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> Message-ID: On Feb 20, 2014 1:20 PM, wrote: > > What I've got is > def stu_scores(): > lines = [] > with open("file.txt") as f: > lines.extend(f.readlines()) > return ("".join(lines[11:])) > > scores = stu_scores() > for line in scores: > fields = line.split() > name = fields[0] Print fields here to see what's up > sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) > sum2 = int(fields[7]) + int(fields[8]) > average1 = sum1 / 3.0 > average2 = sum2 / 2.0 > print ("%s %f %f %") (name, average1, average2) > > It says that the list index is out of range on the sum1 line. I need stu_scores because the table from above starts on line 11. > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kjakupak at gmail.com Thu Feb 20 13:37:43 2014 From: kjakupak at gmail.com (kjakupak at gmail.com) Date: Thu, 20 Feb 2014 10:37:43 -0800 (PST) Subject: The sum of numbers in a line from a file In-Reply-To: References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> Message-ID: <5dacc2f1-811e-4c30-9873-2f7573a7bb76@googlegroups.com> scores = stu_scores() for line in scores: fields = line.split() name = fields[0] print (fields) Error comes up saying "IndexError: list index out of range." From kwpolska at gmail.com Thu Feb 20 13:56:47 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 20 Feb 2014 19:56:47 +0100 Subject: The sum of numbers in a line from a file In-Reply-To: <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> Message-ID: On Thu, Feb 20, 2014 at 7:16 PM, wrote: > What I've got is > def stu_scores(): > lines = [] > with open("file.txt") as f: > lines.extend(f.readlines()) > return ("".join(lines[11:])) This returns a string, not a list. Moreover, lines.extend() is useless. Replace this with: def stu_scores(): with open("file.txt") as f: lines = f.readlines() return lines[11:] > scores = stu_scores() > for line in scores: `for` operating on strings iterates over each character. > fields = line.split() Splitting one character will turn it into a list containing itself, or nothing if it was whitespace. > name = fields[0] This is not what you want it to be ? it?s only a single letter. > sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) Thus it fails here, because ['n'] has just one item, and not nine. > sum2 = int(fields[7]) + int(fields[8]) > average1 = sum1 / 3.0 > average2 = sum2 / 2.0 > print ("%s %f %f %") (name, average1, average2) > > It says that the list index is out of range on the sum1 line. I need stu_scores because the table from above starts on line 11. > -- > https://mail.python.org/mailman/listinfo/python-list -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From __peter__ at web.de Thu Feb 20 13:59:31 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Feb 2014 19:59:31 +0100 Subject: The sum of numbers in a line from a file References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> <5dacc2f1-811e-4c30-9873-2f7573a7bb76@googlegroups.com> Message-ID: kjakupak at gmail.com wrote: > Error comes up saying "IndexError: list index out of range." OK, then the 12th line starts with a whitespace char. Add more print statements to see the problem: > scores = stu_scores() print scores > for line in scores: print repr(line) > fields = line.split() > name = fields[0] > print (fields) Hint: > def stu_scores(): > lines = [] > with open("file.txt") as f: > lines.extend(f.readlines()) > return ("".join(lines[11:])) Why did you "".join the lines? From python at mrabarnett.plus.com Thu Feb 20 14:17:11 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 Feb 2014 19:17:11 +0000 Subject: The sum of numbers in a line from a file In-Reply-To: <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> <9036049f-7d08-4de7-83f8-61e5fa2c2d2f@googlegroups.com> Message-ID: <530654B7.2090105@mrabarnett.plus.com> On 2014-02-20 18:16, kjakupak at gmail.com wrote: > What I've got is > def stu_scores(): > lines = [] > with open("file.txt") as f: > lines.extend(f.readlines()) > return ("".join(lines[11:])) > > scores = stu_scores() > for line in scores: > fields = line.split() > name = fields[0] > sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) > sum2 = int(fields[7]) + int(fields[8]) > average1 = sum1 / 3.0 > average2 = sum2 / 2.0 > print ("%s %f %f %") (name, average1, average2) > > It says that the list index is out of range on the sum1 line. I need stu_scores because the table from above starts on line 11. > Apart from the other replies, the final print is wrong. It should be: print "%s %f %f" % (name, average1, average2) From travisgriggs at gmail.com Thu Feb 20 17:35:17 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Thu, 20 Feb 2014 14:35:17 -0800 Subject: The sum of numbers in a line from a file In-Reply-To: References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: <119D0714-A042-469E-87B6-5D905D91096C@gmail.com> On Feb 20, 2014, at 8:54 AM, Dave Angel wrote: > kxjakkk Wrote in message: >> Let's say I have a sample file like this: >> >> Name 1 2 3 4 5 6 7 8 >> ------------------------------------------------------------------------ >> name1 099-66-7871 A-F Y 100 67 81 59 98 >> name2 999-88-7766 A-F N 99 100 96 91 90 >> name3 000-00-0110 AUD 5 100 28 19 76 >> name4 398-72-3333 P/F Y 76 84 49 69 78 >> name5 909-37-3689 A-F Y 97 94 100 61 79 >> >> For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. >> >> All I've got is >> sum([int(s.strip()) for s in open('file').readlines()]) >> > > Don'ttrytodoitallinoneline.thatwayyouactuallymighthaveaplacetoinse > rtsomeextralogic. > Yes. Clearly the preferred way to do it is with lots of lines with room for expandability. Sorry Dave, couldn?t resist. Clearly a balance between extremes is desirable. (Mark, I intentionally put the blank lines in this time ) Travis Griggs "?Every institution tends to perish by an excess of its own basic principle.? ? Lord Acton From gordon at panix.com Thu Feb 20 17:48:18 2014 From: gordon at panix.com (John Gordon) Date: Thu, 20 Feb 2014 22:48:18 +0000 (UTC) Subject: Just For Inquiry References: Message-ID: In shivang patel writes: > So, I kindly request to you please, give me a very brief info regarding > *Role of Project Manager*. In my organization, a project manager does these things (and a lot more): Ensure that a requirements document exists, and is approved by both the customer and the developer. Work with developers to create a list of all work steps necessary to complete the project. Create a project schedule from developer estimates for each item on the work list, and update the schedule as needed if additional steps are added or a step takes longer than anticipated. Communicate with customers to keep them informed of the project's progress. Schedule meetings with the customer as needed. Ensure that a test plan exists and is carried out. Coordinate project delivery and installation. Coordinate bug reports and bugfixes. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From swdunning at cox.net Fri Feb 21 00:27:47 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 20 Feb 2014 22:27:47 -0700 Subject: Function and turtle help In-Reply-To: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Message-ID: On Feb 20, 2014, at 9:41 PM, Scott W Dunning wrote: > Hello, > > I am trying to make a function that allows me to color in a star that was drawn in Turtle. I just keep having trouble no matter what I do. I?ll post the code I have for the star (just in case). The ultimate goal is to create a script that?ll draw the American flag (we?re learning this piece by piece in class. So, I need to create a function that will color in the star that I can call multiple times for each star. Any help is greatly appreciated! > > Scott > > from turtle import * > from math import sin, sqrt, radians > > showturtle() > def star(width): > R = (width)/2*sin(radians(72)) > A = (2*width)/(3+sqrt(5)) > penup() > left(18) > penup() > forward(R) > pendown() > > left(162) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > penup() > left(180-18) > penup() > forward(R) > penup() > left(180-18) > pendown() > showturtle() > star(500) I think I?m having trouble with how functions operate. Here is what I have so far for the function to fill in the star with the color red. It?s obviously not working and not sure where I?m going wrong. def fill_color(color): color(red) begin_fill() penup() end_fill() fill_color(red) From swdunning at cox.net Thu Feb 20 23:41:06 2014 From: swdunning at cox.net (Scott W Dunning) Date: Thu, 20 Feb 2014 21:41:06 -0700 Subject: Function and turtle help Message-ID: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Hello, I am trying to make a function that allows me to color in a star that was drawn in Turtle. I just keep having trouble no matter what I do. I?ll post the code I have for the star (just in case). The ultimate goal is to create a script that?ll draw the American flag (we?re learning this piece by piece in class. So, I need to create a function that will color in the star that I can call multiple times for each star. Any help is greatly appreciated! Scott from turtle import * from math import sin, sqrt, radians showturtle() def star(width): R = (width)/2*sin(radians(72)) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(180-18) penup() forward(R) penup() left(180-18) pendown() showturtle() star(500) From wrw at mac.com Thu Feb 20 21:25:56 2014 From: wrw at mac.com (William Ray Wing) Date: Thu, 20 Feb 2014 21:25:56 -0500 Subject: Just For Inquiry In-Reply-To: References: Message-ID: <906F5C42-8302-490B-B06E-1466DDAC15A1@mac.com> On Feb 20, 2014, at 5:48 PM, John Gordon wrote: > In shivang patel writes: > >> So, I kindly request to you please, give me a very brief info regarding >> *Role of Project Manager*. > > In my organization, a project manager does these things (and a lot more): > Ensure that a requirements document exists, and is approved by both the > customer and the developer. > Work with developers to create a list of all work steps necessary to > complete the project. > Create a project schedule from developer estimates for each item on the > work list, and update the schedule as needed if additional steps are added > or a step takes longer than anticipated. > Communicate with customers to keep them informed of the project's progress. > Schedule meetings with the customer as needed. > Ensure that a test plan exists and is carried out. > Coordinate project delivery and installation. > Coordinate bug reports and bugfixes. > > -- > John Gordon Imagine what it must be like for a real medical doctor to > gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. An excellent list, I would add that frequently the project manager has significant budget responsibilities as well. In an informal sense, the project manager is the point person for keeping a project on track, on budget, and completed in a timely fashion. Software engineers, working FOR a project manager, frequently feel that the project manager is providing no added value. This is NOT true. -Bill From davea at davea.name Fri Feb 21 01:30:10 2014 From: davea at davea.name (Dave Angel) Date: Fri, 21 Feb 2014 01:30:10 -0500 (EST) Subject: Function and turtle help References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Message-ID: Scott W Dunning Wrote in message: > Hello, > > I am trying to make a function that allows me to color in a star that was drawn in Turtle. I just keep having trouble no matter what I do. I???ll post the code I have for the star (just in case). The ultimate goal is to create a script that???ll draw the American flag (we???re learning this piece by piece in class. So, I need to create a function that will color in the star that I can call multiple times for each star. Any help is greatly appreciated! > > Scott > > from turtle import * > from math import sin, sqrt, radians > > showturtle() > def star(width): > R = (width)/2*sin(radians(72)) > A = (2*width)/(3+sqrt(5)) > penup() > left(18) > penup() > forward(R) > pendown() > > left(162) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > left(144) > forward(A) > right(72) > forward(A) > > penup() > left(180-18) > penup() > forward(R) > penup() > left(180-18) > pendown() > showturtle() > star(500) > Look at turtle.begin_fill and turtle.end_fill That's after making sure your star is a closed shape. -- DaveA From patil.jay2009 at gmail.com Fri Feb 21 01:31:53 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Thu, 20 Feb 2014 22:31:53 -0800 (PST) Subject: TypeError: can't multiply sequence by non-int of type 'tuple' Message-ID: HI, I have a tuple. I need to make sqaure of elements of tuple and after that i want add all suared tuple elements for total. When i trying to do it, below error came. Code: seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) x2 = [x * x for x in seriesxlist1]; Error: Traceback (most recent call last): File "", line 1, in x2 = [x * x for x in seriesxlist1]; TypeError: can't multiply sequence by non-int of type 'tuple' Please suggest me solution. From rustompmody at gmail.com Fri Feb 21 01:36:54 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 20 Feb 2014 22:36:54 -0800 (PST) Subject: TypeError: can't multiply sequence by non-int of type 'tuple' In-Reply-To: References: Message-ID: <66307663-a47a-48ed-ac1d-1cf4703b9c48@googlegroups.com> On Friday, February 21, 2014 12:01:53 PM UTC+5:30, Jaydeep Patil wrote: > HI, > I have a tuple. I need to make sqaure of elements of tuple and after that i want add all suared tuple elements for total. When i trying to do it, below error came. > Code: > seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) > x2 = [x * x for x in seriesxlist1]; > Error: > Traceback (most recent call last): > x2 = [x * x for x in seriesxlist1]; > TypeError: can't multiply sequence by non-int of type 'tuple' > Please suggest me solution. >>> x2 = [x * x for (x,) in seriesxlist1] >>> x2 [0.0, 0.0001, 0.0004, 0.0009, 0.0016, 0.0025000000000000005, 0.0036, 0.004900000000000001, 0.0064, 0.0081, 0.010000000000000002, 0.0121] >>> 1 Why you are making singleton tuples dunno 2 And no need for semicolons in python From lightaiyee at gmail.com Fri Feb 21 01:37:59 2014 From: lightaiyee at gmail.com (Sam) Date: Thu, 20 Feb 2014 22:37:59 -0800 (PST) Subject: Can global variable be passed into Python function? Message-ID: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> I need to pass a global variable into a python function. However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? How can I get function parameters to be passed by reference in Python? From patil.jay2009 at gmail.com Fri Feb 21 01:41:56 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Thu, 20 Feb 2014 22:41:56 -0800 (PST) Subject: TypeError: can't multiply sequence by non-int of type 'tuple' In-Reply-To: <66307663-a47a-48ed-ac1d-1cf4703b9c48@googlegroups.com> References: <66307663-a47a-48ed-ac1d-1cf4703b9c48@googlegroups.com> Message-ID: On Friday, 21 February 2014 12:06:54 UTC+5:30, Rustom Mody wrote: > On Friday, February 21, 2014 12:01:53 PM UTC+5:30, Jaydeep Patil wrote: > > > HI, > > > > > I have a tuple. I need to make sqaure of elements of tuple and after that i want add all suared tuple elements for total. When i trying to do it, below error came. > > > > > Code: > > > seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) > > > > > x2 = [x * x for x in seriesxlist1]; > > > > > Error: > > > Traceback (most recent call last): > > > x2 = [x * x for x in seriesxlist1]; > > > TypeError: can't multiply sequence by non-int of type 'tuple' > > > > > > > Please suggest me solution. > > > > >>> x2 = [x * x for (x,) in seriesxlist1] > > >>> x2 > > [0.0, 0.0001, 0.0004, 0.0009, 0.0016, 0.0025000000000000005, 0.0036, 0.004900000000000001, 0.0064, 0.0081, 0.010000000000000002, 0.0121] > > >>> > > > > 1 Why you are making singleton tuples dunno > > 2 And no need for semicolons in python Answer: 1. This tupple, i get it from excel range extraction. e.g. seriesxlist = newws.Range(newws.Cells(3,2),newws.Cells(usedRows,2)).Value 2. i removed semicolon, still i am facing same error. I am unable to get multiplies values. Please suggest. I have input as below tuple only. seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) From steve+comp.lang.python at pearwood.info Fri Feb 21 01:43:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 06:43:47 GMT Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> Message-ID: <5306f5a3$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 14:09:19 +0200, Marko Rauhamaa wrote: > Chris Angelico : > >> Python has a facility like this. It doesn't namespace the keywords, but >> it does let you choose whether to have them or not. In Python 2.5, you >> could type "from __future__ import with_statement" to turn 'with' into >> a keyword. After Python 2.6, it's always a keyword. > > That certainly softens the blow but might still cause unnecessary > suffering when maintaining/resurrecting legacy Python code. > > How about blocking the introduction of new keywords for ever except if > you specify: > > from __py35__ import syntax > > Eventually, every Python module would likely begin with a statement like > that, and it would document the assumption more clearly than __future__. What *actual* problem is this supposed to solve? Do you often find that Python has introduced new keywords, breaking your code? -- Steven From patil.jay2009 at gmail.com Fri Feb 21 01:49:01 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Thu, 20 Feb 2014 22:49:01 -0800 (PST) Subject: Remove comma from tuples in python. Message-ID: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> I am getting below tuple from excel. How should i remove extra commas in each tuple to make it easy for operations. tuples is: seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) please suggest me solution. Regards jay From steve+comp.lang.python at pearwood.info Fri Feb 21 01:49:17 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 06:49:17 GMT Subject: Just For Inquiry References: Message-ID: <5306f6ed$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 22:48:18 +0000, John Gordon wrote: > In shivang patel > writes: > >> So, I kindly request to you please, give me a very brief info regarding >> *Role of Project Manager*. > > In my organization, a project manager does these things (and a lot > more): What does this have to do with Python? Please don't encourage people to choose a random, inappropriate newsgroup/ mailing list to ask unrelated questions. Some slack can be given to regulars who raise interesting OT questions, but not drive-by posters. -- Steven From steve+comp.lang.python at pearwood.info Fri Feb 21 01:49:51 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 06:49:51 GMT Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> Message-ID: <5306f70f$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 14:46:35 +0200, Marko Rauhamaa wrote: > I would imagine there would be dozens of "branches" in the interpreter > if the latest interpreter were to support all past Python dialects (as > it should, IMO). Well thank goodness you're not in charge of Python's future development. That way leads to madness: madness for the core developers (if you think maintaining Python 2 and 3 branches is hard imagine maintaining *dozens* of them, *forever*), madness of the programmers using the language, and madness for anyone trying to learn the language. It's hard enough for newbies to deal with *two* dialects, 2 and 3. And you want to introduce dozens. Thanks, but no thanks. -- Steven From steve+comp.lang.python at pearwood.info Fri Feb 21 01:51:21 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 06:51:21 GMT Subject: Commonly-used names in the Python standard library References: Message-ID: <5306f769$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 20:39:10 +1100, Chris Angelico wrote: > In working on a proposal that might result in the creation of a new > keyword, I needed to ascertain what names were used extensively in > existing Python code. I would love to steal^W see your script for doing this :-) -- Steven From steve+comp.lang.python at pearwood.info Fri Feb 21 01:59:41 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 06:59:41 GMT Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> Message-ID: <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 12:22:29 +0200, Marko Rauhamaa wrote: > Chris Angelico : > >> In working on a proposal that might result in the creation of a new >> keyword, > > I'm looking forward to the day when every application can add its own > keywords as is customary in Lisp. And what a wonderful day that will be! Reading any piece of code you didn't write yourself -- or wrote a long time ago -- will be an adventure! Every script will have it's own exciting new set of keywords doing who knows what, which makes every script nearly it's own language! Oh joy, I cannot wait! That's sarcasm, by the way. >> I needed to ascertain what names were used extensively in existing >> Python code > > One advantage of Perl is that names and keywords are in separate > namespaces so introducing new keywords is easy. Then I can write code like: for for in in: while while: if if: raise raise which will go a long way to ensuring that my code is an hostile and unreadable as possible. (Sometimes, less can be more. That's especially true of programming languages.) -- Steven From rosuav at gmail.com Fri Feb 21 02:02:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 18:02:53 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <5306f769$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <5306f769$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Feb 21, 2014 at 5:51 PM, Steven D'Aprano wrote: > On Thu, 20 Feb 2014 20:39:10 +1100, Chris Angelico wrote: > >> In working on a proposal that might result in the creation of a new >> keyword, I needed to ascertain what names were used extensively in >> existing Python code. > > I would love to steal^W see your script for doing this :-) No probs! It's part of my ancillary stuff for the PEP 463 research: https://github.com/Rosuav/ExceptExpr/blob/master/find_except_expr.py It basically just runs over one file at a time, parses it into an AST, and walks the tree. Pretty simple. Actually, some of these sorts of things might make neat examples of what can be done with the ast module. Until this week, I had no idea how easy it was to analyze Python code this way. ChrisA From mircescu.andrei at gmail.com Fri Feb 21 02:02:58 2014 From: mircescu.andrei at gmail.com (Mircescu Andrei) Date: Thu, 20 Feb 2014 23:02:58 -0800 (PST) Subject: Remove comma from tuples in python. In-Reply-To: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> Message-ID: <38442805-6700-4086-9e55-acaa74a42979@googlegroups.com> vineri, 21 februarie 2014, 08:49:01 UTC+2, Jaydeep Patil a scris: > I am getting below tuple from excel. > > How should i remove extra commas in each tuple to make it easy for operations. > > > > tuples is: > > seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) > > > > > > > > please suggest me solution. > > > > > > > > Regards > > jay i think you have a tuple of tuples there. a tuple of 12 tuples. you need to parse each one and represent it as you wish From alec.taylor6 at gmail.com Fri Feb 21 02:07:39 2014 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Fri, 21 Feb 2014 18:07:39 +1100 Subject: Looking for an open-source: Task, feature and issue tracker Message-ID: Dear Python list, Do you know of any open-source task, feature and issue trackers which are built with Python? Preferably with: - git integration ("commits <> and <> solve issue/task <>"; "issue is assigned to repo <>") - prioritisation of tasks, features and issues - ability to show dependencies between tasks, features and issues - milestones; ability to link milestones with git tags; and milestone dependencies - Kanban boards - Scrum (support for multiple sprints, burndown charts and backlogs) If you don't know of any ones written in Python which cover this list; then do you know of ones written in any language with this support? Finally if there are no open-source projects fully covering this feature-set; can you recommend a proprietary offering? Thanks for all suggestions, Alec Taylor From rosuav at gmail.com Fri Feb 21 02:10:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 18:10:20 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Feb 21, 2014 at 5:59 PM, Steven D'Aprano wrote: > Then I can write code like: > > for for in in: > while while: > if if: > raise raise > > which will go a long way to ensuring that my code is an hostile and > unreadable as possible. REXX allows that. Most people wouldn't use classic keywords like 'if', as that'll only cause confusion (although "if if then then; else else" is legal), but some of the other keywords are useful in other contexts. The main advantage is that, for instance, the PARSE command can freely use keywords: PARSE VAR x blah blah PARSE VALUE linein(blah) WITH blah blah All those words (parse, var, value, with) are keywords - in that context. But I can happily use "var" and "value" elsewhere, and will do so. Python, on the other hand, has to be more careful; so you see things like "cls" instead of "class", or "import_" and so on, with the trailing underscore. Trade-offs. ChrisA From stephane at wirtel.be Fri Feb 21 02:11:03 2014 From: stephane at wirtel.be (Stephane Wirtel) Date: Fri, 21 Feb 2014 08:11:03 +0100 Subject: Remove comma from tuples in python. In-Reply-To: <38442805-6700-4086-9e55-acaa74a42979@googlegroups.com> References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <38442805-6700-4086-9e55-acaa74a42979@googlegroups.com> Message-ID: <28A39390-989E-4296-BF9B-0B23A42EBCB5@wirtel.be> This is just a tuple of integers and not a tuple of tuples of integers, the parentheses around the number is just there for the evaluation. > On 21 f?vr. 2014, at 08:02 AM, Mircescu Andrei wrote: > > vineri, 21 februarie 2014, 08:49:01 UTC+2, Jaydeep Patil a scris: >> I am getting below tuple from excel. >> >> How should i remove extra commas in each tuple to make it easy for operations. >> >> >> >> tuples is: >> >> seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) >> >> >> >> >> >> >> >> please suggest me solution. >> >> >> >> >> >> >> >> Regards >> >> jay > > i think you have a tuple of tuples there. a tuple of 12 tuples. > > you need to parse each one and represent it as you wish > -- > https://mail.python.org/mailman/listinfo/python-list From dieter at handshake.de Fri Feb 21 02:23:19 2014 From: dieter at handshake.de (dieter) Date: Fri, 21 Feb 2014 08:23:19 +0100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: <87sird7wuw.fsf@handshake.de> Sam writes: > I need to pass a global variable into a python function. Python does not really have the concept "variable". What appears to be a variable is in fact only the binding of an object to a name. If you assign something to a variable, all you do is binding a different object to the name. Thus, if you have: i = 1 def f(x): x = 5 f(i) Then "i" will remain "1" and not become "5". The effect of "x = 5" is that the name "x" gets bound to "5" (where is formerly was bound to "1"). >However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? Python lacks the notion of "variable". Thus, it does not pass variables into functions but objects. The objects, however, get passed by reference. >How can I get function parameters to be passed by reference in Python? You can implement your own concept of variable, e.g. like this: class Variable(object): def __init__(self, value): self.value = value The little program above then becomes: i = Variable(1) def f(x): x.value = 5 f(i) i.value # this is now 5 From Bernd.Nawothnig at t-online.de Fri Feb 21 02:20:31 2014 From: Bernd.Nawothnig at t-online.de (Bernd Nawothnig) Date: Fri, 21 Feb 2014 08:20:31 +0100 Subject: Remove comma from tuples in python. References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <38442805-6700-4086-9e55-acaa74a42979@googlegroups.com> Message-ID: On 2014-02-21, Mircescu Andrei wrote: > vineri, 21 februarie 2014, 08:49:01 UTC+2, Jaydeep Patil a scris: >> I am getting below tuple from excel. >> >> How should i remove extra commas in each tuple to make it easy for operations. >> >> >> >> tuples is: >> >> seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) > > i think you have a tuple of tuples there. a tuple of 12 tuples. No it isn't: #v+ >>> a = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) >>> a (0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11) #v- The comma makes a tuple, not the parenthesis alone: #v+ >>> a = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) >>> a ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) >>> #v- Bernd -- no time toulouse From marko at pacujo.net Fri Feb 21 02:21:56 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 09:21:56 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87y515dj6z.fsf@elektro.pacujo.net> Steven D'Aprano : > On Thu, 20 Feb 2014 12:22:29 +0200, Marko Rauhamaa wrote: >> I'm looking forward to the day when every application can add its own >> keywords as is customary in Lisp. > > And what a wonderful day that will be! Reading any piece of code you > didn't write yourself -- or wrote a long time ago -- will be an > adventure! Every script will have it's own exciting new set of > keywords doing who knows what, which makes every script nearly it's > own language! Oh joy, I cannot wait! > > That's sarcasm, by the way. I don't hear Lispers or C programmers complaining. Yes, you can shoot yourself in the foot with macro trickery, but macros can greatly enhance code readability and remove the need for code generators. That's why they are used extensively in Linux kernel code and GOOPS (Guile's object system), for example. >> One advantage of Perl is that names and keywords are in separate >> namespaces so introducing new keywords is easy. > > Then I can write code like: > > for for in in: > while while: > if if: > raise raise > > which will go a long way to ensuring that my code is an hostile and > unreadable as possible. Perl does that by forcing you to prefix you variables with $ et al. The analogy would be: for $for in @in: while $while: if $if: raise $raise I'm not saying I like the look of that, but it does have a distinct advantage in introducing new keywords. Marko From __peter__ at web.de Fri Feb 21 02:34:47 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Feb 2014 08:34:47 +0100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: Sam wrote: > I need to pass a global variable into a python function. However, the > global variable does not seem to be assigned after the function ends. Is > it because parameters are not passed by reference? How can I get function > parameters to be passed by reference in Python? If the variable you want to process is always the same global variable you can declare it: >>> x = 0 >>> def inc_x(): ... global x ... x += 1 ... >>> x 0 >>> inc_x() >>> x 1 >>> inc_x(); inc_x() >>> x 3 If you want to change ("rebind") varying global names you have to be explicit: >>> def inc(x): ... return x + 1 ... >>> x = 0 >>> x = inc(x) >>> y = 0 >>> y = inc(y) >>> y = inc(y) >>> x, y (1, 2) Then there are ugly hacks that make your code hard to follow. Don't use these: >>> def inc(name): ... globals()[name] += 1 ... >>> inc("x") >>> inc("x") >>> x 3 >>> def inc(module, name): ... setattr(module, name, getattr(module, name) + 1) ... >>> import __main__ >>> inc(__main__, "x") >>> inc(__main__, "x") >>> inc(__main__, "x") >>> x 6 From flebber.crue at gmail.com Fri Feb 21 02:43:58 2014 From: flebber.crue at gmail.com (flebber) Date: Thu, 20 Feb 2014 23:43:58 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> Message-ID: <4b8be77e-beda-4b34-af85-3a746055c6b4@googlegroups.com> Well firstly being windows I assume that you did a restart after install. Python.org python doesn't come with the windows extensions which can be installed separately. On windows I use winpython is totally portable and can be installed as system version includes all extensions as well as Numpy and matplotlib etc which can be a bit tricky to install otherwise. There is enthought and anaconda packaged python a well but my choice is winpython Give it a try and you'll definitely have a working system version. Sayth From nirchernia at gmail.com Fri Feb 21 02:59:16 2014 From: nirchernia at gmail.com (ApathyBear) Date: Thu, 20 Feb 2014 23:59:16 -0800 (PST) Subject: New to working with APIs, any good tutorials/books/guides? Message-ID: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> I don't understand how APIs work to save my life. I am a complete beginner. In fact, I am a bit confused on what API even means and what the meaning entails. I am fairly competent with python, though I do lack some real world experience. Regardless, any tutorials/books/guides that deal with API for a complete beginner would be awesome. Thanks. PS: Something that can explain SDKs would be helpful as well. From johannes.schneider at galileo-press.de Fri Feb 21 03:16:19 2014 From: johannes.schneider at galileo-press.de (Johannes Schneider) Date: Fri, 21 Feb 2014 09:16:19 +0100 Subject: The sum of numbers in a line from a file In-Reply-To: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: <53070B53.8020603@galileo-press.de> s = 4 e = 7 with f = file('path_to_file) as fp: for line in f: if line.startswith(name): avg = sum(map(int, filter(ambda x : len(x) > 0, s.split(' '))[s : e])) / (e - s) On 20.02.2014 17:22, kxjakkk wrote: > Let's say I have a sample file like this: > > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. > > All I've got is > sum([int(s.strip()) for s in open('file').readlines()]) > -- Johannes Schneider Webentwicklung johannes.schneider at galileo-press.de Tel.: +49.228.42150.xxx Galileo Press GmbH Rheinwerkallee 4 - 53227 Bonn - Germany Tel.: +49.228.42.150.0 (Zentrale) .77 (Fax) http://www.galileo-press.de/ Gesch?ftsf?hrer: Tomas Wehren, Ralf Kaulisch, Rainer Kaltenecker HRB 8363 Amtsgericht Bonn From rosuav at gmail.com Fri Feb 21 03:21:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 19:21:18 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87y515dj6z.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 21, 2014 at 6:21 PM, Marko Rauhamaa wrote: > Steven D'Aprano : > >> On Thu, 20 Feb 2014 12:22:29 +0200, Marko Rauhamaa wrote: >>> I'm looking forward to the day when every application can add its own >>> keywords as is customary in Lisp. >> >> And what a wonderful day that will be! Reading any piece of code you >> didn't write yourself -- or wrote a long time ago -- will be an >> adventure! Every script will have it's own exciting new set of >> keywords doing who knows what, which makes every script nearly it's >> own language! Oh joy, I cannot wait! >> >> That's sarcasm, by the way. > > I don't hear Lispers or C programmers complaining. Yes, you can shoot > yourself in the foot with macro trickery, but macros can greatly enhance > code readability and remove the need for code generators. That's why > they are used extensively in Linux kernel code and GOOPS (Guile's object > system), for example. How does C let you create new keywords? ChrisA From gary.herron at islandtraining.com Fri Feb 21 03:27:24 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Fri, 21 Feb 2014 00:27:24 -0800 Subject: Remove comma from tuples in python. In-Reply-To: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> Message-ID: <53070DEC.7060500@islandtraining.com> On 02/20/2014 10:49 PM, Jaydeep Patil wrote: > I am getting below tuple from excel. > How should i remove extra commas in each tuple to make it easy for operations. > > tuples is: > seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) > > > > please suggest me solution. > > > > Regards > jay There are no extra *commas* there. Perhaps you mean extra *parentheses*? When Python parses that line, the extra parentheses are used to control the evaluation (unnecessarily in this case, as it turns out), and won't be in the final result. >>> seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) >>> seriesxlist1 (0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11) A bit of notation, because I''m not sure we are communicating well here: A tuple is a Python data structure. It has no commas or parentheses. The *printing* of a Python tuple uses both for it's appearance on the output, but the tuple itself has no such thing. Gary Herron From gary.herron at islandtraining.com Fri Feb 21 03:41:59 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Fri, 21 Feb 2014 00:41:59 -0800 Subject: Can global variable be passed into Python function? In-Reply-To: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: <53071157.9050909@islandtraining.com> On 02/20/2014 10:37 PM, Sam wrote: > I need to pass a global variable into a python function. However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? How can I get function parameters to be passed by reference in Python? Are you passing a value *into* a function, or back *out of* the function? These are two very different things, and your question mentions both and seems to confuse them. You can pass any value into a function through its parameters, whether that value comes from a local variable, global variable, or the result of some computation. (But consider: it is the value that is being passed in -- not the variable that contains that value.) You can't pass values back out from a function through assignment to any of the parameters. The global statement is a way to allow a function to assign to a global variable, but this would not be considered "passing" a global into a function. It's just a way to access and assign to a global variable from withing a function. v = 123 def f(...): global v # Now v refers to the global v print(v) # Accesses and prints the global v v = 456 # Assigns to the global v. Gary Herron From steve+comp.lang.python at pearwood.info Fri Feb 21 03:55:12 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 08:55:12 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: <53071470$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 22:37:59 -0800, Sam wrote: > I need to pass a global variable into a python function. However, the > global variable does not seem to be assigned after the function ends. Is > it because parameters are not passed by reference? How can I get > function parameters to be passed by reference in Python? You cannot. Python does not support either pass-by-reference or pass-by- value calling conventions. Instead, it supports the same calling convention as Java, Ruby and other modern languages (which confusingly those two languages both call something different), "call by object sharing". To understand more about Python's calling convention, and why neither call-by-reference nor call-by-value are appropriate, please read these articles: https://mail.python.org/pipermail/tutor/2010-December/080505.html http://effbot.org/zone/call-by-object.htm and also see the Wikipedia article: http://en.wikipedia.org/wiki/Evaluation_strategy If you show us a sample of your code, together of a sample of how you expect it to work, we can suggest an alternate way to solve that problem. -- Steven From jpiitula at ling.helsinki.fi Fri Feb 21 03:55:34 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 21 Feb 2014 10:55:34 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: dieter writes: > Sam writes: > > > I need to pass a global variable into a python function. > > Python does not really have the concept "variable". > > What appears to be a variable is in fact only the binding of an > object to a name. If you assign something to a variable, > all you do is binding a different object to the name. > > Thus, if you have: > > i = 1 > def f(x): x = 5 > > f(i) > > Then "i" will remain "1" and not become "5". > The effect of "x = 5" is that the name "x" gets bound to "5" > (where is formerly was bound to "1"). In alleged contrast, the observable behaviour of languages that "have variables" is the same. This is not considered confusing by the people who insist that there are no variables in Python. Note: I do not object to Python's choice of different preferred terminology. Python seems to be doing fine with that. I do object to the insistence that Python needs this different terminology because it behaves differently from the languages where variables are called variables. Python behaves the same. Here's Java, where I demonstrate with both a class variable i and a local variable j; I used String so that this same demonstration will still serve after someone points out that Java's primite numbers are not quite objects, which is true but irrelevant: $ cat Var.java public class Var { public static String i = "1"; public static String f(String x) { x = "5"; return x; } public static void main(String... args) { String j = "2"; System.out.println("i == " + i + ", j == " + j); System.out.println("f(i) == " + f(i) + ", " + "f(j) == " + f(j)); System.out.println("i == " + i + ", j == " + j); } } $ javac Var.java $ java -cp . Var i == 1, j == 2 f(i) == 5, f(j) == 5 i == 1, j == 2 $ This is C, where I again demonstrate with both a global and a local variable, but here I leave them as ints; I think C might be a language where the word "variable" has been used to mean something like a block of memory, which is a different usage; still, would someone be willing to explain the behaviour of this program by "C lacks variables": $ cat var.c #include int i = 1; int f(int x) { x = 5; return x; } main() { int j = 2; printf("i == %d, j == %d\n", i, j); printf("f(i) == %d, f(j) == %d\n", f(i), f(j)); printf("i == %d, j == %d\n", i, j); } $ gcc -o var var.c $ ./var i == 1, j == 2 f(i) == 5, f(j) == 5 i == 1, j == 2 $ This is Scheme, which is where I come from; its variables behave the same as the corresponding machinery in Python with regard to the problem at hand: $ cat var.scm (define i 1) (define (f x) (set! x 5) x) (let ((j 2)) (display "i == ") (write i) (display ", j == ") (write j) (newline) (display "f(i) == ") (write (f i)) (display ", f(j) == ") (write (f j)) (newline) (display "i == ") (write i) (display ", j == ") (write j) (newline)) $ gsi var.scm i == 1, j == 2 f(i) == 5, f(j) == 5 i == 1, j == 2 $ > > However, the global variable does not seem to be assigned after > > the function ends. Is it because parameters are not passed by > > reference? > > Python lacks the notion of "variable". Thus, it does not > pass variables into functions but objects. > The objects, however, get passed by reference. I think the relevant answer is simply that i and x are different variables. In Python terminology, I think you would have to say that they are different names. With a slight change, you would need to explain how i and i are different names (I think), and then you would introduce the concept of different namespaces. Python indeed does not pass variables (and this is a relevant), but neither do the other languages that "have variables". [snip] From steve+comp.lang.python at pearwood.info Fri Feb 21 04:12:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 09:12:16 GMT Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> Message-ID: <53071870$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 09:21:56 +0200, Marko Rauhamaa wrote: > I don't hear Lispers or C programmers complaining. Lisp is not a popular language. Despite being more powerful, more efficient, and a lot older, I expect that there are far fewer people who know Lisp (let alone use it regularly) than Python. I wouldn't go so far as to say that the Lisp/Scheme family of languages is moribund, but they are certainly niche. And by the way, that niche includes some of the best and brightest developers. (Some of whom are too clever by half, but that's another story.) Merely mediocre programmers don't learn Lisp. So if you take the smartest 0.1% of programmers, and give them a language that lets them chainsaw their leg off, they won't complain, they're just keep their leg out of the way. But if you take the average 50% programmers, and give them a language that lets them chainsaw their leg off, there will be a lot of one-legged programmers. I'm really glad that Lisp exists, but I don't want Python to aspire to be Lisp. In the same way, I am very fond of Forth. Forth too lets you re- define *everything* about the language, including creating new flow- control commands. I love that language. But there is a very good reason why there are a thousand Python coders for every one Forth coder, and it isn't the stack or the reverse Polish notation. As for C, there are a lot of mediocre C programmers writing mediocre C programs filled with buffer overflows, null-pointer bugs and all sorts of other problems. And they don't complain about those either. Because the smart ones know how not to chainsaw their leg off (but even they still make mistakes, which is why there are periodic security vulnerabilities even in code written by people of the calibre of Linus Torvalds and the Linux kernel devs), or have moved to another language and write the bare minimum of code in C only when they really need to. > Yes, you can shoot > yourself in the foot with macro trickery, but macros can greatly enhance > code readability Or greatly destroy it, which is precisely the reason why Python doesn't have a macro system. When Guido van Rossum reads Python code, he wants it to look like Python code, not some arbitrary custom-built language. -- Steven From jpiitula at ling.helsinki.fi Fri Feb 21 04:13:30 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 21 Feb 2014 11:13:30 +0200 Subject: Remove comma from tuples in python. References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> Message-ID: Gary Herron writes: > On 02/20/2014 10:49 PM, Jaydeep Patil wrote: > > I am getting below tuple from excel. > > How should i remove extra commas in each tuple to make it easy for > > operations. > > > > tuples is: > > seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) > > > > please suggest me solution. > > There are no extra *commas* there. Perhaps you mean extra There were extra commas in a previous thread. Jaydeep, Rustom Mody gave you the answer, which you even quoted but apparently failed to notice. Go back and see. That answer was this: >>> seriesxlist1 = ((0.0,), (0.01,), (0.02,)) >>> x2 = [x*x for (x,) in seriesxlist1] I tend to omit those parentheses and use just the comma: >>> x2 = [x*x for x, in seriesxlist1] From thrinaxodons at creationists-crap.studies Fri Feb 21 04:15:45 2014 From: thrinaxodons at creationists-crap.studies (THRINAXODON'S CREATIONIST STUDIES) Date: Fri, 21 Feb 2014 04:15:45 -0500 Subject: NEW GROUND BREAKING STUDIES IN CREATIONIST BULLSHIT: Message-ID: http://www.evolutionnews.org/2014/02/at_first_things_1082371.html , NOW FOR YOUR FAVORITE TIME SLOT: HUMANS HAVE ORIGINS IN THE DEVONIAN: https://groups.google.com/forum/#!topic/alt.atheism.holysmoke/etpGIbTPXz8 -- Thrinaxodon, the ultimate defender of USENET. From steve+comp.lang.python at pearwood.info Fri Feb 21 04:19:52 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Feb 2014 09:19:52 GMT Subject: New to working with APIs, any good tutorials/books/guides? References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> Message-ID: <53071a38$0$29985$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Feb 2014 23:59:16 -0800, ApathyBear wrote: > I don't understand how APIs work to save my life. I am a complete > beginner. In fact, I am a bit confused on what API even means and what > the meaning entails. API stands for "Application Programming Interface", and it essentially means the set of interfaces, calling conventions, functions, methods etc. of a language, library or even a single function. For example, in Python, the API of the len() function is really simple: - len() takes a single mandatory argument; - that argument must be a sequence, mapping, or some other object with a __len__ method; - otherwise len() will raise TypeError; - len() will always return an int; - which is supposed to be the length of the sequence or mapping. That's pretty much the API for the function len(). Simple, isn't it? Now, obviously the API for an entire library is more complicated. It includes rules for how many and what kind of arguments each function, class or method expects; what values they are allowed to be; what sort of values will be returned; what exceptions will be raised, and so forth. Basically, when you read the manual for a language or library, that's documenting the API. That's all there is to it. -- Steven From alister.ware at ntlworld.com Fri Feb 21 04:29:08 2014 From: alister.ware at ntlworld.com (Alister) Date: Fri, 21 Feb 2014 09:29:08 GMT Subject: Remove comma from tuples in python. References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> Message-ID: On Fri, 21 Feb 2014 11:13:30 +0200, Jussi Piitulainen wrote: > Gary Herron writes: > >> On 02/20/2014 10:49 PM, Jaydeep Patil wrote: >> > I am getting below tuple from excel. >> > How should i remove extra commas in each tuple to make it easy for >> > operations. >> > >> > tuples is: >> > seriesxlist1 = ((0.0), (0.01), (0.02), (0.03), (0.04), (0.05), >> > (0.06), (0.07), (0.08), (0.09), (0.1), (0.11)) >> > >> > please suggest me solution. >> >> There are no extra *commas* there. Perhaps you mean extra > > There were extra commas in a previous thread. > > Jaydeep, Rustom Mody gave you the answer, which you even quoted but > apparently failed to notice. Go back and see. > > That answer was this: > > >>> seriesxlist1 = ((0.0,), (0.01,), (0.02,)) > >>> x2 = [x*x for (x,) in seriesxlist1] > > I tend to omit those parentheses and use just the comma: > > >>> x2 = [x*x for x, in seriesxlist1] I had not though of using unpacking in this way & would have written x2= [x[0]**2 for x in serisexlist1] I am not sure which is easier to read in this instance (single element tupple) but unpacking would definitely be the way to go if the tupple had multiple values. -- Q: What do they call the alphabet in Arkansas? A: The impossible dream. From marko at pacujo.net Fri Feb 21 05:10:56 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 12:10:56 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: <87fvnc6aj3.fsf@elektro.pacujo.net> Jussi Piitulainen : > In alleged contrast, the observable behaviour of languages that "have > variables" is the same. This is not considered confusing by the people > who insist that there are no variables in Python. But of course there are variables in Python: By ?frozen? we mean that all local state is retained, including the current bindings of local variables, [...] () The public names defined by a module are determined by checking the module?s namespace for a variable named __all__ () It would be impossible to assign to a global variable without global () etc etc. However, your point about "observable behavior" is key, and Python users of all people should get the principle (as it is related to duck typing). > Python indeed does not pass variables (and this is a relevant), but > neither do the other languages that "have variables". Maybe the idea comes from the fact that you can't easily pass a variable to a function for modification. Consider this C function: void make_printable(const char **ref) { if (!*ref) *ref = ""; } which allows: make_printable(&x); make_printable(&s->name); make_printable(&a[i]); Marko From marko at pacujo.net Fri Feb 21 05:26:48 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 12:26:48 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> Message-ID: <87bny069sn.fsf@elektro.pacujo.net> Chris Angelico : > How does C let you create new keywords? With #define. Nowhere near as elegant (flexible, hygienic) as in Lisp, but used to create new syntax: include/linux/list.h: #define list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) include/linux/wait.h: #define __wait_event_interruptible(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (!signal_pending(current)) { \ schedule(); \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) In the latter example, note how "condition" is embedded in the middle of the macro and evaluated repeatedly. Marko From rosuav at gmail.com Fri Feb 21 05:49:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Feb 2014 21:49:41 +1100 Subject: Commonly-used names in the Python standard library In-Reply-To: <87bny069sn.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> <87bny069sn.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 21, 2014 at 9:26 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> How does C let you create new keywords? > > With #define. Nowhere near as elegant (flexible, hygienic) as in Lisp, > but used to create new syntax: That can't create new syntax, though. All it can do is create a thing that looks like a symbol or a function call and plonks a bit of code in at that point. That's all. It's more akin to creating a function that's able to work with blocks of unexecuted code. ChrisA From davea at davea.name Fri Feb 21 06:28:14 2014 From: davea at davea.name (Dave Angel) Date: Fri, 21 Feb 2014 06:28:14 -0500 (EST) Subject: TypeError: can't multiply sequence by non-int of type 'tuple' References: Message-ID: Jaydeep Patil Wrote in message: > HI, > > I have a tuple. I need to make sqaure of elements of tuple and after that i want add all suared tuple elements for total. When i trying to do it, below error came. > > > Code: > seriesxlist1 = ((0.0,), (0.01,), (0.02,), (0.03,), (0.04,), (0.05,), (0.06,), (0.07,), (0.08,), (0.09,), (0.1,), (0.11,)) > > x2 = [x * x for x in seriesxlist1]; > > Error: > Traceback (most recent call last): > File "", line 1, in > x2 = [x * x for x in seriesxlist1]; > TypeError: can't multiply sequence by non-int of type 'tuple' > The cause of the error is easy enough. (0.0,) * (0.0,) is undefined. It's unclear however what you actually intended because the problem is incompletely specified. Start with python version. I'll assume 3.3. Next show us what result you actually expect. Can we assume all tuples will have a single element in them? Are you looking to flatten both list and tuples, and get a single float sum? Wild guess: x2 = [x[0]* x[0] for x in seriesxlist1]; res = sum (x2) -- DaveA From biolord9 at gmail.com Fri Feb 21 06:24:36 2014 From: biolord9 at gmail.com (THRINAXODON TIMES) Date: Fri, 21 Feb 2014 03:24:36 -0800 (PST) Subject: NEWS FLASH: ATHEISTS DOWN AND BLEEDING AFTER THEIR FAVORITE PET THEORY GOES DOWN THE DRAIN. Message-ID: <53f41e23-e5d0-4d60-bbb8-cb455125b2f8@googlegroups.com> ================== >BREAKING NEWS!!!! ================== > THRINAXODON JUST BEAT RICHARD LEAKEY 100-0 IN WORLD SCIENCE CHAMPIONSHIP. LEAKEY WAS TRYING WITH ALL HIS MIGHT TO PROVE HUMAN'S QUATERNARY ORIGINS, BUT THRINAXODON DEFEATED HIM WITH A FEW HUMAN DEVONIAN FOSSILS. > THE FOSSILS WERE EXACT, SAYS TOP SCIENTIST BOB CASANOVA, WHO EXAMINED THE FOSSILS AND SAW PROOF THAT THESE FOSSILS WERE THE REAL DEAL. > LEAKEY WAS CRYING WHEN THRINAXODON GAINED ONE MILLION DOLLARS FOR HIS CONTRIBUTIONS TO SCIENCE. > ================================= EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER. From davea at davea.name Fri Feb 21 06:49:50 2014 From: davea at davea.name (Dave Angel) Date: Fri, 21 Feb 2014 06:49:50 -0500 (EST) Subject: New to working with APIs, any good tutorials/books/guides? References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> Message-ID: ApathyBear Wrote in message: > I don't understand how APIs work to save my life. I am a complete beginner. In fact, I am a bit confused on what API even means and what the meaning entails. > > I am fairly competent with python, though I do lack some real world experience. Regardless, any tutorials/books/guides that deal with API for a complete beginner would be awesome. > At its most fundamental, the API is the documentation that makes it practical to reuse code you didn't write yourself, or that you wrote longer than 30 days ago. "Application Programmer Interface" describes the functions, the classes, the globals. The semantics, the algorithms, the assumptions, the gotchas. The license, the restrictions. If you inherit a body of code and it doesn't define an API, chances are it's throwaway code, good only for examples. > > > PS: Something that can explain SDKs would be helpful as well. > SDK is "Software Development Kit" Generally it's a bunch of related APIs plus one or more of tools like editor, compiler, interpreter, debugger, profiler, test generator, IDE, source control system, bug tracker, etc. -- DaveA From marko at pacujo.net Fri Feb 21 07:03:26 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 14:03:26 +0200 Subject: Commonly-used names in the Python standard library References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> <87bny069sn.fsf@elektro.pacujo.net> Message-ID: <87txbsekq9.fsf@elektro.pacujo.net> Chris Angelico : > On Fri, Feb 21, 2014 at 9:26 PM, Marko Rauhamaa wrote: >> With #define. Nowhere near as elegant (flexible, hygienic) as in >> Lisp, but used to create new syntax: > > That can't create new syntax, though. All it can do is create a thing > that looks like a symbol or a function call and plonks a bit of code > in at that point. That's all. It's more akin to creating a function > that's able to work with blocks of unexecuted code. Exactly! Lisp functions and macros (including special forms) are closely related. The whole scheme (no pun intended) is so attractive because of the S expression "supersyntax." A "while" macro is syntactically no different from a "while" function. A macro is a "function" whose automatic argument evaluation is disabled; the macro "function" gets the ASTs of the arguments as input. A macro can always simulate a function but not the other way round. With the addition of macros, Python would become a (remote) Lisp dialect. Defining macros would become more complicated because of Python's more complex "supersyntax." Marko From ned at nedbatchelder.com Fri Feb 21 07:13:25 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 21 Feb 2014 07:13:25 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <87sird7wuw.fsf@handshake.de> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> Message-ID: On 2/21/14 2:23 AM, dieter wrote: > Sam writes: > >> >I need to pass a global variable into a python function. > Python does not really have the concept "variable". > > What appears to be a variable is in fact only the binding of an > object to a name. If you assign something to a variable, > all you do is binding a different object to the name. > Man, do I hate this idea that Python has no variables. It has variables (names associated with values, and the values can change over the course of the program), they just don't work the same as C or Fortran variables. In fact, they work exactly the same as Javascript or Ruby variables. Python's variables are names bound to values. http://nedbatchelder.com/text/names.html has lots more details. -- Ned Batchelder, http://nedbatchelder.com From marko at pacujo.net Fri Feb 21 07:52:45 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 14:52:45 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> Message-ID: <87ppmgeig2.fsf@elektro.pacujo.net> Ned Batchelder : > Man, do I hate this idea that Python has no variables. It has > variables (names associated with values, and the values can change > over the course of the program), In classic functional programming, the values of variables can't change but they are still called variables (even though "parameters" might be more fitting). > they just don't work the same as C or Fortran variables. In fact, they > work exactly the same as Javascript or Ruby variables. Apart from a fact that a C variable has an address (references are first-class objects, if you will), I really don't see a difference between a C variable and a Python variable. Marko From python.list at tim.thechases.com Fri Feb 21 09:00:32 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Feb 2014 08:00:32 -0600 Subject: Remove comma from tuples in python. In-Reply-To: References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> Message-ID: <20140221080032.67e536f9@bigbox.christie.dr> On 2014-02-21 09:29, Alister wrote: > > >>> seriesxlist1 = ((0.0,), (0.01,), (0.02,)) > > >>> x2 = [x*x for (x,) in seriesxlist1] > > > > I tend to omit those parentheses and use just the comma: > > > > >>> x2 = [x*x for x, in seriesxlist1] > > I had not though of using unpacking in this way & would have written > > x2= [x[0]**2 for x in serisexlist1] > > I am not sure which is easier to read in this instance (single > element tupple) but unpacking would definitely be the way to go if > the tupple had multiple values. With the single-value tuple, I tend to find the parens make it more readable, so I'd go with [x*x for (x,) in lst] whereas if they were multi-value tuples, I tend to omit the parens: [x*y for x,y in lst] though, tangentially, Python throws a SyntaxError if you try and pass a generator to a function without extra outer parens because it makes parsing them ambiguous otherwise: >>> x = sum(a+b for a, b in lst, 10) File "", line 1 SyntaxError: Generator expression must be parenthesized if not sole argument >>> x = sum((a+b) for a,b in lst), 10) [no error] -tkc From breamoreboy at yahoo.co.uk Fri Feb 21 09:02:33 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 21 Feb 2014 14:02:33 +0000 Subject: Remove comma from tuples in python. In-Reply-To: <53070DEC.7060500@islandtraining.com> References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <53070DEC.7060500@islandtraining.com> Message-ID: On 21/02/2014 08:27, Gary Herron wrote: > > A bit of notation, because I''m not sure we are communicating well here: > A tuple is a Python data structure. It has no commas or > parentheses. The *printing* of a Python tuple uses both for it's > appearance on the output, but the tuple itself has no such thing. > >>> a = 1,2,3 >>> type(a) I see commas and a tuple above but I don't see a print. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Fri Feb 21 09:14:39 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Feb 2014 15:14:39 +0100 Subject: Remove comma from tuples in python. References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <20140221080032.67e536f9@bigbox.christie.dr> Message-ID: Tim Chase wrote: > With the single-value tuple, I tend to find the parens make it more > readable, so I'd go with > > [x*x for (x,) in lst] Hardly ever seen in the wild, but unpacking works with [...], too: >>> items = zip(range(5)) >>> [x*x for [x] in items] [0, 1, 4, 9, 16] From p at google-groups-2014.dobrogost.net Fri Feb 21 09:12:45 2014 From: p at google-groups-2014.dobrogost.net (Piotr Dobrogost) Date: Fri, 21 Feb 2014 06:12:45 -0800 (PST) Subject: Cross-platform way to get default directory for binary files like console scripts? In-Reply-To: <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> References: <405ad1dc-691e-4c71-adfd-c19c599ad555@googlegroups.com> <991f7bda-7313-4192-9e56-410a454b79d8@googlegroups.com> Message-ID: On Thursday, February 20, 2014 4:34:25 PM UTC+1, Piotr Dobrogost wrote: > > I'm wondering if there's some API to get this info as what you showed is really roundabout way to achieve the goal... Turns out there is API for this - see thread on distutils-sig mailing list at https://mail.python.org/pipermail/distutils-sig/2014-February/023867.html Regards, Piotr Dobrogost From roy at panix.com Fri Feb 21 09:32:18 2014 From: roy at panix.com (Roy Smith) Date: Fri, 21 Feb 2014 09:32:18 -0500 Subject: Remove comma from tuples in python. References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <20140221080032.67e536f9@bigbox.christie.dr> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > [x*x for (x,) in lst] > > [paraphrasing...] can be better written as: > > [x*x for [x] in items] I'm torn between, "Yes, the second form is distinctly easier to read" and, "If you think the second form is easier to read, you're admitting you're not really fluent in Python". From travisgriggs at gmail.com Fri Feb 21 12:48:42 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Fri, 21 Feb 2014 09:48:42 -0800 Subject: Remove comma from tuples in python. In-Reply-To: References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <20140221080032.67e536f9@bigbox.christie.dr> Message-ID: <713237AA-4017-45AB-922F-A7121CBE4593@gmail.com> On Feb 21, 2014, at 6:32 AM, Roy Smith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > > >> [x*x for (x,) in lst] >> >> [paraphrasing...] can be better written as: >> >> [x*x for [x] in items] > > I'm torn between, "Yes, the second form is distinctly easier to read" > and, "If you think the second form is easier to read, you're admitting > you're not really fluent in Python?. I?ve used the comma form with struct.unpack() frequently: count, = struct.unpack(?!I?, self.packet) That?s after I don?t use it and end up scratching my head for a while and finally remember that unpack returns a tuple regardless of how many things I unpack from it. It?s just natural if you?re doing lots of single unpacks to think it returns a single value. Either way, I much prefer it to: count = struct.unpack(?!I?, self.packet)[0] From travisgriggs at gmail.com Fri Feb 21 12:59:17 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Fri, 21 Feb 2014 09:59:17 -0800 Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> Message-ID: <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> On Feb 21, 2014, at 4:13 AM, Ned Batchelder wrote: > Man, do I hate this idea that Python has no variables. It has variables (names associated with values, and the values can change over the course of the program), they just don't work the same as C or Fortran variables. In fact, they work exactly the same as Javascript or Ruby variables. Thank you! +11 I get tired of the ?Python doesn?t have variables? line. What makes Python variables/bindings/references/aliases/namedvalues/slots/bucketsofstuff surprising to new arrivals from other language kingdoms, is that accessing is pragmatically implicit (walks the scope tree for you) and assignment may require explicitness. IOW, for some ?variables?, you have to do something explicit to make the variable you want to refer to, vary. Some might say there is a lack of symmetry. Pros and cons. Personally, I don?t care. It?s one of those lessons you just learn as you go. From python.list at tim.thechases.com Fri Feb 21 13:07:00 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 21 Feb 2014 12:07:00 -0600 Subject: Remove comma from tuples in python. In-Reply-To: <713237AA-4017-45AB-922F-A7121CBE4593@gmail.com> References: <8ca893cc-c010-486b-ace3-070ff7ffdac8@googlegroups.com> <20140221080032.67e536f9@bigbox.christie.dr> <713237AA-4017-45AB-922F-A7121CBE4593@gmail.com> Message-ID: <20140221120700.30adebae@bigbox.christie.dr> On 2014-02-21 09:48, Travis Griggs wrote: > I?ve used the comma form with struct.unpack() frequently: > > count, = struct.unpack(?!I?, self.packet) This is *especially* one of those places I want extra parens to make sure I see what's happening. I've been stung too many times by the easy-to-miss nature of just a single comma. -tkc From rosuav at gmail.com Fri Feb 21 13:16:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 05:16:59 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> Message-ID: On Sat, Feb 22, 2014 at 4:59 AM, Travis Griggs wrote: > What makes Python variables/bindings/references/aliases/namedvalues/slots/bucketsofstuff surprising to new arrivals from other language kingdoms, is that accessing is pragmatically implicit (walks the scope tree for you) and assignment may require explicitness. IOW, for some ?variables?, you have to do something explicit to make the variable you want to refer to, vary. Some might say there is a lack of symmetry. Pros and cons. > What you're looking at there, I think, is actually quite tangential to the question of Python having/not having variables, and it's to do with scoping rules. Correct me if I'm wrong. g = "global" c = 0 def f(): print(g) # References two globals l = "local" print(l) # References one global and one local global c c = 1 # References one global As an alternative, Python could have asked us to declare the other way: def f(): print(g) # References two globals local l l = "local" print(l) # References one global and one local c = 1 # References one global It would still be the same name binding / object reference model, with just a different keyword used to change the default behaviour of name lookups. And the difference is comparatively slight. We get an encouragement to use locals rather than globals, but on the flip side, we need two keywords (global/nonlocal) where a single one (local, or as ECMAScript puts it, "var") could handle the other case. It's a lack of symmetry, but having worked with PHP (where you have to declare *every* global, except for the magical superglobals, and except for functions (which are in a completely different namespace), and except for constants), I am very much glad that Python puts everything in together as just "names", and then allows us to reference global names like "print" without declarations. It's a miswart. ChrisA From denismfmcmahon at gmail.com Fri Feb 21 13:35:32 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 21 Feb 2014 18:35:32 +0000 (UTC) Subject: Just For Inquiry References: Message-ID: On Thu, 20 Feb 2014 20:58:52 +0530, shivang patel wrote: > So, I kindly request to you please, give me a very brief info regarding > *Role of Project Manager*. while not project_is_finished(): take_steps_to_advance_project() -- Denis McMahon, denismfmcmahon at gmail.com From rich at noir.com Fri Feb 21 13:58:00 2014 From: rich at noir.com (K Richard Pixley) Date: Fri, 21 Feb 2014 10:58:00 -0800 Subject: property confusion Message-ID: Could someone please explain to me why the two values at the bottom of this example are different? Python-3.3 if it makes any difference. Is this a difference in evaluation between a class attribute and an instance attribute? --rich class C: def __init__(self): self._x = None def getx(self): print('getx') return self._x def setx(self, value): print('setx') self._x = value def delx(self): print('delx') del self._x x = property(getx, setx, delx, "I'm the 'x' property.") class D: def getx(self): print('getx') return self._x def setx(self, value): print('setx') self._x = value def delx(self): print('delx') del self._x def __init__(self): self._x = None self.x = property(self.getx, self.setx, self.delx, "I'm the 'x' property.") type(C().x) type(D().x) From marko at pacujo.net Fri Feb 21 14:20:12 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 21 Feb 2014 21:20:12 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> Message-ID: <87bny0w9w3.fsf@elektro.pacujo.net> On the question of how variables can be passed to functions, C, of course, has the & operator and Pascal has the "var" keyword. An analogous thing can be achieved in Python 3 (but not in Python 2, I'm afraid). The & operator corresponds to an ad hoc property class as in the program below (not intended to be serious). The program demonstrates how to write a universal "swap" function that interchanges two references. Marko ==clip=clip=clip======================================================== #!/usr/bin/env python3 import sys def main(): some_list = [ 'a', 'b', 'c' ] some_dict = { 'few' : 'ding', 'good' : 'dang', 'men' : 'dong' } some_value = 'certainly' class SomeListElementProperty: """&some_list[1]""" def get(self): return some_list[1] def set(self, value): some_list[1] = value class SomeDictEntryProperty: """&some_dict["men"]""" def get(self): return some_dict['men'] def set(self, value): some_dict['men'] = value class SomeValueProperty: """&some_value""" def get(self): return some_value def set(self, value): nonlocal some_value some_value = value swap(SomeListElementProperty(), SomeDictEntryProperty()) swap(SomeListElementProperty(), SomeValueProperty()) sys.stdout.write("{}\n".format(some_list)) sys.stdout.write("{}\n".format(some_dict)) sys.stdout.write("{}\n".format(some_value)) def swap(px, py): x = px.get() y = py.get() px.set(y) py.set(x) if __name__ == '__main__': main() ==clip=clip=clip======================================================== From sg552 at hotmail.co.uk Fri Feb 21 14:33:41 2014 From: sg552 at hotmail.co.uk (Rotwang) Date: Fri, 21 Feb 2014 19:33:41 +0000 Subject: property confusion In-Reply-To: References: Message-ID: On 21/02/2014 18:58, K Richard Pixley wrote: > Could someone please explain to me why the two values at the bottom of > this example are different? > > Python-3.3 if it makes any difference. > > Is this a difference in evaluation between a class attribute and an > instance attribute? Yes, see below. > --rich > > class C: > def __init__(self): > self._x = None > > def getx(self): > print('getx') > return self._x > def setx(self, value): > print('setx') > self._x = value > def delx(self): > print('delx') > del self._x > x = property(getx, setx, delx, "I'm the 'x' property.") > > class D: > def getx(self): > print('getx') > return self._x > def setx(self, value): > print('setx') > self._x = value > def delx(self): > print('delx') > del self._x > > def __init__(self): > self._x = None > self.x = property(self.getx, self.setx, self.delx, "I'm the 'x' > property.") > > type(C().x) > type(D().x) Properties are implemented as descriptors, i.e. objects that have __get__, __set__ and/or __delete__ methods: http://docs.python.org/3/reference/datamodel.html#invoking-descriptors If a is an instance and type(a) has an attribute named 'x' which is a descriptor then a.x is transformed into type(a).__dict__['x'].__get__(a, type(a)); in the case of your code, C.__dict__['x'] is the property you defined, and its __get__ method is just getx. But because of the way attribute lookup works for descriptors, properties don't work as attributes of instances as is the case with D(); D().x just gives you D().__dict__['x'] which is the property itself. From ethan at stoneleaf.us Fri Feb 21 14:16:55 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 21 Feb 2014 11:16:55 -0800 Subject: Commonly-used names in the Python standard library In-Reply-To: <87txbsekq9.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <5306f95d$0$29985$c3e8da3$5496439d@news.astraweb.com> <87y515dj6z.fsf@elektro.pacujo.net> <87bny069sn.fsf@elektro.pacujo.net> <87txbsekq9.fsf@elektro.pacujo.net> Message-ID: <5307A627.5010106@stoneleaf.us> On 02/21/2014 04:03 AM, Marko Rauhamaa wrote: > > With the addition of macros, Python would become a (remote) Lisp > dialect. Defining macros would become more complicated because of > Python's more complex "supersyntax." Have you tried MacroPy? If not, you should. If so, what were its failings? -- ~Ethan~ From nirchernia at gmail.com Fri Feb 21 15:12:00 2014 From: nirchernia at gmail.com (ApathyBear) Date: Fri, 21 Feb 2014 12:12:00 -0800 (PST) Subject: New to working with APIs, any good tutorials/books/guides? In-Reply-To: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> Message-ID: <3fa5e368-a47c-4a7e-80dc-c5333fb5603e@googlegroups.com> Thanks, I think I have an understanding of what they are, but now am still a little confused on how one goes about using it: how am I supposed to know how to use an API in python? or in any other language for that matter? If an API is defining rules in C, is all hope lost for trying to use it in python? Examples?? From joel.goldstick at gmail.com Fri Feb 21 15:21:34 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 21 Feb 2014 15:21:34 -0500 Subject: New to working with APIs, any good tutorials/books/guides? In-Reply-To: <3fa5e368-a47c-4a7e-80dc-c5333fb5603e@googlegroups.com> References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> <3fa5e368-a47c-4a7e-80dc-c5333fb5603e@googlegroups.com> Message-ID: On Feb 21, 2014 3:15 PM, "ApathyBear" wrote: > > Thanks, I think I have an understanding of what they are, but now am still a little confused on how one goes about using it: how am I supposed to know how to use an API in python? or in any other language for that matter? If an API is defining rules in C, is all hope lost for trying to use it in python? > > Examples?? Google to find some sport that interest you. Read the docs and tutorial > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From dihedral88888 at gmail.com Fri Feb 21 15:57:40 2014 From: dihedral88888 at gmail.com (88888 Dihedral) Date: Fri, 21 Feb 2014 12:57:40 -0800 (PST) Subject: Commonly-used names in the Python standard library In-Reply-To: <87mwhl699j.fsf@elektro.pacujo.net> References: <87mwhm6q3e.fsf@elektro.pacujo.net> <87eh2y6n1d.fsf@elektro.pacujo.net> <87a9dm6l5c.fsf@elektro.pacujo.net> <8738je6jf8.fsf@elektro.pacujo.net> <87txbt6ckn.fsf@elektro.pacujo.net> <87mwhl699j.fsf@elektro.pacujo.net> Message-ID: <214ede46-fd8e-4c05-9083-8bb9f7a9ed20@googlegroups.com> On Friday, February 21, 2014 12:26:00 AM UTC+8, Marko Rauhamaa wrote: > Chris Angelico : > > > > > Also, what happens if two modules (one of which might be your script) > > > written for different versions both import some third module? Should > > > they get different versions, based on what version tags they use > > > themselves? Compatibility can't be changed that easily. You either run > > > on the new version, or run on the old. Not both. > > > > Shared C libraries face the exact same issue. Java seems pretty good on > > this front as well. When there is a will, there is a way. > > > > > > Marko Well, please check jython first under OS Andrioids( LINUX+JAVA-XWIN). The mobile phone SW applications are getting hoter and hoter these days. From usanovdd at gmail.com Fri Feb 21 15:59:11 2014 From: usanovdd at gmail.com (Denis Usanov) Date: Fri, 21 Feb 2014 12:59:11 -0800 (PST) Subject: Storing the state of script between steps Message-ID: Good evening. First of all I would like to apologize for the name of topic. I really didn't know how to name it more correctly. I mostly develop on Python some automation scripts such as deployment (it's not about fabric and may be not ssh at all), testing something, etc. In this terms I have such abstraction as "step". Some code: class IStep(object): def run(): raise NotImplementedError() And the certain steps: class DeployStep: ... class ValidateUSBFlash: ... class SwitchVersionS: ... Where I implement run method. Then I use some "builder" class which can add steps to internal list and has a method "start" running all step one by one. And I like this. It's loosely coupled system. It works fine in simple cases. But sometimes some steps have to use the results from previous steps. And now I have problems. Before now I had internal dict in "builder" and named it as "world" and passed it to each run() methods of steps. It worked but I disliked this. How would you solve this problem and how would you do it? I understant that it's more architecture specific question, not a python one. I bet I wouldn't have asked this if I had worked with some of functional programming languages. From rsw at therandymon.com Fri Feb 21 16:02:44 2014 From: rsw at therandymon.com (RS Wood) Date: Fri, 21 Feb 2014 21:02:44 +0000 (UTC) Subject: new life at comp.misc Message-ID: If you weren't already aware, a bunch of people who usually read slashdot.org got frustrated and went back to Usenet, partly because of the new slashdot beta interface Dice Media is imposing, partly because we all suddenly remembered how much we love Usenet. We all landed at comp.misc. If you love Usenet and want to contribute to a community of people posting and commenting on tech stories, please come join us. A bit off topic, but I figure there are a fair number of techies here at comp.lang.python. From ineedsolutionsbook at gmail.com Fri Feb 21 16:13:57 2014 From: ineedsolutionsbook at gmail.com (ineedsolutionsbook at gmail.com) Date: Fri, 21 Feb 2014 13:13:57 -0800 (PST) Subject: solutions manual and test banks Message-ID: ineedsolutionsbook(at)hotmail.com i n e e d s o l u t i o n s b o o k @ h o t m a i l . c o m We're a team found for providing solution manuals to help students in their study. We sell the books in a soft copy, PDF format. We will do our best to find any book or solution manual for you. Before purchase, we will give you a full details and sample of solution manual you want Just email us: i n e e d s o l u t i o n s b o o k @ h o t m a i l . c o m List of some books we have ============================= A Course in Modern Mathematical Physics by Peter Szekeres A First Course in Abstract Algebra by John B. Fraleigh A first course in probability 6th edition by Ross A First Course in String Theory by Barton Zwiebach A Practical Introduction to Data Structures and Algorithm Analysis 2nd edition by Clifford A. Shaffer A Quantum Approach to Condensed Matter Physics by Philip L. Taylor A Short Introduction to Quantum Information and Quantum Computation by Michel Le Bellac Accompany Digital Systems Principles and Applications 10th edition by Ronald J. Tocci, Neal S. Widmer, Gregory L. Moss Accompany Electric Machinery and Power System Fundamentals 1st edition by Stephen J. Chapman Accompany Electronic Devices and Circuit Theory 8th edition by Robert L. Boylestad; Louis Nashelsky; Franz J. Monseen Accompany Elementary Statistics 9th edition by Milton Loyer Accompany Engineering circuit analysis 6th edition by Hayt Accompany Foundations of Electromagnetic Theory 2nd edition by John R. Reitz, Frederick J. Milford Accompany Fundamentals of Fluid Mechanics 5th edition by Bruce R. Munson, Donald F. Young, Theodore H. Okiishi Accompany Introduction to algorithms by Sussman J Accompany Physics for Poets 2nd edition by Robert H. March Accompany Principles of geotechnical engineering 6th edition by braja M. DAS Adaptive Control 2nd edition by Karl Johan Astrom, Bjorn Wittenmark Adaptive filter thoery 4th edition by Simon Haykin Advanced Digital Design with the Verilog HDL by Michael D. Ciletti (Selected problems) Advanced engineering electromagnetics by Constantine A. Balanis Advanced Engineering Mathematics 8th edition by Erwin Kreyszig Advanced Engineering Mathematics 9th edition by Erwin Kreyszig Advanced Modern Engineering Mathematics 3rd edition by Glyn James Aircraft Structures for Engineering Students 4th edition by T. H. G. Megson (2007) Algebra and Trigonometry and Precalculus 3rd edition by Penna and Bittinger Beecher An introduction to database systems 8th edition by C J Date An Introduction to Ordinary Differential Equations by James C. Robinson An Introduction to Signals and Systems 1st edition by John Stuller An Introduction to The Finite Element Method 3rd edition by J. N. REDDY Analysis and design of analog integrated circuits 4th edition by Srikanth Vaidianathan and Haoyuee Wang Analytical Mechanics 7th edition by Fowles and Cassiday Antenna Theory Analysis and Design 2nd Edition Balanis Antennas for all Applications 3rd edition by John D. Kraus & Ronald J. Marhefka Anton Calculus 8th edition by Anton Applied Numerical Analysis 7th edition by Curtis F. Gerald,Patrick O. Wheatley Applied Partial Differential Equations with Fourier Series and Boundary Value Problems 4th edition by Richard Haberman Applied Quantum Mechanics by A. F. J. Levi Applied Statistics And Probability For Engineers 3rd edition by Montgomery,Runger Applied Statistics And Probability For Engineers 4th edition by Montgomery,Runger Applied Strength of Materials 4th edition by Robert L. Mott Artificial Intelligence A ModernApproach 2nd edition by StuartJ. Russelland, Peter Norvig Assembly Language for Intel-Based Computers 3rd edition by Kip R. Irvine Automatic Control Systems 8th edition by Kuo and Golnaraghi Basic Electrical Engineering by Nagrath, D P Kothari, Nagrath D P Kothari I J Nagrath, I J Nagrath (2002) Basic Engineering Circuit Analysis 7th edition by J. David Irwin (Selected Problems) Basic Engineering Circuit Analysis 8th edition by J. David Irwin C++ How to Program 3rd C++ How to Program 3rd edition by Harvey M. Deitel, Paul J. Deitel C++ How to Program 3rd edition by Deitel & Nieto Calculus 5th edition by James Stewart Calculus A Complete Course 6th edition by R.A. Adams Calculus Early Transcendentals 5th edition by Stewart Calculus early transcendentals 7th edition by Anton Bivens Davis calculus multivariable 4th edition by Deborah Hughes-Hallett, Andrew M. Gleason, et al Calculus Single Variable by Hughes-Hallett, Gleason, McCallum, et al Chemical and Engineering Thermodynamics 3rd edition by Stanley I. Sandler Chemical Enginering Vol 6 edition by 4th Coulson and Richardson Classical Dynamics A Contemporary Approach by Jorge V. Jose, Eugene J. Saletan Classical Dynamics of Particles and Systems 5th edition by Stephen T. Thornton, Jerry B. Marion Classical Electrodynamics 2nd edition by John David Jackson by Kasper van Wijk Classical Mechanics - An Undergraduate Text by R. Douglas Gregory Classical Mechanics 2nd edition by Goldstein & Safko CMOS Digital Integrated Circuits 3rd edition by Sung-Mo Kang,Yusuf Leblebici CMOS VLSI Design 3rd edition by ananymous Communication Networks Fundamental Concepts and Key Architectures byAlberto Leon-Garcia Communication Systems 4th edition by Bruce carlson Communication Systems 4th edition by Simon Haykin Communication Systems Engineering 2nd edition by John G. Proakis Masoud Salehi Computational Techniques for Fluid Dynamics (Scientific Computation) by Karkenahalli Srinivas, Clive A. J. Fletcher Computer Networking A Top-Down Approach 3rd edition by James F.Kurose,Keith W. Ross Computer Networks 4th edition by Andrew S. Tanenbaum Computer Networks A Systems Approach 2nd edition by Peterson and Davie Computer Organization 5th edition by Hamacher,Vranesic and Zaky Computer Organization and Design The HardwareSoftware Interface 3rd edition by David A. Patterson, John L. Hennessy Computer-Controlled Systems 3rd edition by Karl J. Astrom Concepts of Programming Languages 7th edition by Robert Sebesta Control systems Principles and Design 2nd edition by Madan Gopal Control Systems Engineering 4th edition by Norman S. Nise Corporate Finance 6th edition by Ross Cryptography and network security-principles and practice 4th edition by William Stallings Data and computer communications 7th edition by William Stallings Data Communications and Networking 4th edition by Behroz Forouzan Database Management Systems 3rd edition by Raghu Ramakrishnan Johannes Gehrke Design of Analog CMOS Integrated Circuits by Behzad Razavi Design of Nonlinear Control Systems with the Highest Derivative in Feedback 1st edition by Valery D. Yurkevich (student solution manual) Design with Operational Amplifiers and Analog Integrated Circuits 3rd edition by Franco, Sergio Device Electronics for Integrated Circuits 3rd edition by Muller Kamins Differential Equations with Boundary Value Problem 2nd edition by JOHNPOLKING and DAVID ARNOLD Differential Equations with Boundary Value Problem 2nd edition by John Polking Digital and Analog Communication Systems 7th edition by Leon W. Couch Digital Communication 4th edition by Proakis Digital Communications 5th edition by John Proakis Digital Communications Fundamentals and Applications 2nd edition by Bernard sklar Digital Control and state variable methods by M.Gopal Digital Design 2nd edition by M. Morris Mano,Michael D. Ciletti Digital Design 3rd edition by M. Morris Mano,Michael D. Ciletti Digital Design 4th edition by Morris Mano Digital Design-Principles and Practices 3rd edition by John F. Wakerly (selected problems) Digital Fundamentals 9th edition byThomas L. Floyd Digital Image Processing 2nd edition by Rafael C. Gonzalez Digital Integrated Circuits 2nd edition by Rabaey Digital Integrated Circuits by Thomas A. DeMassa & Zack Ciccone Digital Logic Design 2nd edition by M. Morris Mano Digital Signal Processing - A Modern Introduction 1st edition by Cengage learning Ashok Ambardar Digital Signal Processing - A Computer-Based Approach 1st edition by Sanjit K. Mitra Digital Signal Processing 2nd edition by Sanjit K. Mitra Digital Signal Processing 3rd edition by Sanjit K. Mitra Digital Signal Processing 4th edition by John G. Proakis and Dimitri s G. Manolakis Digital Signal Processing by Thomas J. Cavicchi Digital signal processing 2nd edition by Proakis manolakis Digital Signal Processing Signals, Systems, and Filters by Andreas Antoniou Digital Signal Processing Using Matlab 2nd edition by Vinay K Ingle Proakis Digital Systems-Principles and Applications 10th edition by Ronald Tocci, Neal S. Widmer & Gregory L. Moss Discrete Mathematics with Applications 3rd edition by Susanna S. Epp Discrete Time Signal Processing 2nd edition by Alan V. Oppenheim Discrete time signal processing 3rd edition by Alan V. Oppenheim Econometric Analysis 5th edition by William H. Greene Electric Circuits 7th edition by Nilsson Electric Circuits 8th edition by Nilsson Electric Machinery 6th edition by Fitzgerald Kingsley Electric Machinery Fundamentals 4th edition by Stephen J. Chapman Electric Machinery and Power System Fundamentals 1st edition by Stephen Chapman Electric Machines Analysis and Design Applying MATLAB by Jim Cathey Electrical Engineering Principles and Applications 3rd edition by Allan R. Hambley Electrical Machines, Drives and Power Systems 6th edition by Theodore Wildi Electromagnetic Fields and Energy 1st edition by Haus and Melcher Electromagnetics for Engineers by Ulaby Electromagnetism Major American Universities Ph.D. Qualifying by Lim Yung-Kuo Electronic Circuit Analysis and Design 2nd edition by Donald A. Neamen Electronic Devices 6th edition by Thomas L. Floyd Electronic devices - electron flow version 4th edition by Thomas l.Floyd Electronic Devices and Circuit Theory with Lab Solutions, and Test Item File 8th edition by Robert Boylestad Electronic Physics by Strabman Elementary Differential Equation 8th edition by Boyce Elementary Differential Equations And Boundary Value Problems 7th edition by Boyce And Diprima Elementary Linear Algebra with Applications 9th edition by Howard Anton, Chris Rorres Elementary Mechanics and Thermodynamics by Jhon W. Norbury Elementary Number Theory and Its Applications 5th edition by Kenneth H. Rosen Elementary Number Theory and Its Applications 6th edition by Kenneth H. Rosen Elementary Principles of Chemical Processes 3rd edition by Richard M. Felder,Ronald W. Rousseau Elements of Chemical Reaction Engineering 3rd edition by H. Scott Fogler Elements of electromagnetics 2nd edition by Sadiku Elements of electromagnetics 3rd edition by Sadiku Elements of Power System Analysis 4th edition by William D. Stevenson Embedded Microcomputer Systems Real Time Interfacing 2nd edition by Jonathan W. Valvano Engineering Circuit Analysis 6th edition by Hayt Engineering Circuit Analysis 7th edition by Hayt Engineering Electromagnetics 7th edition by Hayt Engineering Electromagnetics 2nd edition by Nathan Ida Engineering Electromagnetics 6th edition by William H. Hayt Jr. and Hohn A. Buck Engineering Fluid Mechanics 7th edition by Clayton T. Crowe, Donald F. Elger & John A. Roberson Engineering Mathematics 4th John edition by Bird Engineering Mathematics 4th edition by NEWNES Engineering Mechanic STATICS 10th edition by R.C. Hibbeler Engineering Mechanics - Dynamics 2nd edition by Riley and Sturges Engineering Mechanics - Dynamics 11th edition by R. C. Hibbeler Engineering Mechanics - STATICS 4th edition by Bedford and Fowler Engineering mechanics - statics 10th edition by R. C. Hibbeler Engineering mechanics Dynamics 4th edition by Bedford and Fowler Engineering Mechanics Dynamics 5th edition by J.L Meriam Engineering Mechanics Statics 6th edition by J.L Meriam Engineering Mechanics Statics 11th edition by R.C.Hibbeler Feedback Control of Dynamic Systems 4th edition by G. F. Franklin, J. D. Powell, A. Emami Feedback Control of Dynamic Systems 6th edition by G. F. Franklin, J. D. Powell, A. Emami Field and Wave Electromagnetics 2nd edition by Wesley Cheng Field and Wave Electromagnetics International Edition Inrenational edition by David K Fluid Mechanics 1st edition by CENGEL Fluid Mechanics 5th edition by White Fluid Mechanics With Engineering Applications 10th edition by E. John Finnemore, Joseph B Franzini Fracture mechanics fundamentals and applications 2nd edition by Northam Anderson Fundamental of Electric Circuits 3rd edition by C. K. Alexander M. N. O. Sadiku Fundamental of engineering electromagnetics by David Cheng Fundamentals of Digital Logic with Verilog Design 1st edition by S. Brown Z. Vranesic Fundamentals of Digital Logic with VHDL Design 1st edition by S. Brown, Z. Vranesic Fundamentals of Electric Circuits 2nd edition by C. K. Alexander M. N. O. Sadiku Fundamentals of Electric Circuits 3rd edition by C. K. Alexander M. N. O. Sadiku Fundamentals of engineering thermodynamics by M. j. moran h. n. shapiro Fundamentals of Fluid mechanics 4th edition by Munson Fundamentals of Fluid Mechanics 3rd edition (Student solution manual) Fundamentals of Heat and Mass Transfer 4th edition by Incropera & Dewitt Fundamentals of logic design 5th edition by Charles Roth Fundamentals of Machine Component Design 3rd edition by Robert C. Juvinall and Kurt M. Marshek Fundamentals of Machine Component Design 4th edition by Robert C. Juvinall and Kurt M. Marshek Fundamentals of Physics 7th edition by Halliday, Resnick & Walker Fundamentals of Physics 8th edition by Halliday, Resnick & Walker Fundamentals of Power Electronics 2nd edition by R.W. Erickson Fundamentals of Power Semiconductor Devices 1st edition by B. Jayant Baliga Fundamentals of Signals and systems using web and matlab 3rd edition by Edward W. Kamen, Bonnie S Heck Fundamentals of Solid-State Electronics by Chih-Tang Sah Fundamentals of Thermal Fluid Sciences edition by Yunus A. Cengel, Robert H. Turner, Yunus Cengel, Robert Turner Fundamentals of Thermodynamics by Richard Sonntag Claus Borgnakke Gordon Van Wylen Fundamentals of Wireless Communication by Tse and Viswanath Heat Transfer A Practical Approach 2nd ediion by Yunus A. Cengel, Yunus Cengel How English Works A Grammar Handbook with Readings Instructor's Manual by Ann Raimes Introduction to Algorithms 2nd edition by Philip Bille Introduction to Algorithms 2nd edition by Thomas H. Cormen Introduction to chemical engineering thermodynamics 6th edition by j. m. smith Introduction to Communication Systems 3rd edition by Stremler Introduction to Computing and Programming with JAVA-A Multimedia Approach 1st edition by Mark Guzdial and Barbara Ericson Introduction to electric circuits 6th edition by Dorf Svaboda Introduction to Electric Circuits 7th edition by Richard C. Dorf & James A. Svoboda Introduction to Electrodynamics 3rd edition by David J. Griffiths Introduction to Environmental Engineering and Science 3rd edition Introduction to Ergonomics by Robert Bridger Introduction to fluid mechanics 5th edition by Fox and mcdonald Introduction to fluid mechanics 6th edition by Fox and mcdonald Introduction to Java Programming 7th edition by Y. Daniel Liang Introduction to Linear Algebra 3rd edition by Gilbert Strang Introduction to Linear Programming 1st edition by L. N. Vaserstein (student solution manual) Introduction to Probability by Dimitri P. Bertsekas Introduction to Quantum Mechanics (1995) by David J. Griffiths Introduction to Solid State Physics by Charles Kittel Introduction to VLSI Circuits and Systems by John P Uyemura Introduction to Wireless Systems by P.M. Shankar IP Telephony Solution guide IT Networking Labs by Tom Cavaiani Java How to Program 5th edtion by Harvey M. Deitel, Paul J. Deitel Journey into Mathematics An Introduction to Proofs by Joseph J. Rotman (Book and solution manual) KC's Problems and Solutions for Microelectronic Circuits 4th edition by Adel S. Sedra, K. C. Smith, Kenneth C. Smith Labview for engineers 1st edition by R.W. Larsen Linear Algebra and Its Applications by David C. Lay Linear Algebra by Otto Bretscher Linear Algebra with Applications 6th edition by Leon Linear dynamic systems and signals by Zoran Gajic (with matlab experiments and power point slides) Linear circuit analysis 2nd edition by R. A. DeCarlo and P. Lin Linear Systems And Signals 1st edition by B P Lathi Logic and Computer Design Fundamentals 3rd edition by Morris Mano & Charles Kime Logic and Computer Design Fundamentals 4th edition by Morris Mano Managerial Accounting 11th edition by Eric W. Noreen, Peter C. Brewer, Ray H. Garrison Materials and Processes in Manufacturing 9th edition by E. Paul DeGarmo, Solutions Manual by Barney E. Klamecki Materials Science and Engineering 6th edition by Callister Materials Science and Engineering 7th edition by Callister Materials Science by Milton Ohring Mathematical Methods for Physics and Engineering 3rd edition by K. F. Riley, M. P. Hobson Mathematical Models in Biology An Introduction by Elizabeth S. Allman, John A. Rhodes Mathematical Olympiad in China Problems and Solutions Mathematical Proofs A Transition to Advanced Mathematics 2nd edition by Gary Chartrand, Albert D. Polimeni, Ping Zhang Mathematics for Economists by Carl P. Simon Lawrence Blume MATLAB Programming for Engineers by Tephen J. Chapman, Cengage Learning (m files) Matrix Analysis and Applied Linear Algebra by Carl D. Meyer (Book and solution manual) Mechanical Design of Machine Elements and Machines 1st edition by Collins Mechanical Engineering Design 7th edition by Shigley Mechanical Engineering Design 8th edition by Shigley Mechanical Vibrations 3rd edition by Singiresu Rao Mechanics of Fluids 5th edition by Frank White Mechanics of Fluids 8th edition by Massey Mechanics of Materials 3rd edition by Beer Mechanics of Materials 4th edition by Hibbeler Mechanics of materials 6th edition by James Gere Mechanics of Materials 6th edition by R. C. Hibbeler Mechanics of Materials 7th edition by R. C. Hibbeler Microelectronic Circuit Design 2nd edition by Richard C. Jaeger and Travis N. Blalock Microelectronic Circuit Design 3rd edition by Richard C. Jaeger and Travis N. Blalock Microelectronic Circuit Design 3rd edition by R. Jaeger Microelectronic circuits 5th edition by Adel S. Sedra kennethSmith Microelectronics 1 and 2 by Dr. Wen Ching Chang Microprocessors and Interfacing-Programming and Hardware 2nd by Douglas V. Hall Microwave and RF design of wireless systems by David M Pozar Microwave Engineering 2nd edition by David M Pozar Microwave Engineering 3rd edition by David M Pozar Microwave transistor amplifiers analysis and design 2nd edition by Guillermo Gonzalez Millman - Microelectronics digital and analog circuits and systems by Thomas V. Papathomas Mobile Communications 2nd edition by Jochen H. Schiller Modern Control Engineering 3rd edition by K. OGATA Modern Control Systems 11th edition by Richard C. Dorf Robert H Bishop Modern Control Systems 12th edition by Richard C. Dorf, Robert H. Bishop Modern Digital and Analog Communications Systems 3rd edition by B P Lathi Modern Digital Signal Processing by Roberto Cristi Modern physics by Randy Harris Multivariable Calculus 4th edition by Stewart Dan Clegg Barbara Frank Musculoskeletal Function An Anatomy and Kinesiology Laboratory Manual by Dortha Esch Esch Nanoengineering of Structural, Functional and Smart Materials Network Flows Theory, Algorithms, And Applications by Ravindra K. Ahuja, Thomas L. Magnanti, and James B. Orlin Network Simulation Experiments Manual (The Morgan Kaufmann Series in Networking) by Emad Aboelela Neural networks and learning machines 3rd edition by Simon S. Haykin Nonlinear Programming 2nd edition by Dimitri P. Bertsekas Numerical Analysis 8th edition by Richard L. Burden, J Douglas Faires Numerical Methods For Engineers 4th edition by Chapra Numerical Solution of Partial Differential Equations An Introduction by K. W. Morton, D. F. Mayers Operating Systems 4th edition by Stallings Optimal Control Theory An Introduction by Donald E. Kirk Options, Futures and Other Derivatives 4th edition by John Hull, John C. Hull Options, Futures and Other Derivatives 5th edition by John Hull, John C. Hull Organic chemistry 5th edition by Robert C. Athkins and Francis Carey Organic Chemistry 7th edition by Susan McMurry Partial Differential Equations With Fourier Series And Boundary Value Problems 2nd edition by Nakhle H.Asmar Physical Chemistry 7th edition by Peter Atkins and Julio de Paula Physical Chemistry 8th edition by Peter Atkins and Julio de Paula Physical Chemistry by Prem Dhawan Physics 5th edition by Halliday , Resnick , Krane Physics for Scientist and Engineers 1st edition by Knight Physics for Scientists and Engineers 5th edition by Paul A. Tipler, Gene Mosca Physics For Scientists And Engineers 6th edition by Serway And Jewett Physics for Scientists and Engineers with Modern Physics 3rd edition PIC Microcontroller and Embedded Systems 1st edition by Mazidi (Book and solution manual) Piping and Pipeline Calculations Manual Construction, Design Fabrication and Examination by Phillip Ellenberger Power Electronics-Converters, Applications and Design 2nd edition by Ned Mohan, Tore M. Undeland and William P. Robbins Power Electronics-Converters, Applications and Design 3rd edition by Ned Mohan, Tore M. Undeland and William P. Robbins (Solutions to Supplemental Problems) Power System Analysis by John Grainger and William Stevenson Power Systems Analysis and Design 4th edition by Glover J. Duncan, Sarma Mulkutla .S Principles and Applications of Electrical Engineering 2nd edition by Giorgio Rizzoni Principles and Applications of Electrical Engineering 4th edition by Giorgio Rizzoni Principles of Communications Systems, Modulation and Noise 5th edition by William H. Tranter and Rodger E. Ziemer Principles of Digital Communication and Coding 1st edition by Andrew J. Viterbi and Jim K. Omura Principles of Electronic Materials and Devices 3rd edition by Safa O. Kasap Principles of Neurocomputing for Science and Engineering 1st edition by Fredric M. Ham and Ivica Kostanic Principles of Physics 4th edition by Serway and Jewett Probability and Random Processes for Electrical Engineering by Alberto Leon-Garcia Probability and Statistical Inference 7th edition by Robert Hogg, Elliot A. Tanis Probability and Statistics for Engineering and the Sciences by Jay L. Devore Probability and Statistics for Engineers and Scientist 8th edition by Sharon Myers , Keying Ye, Walpole Probability and Statistics for Engineers and Scientists 3rd edition by Anthony Hayter Probability and Statistics for Engineers and Scientists by HAYLER Probability and Stochastic Processes 2nd edition by David J. Goodman Probability Random Variables And Stochastic Processes 4th edition by Papoulis Probability Random Variables and Random Signal Principles 4th edition by Peyton Peebles Jr Process Control Instrumentation Technology 8th edition by Johnson Process Dynamics and Control 2nd edition by Dale E. Seborg Process systems analysis and control by Donald r. Coughanowr Programmable logic controllers 1st edition by Rehg and Sartori Project Management Casebook by Karen M. Bursic, A. Yaroslav Vlasak Quantum Field Theory 2007 by Mark Srednick Quantum Physics 3rd edition by Stephen Gasiorowicz RF circuit Design Theory and Application by Ludwig bretchkol Scientific Computing with Case Studies 1st edition by Dianne P. O'Leary Semiconductor Device Fundamentals by Robert Pierret Semiconductor Manufacturing Technology 1st edition by Michael Quirk and Julian Serda Semiconductor Physics and Devices Basic Principles 3rd edition Signal Processing and Linear Systems by B P Lathi Signal Processing First by Mclellan , Schafer and Yoder Signals and Systems 2nd edition by Oppenheim Willsky Signals and Systems 2003 by M.J. Roberts Signals and Systems Analysis of Signals Through Linear Systems by M.J. Roberts Signals and Systems 2nd edition by Simon Haykin, Barry Van Veen Signals, Systems and Transforms 4th edition by Phillips, Parr and Riskin Sipser's Introduction to the Theory of Computation by Ching Law Solid State Electronic Device 6th edition by Ben Streetman Skill - Assessment Exercises to Accompany Control Systems Engineering 3rd edition by Norman S. Nise Starting Out with Java 5 Lab Manual to Accompany Starting out with Java 5 by Diane Christen Statistical digital signal processing and modeling by Monson hayes Statistical Physics of Fields by Mehran Kardar statistical physics of particles by Mehran Kardar Structural analysis 5th edition by Hibbeler Student Solution Manual for Essential Mathematical Methods for the Physical Sciences by K. F. Riley, M. P. Hobson System Dynamics 3rd edition by Katsuhiko Ogata System Dynamics and Response 1st edition by S. Graham Kelly The 8051 Microcontroller 4th edition by I. Scott MacKenzie and Raphael C.-W. Phan The 8088 and 8086 Microprocessors Programming, Interfacing, Software, Hardware, and Applications 4th edition by Walter A. Triebel, Avtar Singh The ARRL Instructor's Manual for Technician and General License Courses by American Radio Relay League The Art of Electronics by Thomas C. Hayes & Paul Horowitz (student solution manual) The C++ Programming Language 3rd edition by Bjarne Stroustrup The Calculus 7th edition by Louis Leithold The Language of Machines, An Introduction to Computability and Formal Languages by Robert W. Floyd, Richard Beigel The Science and Engineering of Materials 4th edition by Donald R. Askeland Frank Haddleton The Structure and Interpretation of Signals and Systems 1st edition by Edward A. Lee and Pravin Varaiya Thermodynamics An Engineering Approach 5th edition by Yunus A Cengel and Michael A Boles Thermodynamics An Engineering Approach 6th edition by Yunus A Cengel and Michael A Boles Thomas Calculus 11th edition by George B.Thomas Thomas' Calculus, Eleventh Edition (Thomas Series) 11th edition by George B. Thomas, Maurice D. Weir, Joel D. Hass, Frank R. Giordano Transport Phenomena 2nd edition by Bird, Stewart and Lightfoot Transport Phenomena in Biological Systems 2nd edition by George A. Truskey, Fan Yuan, David F. Katz Unit operations of chemical engineering 7th edition by Warren l. Mccabe University physics 11th edition by Young and Freedman Vector Calculus , Linear Algebra and Differential Forms 2nd edition by Hubbard and Burke Vector Mechanics for Engineers , Dynamics 6th edition by Beer Vector Mechanics for Engineers , Dynamics 7th edition by Beer Vector Mechanics for Engineers Statics and Dynamics 8th edition by Beer Vector Mechanics Statics 7th edition by Beer and Johnston VHDL for Engineers International Edition by Kenneth L. Short Wireless Communications 1st edition by A. F. Molisch Wireless Communications 1st edition by Andrea Goldsmith Wireless Communications Principles and Practice 2nd edition by Theodore S. Rappaport Zill's a First Course in Differential Equations with Modeling Applications (7th ed.) and Zill & Cullen's Diferential Equations with Boundary-Value Problems (5th ed.) ==================================== If your request isn't in the list , we will find it for you, just contact us ineedsolutionsbook at hotmail.com From khanta at gmail.com Fri Feb 21 16:32:35 2014 From: khanta at gmail.com (khanta at gmail.com) Date: Fri, 21 Feb 2014 13:32:35 -0800 (PST) Subject: Win32 Write RAW Physical Disk Python 3.3.2 In-Reply-To: References: Message-ID: <064bf62f-0cca-4dfb-ac37-d1d9b9c9711e@googlegroups.com> Can anyone tell me if it is not possible? It would save me a lot of time. Has anyone ever written to the raw disk on windows? On Wednesday, February 19, 2014 7:42:02 AM UTC-5, khanta wrote: > Hello, > > I am trying to write to the raw physical disk on Windows 8.1 but I > > get an error: > > PermissionError: [Errno 13] Permission denied: '\\\\.\\PHYSICALDRIVE2\\\\' > > > > OS: Windows 8.1 > > Python: 3.3.2 > > Drive is a USB drive > > Running as administrator > > > > Code Snippet: > > > > with open(r"\\.\PHYSICALDRIVE2\\", "rb+") as f: #Writing Binary! > > f.seek(unallocatedoffset + 0) > > f.write(t1) > > > > > > or > > > > with open('\\\\.\\PHYSICALDRIVE2\\', "rb+") as f: #Writing Binary! > > f.seek(unallocatedoffset + 0) > > f.write(t1) > > > > or > > > > f = os.fdopen(os.open('\\\\.\\PHYSICALDRIVE2\\' os.O_CREAT | > > os.O_WRONLY | os.O_APPEND | os.O_EXCL)) > > > > > > Any suggestions? Is it possible? From craig at milhiser.com Fri Feb 21 16:36:20 2014 From: craig at milhiser.com (craig at milhiser.com) Date: Fri, 21 Feb 2014 13:36:20 -0800 (PST) Subject: inheriting a large python code base In-Reply-To: References: Message-ID: <85611dc7-4691-4514-9355-0f3a7fcda5e3@googlegroups.com> Look at the algorithms and see if there are faster ways. Great advice with the comments of writing test cases, getting into version control, taking passes through the code with tools, understanding what is slow and why it is considered slow. Then you should invest the time to understand the internal logic and the algorithms. Understand the performance O(N log N), O(N^2), O(2^N). See if there are better algorithms that should be used - is there an O(N). Implement that algorithm, test, then compare performance. Finally optimize the coding constructs. Depending on how long your program takes (a few milli-secs, a few secs, a few hours, a few days), optimized coding constructs may make no measurable difference. Finding better algorithms will. But a better algorithm changing code from 2 milli-secs to 1 milli-sec is only useful in specific environments - so it may not be worth your effort. Understand the performance of the code and the environment it is executed in. That is how I have gone about it type of work. From breamoreboy at yahoo.co.uk Fri Feb 21 16:42:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 21 Feb 2014 21:42:31 +0000 Subject: Win32 Write RAW Physical Disk Python 3.3.2 In-Reply-To: <064bf62f-0cca-4dfb-ac37-d1d9b9c9711e@googlegroups.com> References: <064bf62f-0cca-4dfb-ac37-d1d9b9c9711e@googlegroups.com> Message-ID: On 21/02/2014 21:32, khanta at gmail.com wrote: > Can anyone tell me if it is not possible? It would save me a lot of time. > Has anyone ever written to the raw disk on windows? > Sorry I can't help you, but you're more likely to get answers if you didn't top post and you use a decent email client or follow the instructions here https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From malaclypse2 at gmail.com Fri Feb 21 16:46:16 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 21 Feb 2014 16:46:16 -0500 Subject: Win32 Write RAW Physical Disk Python 3.3.2 In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 7:42 AM, khanta wrote: > Hello, > I am trying to write to the raw physical disk on Windows 8.1 but I > get an error: > PermissionError: [Errno 13] Permission denied: '\\\\.\\PHYSICALDRIVE2\\\\' Is there a volume mounted from the drive at the time you're attempting to write to the physical device? According to some MSDN documentation (http://msdn.microsoft.com/en-us/library/aa365747%28VS.85%29.aspx ), it doesn't look like you can write to a physical device if the sectors you're attempting to write are mounted at the time. There appear to be a lot of caveats. Take a look at the section of that page starting with "If you write directly to a volume that has a mounted file system, you must first obtain exclusive access to the volume." for lots of details. -- Jerry From Hobie.Audet at comcast.net Fri Feb 21 17:48:05 2014 From: Hobie.Audet at comcast.net (Hobie Audet) Date: Fri, 21 Feb 2014 17:48:05 -0500 Subject: Error getting REMOTE_USER Environment Variable Message-ID: <3fW7Cb0xX8z7Ljf@mail.python.org> > >How many other environment variables are doubled? All of them? The only other environment variable I have tried is REMOTE_ADDR, and that does not appear to be doubled. >Does the problem exist when the Python script is run directly, outside >Abyss, or in IDLE, for example? The problem is with the REMOTE_USER and REMOTE_AUTH variables, which are set as a result of user authentication by the web browser. Thus, they don't exist outside of the web server environment. Since my posting yesterday, I've done a LOT of fiddling around with this and found a couple of interesting things. First of all, there was a minor typo in my web page HTML. The closing tag was lacking the last right angle bracket, so it looked like this: From python at mrabarnett.plus.com Fri Feb 21 18:02:32 2014 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Feb 2014 23:02:32 +0000 Subject: Error getting REMOTE_USER Environment Variable In-Reply-To: <3fW7Cb0xX8z7Ljf@mail.python.org> References: <3fW7Cb0xX8z7Ljf@mail.python.org> Message-ID: <5307DB08.9060609@mrabarnett.plus.com> On 2014-02-21 22:48, Hobie Audet wrote: >> >> How many other environment variables are doubled? All of them? > > The only other environment variable I have tried is REMOTE_ADDR, and > that does not appear to be doubled. > > >> Does the problem exist when >> the Python script is run directly, outside >> Abyss, or in IDLE, for example? > > The problem is with the REMOTE_USER and REMOTE_AUTH variables, which are > set as a result of user authentication by the web browser. Thus, they > don't exist outside of the web server environment. > > Since my posting yesterday, I've done a LOT of fiddling around with this > and found a couple of interesting things. First of all, there was a > minor typo in my web page HTML. The closing tag was lacking the > last right angle bracket, so it looked like this: > However, that doesn't seem to have affected the issue at hand. > > The second interesting thing is that this error occurs in the index.py > script. If I invoke it implicitly (by pointing my browser at > 127.0.0.1/Test), the REMOTE_USER and REMOTE_AUTH variables are doubled. > But if I invoke it explicitly (by pointing my browser at > 127.0.0.1/Test/index.py), the variables are NOT doubled and are returned > correctly. Strange! I hate to say it, but this sounds like a bug in the > Abyss web server. > Yep. If it had been a bug in the os module, I'm sure plenty of people would've already noticed, hence the suggestion to run it outside Abyss! > I have already reported this to Aprelium support. > From anujg1984 at gmail.com Fri Feb 21 18:28:55 2014 From: anujg1984 at gmail.com (anujg1984 at gmail.com) Date: Fri, 21 Feb 2014 15:28:55 -0800 (PST) Subject: is there a package similar to SHINY in R for python ... Message-ID: I want to have textboxes, sliders, and buttons in the web browser that change the data visualization just like shiny does in R. Is there something like that in python. Bokeh makes graphs in the browser, but they dont provide a way to manipulate the graph with sliders, textboxes etc. ? From cs at zip.com.au Fri Feb 21 18:30:59 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 22 Feb 2014 10:30:59 +1100 Subject: Storing the state of script between steps In-Reply-To: References: Message-ID: <20140221233059.GA69890@cskk.homeip.net> On 21Feb2014 12:59, Denis Usanov wrote: > I mostly develop on Python some automation scripts such as deployment (it's not about fabric and may be not ssh at all), testing something, etc. In this terms I have such abstraction as "step". > > Some code: > > class IStep(object): > def run(): > raise NotImplementedError() > > And the certain steps: > > class DeployStep: ... > class ValidateUSBFlash: ... > class SwitchVersionS: ... > > Where I implement run method. > Then I use some "builder" class which can add steps to internal list and has a method "start" running all step one by one. > > And I like this. It's loosely coupled system. It works fine in simple cases. But sometimes some steps have to use the results from previous steps. And now I have problems. Before now I had internal dict in "builder" and named it as "world" and passed it to each run() methods of steps. It worked but I disliked this. Can you qualify exactly what you dislike about it? I have a similar system I'm working on which chains operational steps, and each step can queue multiple following steps. It is still somewhat alpha. I think it has pretty much the same state issue that you describe: you need to keep state around, but passing it to each step feels clunky: you have this state parameter that you need to maintain and pass around all the time. My wishlist for state is twofold; I'd like it to be more implicit, for example have the state be implicit, such as in the program scope, and wouldn't it be better to be able to ignore it when you don't care about the state? My solution is threefold at present: First up, the core algorithm/framework always passes the state variable around. So every "step" function looks somewhat like this: def step(self, argument, state): where "state" is an object instead of a dict; otherwise esssentially that same as your dict based approach. "argument" it the item to be worked on in this step; my framework looks like a UNIX shell pipeline, where arguments are passed down the pipeline from step to step. Second, steps which do not care about the state are written like this: def step(self, argument) and installed via a wrapper: def step_full(self, argument, state): return step(self, argument) to make it easier to write the simple case. In your setup, I'd be writing each Step class as a subclass of a generic step class that incorporates the wrapper: class GenericStep: def step(self, argument, state): return self.stateless_step(argument) and then classes which do not care about the state would look like this: class SimpleOperation(GenericStep): def stateless_step(self, argument): ... do stuff with argument ... and classes which do operate on the state look like this: class StepWith SideEffects(GenericStep): def step(self, argument, state): ... do stuff with argument and modify state ... From the outside you call .step(....) with the full argument list. But on the inside your define the method which is the simplest mapping to what the step does. That leaves you freer to choose the style for each step function, using the less cluttered form when you don't care about the state. Third, in my scheme the return from step() is a sequence of (new_argument, new_state) tuples because each step can fire multiple following steps. Depending on the operations in the step, new_argument might just be the original argument, and new_state will usually be the original state. But sometimes new_state will be a shallow copy of the original, with one or more parts deep copied. This is to accomodate the implicit branching of state you might imagine in a pipeline: each of the following steps might want its own independent state from that point onward. Again, there's some wrapper logic in the GenericStep class to handle the return value, much as with the stpe() and stateless_step() calls: a simple step might just think in terms of the argument and ignore the state entirely: def one_to_one_step(self, argument): ... do stuff with argument ... new_argument = ... blah ... return new_argument def one_to_many_step_with_state(self, argument, state): return [ (self.one_to_one_step(argument), state) ] You can see the "full" step just calls the simple step and then repackages the result for passing down the pipeline. This lets you write the "one_to_one_step" method simply, without clutter. Hopefully this will give you some ideas for keeping the simple steps simple while still accomodating the complex cases with state. > I bet I wouldn't have asked this if I had worked with some of functional programming languages. Possibly, but you still need state. Cheers, -- Cameron Simpson Mark Crowder : Possessor of a mind not merely twisted, but actually sprained! From ben+python at benfinney.id.au Fri Feb 21 19:13:44 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Feb 2014 11:13:44 +1100 Subject: Python and variables (was: Can global variable be passed into Python function?) References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> Message-ID: <85d2ig2edj.fsf_-_@benfinney.id.au> Ned Batchelder writes: > On 2/21/14 2:23 AM, dieter wrote: > > Sam writes: > > > >> >I need to pass a global variable into a python function. > > Python does not really have the concept "variable". > > > > What appears to be a variable is in fact only the binding of an > > object to a name. If you assign something to a variable, > > all you do is binding a different object to the name. > > > > Man, do I hate this idea that Python has no variables. I agree with the sentiment of you've quoted from ?dieter?, above. But I also agree with your sentiment. I think it's misleading to use the term ?variable? to describe what Python has, because that term has an unavoidable collection of implications in the wider programming community, and many of those implications are plain false for Python. I think it's misleading to claim Python ?has no variables? ? which is not quite the same as what ?dieter? claimed. Python has a model of binding references to values, and the Python documentation calls these bindings ?variables? in the special case where the reference is a name. So, in that sense, Python has variables. > Python's variables are names bound to values. The ideal, in my view, would be for the Python documentation to never use the term ?variable? for this concept, since it leads newcomers predictably to false inferences that mar their understanding of Python. The damage isn't small, since it makes a rather simple and clear concept needlessly difficult to understand, and falsehoods learned about Python's data model need to be carefully rooted out and repaired later down the track. We should, instead, consistently use ?reference? and/or ?binding? for this concept, since those lead to much more accurate inferences about what is happening. -- \ ?People always ask me, ?Where were you when Kennedy was shot?? | `\ Well, I don't have an alibi.? ?Emo Philips | _o__) | Ben Finney From swdunning at cox.net Fri Feb 21 20:39:10 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 21 Feb 2014 18:39:10 -0700 Subject: Function and turtle help In-Reply-To: References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Message-ID: On Feb 20, 2014, at 11:30 PM, Dave Angel wrote: > Look at turtle.begin_fill and turtle.end_fill > > That's after making sure your star is a closed shape. So, this is what I have so far and it ?works? but, it fills in the star with black and as you can see below I am trying to fill it in with red. So I?m obviously messing up somewhere. def fillcolor(red): pencolor() begin_fill() star(500) end_fill() red = pencolor fillcolor(red) Scott From roy at panix.com Fri Feb 21 20:52:06 2014 From: roy at panix.com (Roy Smith) Date: Fri, 21 Feb 2014 20:52:06 -0500 Subject: New to working with APIs, any good tutorials/books/guides? References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> <3fa5e368-a47c-4a7e-80dc-c5333fb5603e@googlegroups.com> Message-ID: In article <3fa5e368-a47c-4a7e-80dc-c5333fb5603e at googlegroups.com>, ApathyBear wrote: > Thanks, I think I have an understanding of what they are, but now am still a > little confused on how one goes about using it: how am I supposed to know how > to use an API in python? or in any other language for that matter? If an API > is defining rules in C, is all hope lost for trying to use it in python? API is a very generic term for Application Programming Interface. It's just the protocol that you need to follow to communicate with some kind of system of software package. The documentation for an API should describe what operations are available, how you send data to it, and how it sends things back to you. Beyond that, there's not a whole lot that can be said because there are so many different kinds of APIs with vastly different interfaces. From davea at davea.name Fri Feb 21 21:13:26 2014 From: davea at davea.name (Dave Angel) Date: Fri, 21 Feb 2014 21:13:26 -0500 (EST) Subject: Function and turtle help References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Message-ID: Scott W Dunning Wrote in message: > > On Feb 20, 2014, at 11:30 PM, Dave Angel wrote: > >> Look at turtle.begin_fill and turtle.end_fill >> >> That's after making sure your star is a closed shape. > > > > So, this is what I have so far and it ???works??? but, it fills in the star with black and as you can see below I am trying to fill it in with red. So I???m obviously messing up somewhere. > > def fillcolor(red): > pencolor() > begin_fill() > star(500) > end_fill() > > red = pencolor > fillcolor(red) > You seem to have a fundamental misunderstanding of how variables and function parameters work. > def fillcolor(red): The parameter should be something like color, not red. > pencolor() You need an argument to this function if you expect it to change the color. I suggest color, the parameter we just renamed. > red = pencolor That does nothing at all useful for you. I expect you really want red = "red" -- DaveA From steve+comp.lang.python at pearwood.info Fri Feb 21 21:45:49 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 02:45:49 GMT Subject: New to working with APIs, any good tutorials/books/guides? References: <9f4db1e7-800f-4fd2-945d-d0972a440071@googlegroups.com> <3fa5e368-a47c-4a7e-80dc-c5333fb5603e@googlegroups.com> Message-ID: <53080f5d$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 12:12:00 -0800, ApathyBear wrote: > Thanks, I think I have an understanding of what they are, but now am > still a little confused on how one goes about using it: how am I > supposed to know how to use an API in python? *scratches head* Er, first you learn how to program in Python, then you read the API documentation and do what it says. If the documentation says that the function requires a single string argument, then you give the function a single string argument. I suspect that either your question is much more subtle and complicated than your actual words allow, or you're making things much, much, much more complicated than they actually are. In an earlier post, you said you had some experience programming in Python. If your code works, then you know how to use the APIs of the functions and libraries that you used. Here I am using the API for the len() function: alist = [1, 2, 3] number_of_items = len(alist) That's all. Easy, wasn't it? I'm using the API for the len() function. If you were asking for help with some *specific* API ("I don't understand the multiprocessing module!"), that I could get. Some APIs are complicated, or badly designed, or badly written, or require advanced understanding. But APIs *in general* can be as simple as len(). > or in any other language > for that matter? If an API is defining rules in C, is all hope lost for > trying to use it in python? If an API is defined for a C library or function, then, no, you can't use it in Python, or Lisp, or Ruby, just as you can't use a Lisp function in C or Forth or Pascal. Not unless one or the other language makes special provision to allow such cross-language communication. It might be better for you to give us concrete examples of what you don't understand, rather than to continue talking in vague generalities. -- Steven From torriem at gmail.com Fri Feb 21 22:10:39 2014 From: torriem at gmail.com (Michael Torrie) Date: Fri, 21 Feb 2014 20:10:39 -0700 Subject: is there a package similar to SHINY in R for python ... In-Reply-To: References: Message-ID: <5308152F.2040603@gmail.com> On 02/21/2014 07:57 PM, Dennis Lee Bieber wrote: > On Fri, 21 Feb 2014 15:28:55 -0800 (PST), anujg1984 at gmail.com declaimed the > following: > >> I want to have textboxes, sliders, and buttons in the web browser that change the data visualization just like shiny does in R. >> >> Is there something like that in python. > > Python doesn't really matter here... You've described HTML objects, and > for dynamic ones, you are likely talking either M$ "ASP", or Javascript > (unless you have a browser that can run embedded Python scripts). > > At least, I'm guessing you don't intend to have every movement of a > "slider" trigger a page refresh from a server -- you want the action to > operate /in/ the browser. "In the browser" means the server language > doesn't matter -- it's solely the Javascript that gets sent to the browser. I'm pretty sure he's talking about tools that make it really slick to put up graphs in a window and manipulate them with GUI controls. Nothing to do with html or web programming here, at least not what the OP was asking for. Such things can be done in Python using a GUI library, but that's quite a bit more work than using the SHINY library appears to be in R. The OP might be advised to check out the SciPy forums and mailing lists. Or talk to the folks at the Sage project. From ned at nedbatchelder.com Fri Feb 21 22:14:14 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 21 Feb 2014 22:14:14 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: On 2/21/14 9:47 PM, Dennis Lee Bieber wrote: > On Fri, 21 Feb 2014 09:59:17 -0800, Travis Griggs > declaimed the following: > >> On Feb 21, 2014, at 4:13 AM, Ned Batchelder wrote: >> >>> Man, do I hate this idea that Python has no variables. It has variables (names associated with values, and the values can change over the course of the program), they just don't work the same as C or Fortran variables. In fact, they work exactly the same as Javascript or Ruby variables. >> >> Thank you! >> >> +11 >> >> I get tired of the ?Python doesn?t have variables? line. >> > > If one is coming from the world where "variable" means "name > identifying a fixed location in memory" then Python does not have > "variables". > > BASIC, C, FORTRAN, COBOL, Assembly... A "variable" is synonym for an > address [a box that holds things]. > > Even Python's mutable types (list, dictionary, for example) do not > follow the "fixed location" metaphor. Each cell in a list merely references > some object, and assignment to that cell changes the reference, not the > object. > So we agree: variables in Python work differently than they do in those languages. If one is coming from the world where "variable" means "name bound to a value", then Python does have "variables". Javascript, Ruby, Lisp, Perl, PHP, Smalltalk, Lua, Julia... a "variable" is a name bound to a value. -- Ned Batchelder, http://nedbatchelder.com From harrismh777 at gmail.com Fri Feb 21 22:14:12 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 21 Feb 2014 19:14:12 -0800 (PST) Subject: IDLE won't run after installing Python 3.3 in Windows In-Reply-To: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> References: <704f5dde-49df-4c75-8215-5c59650d15c7@googlegroups.com> Message-ID: <85141301-efb3-4c9c-aa64-789c655df80f@googlegroups.com> On Tuesday, February 18, 2014 8:56:51 AM UTC-6, eglows... at gmail.com wrote: > Any suggestions? Thanks in advance! > Is there any possibility that you are bumping up against open IDLE Issue 14576? http://bugs.python.org/issue14576 From steve+comp.lang.python at pearwood.info Fri Feb 21 22:28:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 03:28:16 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> Message-ID: <5308194f$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 07:13:25 -0500, Ned Batchelder wrote: > On 2/21/14 2:23 AM, dieter wrote: >> Sam writes: >> >>> >I need to pass a global variable into a python function. >> Python does not really have the concept "variable". >> >> What appears to be a variable is in fact only the binding of an object >> to a name. If you assign something to a variable, all you do is binding >> a different object to the name. >> >> > Man, do I hate this idea that Python has no variables. It has variables > (names associated with values, and the values can change over the course > of the program), they just don't work the same as C or Fortran > variables. In fact, they work exactly the same as Javascript or Ruby > variables. I sympathise with your view. It seems quite ridiculous to claim that Python has no variables. If it has no variables, what on earth does it mean when we say "x = 42"? But the very ridiculousness is what gives it the attention-grabbing power that makes it a useful meme. "Python variables don't behave like C variables" might be true, but it's also wish-washy and forgettable. In my own case, I never quite got Python's name binding semantics until I was introduced to the "Python has no variables" meme. That got my attention long enough to listen to the actual message: my assumptions about how variables behave was based on Pascal semantics, and Python doesn't quite follow the same rules. Consequently, if I implicitly define "variable" to mean "Pascal variables", as I had been, then Python has no variables, it has these things called "name bindings". That's when I got it. I went through a phase where I too insisted that Python had no variables. But then my natural laziness asserted itself, and I decided that the word "variable" is too useful to always reject it (and besides, C- and Pascal- like languages don't have a monopoly on the word "variable"). Now, I use the terms "variable" or "reference" or "name binding" as I feel makes the most sense in context, depending on my best guess of the risk of misunderstanding or confusion. -- Steven From steve+comp.lang.python at pearwood.info Fri Feb 21 22:42:35 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 03:42:35 GMT Subject: Storing the state of script between steps References: Message-ID: <53081cab$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 12:59:11 -0800, Denis Usanov wrote: > I mostly develop on Python some automation scripts such as deployment > (it's not about fabric and may be not ssh at all), testing something, > etc. In this terms I have such abstraction as "step". > > Some code: > > class IStep(object): > def run(): > raise NotImplementedError() > > And the certain steps: > > class DeployStep: ... > class ValidateUSBFlash: ... > class SwitchVersionS: ... > > Where I implement run method. Why are these classes? Unless you have multiple instances, or are using inheritance, the use of classes is a Java-ism and a waste of time. http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html Since I see no reason to (say) have multiple ValidateUSBFlash instances, with different state, at the same time, and no reason to have (say) SwitchVersionS inherit from (say) DeployStep, I suggest a better approach is to use functions. No more ValidateUSBFlash.run method calls, just call function validate_usb_flash. > Then I use some "builder" class which can add steps to internal list and > has a method "start" running all step one by one. That becomes: steps = [deploy_step, validate_usb_flash, switch_version_s, ...] for step in steps: step() > And I like this. It's loosely coupled system. It works fine in simple > cases. But sometimes some steps have to use the results from previous > steps. And now I have problems. Before now I had internal dict in > "builder" and named it as "world" and passed it to each run() methods of > steps. It worked but I disliked this. > > How would you solve this problem and how would you do it? I understant > that it's more architecture specific question, not a python one. I'd avoid over-generalisation, and just write a script. Let each step function take whatever arguments it needs, and return whatever arguments it requires, then write it like this: deploy_step() result = validate_usb_flash() if result == 1: validate_other_usb_flash() else: validate_something_else(result) I mean, how many steps do you have? Twenty? A hundred? It's not that hard to maintain a 100 or 200 line script. And are you likely to have so many different versions of it that you need extra abstraction layers? Of course, I might be misinterpreting your post. Perhaps you do have so many steps, and so many different types of deployment, that you do need a more heavily abstracted system. In that case, I think you need to describe your system in more detail to get any useful answers. But don't over-generalise, and don't become an Architecture Astronaut :-) -- Steven From ned at nedbatchelder.com Fri Feb 21 22:45:14 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 21 Feb 2014 22:45:14 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <5308194f$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <5308194f$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2/21/14 10:28 PM, Steven D'Aprano wrote: > On Fri, 21 Feb 2014 07:13:25 -0500, Ned Batchelder wrote: > >> On 2/21/14 2:23 AM, dieter wrote: >>> Sam writes: >>> >>>>> I need to pass a global variable into a python function. >>> Python does not really have the concept "variable". >>> >>> What appears to be a variable is in fact only the binding of an object >>> to a name. If you assign something to a variable, all you do is binding >>> a different object to the name. >>> >>> >> Man, do I hate this idea that Python has no variables. It has variables >> (names associated with values, and the values can change over the course >> of the program), they just don't work the same as C or Fortran >> variables. In fact, they work exactly the same as Javascript or Ruby >> variables. > > I sympathise with your view. It seems quite ridiculous to claim that > Python has no variables. If it has no variables, what on earth does it > mean when we say "x = 42"? > > But the very ridiculousness is what gives it the attention-grabbing power > that makes it a useful meme. "Python variables don't behave like C > variables" might be true, but it's also wish-washy and forgettable. > > In my own case, I never quite got Python's name binding semantics until I > was introduced to the "Python has no variables" meme. That got my > attention long enough to listen to the actual message: my assumptions > about how variables behave was based on Pascal semantics, and Python > doesn't quite follow the same rules. Consequently, if I implicitly define > "variable" to mean "Pascal variables", as I had been, then Python has no > variables, it has these things called "name bindings". > > That's when I got it. > > I went through a phase where I too insisted that Python had no variables. > But then my natural laziness asserted itself, and I decided that the word > "variable" is too useful to always reject it (and besides, C- and Pascal- > like languages don't have a monopoly on the word "variable"). Now, I use > the terms "variable" or "reference" or "name binding" as I feel makes the > most sense in context, depending on my best guess of the risk of > misunderstanding or confusion. > > This is an interesting perspective, thanks. I think it might be that the OP's question, "Can a global variable be passed into a function", really had nothing to do with the name/value/variable distinction, and we've done it again: taken a simple question and spun off into pedantry and trivia. -- Ned Batchelder, http://nedbatchelder.com From cs at zip.com.au Fri Feb 21 22:30:10 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 22 Feb 2014 14:30:10 +1100 Subject: New to working with APIs, any good tutorials/books/guides? In-Reply-To: <53080f5d$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <53080f5d$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20140222033010.GA5706@cskk.homeip.net> On 22Feb2014 02:45, Steven D'Aprano wrote: > On Fri, 21 Feb 2014 12:12:00 -0800, ApathyBear wrote: > > [...] or in any other language > > for that matter? If an API is defining rules in C, is all hope lost for > > trying to use it in python? > > If an API is defined for a C library or function, then, no, you can't use > it in Python, or Lisp, or Ruby, just as you can't use a Lisp function in > C or Forth or Pascal. Not unless one or the other language makes special > provision to allow such cross-language communication. What Steven says is true, at the simplest level. However, MANY popular APIs that come with (for example) C libraries and which are documented in terms of a C programming interface have Python modules whose entire purpose in life is to present a Python API which in turn accesses the C API for you. For one example, consider the "bsddb" Python 2 module, which is part of the standard library: if you have Python 2, you have the bsddb module: http://docs.python.org/2/library/bsddb.html#module-bsddb The BSD dbm libraries are C libraries with a C API. However, the bsddb module is a Python module which contains python calls which operate on BSD dbm files. If you're using Python, you can use this module, which of course has a _Python_ API, to use the BSD dbm library. So: if you have some library which has a C API, it is possible that there is a Python module which interfaces to it, and that module will have a Python API. You may need to fetch such a module from a third place, such as PyPI. Cheers, -- Cameron Simpson Who are all you people and why are you in my computer? - Kibo From swdunning at cox.net Fri Feb 21 22:38:02 2014 From: swdunning at cox.net (Scott W Dunning) Date: Fri, 21 Feb 2014 20:38:02 -0700 Subject: Function and turtle help In-Reply-To: References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> Message-ID: <83EDD1E2-1F6F-498E-900D-B604BAF47EE9@cox.net> On Feb 21, 2014, at 7:13 PM, Dave Angel wrote: > Scott W Dunning Wrote in message: >> >> On Feb 20, 2014, at 11:30 PM, Dave Angel wrote: >> >>> Look at turtle.begin_fill and turtle.end_fill >>> >>> That's after making sure your star is a closed shape. >> >> >> >> So, this is what I have so far and it ?works? but, it fills in the star with black and as you can see below I am trying to fill it in with red. So I?m obviously messing up somewhere. >> >> def fillcolor(red): >> pencolor() >> begin_fill() >> star(500) >> end_fill() >> >> red = pencolor >> fillcolor(red) >> > > You seem to have a fundamental misunderstanding of how variables > and function parameters work. Yes I just learned a little bit about functions a couple days ago in school. I am completely new to programming so thanks for any help! > >> def fillcolor(red): > The parameter should be something like color, not red. Ok I see. I changed it a little based on what you suggested and I got a change, the outline became red but the fill is still black. Can you walk me through where I?m going wrong on what I have below? From what I gather, I have a function called fillcolor with a parameter called color. I know this is going to sound stupid but I get a little lost after that. The function says when ever I call fillcolor do what?s in the body? What exactly does the parameter do (in this case color, how is that doing anything) and what is an argument? def fillcolor(color): <- Function with parameter, right? pencolor(color) <- Says make pencolor whatever I state when I call fill color, right? begin_fill() <- starts filling the star. When I put color in () though I get an error that it takes no arguments? star(500) <- Star function end_fill() <- Ends fill red = "red" fillcolor(red) I know that I know absolutely nothing but I?m trying and I just started so please bare with me. And thanks for any help, it's GREATLY appreciated!! Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Feb 21 23:30:02 2014 From: davea at davea.name (Dave Angel) Date: Fri, 21 Feb 2014 23:30:02 -0500 Subject: Function and turtle help In-Reply-To: <83EDD1E2-1F6F-498E-900D-B604BAF47EE9@cox.net> References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> <83EDD1E2-1F6F-498E-900D-B604BAF47EE9@cox.net> Message-ID: <530827CA.4020600@davea.name> On 02/21/2014 10:38 PM, Scott W Dunning wrote: > > On Feb 21, 2014, at 7:13 PM, Dave Angel wrote: > >> Scott W Dunning Wrote in message: >>> >>> On Feb 20, 2014, at 11:30 PM, Dave Angel wrote: >>> >>>> Look at turtle.begin_fill and turtle.end_fill >>>> >>>> That's after making sure your star is a closed shape. >>> >>> >>> >>> So, this is what I have so far and it ?works? but, it fills in the star with black and as you can see below I am trying to fill it in with red. So I?m obviously messing up somewhere. >>> >>> def fillcolor(red): >>> pencolor() >>> begin_fill() >>> star(500) >>> end_fill() >>> >>> red = pencolor >>> fillcolor(red) >>> >> >> You seem to have a fundamental misunderstanding of how variables >> and function parameters work. > > Yes I just learned a little bit about functions a couple days ago in school. I am completely new to programming so thanks for any help! > >> >>> def fillcolor(red): >> The parameter should be something like color, not red. > > Ok I see. > > I changed it a little based on what you suggested and I got a change, the outline became red but the fill is still black. Can you walk me through where I?m going wrong on what I have below? I'll try. First, a web page from Python's library reference http://docs.python.org/3.3/library/turtle.html#turtle.pencolor This assumes Python 3.3, but you didn't say. If you're using 2.x, then change the 3.3 in the link to 2 Notice that I've never actually used the turtle module, and I don't believe I've even looked at the docs till responding to your questions. So I may easily make errors in the API. > > From what I gather, I have a function called fillcolor with a parameter called color. I know this is going to sound stupid > but I get a little lost after that. The function says when ever I call fillcolor do what?s in the body? That's right. When you call a function, it causes the body to be executed, after filling in a value for the parameters if any. > What exactly does the parameter do (in this case color, how is that doing anything) and what is an argument? The argument was the top-level variable red, which has the value of string "red". So when the function starts, the parameter color is equal to the string "red" That doesn't do anything till you use the parameter color (which is a local variable). You used it as a parameter in the call to pencolor(), and if you also used in the call to fillcolor(), you'd get the effect you want. > > def fillcolor(color): <- Function with parameter, right? > pencolor(color) <- Says make pencolor whatever I state when I call fill color, right? turtle.fillcolor(color) > begin_fill() <- starts filling the star. When I put color in () though I get an error that it takes no arguments? > star(500) <- Star function > end_fill() <- Ends fill > > red = "red" > fillcolor(red) > > > I know that I know absolutely nothing but I?m trying and I just started so please bare with me. And thanks for any help, it's GREATLY appreciated!! > > Scott > > > The remaining problem is that after doing the from turtle import * (which I generally avoid doing), you then define your own function fillcolor(), which masks the one you just imported. So as a minimum change, I might pick a new function name: def filledpolygon(size, color): <- Function with parameter, right? pencolor(color) fillcolor(color) begin_fill() star(size) end_fill() red = "red" filledpolygon(500, red) Some terminology: def myfunc(parm1, parm2): q = 3*4 otherfunc(parm1, q) stillotherfunc(param2) return 12 arg = 42 res = myfunc(arg, 99) Top level varaibles are arg and res. When myfunc is called, it is passed two "arguments", arg and 99. When myfunc actually starts running, it has 3 local variables. The first two, called parameters, are set from the arguments above, arg and 99. In effect, the function begins: parm1 = arg parm2 = 99 The other local variable is q, and it's set right away. Then two other functions are called, using these local variables are arguments. We're not going to study them, just assume they're there. Now a value of 12 is returned. That value will end up in res, as we turn control back to the top-level code. Most of the functions a beginner calls are already written for him, so he just worries about the arguments to those functions. But it's still important to have the right number and types of arguments for whatever those functions are expecting. Obviously it gets trickier to explain when you are calling your own function, so you have to worry about caller and callee. I hope this helps some. -- DaveA From steve+comp.lang.python at pearwood.info Sat Feb 22 01:29:58 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 06:29:58 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <5308194f$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530843e6$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 22:45:14 -0500, Ned Batchelder wrote: > I think it might be that the OP's question, "Can a global variable be > passed into a function", really had nothing to do with the > name/value/variable distinction, and we've done it again: taken a simple > question and spun off into pedantry and trivia. You might be right, but the OP's question isn't really clear. Surely he didn't mean something as trivial as this? x = 1 # This is a global some_function(x) # Passing a global into a function His description, especially the comment about pass by reference, suggests that there is more to it than just passing a global variable as argument to a function. I think he is trying to *write* to the variable as well, as an output variable, something like this: x = 1 y = 2 some_function(x) assert x == 99 some_function(y) assert y == 99 Sadly, it appears to have been a drive-by question: Sam tossed a question out the window as he drove by, and may never come back for the answer... I hope I'm wrong, but it's been nearly 24 hours since the question was asked and not a peep from the OP. Sam, if you're out there reading this, please respond with more detail about what you are trying to do! -- Steven From rosuav at gmail.com Sat Feb 22 01:36:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 17:36:52 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87bny0w9w3.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> Message-ID: On Sat, Feb 22, 2014 at 6:20 AM, Marko Rauhamaa wrote: > On the question of how variables can be passed to functions, C, of > course, has the & operator and Pascal has the "var" keyword. That doesn't pass a variable into a function, though. It passes the address of that variable, and C lets you stuff something into an address. That's not the same thing. ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 22 01:57:24 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 06:57:24 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> Message-ID: <53084a53$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Feb 2014 21:20:12 +0200, Marko Rauhamaa wrote: > On the question of how variables can be passed to functions, C, of > course, has the & operator and Pascal has the "var" keyword. > > An analogous thing can be achieved in Python 3 (but not in Python 2, I'm > afraid). The & operator corresponds to an ad hoc property class as in > the program below (not intended to be serious). I'm glad you added that comment about not being serious. But even so, your code is extremely unPythonic and doesn't even succeed in doing what you try to accomplish: > The program demonstrates how to write a universal "swap" function that > interchanges two references. For the record, there is no need for such a universal swap function in Python, as the right way to do it is: x, y = y, x But your code doesn't succeed at doing what it sets out to do. If you try to call it like this: py> x = 23 py> y = 42 py> swap(x, y) Traceback (most recent call last): File "", line 1, in File "", line 2, in swap AttributeError: 'int' object has no attribute 'get' not only doesn't it swap the two variables, but it raises an exception. Far from being a universal swap, it's merely an obfuscated function to swap a few hard-coded local variables. -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 22 02:18:27 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 07:18:27 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> Message-ID: <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 17:36:52 +1100, Chris Angelico wrote: > On Sat, Feb 22, 2014 at 6:20 AM, Marko Rauhamaa > wrote: >> On the question of how variables can be passed to functions, C, of >> course, has the & operator and Pascal has the "var" keyword. > > That doesn't pass a variable into a function, though. It passes the > address of that variable, and C lets you stuff something into an > address. That's not the same thing. Be careful about conflating the implementation with the interface. As I understand it, the interface C literally is that &x gives you the address of x. But that's not what the var keyword is for in Pascal (although that may be how it is implemented). In Pascal, if you have a function or procedure: procedure plus(a:integer, var b:integer); begin b := a+b; end; and a couple of variables in some other scope, for simplicity lets make them global: var foo: int; bar: int; begin foo := 23; bar := 1; plus(bar, foo); writeln(foo); end. the output will be 24. If we could peek into procedure plus, we would see that argument a was a *copy* of global bar, while argument b wasn't merely a copy of foo, it actually was foo. So assigning to b inside plus is the same as assigning to foo in the global scope. If we added a call: plus(2, bar); to the main program, then inside plus argument a would have the value 2, and argument b would now be precisely the same variable as global bar. After the procedure returns, bar would have the value 3. Now I daresay that under the hood, Pascal is passing the address of foo (or bar) to the procedure plus, but inside plus you don't see that address as the value of b. You see the value of foo (or bar). C does not do that -- you have to manually manage the pointers yourself, while Pascal does it for you. And Python also has nothing like that. -- Steven From rosuav at gmail.com Sat Feb 22 02:29:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 18:29:02 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 22, 2014 at 6:18 PM, Steven D'Aprano wrote: > Now I daresay that under the hood, Pascal is passing the address of foo > (or bar) to the procedure plus, but inside plus you don't see that > address as the value of b. You see the value of foo (or bar). > > C does not do that -- you have to manually manage the pointers yourself, > while Pascal does it for you. And Python also has nothing like that. Yep. I should have clarified that I wasn't talking about Pascal; I'm not fluent in the language (last time I did anything at all with Pascal was probably about ten years ago, and not much then). In C, it strictly does what I said: & takes the address of something, * dereferences an address. There's no way to "pass a variable" - you have to pass the address, and that has consequences if, for instance, you *return* an address and the variable ceases to exist. (Does Pascal have an equivalent of that?) And Python has no such concept, anywhere. But anything that you can achieve in C using pointers, you can probably achieve in Python using more complex objects. ChrisA From marko at pacujo.net Sat Feb 22 02:28:10 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 22 Feb 2014 09:28:10 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084a53$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <878ut3ehdh.fsf@elektro.pacujo.net> Steven D'Aprano : > But your code doesn't succeed at doing what it sets out to do. If you try > to call it like this: > > py> x = 23 > py> y = 42 > py> swap(x, y) > Traceback (most recent call last): > File "", line 1, in > File "", line 2, in swap > AttributeError: 'int' object has no attribute 'get' > > not only doesn't it swap the two variables, but it raises an exception. > Far from being a universal swap, it's merely an obfuscated function to > swap a few hard-coded local variables. You are calling the function wrong. Imagine the function in C. There, you'd have to do this: x = 23; y = 42; swap(&x, &y); You've left out the ampersands and gotten a "segmentation fault." You should have done this: x = 23 y = 42 class XP: def get(self): return x def set(self, value): nonlocal x x = value class YP: def get(self): return y def set(self, value): nonlocal y y = value swap(XP(), YP()) So we can see that Python, too, can emulate the ampersand, albeit with some effort. Marko From wxjmfauth at gmail.com Sat Feb 22 03:02:18 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 22 Feb 2014 00:02:18 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <585851dd-6106-4bc0-a7a2-8679aaa6ea29@googlegroups.com> >>> # a swapping variant >>> def swap(a, b): ... ab = [a, b] ... ab[1], ab[0] = ab[0], ab[1] ... return ab[0], ab[1] ... >>> a = 111 >>> id(a) 505627864 >>> b = 999 >>> id(b) 58278640 >>> a, b = swap(a, b) >>> a, id(a) (999, 58278640) >>> b, id(b) (111, 505627864) jmf From rosuav at gmail.com Sat Feb 22 03:10:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 19:10:02 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <585851dd-6106-4bc0-a7a2-8679aaa6ea29@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <585851dd-6106-4bc0-a7a2-8679aaa6ea29@googlegroups.com> Message-ID: On Sat, Feb 22, 2014 at 7:02 PM, wrote: >>>> # a swapping variant >>>> def swap(a, b): > ... ab = [a, b] > ... ab[1], ab[0] = ab[0], ab[1] > ... return ab[0], ab[1] Provably identical to: def swap(a, b): return b, a The rest is just fluff. ChrisA From wxjmfauth at gmail.com Sat Feb 22 03:26:43 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sat, 22 Feb 2014 00:26:43 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <585851dd-6106-4bc0-a7a2-8679aaa6ea29@googlegroups.com> Message-ID: <2dab8e37-dd35-43d7-aa3f-c4936d82b478@googlegroups.com> Le samedi 22 f?vrier 2014 09:10:02 UTC+1, Chris Angelico a ?crit?: > On Sat, Feb 22, 2014 at 7:02 PM, wrote: > > >>>> # a swapping variant > > >>>> def swap(a, b): > > > ... ab = [a, b] > > > ... ab[1], ab[0] = ab[0], ab[1] > > > ... return ab[0], ab[1] > > > > Provably identical to: > > > > def swap(a, b): > > return b, a > > > > The rest is just fluff. > > > > ChrisA Right. My bad, (just wake up). jmf From steve+comp.lang.python at pearwood.info Sat Feb 22 03:28:17 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 08:28:17 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <585851dd-6106-4bc0-a7a2-8679aaa6ea29@googlegroups.com> Message-ID: <53085fa1$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 19:10:02 +1100, Chris Angelico wrote: > On Sat, Feb 22, 2014 at 7:02 PM, wrote: >>>>> # a swapping variant >>>>> def swap(a, b): >> ... ab = [a, b] >> ... ab[1], ab[0] = ab[0], ab[1] >> ... return ab[0], ab[1] > > Provably identical to: > > def swap(a, b): > return b, a > > The rest is just fluff. You don't even need the function call. a, b = b, a -- Steven From steve+comp.lang.python at pearwood.info Sat Feb 22 03:35:25 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 08:35:25 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 18:29:02 +1100, Chris Angelico wrote: > On Sat, Feb 22, 2014 at 6:18 PM, Steven D'Aprano > wrote: >> Now I daresay that under the hood, Pascal is passing the address of foo >> (or bar) to the procedure plus, but inside plus you don't see that >> address as the value of b. You see the value of foo (or bar). >> >> C does not do that -- you have to manually manage the pointers >> yourself, while Pascal does it for you. And Python also has nothing >> like that. > > Yep. I should have clarified that I wasn't talking about Pascal; I'm not > fluent in the language (last time I did anything at all with Pascal was > probably about ten years ago, and not much then). In C, it strictly does > what I said: & takes the address of something, * dereferences an > address. There's no way to "pass a variable" - you have to pass the > address, and that has consequences if, for instance, you *return* an > address and the variable ceases to exist. (Does Pascal have an > equivalent of that?) Yes, Pascal has pointers as a first-class data type. Syntax is similar to C, ^x is a pointer to x, p^ dereferences the pointer p. > And Python has no such concept, anywhere. But anything that you can > achieve in C using pointers, you can probably achieve in Python using > more complex objects. Not even that complex. Although Python doesn't do pointers, the model of the language is such that you don't need to. Where in C or Pascal you would pass a pointer to a record, in Python you just pass the record, safe in the knowledge that the entire record won't be copied. There are a few idioms which don't work as neatly in Python as in Pascal, such as output parameter, but you don't need them. Just return a tuple. If you insist on an output parameter, do it like this: def func(inarg, outarg): if inarg % 2: outarg[0] == "even" else: outarg[0] == "odd" return inarg + 1 out = [None] x = 42 result = func(x, out) print(out[0]) -- Steven From rosuav at gmail.com Sat Feb 22 03:45:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 19:45:34 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 22, 2014 at 7:35 PM, Steven D'Aprano wrote: >> Yep. I should have clarified that I wasn't talking about Pascal; I'm not >> fluent in the language (last time I did anything at all with Pascal was >> probably about ten years ago, and not much then). In C, it strictly does >> what I said: & takes the address of something, * dereferences an >> address. There's no way to "pass a variable" - you have to pass the >> address, and that has consequences if, for instance, you *return* an >> address and the variable ceases to exist. (Does Pascal have an >> equivalent of that?) > > Yes, Pascal has pointers as a first-class data type. Syntax is similar to > C, ^x is a pointer to x, p^ dereferences the pointer p. > Right, I remember those now. Yes. (See how rusty I am on it? Heh.) ChrisA From steve+comp.lang.python at pearwood.info Sat Feb 22 03:45:19 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Feb 2014 08:45:19 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084a53$0$29985$c3e8da3$5496439d@news.astraweb.com> <878ut3ehdh.fsf@elektro.pacujo.net> Message-ID: <5308639e$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 09:28:10 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> But your code doesn't succeed at doing what it sets out to do. If you >> try to call it like this: >> >> py> x = 23 >> py> y = 42 >> py> swap(x, y) >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 2, in swap >> AttributeError: 'int' object has no attribute 'get' >> >> not only doesn't it swap the two variables, but it raises an exception. >> Far from being a universal swap, it's merely an obfuscated function to >> swap a few hard-coded local variables. > > You are calling the function wrong. Imagine the function in C. There, > you'd have to do this: [...] Sorry, I misunderstood you. When you called it a universal swap function, I thought you meant a universal swap function. I didn't realise you intended it as a demonstration of how to emulate a C idiom using overly- complicated Python code *wink* If you want to emulate pointers in Python, the simplest way is to use lists as pseudo-pointers. # think of ptr[0] as pointer dereferencing # think of [value] as quasi "address of" operator def swap(p, q): p[0], q[0] = q[0], p[0] x = ["anything"] y = ["something"] z = [23] swap(x, y) swap(x, z) print(x[0], y[0], z[0]) => prints "23 anything something" But why bother to write C in Python? Python makes a really bad C, and C makes a really bad Python. -- Steven From rosuav at gmail.com Sat Feb 22 03:54:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 19:54:24 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <5308639e$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084a53$0$29985$c3e8da3$5496439d@news.astraweb.com> <878ut3ehdh.fsf@elektro.pacujo.net> <5308639e$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Feb 22, 2014 at 7:45 PM, Steven D'Aprano wrote: > But why bother to write C in Python? Python makes a really bad C, and C > makes a really bad Python. +1. ChrisA From orgnut at yahoo.com Sat Feb 22 05:57:45 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sat, 22 Feb 2014 02:57:45 -0800 Subject: argparse question Message-ID: I have been reading the argparse section of the 3.3 docs, and running all the example code. But in section 16.4.2.6. for the formatter_class, the second example in that section illustrating RawDescriptionHelpFormatter, the example code is: parser = argparse.ArgumentParser( prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\ Please do not mess up this text! -------------------------------- I have indented it exactly the way I want it ''')) parser.print_help() But trying to run this gives a NameError on the "description=" line, saying textwrap is not defined. If I delete the "textwrap.dedent" (with or without also deleting the extra parentheses) it will then run, but without the un-indenting it is trying to illustrate. What is the proper way to enable the dedent() method here? All the other examples have run correctly (that is, the one's I've tried -- I'm still reading). Also, it should be obvious that while the "import argparse" line is not shown in the examples, it IS in the code samples I've been running. Using 3.3 under Linux (Mint 15). -=- Larry -=- From rosuav at gmail.com Sat Feb 22 06:00:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 22:00:52 +1100 Subject: Python stdlib code that looks odd Message-ID: I'm poking around in the stdlib, and Lib/mailbox.py has the following inside class Mailbox: def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'iteritems'): source = arg.items() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for key, message in source: ... use key/message ... Looks odd to check if it has iteritems and then use items. Presumably this will catch a Python 2 dictionary, and take its items as a list rather than an iterator; but since the only thing it does with source is iterate over it, would it be better done as iteritems? Mainly, it just looks really weird to check for one thing and then call on another, especially as it then checks for the other thing in the next line. ChrisA From laurent.pointal at free.fr Sat Feb 22 06:15:36 2014 From: laurent.pointal at free.fr (Laurent Pointal) Date: Sat, 22 Feb 2014 12:15:36 +0100 Subject: What are the kinds of software that are not advisable to be developed using Python? References: Message-ID: <530886d8$0$2301$426a74cc@news.free.fr> Chris Angelico wrote: > Heavy computation might be unideal in Python, but if you can grunge it > into NumPy operations, that won't be a problem. May take a look to Pythran too, which generate C++ code from (limited subset of) Python code, usable as a Python compiled module or as standalone C++. https://github.com/serge-sans-paille/pythran A+ Laurent. From __peter__ at web.de Sat Feb 22 06:54:59 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Feb 2014 12:54:59 +0100 Subject: Python stdlib code that looks odd References: Message-ID: Chris Angelico wrote: > I'm poking around in the stdlib, and Lib/mailbox.py has the following > inside class Mailbox: > > def update(self, arg=None): > """Change the messages that correspond to certain keys.""" > if hasattr(arg, 'iteritems'): > source = arg.items() > elif hasattr(arg, 'items'): > source = arg.items() > else: > source = arg > bad_key = False > for key, message in source: > ... use key/message ... > > Looks odd to check if it has iteritems and then use items. Presumably > this will catch a Python 2 dictionary, and take its items as a list > rather than an iterator; but since the only thing it does with source > is iterate over it, would it be better done as iteritems? Remember that you are looking at Python 3 code here where items() is the new iteritems(). > Mainly, it > just looks really weird to check for one thing and then call on > another, especially as it then checks for the other thing in the next > line. Someone mechanically removed occurences of iteritems() from the code and ended up being either too aggressive as the Mailbox class still has an iteritems() method, so mb1.update(mb2) could avoid building a list, or too conservative as Mailbox.iterXXX could be removed, and .XXX() turned into a view following the example of the dict class. If nobody has complained until now (you get an error only for objects with an iteritems() but without an items() method, and those should be rare to non-existent) I think the path to progress is to remove the first alternative completely. def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False ... Please file a bug report. From __peter__ at web.de Sat Feb 22 06:58:15 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Feb 2014 12:58:15 +0100 Subject: argparse question References: Message-ID: Larry Hudson wrote: > I have been reading the argparse section of the 3.3 docs, and running all > the example code. > > But in section 16.4.2.6. for the formatter_class, the second example in > that section illustrating RawDescriptionHelpFormatter, the example code > is: > > parser = argparse.ArgumentParser( > prog='PROG', > formatter_class=argparse.RawDescriptionHelpFormatter, > description=textwrap.dedent('''\ > Please do not mess up this text! > -------------------------------- > I have indented it > exactly the way > I want it > ''')) > parser.print_help() > > But trying to run this gives a NameError on the "description=" line, > saying textwrap is not > defined. If I delete the "textwrap.dedent" (with or without also deleting > the extra parentheses) it will then run, but without the un-indenting it > is trying to illustrate. > > What is the proper way to enable the dedent() method here? textwrap is a module like argparse, and the example doesn't show import argparse either. Insert import textwrap at the beginning of your module and the code should run without error. From rosuav at gmail.com Sat Feb 22 07:46:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 22 Feb 2014 23:46:06 +1100 Subject: Python stdlib code that looks odd In-Reply-To: References: Message-ID: On Sat, Feb 22, 2014 at 10:54 PM, Peter Otten <__peter__ at web.de> wrote: > Please file a bug report. http://bugs.python.org/issue20729 created. ChrisA From breamoreboy at yahoo.co.uk Sat Feb 22 09:15:22 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Feb 2014 14:15:22 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: On 22/02/2014 02:47, Dennis Lee Bieber wrote: > BASIC, C, FORTRAN, COBOL, Assembly... A "variable" is synonym for an > address [a box that holds things]. > In C. int xyz = 1; xyz is placed in a register. What is xyz called now as it's not in memory? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From thrinaxodon.lord.of at users-network.thrinaxodon Sat Feb 22 09:37:14 2014 From: thrinaxodon.lord.of at users-network.thrinaxodon (THRINAXODON, LORD OF USER'S NETWORK) Date: Sat, 22 Feb 2014 09:37:14 -0500 Subject: SMITHSONIAN DOWN AND BLEEDING -- THE THRINAXODON TIMES REPORTS Message-ID: ============== >BREAKING NEWS ============== > SMITHSONIAN FINALLY SHUT DOWN AFTER YEARS OF CENSORSHIP, SCAMS AND CON ARTISTRY. > THRINAXODON BLEW DOWN THE BUILDINGS, LIT IT ON FIRE AND HAD THE ASSHOLES ARRESTED. > R. DAWKINS WAS THROWN IN THE DOGHOUSE, ONLY TO GET KILLED BY ANGRY FELONS WHO WANTED PAYBACK FOR FRAMING THEM. > THRINAXODON DANCED ON DAWKINS' GRAVE, AND BURNED A FEW SMITHSONIAN MAGAZINES. > ================================= EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER. ====================================== > THRINAXODON WAS AWARDED US$100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 DOLLARS FOR HIS BRAVE EFFORTS IN SHUTTING DOWN THE EVOLUTIONARY SCAMS. -- Thrinaxodon, the ultimate defender of USENET. From marko at pacujo.net Sat Feb 22 09:44:03 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 22 Feb 2014 16:44:03 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: <87ppmfcimk.fsf@elektro.pacujo.net> Mark Lawrence : > On 22/02/2014 02:47, Dennis Lee Bieber wrote: >> BASIC, C, FORTRAN, COBOL, Assembly... A "variable" is synonym >> for an address [a box that holds things]. > > In C. > > int xyz = 1; > > xyz is placed in a register. What is xyz called now as it's not in > memory? It's still a box, just like in Python. The difference is that while in C, the box looks like this: in Python, it looks like this: Marko From anthra.norell at bluewin.ch Sat Feb 22 09:56:41 2014 From: anthra.norell at bluewin.ch (F.R.) Date: Sat, 22 Feb 2014 15:56:41 +0100 Subject: Storing the state of script between steps In-Reply-To: References: Message-ID: <5308BAA9.10707@bluewin.ch> On 02/21/2014 09:59 PM, Denis Usanov wrote: > Good evening. > > First of all I would like to apologize for the name of topic. I really didn't know how to name it more correctly. > > I mostly develop on Python some automation scripts such as deployment (it's not about fabric and may be not ssh at all), testing something, etc. In this terms I have such abstraction as "step". > > Some code: > > class IStep(object): > def run(): > raise NotImplementedError() > > And the certain steps: > > class DeployStep: ... > class ValidateUSBFlash: ... > class SwitchVersionS: ... > > Where I implement run method. > Then I use some "builder" class which can add steps to internal list and has a method "start" running all step one by one. > > And I like this. It's loosely coupled system. It works fine in simple cases. But sometimes some steps have to use the results from previous steps. And now I have problems. Before now I had internal dict in "builder" and named it as "world" and passed it to each run() methods of steps. It worked but I disliked this. > > How would you solve this problem and how would you do it? I understant that it's more architecture specific question, not a python one. > > I bet I wouldn't have asked this if I had worked with some of functional programming languages. A few months ago I posted a summary of a data transformation framework inviting commentary. (https://mail.python.org/pipermail/python-list/2013-August/654226.html). It didn't meet with much interest and I forgot about it. Now that someone is looking for something along the line as I understand his post, there might be some interest after all. My module is called TX. A base class "Transformer" handles the flow of data. A custom Transformer defines a method "T.transform (self)" which transforms input to output. Transformers are callable, taking input as an argument and returning the output: transformed_input = T (some_input) A Transformer object retains both input and output after a run. If it is called a second time without input, it simply returns its output, without needlessly repeating its job: same_transformed_input = T () Because of this IO design, Transformers nest: csv_text = CSV_Maker (Data_Line_Picker (Line_Splitter (File_Reader ('1st-quarter-2013.statement')))) A better alternative to nesting is to build a Chain: Statement_To_CSV = TX.Chain (File_Reader, Line_Splitter, Data_Line_Picker, CSV_Maker) A Chain is functionally equivalent to a Transformer: csv_text = Statement_To_CSV ('1st-quarter-2013.statement') Since Transformers retain their data, developing or debugging a Chain is a relatively simple affair. If a Chain fails, the method "show ()" displays the innards of its elements one by one. The failing element is the first one that has no output. It also displays such messages as the method "transform (self)" would have logged. (self.log (message)). While fixing the failing element, the element preceding keeps providing the original input for testing, until the repair is done. Since a Chain is functionally equivalent to a Transformer, a Chain can be placed into a containing Chain alongside Transformers: Table_Maker = TX.Chain (TX.File_Reader (), TX.Line_Splitter (), TX.Table_Maker ()) Table_Writer = TX.Chain (Table_Maker, Table_Formatter, TX.File_Writer (file_name = '/home/xy/office/addresses-4214')) DB_Writer = TX.Chain (Table_Maker, DB_Formatter, TX.DB_Writer (table_name = 'contacts')) Better: Splitter = TX.Splitter (TX.Table_Writer (), TX.DB_Writer ()) Table_Handler = TX.Chain (Table_Maker, Splitter) Table_Handler ('home/xy/Downloads/report-4214') # Writes to both file and to DB If a structure builds up too complex to remember, the method "show_tree ()" would display something like this: Chain Chain[0] - Chain Chain[0][0] - Quotes Chain[0][1] - Adjust Splits Chain[1] - Splitter Chain[1][0] - Chain Chain[1][0][0] - High_Low_Range Chain[1][0][1] - Splitter Chain[1][0][1][0] - Trailing_High_Low_Ratio Chain[1][0][1][1] - Standard Deviations Chain[1][1] - Chain Chain[1][1][0] - Trailing Trend Chain[1][1][1] - Pegs Following a run, all intermediary formats are accessible: standard_deviations = C[1][0][1][1]() TM = TX.Table_Maker () TM (standard_deviations).write () 0 | 1 | 2 | 116.49 | 132.93 | 11.53 | 115.15 | 128.70 | 11.34 | 1.01 | 0.00 | 0.01 | A Transformer takes parameters, either at construction time or by means of the method "T.set (key = parameter)". Whereas a File Reader doesn't get payload passed and may take a file name as input argument, as a convenient alternative, a File Writer does take payload and the file name must be set by keyword: File_Writer = TX.File_Writer (file_name = '/tmp/memos-with-dates-1') File_Writer (input) # Writes file File_Writer.set ('/tmp/memos-with-dates-2') File_Writer () # Writes the same thing to the second file That's about it. I am very pleased with the design. I developed it to wrap a growing jungle of existing modules and classes having no interconnectability and no common input-output specifications. The improvement in terms of work time and resource management is enormous. I would share the base class and a few custom classes, reasonably autonomous to not require surgical extraction from the jungle. Writing a custom class requires no more than defining private keywords, if any, and writing the method "transform (self)", or "process_record (self, record)" if the input is a list of records, which it often is. The modular design encourages to have a Transformer do just one simple thing, easy to write and easy to debug. Complexity comes from assembling simple Transformers in a great variety of configurations. Frederic From davea at davea.name Sat Feb 22 10:02:10 2014 From: davea at davea.name (Dave Angel) Date: Sat, 22 Feb 2014 10:02:10 -0500 (EST) Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: Mark Lawrence Wrote in message: > On 22/02/2014 02:47, Dennis Lee Bieber wrote: >> BASIC, C, FORTRAN, COBOL, Assembly... A "variable" is synonym for an >> address [a box that holds things]. >> > > In C. > > int xyz = 1; > > xyz is placed in a register. What is xyz called now as it's not in memory? Don't know why you'd assume it's a register. It could just as well be nowhere. If a later reference in the same function adds it to something else, there might not need to be any hardware anywhere representing the value 1. Once you turn on a C optimizer, the real existence of local values is not assured. -- DaveA From thrinaxodon.lord.of.usenet123 at gmail.com Sat Feb 22 10:51:22 2014 From: thrinaxodon.lord.of.usenet123 at gmail.com (thrinaxodon.lord.of.usenet123 at gmail.com) Date: Sat, 22 Feb 2014 07:51:22 -0800 (PST) Subject: RICHARD LEAKEY JUMPS SINKING SHIP Message-ID: <6f3bdd4f-9f4b-40fc-86f7-307cf15bfb70@googlegroups.com> ================== >BREAKING NEWS!!!! ================== > THRINAXODON JUST BEAT RICHARD LEAKEY 100-0 IN WORLD SCIENCE CHAMPIONSHIP. LEAKEY WAS TRYING WITH ALL HIS MIGHT TO PROVE HUMAN'S QUATERNARY ORIGINS, BUT THRINAXODON DEFEATED HIM WITH A FEW HUMAN DEVONIAN FOSSILS. > THE FOSSILS WERE EXACT, SAYS TOP SCIENTIST BOB CASANOVA, WHO EXAMINED THE FOSSILS AND SAW PROOF THAT THESE FOSSILS WERE THE REAL DEAL. > LEAKEY WAS CRYING WHEN THRINAXODON GAINED ONE MILLION DOLLARS FOR HIS CONTRIBUTIONS TO SCIENCE. > ================================= EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER. From milos2244 at gmail.com Sat Feb 22 16:48:17 2014 From: milos2244 at gmail.com (milos2244 at gmail.com) Date: Sat, 22 Feb 2014 13:48:17 -0800 (PST) Subject: Wheezy.web - is it been developed? In-Reply-To: References: Message-ID: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Let's open a group for Wheezy.web. I'm just wondering which forum site to choose? Any suggestions? From milos2244 at gmail.com Sat Feb 22 17:12:43 2014 From: milos2244 at gmail.com (milos2244 at gmail.com) Date: Sat, 22 Feb 2014 14:12:43 -0800 (PST) Subject: Wheezy.web - is it been developed? In-Reply-To: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> References: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Message-ID: <37c74978-2e73-4975-bdee-bfcc18e5f3c5@googlegroups.com> https://groups.google.com/forum/#!forum/wheezyweb Here's a forum. I am not sure where this will lead, but maybe we need it in the future. From rosuav at gmail.com Sat Feb 22 17:30:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 09:30:42 +1100 Subject: Wheezy.web - is it been developed? In-Reply-To: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> References: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Message-ID: On Sun, Feb 23, 2014 at 8:48 AM, wrote: > Let's open a group for Wheezy.web. I'm just wondering which forum site to choose? Any suggestions? If you want to discuss something serious, use a Mailman list. Everywhere I go, Mailman lists have high signal-to-noise ratios, higher than pretty much everything else I know. (And most of the problems on python-list come from the newsgroup side. Google Groups's messes, a lot of the spam, it's all from comp.lang.python rather than python-list.) Use a web forum like PHPBB or VBulletin if you think you need to; a Facebook or G+ group if you want inanity; a weekly get-together if you want tea; but a Mailman list if you want solid content. ChrisA From torriem at gmail.com Sat Feb 22 18:07:55 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 22 Feb 2014 16:07:55 -0700 Subject: is there a package similar to SHINY in R for python ... In-Reply-To: References: <5308152F.2040603@gmail.com> Message-ID: <53092DCB.9080900@gmail.com> On 02/22/2014 12:04 PM, Dennis Lee Bieber wrote: > Except he did state "... in the web browser ...", so I responded on > that side... You're right of course. Sorry about that. I kind of wondered why he was asking when R does the job. > > Apparently "shiny" is rather new... It isn't mentioned in any of: R in > a Nutshell 2nd ed; R Graphics Cookbook; R Graphics 2nd ed; The R Book 2nd > ed; Guidebook to R Graphics Using Microsoft Windows, nor Using R for > Introductory Statistics... From steve+comp.lang.python at pearwood.info Sat Feb 22 19:39:36 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Feb 2014 00:39:36 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: <53094348$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 13:03:33 -0500, Dennis Lee Bieber wrote: > As I recall, to handle garbage collection, Apple used to use two stage > look ups... The user variable (handle) was a reference into a table of > handles, and each entry in that table was a reference to the real object > out in memory. Garbage collection would move the objects around to > compact used memory, updating the address in the table -- the user > program never sees the object moving as its handle address never > changed. Yes, but that was not transparent to the user. You actually had to explicitly use the Mac Toolbox memory routines to allocate memory, create and destroy handles, etc. If you just used your programming language's normal pointers, they couldn't and wouldn't move. -- Steven From glenn.a.isaac at gmail.com Sat Feb 22 19:39:50 2014 From: glenn.a.isaac at gmail.com (glenn.a.isaac at gmail.com) Date: Sat, 22 Feb 2014 16:39:50 -0800 (PST) Subject: Google app engine database Message-ID: Is there a way to make sure that whenever you're making google engine app iterations to a database that that info does not get wiped/deleted. Please advise From breamoreboy at yahoo.co.uk Sat Feb 22 19:57:11 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Feb 2014 00:57:11 +0000 Subject: Google app engine database In-Reply-To: References: Message-ID: On 23/02/2014 00:39, glenn.a.isaac at gmail.com wrote: > Is there a way to make sure that whenever you're making google engine app iterations to a database that that info does not get wiped/deleted. Please advise > What Python code have you tried or are you contemplating using? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From steve+comp.lang.python at pearwood.info Sat Feb 22 20:39:18 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Feb 2014 01:39:18 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> Message-ID: <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 14:15:22 +0000, Mark Lawrence wrote: > On 22/02/2014 02:47, Dennis Lee Bieber wrote: >> BASIC, C, FORTRAN, COBOL, Assembly... A "variable" is synonym for >> an address [a box that holds things]. >> >> > In C. > > int xyz = 1; > > xyz is placed in a register. What is xyz called now as it's not in > memory? Of course it is in memory, just not main memory, and it is still accessed via an address. It's just that the address is something equivalent to "Register 5" instead of "address 12345678 in RAM". You're focusing on the wrong thing here. The distinction is not "in main memory" versus "in a register" (or somewhere else). The distinction is not *where* the value lives, but the semantics of what it means to associate a name with a value. In C or Pascal-style languages, what we might call the "fixed address" style of variables, a variable assignment like xyz = 1 does something like this: - associate the name 'xyz' with some fixed location - stuff the value 1 into that location In Python-style languages, what we might call the "name binding" style of variables, that same xyz = 1 means: - find or create the object 1 - associate the name 'xyz' with that object In implementations like Jython and IronPython, the object is even free to move in memory while in use. But that's not the only difference. The big difference is that in "fixed location" languages, it makes sense to talk about the address of a *variable*. In C, you might ask for &xyz and get 123456 regardless of whether xyz is assigned the value 1, or 23, or 999. But in Python, you can't ask for the address of a variable, only of the address of an *object* (and even that is useless to you, as you can't do anything with that address). -- Steven From rosuav at gmail.com Sat Feb 22 20:50:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 12:50:26 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 23, 2014 at 12:39 PM, Steven D'Aprano wrote: > In C or Pascal-style languages, what we might call the "fixed address" > style of variables, a variable assignment like xyz = 1 does something > like this: > > - associate the name 'xyz' with some fixed location > - stuff the value 1 into that location Kinda. In its purest sense, C is like that. When you declare "int xyz;", the compiler allocates one machine word of space either in the data segment (if that's at top level, or is declared static) or on the stack (if it's local), and records that the name xyz points there. But an optimizing C compiler is allowed to do what it likes, as long as it maintains that name binding... and as long as any recorded address of it remains valid. It's actually very similar to what was discussed in another thread recently about PyPy and the id() function - the compiler's free to have xyz exist in different places, or not exist at all, as long as the program can't tell the difference. I don't know whether PyPy allocates an id for everything or only when you call id(), but if the latter, then it's exactly the same as a C compiler with the address-of operator - if you never take the address, it doesn't have to have one (and even if you do, it's free to fiddle with things, unless you declare the variable volatile). So, these days, C is becoming more like Python. ChrisA From swdunning at cox.net Sat Feb 22 20:52:19 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 22 Feb 2014 18:52:19 -0700 Subject: Function and turtle help In-Reply-To: References: <75339005-9609-48D8-9DEF-EF0B0CEE7B39@cox.net> <83EDD1E2-1F6F-498E-900D-B604BAF47EE9@cox.net> Message-ID: <411D00F0-9365-44A7-A949-C9E6DD8AF3A0@cox.net> On Feb 21, 2014, at 9:30 PM, Dave Angel wrote: You?re awesome David! Thanks for taking the time to not only help answer my question but helping me to understand it as well!! Scott From lightaiyee at gmail.com Sat Feb 22 23:06:13 2014 From: lightaiyee at gmail.com (Sam) Date: Sat, 22 Feb 2014 20:06:13 -0800 (PST) Subject: Can tuples be replaced with lists all the time? Message-ID: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> My understanding of Python tuples is that they are like immutable lists. If this is the cause, why can't we replace tuples with lists all the time (just don't reassign the lists)? Correct me if I am wrong. From no.email at nospam.invalid Sat Feb 22 23:28:54 2014 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 22 Feb 2014 20:28:54 -0800 Subject: Can tuples be replaced with lists all the time? References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: <7xios6wiyh.fsf@ruckus.brouhaha.com> Sam writes: > My understanding of Python tuples is that they are like immutable > lists. If this is the cause, why can't we replace tuples with lists > all the time (just don't reassign the lists)? You can do that a lot of the time but not always. For example, you can use a tuple as a dictionary key, but not a list, since keys are supposed to be immutable. From rosuav at gmail.com Sat Feb 22 23:18:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 15:18:27 +1100 Subject: Can tuples be replaced with lists all the time? In-Reply-To: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: On Sun, Feb 23, 2014 at 3:06 PM, Sam wrote: > My understanding of Python tuples is that they are like immutable lists. If this is the cause, why can't we replace tuples with lists all the time (just don't reassign the lists)? Correct me if I am wrong. > One reason is performance/efficiency. If Python knows this is never going to change, it can save some effort. But a more important reason is hashability. >>> mapping = {} >>> key = (1,2) >>> mapping[key] = "Hello" >>> key = (1,3) >>> mapping[key] = "World" >>> key = (2,3) >>> mapping[key] = "!" >>> mapping {(1, 2): 'Hello', (1, 3): 'World', (2, 3): '!'} You can't do this with lists: >>> key = [1,2] >>> mapping[key] Traceback (most recent call last): File "", line 1, in mapping[key] TypeError: unhashable type: 'list' This is because any two tuples are either equal or not equal, they can't be otherwise. I can create another tuple and look up something in the above mapping: >>> mapping[1,3] 'World' But with lists, their equality can change. >>> lst1 = [1,2] >>> lst2 = [1,3] >>> lst1 == lst2 False >>> lst1[1] += 1 >>> lst1 == lst2 True >>> lst1[1] += 1 >>> lst1 == lst2 False So it would be very difficult and dangerous to try to use a list as a dictionary key. The only safe way to do it is by identity, and that's only useful in a very small set of situations. So Python happily declares that a tuple can be a dict key and a list can't, and that's now a key (if you'll excuse the pun) difference between them. ChrisA From ben+python at benfinney.id.au Sat Feb 22 23:49:19 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Feb 2014 15:49:19 +1100 Subject: Can tuples be replaced with lists all the time? References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: <85y512ph68.fsf@benfinney.id.au> Sam writes: > My understanding of Python tuples is that they are like immutable > lists. That's a common expression, but I think it's not a helpful way to think of them. Rather, the different sequence types have different semantic purposes: * For representing a sequence where each item means exactly the same no matter which position it's in (a ?homogeneous sequence?), use a list. * For representing a sequence where the meaning of each item is strongly dependent on its position in the sequence (a ?heterogeneous sequence?), use a tuple. See for the official Python description of the type differences. > If this is the cause, why can't we replace tuples with lists all the > time (just don't reassign the lists)? Correct me if I am wrong. Because we need to represent different semantic concepts in our code, and have each type support the semantics with different operations. -- \ ?I went camping and borrowed a circus tent by mistake. I didn't | `\ notice until I got it set up. People complained because they | _o__) couldn't see the lake.? ?Steven Wright | Ben Finney From orgnut at yahoo.com Sun Feb 23 00:58:28 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sat, 22 Feb 2014 21:58:28 -0800 Subject: argparse question In-Reply-To: References: Message-ID: On 02/22/2014 03:58 AM, Peter Otten wrote: > Larry Hudson wrote: > >> I have been reading the argparse section of the 3.3 docs, and running all >> the example code. >> >> But in section 16.4.2.6. for the formatter_class, the second example in >> that section illustrating RawDescriptionHelpFormatter, the example code >> is: >> >> parser = argparse.ArgumentParser( >> prog='PROG', >> formatter_class=argparse.RawDescriptionHelpFormatter, >> description=textwrap.dedent('''\ >> Please do not mess up this text! >> -------------------------------- >> I have indented it >> exactly the way >> I want it >> ''')) >> parser.print_help() >> >> But trying to run this gives a NameError on the "description=" line, >> saying textwrap is not >> defined. If I delete the "textwrap.dedent" (with or without also deleting >> the extra parentheses) it will then run, but without the un-indenting it >> is trying to illustrate. >> >> What is the proper way to enable the dedent() method here? > > textwrap is a module like argparse, and the example doesn't show > > import argparse > > either. Insert > > import textwrap > > at the beginning of your module and the code should run without error. > Thanx. Guess I shoulda searched for textwrap or dedent in the docs. :-) -=- Larry -=- From steve+comp.lang.python at pearwood.info Sun Feb 23 01:20:41 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Feb 2014 06:20:41 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <53099339$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 23 Feb 2014 12:50:26 +1100, Chris Angelico wrote: > On Sun, Feb 23, 2014 at 12:39 PM, Steven D'Aprano > wrote: >> In C or Pascal-style languages, what we might call the "fixed address" >> style of variables, a variable assignment like xyz = 1 does something >> like this: >> >> - associate the name 'xyz' with some fixed location >> - stuff the value 1 into that location > > Kinda. In its purest sense, C is like that. When you declare "int xyz;", > the compiler allocates one machine word of space either in the data > segment (if that's at top level, or is declared static) or on the stack > (if it's local), and records that the name xyz points there. But an > optimizing C compiler is allowed to do what it likes, as long as it > maintains that name binding... and as long as any recorded address of it > remains valid. I think that's a red herring. The semantics of the language are that it behaves as if the variable had a fixed location. What goes on behind the scenes is interesting but fundamentally irrelevant if you want to understand the language itself: the compiler's implementation may give that variable a fixed location, or not, or multiple locations, or non- fixed, or whatever it finds useful at the time, so long as the C code you write can assume that it is fixed. (That's like Python, which has no pointers. The fact that the implementation of some Python interpreters uses pointers all over the place is strictly irrelevant.) In practice, because C compilers usually work so close to the metal, and programmers expect there to be a very direct correspondence between the C code you write and the machine code you get, the compiler is unlikely to simulate fixed addresses unless there is real benefit to be gained, it is more likely to actually use fixed addresses. But in principle, one might write a C interpreter in Jython, and simulate fixed addresses over the top of a language without any addresses at all (Python), which in turn is written in a language where the garbage collector can move things around (Java). The important thing here is not so much that we are disagreeing, but that we are talking about two different levels of explanation. ("G?del, Escher And Bach" has an very interesting section about how explanations at different levels can be radically different and even contradict each other.) At the C source code level, the language mandates that variables have fixed addresses, to the extent that C source code knows about addresses at all. At the generated machine code level, the compiler is free to play tricks if necessary. Another example: if you have a variable unused=23, and the compiler removes it because it's dead code, we wouldn't argue that therefore C variables have no existence at all. Would we? :-) > So, these days, C is becoming more like Python. *raises eyebrow* I think the stress of the exception-expression PEP is getting to you. They truly aren't. *wink* -- Steven From rosuav at gmail.com Sun Feb 23 02:23:57 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 18:23:57 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <53099339$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <53099339$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Feb 23, 2014 at 5:20 PM, Steven D'Aprano wrote: > The important thing here is not so much that we are disagreeing, but that > we are talking about two different levels of explanation. ("G?del, Escher > And Bach" has an very interesting section about how explanations at > different levels can be radically different and even contradict each > other.) At the C source code level, the language mandates that variables > have fixed addresses, to the extent that C source code knows about > addresses at all. At the generated machine code level, the compiler is > free to play tricks if necessary. I think that's a good summary, actually. C has variables, at the source code level, but once you compile it down, it might not. From which it follows that C variables have addresses (unless they're declared 'register', in which case they might still be stored in RAM but no longer have addresses), which may or may not have any actual relationship to memory addresses. > Another example: if you have a variable unused=23, and the compiler > removes it because it's dead code, we wouldn't argue that therefore C > variables have no existence at all. Would we? :-) > >> So, these days, C is becoming more like Python. > > *raises eyebrow* > > I think the stress of the exception-expression PEP is getting to you. > They truly aren't. > > *wink* Haha. I wasn't joking, though; a fully-optimizing compiler is free to do so much that, in reality, you're not writing bare-metal code - you're writing guidelines to a sophisticated program generator. C has become as high level a language as any other, and has acquired some Python-like features (check out some of the recent standards); and, the part that I was talking about here, it makes the most sense to talk about "name bindings" rather than memory addresses. Variables might move around, but if you say "int xyz=5;", then you can be sure that querying xyz will give you back 5. The concreteness of "declare a variable ergo memory is allocated for it" is no longer the case. ChrisA From swdunning at cox.net Sun Feb 23 00:43:17 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sat, 22 Feb 2014 22:43:17 -0700 Subject: Functions help Message-ID: <9E019BD7-4C9D-4DED-A626-22BF474CC7F8@cox.net> Hello, I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? Thanks for any help! Scott From ben+python at benfinney.id.au Sun Feb 23 02:59:15 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Feb 2014 18:59:15 +1100 Subject: Functions help References: <9E019BD7-4C9D-4DED-A626-22BF474CC7F8@cox.net> Message-ID: <85txbqp8do.fsf@benfinney.id.au> Scott W Dunning writes: > I had a question regarding functions. Is there a way to call a > function multiple times without recalling it over and over. You should ask question like this on the ?python-tutor? forum. I say that because this question suggests you have yet to learn about basic Python features like loops. My recommendation is that you work your way thoroughly through the Python tutorial , doing each example and experimenting to understand it before progressing. By the end, you will have a much more comprehensive grasp of the basics of Python, and have a toolkit of concepts and techniques for addressing questions like the above. > Thanks for any help! Hope that helps! Feel free to ask for help on the Tutor forum . -- \ ?We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up.? ?Phyllis Diller | Ben Finney From andriy.kornatskyy at live.com Sun Feb 23 03:03:25 2014 From: andriy.kornatskyy at live.com (Andriy Kornatskyy) Date: Sun, 23 Feb 2014 10:03:25 +0200 Subject: Wheezy.web - is it been developed? In-Reply-To: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> References: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Message-ID: Marcio, The existence of forum site / mailing list does not guarantee your problem will be solved. The bitbucket.org doesn?t offer mailing list feature, however you can subscribe to any changes happening by following me or concrete project there. The specific issues can be tracked down to commit via issues list. What relates to mailing list? I have sent request to google groups to allow dot in name, however there was no reply yet. I suppose that might take a week to hear something back from them. Anyway, should you have any specific questions please use this mailing list or contact me directly. I will be happy to answer in either case. Thanks. Andriy Kornatskyy On Feb 22, 2014, at 11:48 PM, milos2244 at gmail.com wrote: > Let's open a group for Wheezy.web. I'm just wondering which forum site to choose? Any suggestions? > -- > https://mail.python.org/mailman/listinfo/python-list From andriy.kornatskyy at live.com Sun Feb 23 03:21:28 2014 From: andriy.kornatskyy at live.com (Andriy Kornatskyy) Date: Sun, 23 Feb 2014 10:21:28 +0200 Subject: Wheezy.web - is it been developed? In-Reply-To: References: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Message-ID: Chris, Your comments are very valuable. I didn?t find any free mailman lists, so it appears google groups is the only option. Thanks. Andriy Kornatskyy On Feb 23, 2014, at 12:30 AM, Chris Angelico wrote: > On Sun, Feb 23, 2014 at 8:48 AM, wrote: >> Let's open a group for Wheezy.web. I'm just wondering which forum site to choose? Any suggestions? > > If you want to discuss something serious, use a Mailman list. > Everywhere I go, Mailman lists have high signal-to-noise ratios, > higher than pretty much everything else I know. (And most of the > problems on python-list come from the newsgroup side. Google Groups's > messes, a lot of the spam, it's all from comp.lang.python rather than > python-list.) Use a web forum like PHPBB or VBulletin if you think you > need to; a Facebook or G+ group if you want inanity; a weekly > get-together if you want tea; but a Mailman list if you want solid > content. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list From twizansk at gmail.com Sun Feb 23 03:43:14 2014 From: twizansk at gmail.com (twiz) Date: Sun, 23 Feb 2014 00:43:14 -0800 (PST) Subject: Mac vs. Linux for Python Development Message-ID: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Hello, I'm sure this is a common question but I can't seem to find a previous thread that addresses it. If one one exists, please point me to it. I've been developing with python recreationally for a while on Ubuntu but will soon be transitioning to full-time python development. I have the option of using a Mac or Ubuntu environment and I'd like to hear any thoughts on the pros and cons of each. Specifically, how's the support for numpy and scipy? How are the IDEs? Since I generally like working with a Mac, I'd like to hear if there are any significant downsides to python dev on OsX. Thanks From steve+comp.lang.python at pearwood.info Sun Feb 23 03:44:25 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Feb 2014 08:44:25 GMT Subject: Functions help References: Message-ID: <5309b4e9$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Feb 2014 22:43:17 -0700, Scott W Dunning wrote: > Hello, > > I had a question regarding functions. Is there a way to call a function > multiple times without recalling it over and over. Meaning is there a > way I can call a function and then add *5 or something like that? Sorry, I don't really understand your question. Could you show an example of what you are doing? Do you mean "add 5" or "*5"? "Add *5 doesn't really mean anything to me. -- Steven From rosuav at gmail.com Sun Feb 23 03:48:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 19:48:08 +1100 Subject: Wheezy.web - is it been developed? In-Reply-To: References: <9a942a32-ba82-46c9-bc69-73ee2b26d340@googlegroups.com> Message-ID: On Sun, Feb 23, 2014 at 7:21 PM, Andriy Kornatskyy wrote: > Chris, > > Your comments are very valuable. I didn?t find any free mailman lists, so it appears google groups is the only option. The easiest way is usually to just host one. I couldn't find any mailing list about Alice in Wonderland, so I created one: http://lists.rosuav.com/cgi-bin/mailman/listinfo/alice Mailman is free and, to drag this vaguely back on topic, is written in Python. ChrisA From rosuav at gmail.com Sun Feb 23 03:58:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 19:58:27 +1100 Subject: Mac vs. Linux for Python Development In-Reply-To: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: On Sun, Feb 23, 2014 at 7:43 PM, twiz wrote: > I'm sure this is a common question but I can't seem to find a previous thread that addresses it. If one one exists, please point me to it. > > I've been developing with python recreationally for a while on Ubuntu but will soon be transitioning to full-time python development. I have the option of using a Mac or Ubuntu environment and I'd like to hear any thoughts on the pros and cons of each. Specifically, how's the support for numpy and scipy? How are the IDEs? > > Since I generally like working with a Mac, I'd like to hear if there are any significant downsides to python dev on OsX. There have been some issues with running Python on OSX, so you'd want to make sure you're running the very latest; for instance, 3.3.4 fixed some issues with 10.9 Mavericks. Generally, I'd say you'll do reasonably well on either platform, as long as you're happy with the editor and related tools; but personally, I love my Linux for development. I use Debian (Ubuntu is closely related to Debian), with Xfce, SciTE, and roughly ten thousand terminal windows - that's my "IDE". SciTE is available for a Mac, and there are plenty of other excellent text editors as well, so you shouldn't have any trouble on that score. Your text editor is probably more important to your productivity than your OS is. Whether you're on Windows, Mac OS, or Linux, or something more obscure like OS/2, you can run your scripts just fine (OS/2 isn't an officially supported Python platform, but I have a third-party build that works fine for me); the important part is getting code from your brain through your fingers into the computer, and a good editor can help hugely with that. You'll hear advocates for vi/vim, emacs, and myriad others, but ultimately, just grab one that looks good and get to know it :) Personally, I'd recommend going Linux, for the openness; among other benefits, it's generally easier to build C stuff from source on Linux than on pretty much any other platform. But you should be able to use your preferred Mac just fine, and learning something new is a cost that's hard to justify. Just do be sure (and yes, I'm reiterating this) that you're on the very latest Python you can get. At the moment, that's 3.3.4, but soon there'll be a 3.4 release. ChrisA From andriy.kornatskyy at live.com Sun Feb 23 04:51:44 2014 From: andriy.kornatskyy at live.com (Andriy Kornatskyy) Date: Sun, 23 Feb 2014 11:51:44 +0200 Subject: Mac vs. Linux for Python Development In-Reply-To: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: I used to do core python development using debian linux (gnome). All way long work just fine. However recently I have had a chance to try MacOS X 10.8 and later 10.9. I used macports.org to setup everything I found ?missing?. Vim works fine regardless the platform? quite happy. Thanks. Andriy Kornatskyy On Feb 23, 2014, at 10:43 AM, twiz wrote: > Hello, > > I'm sure this is a common question but I can't seem to find a previous thread that addresses it. If one one exists, please point me to it. > > I've been developing with python recreationally for a while on Ubuntu but will soon be transitioning to full-time python development. I have the option of using a Mac or Ubuntu environment and I'd like to hear any thoughts on the pros and cons of each. Specifically, how's the support for numpy and scipy? How are the IDEs? > > Since I generally like working with a Mac, I'd like to hear if there are any significant downsides to python dev on OsX. > > Thanks > > -- > https://mail.python.org/mailman/listinfo/python-list From marko at pacujo.net Sun Feb 23 04:52:05 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 23 Feb 2014 11:52:05 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <877g8mcg1m.fsf@elektro.pacujo.net> Steven D'Aprano : > The big difference is that in "fixed location" languages, it makes > sense to talk about the address of a *variable*. The address could be a symbol, too. The Python statement xyz = 3 places a number in the address "xyz". You can read the value from the address "xyz" with locals()["xyz"] Marko From kevin.p.dwyer at gmail.com Sun Feb 23 04:56:55 2014 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sun, 23 Feb 2014 09:56:55 +0000 Subject: Google app engine database References: Message-ID: glenn.a.isaac at gmail.com wrote: > Is there a way to make sure that whenever you're making google engine app > iterations to a database that that info does not get wiped/deleted. > Please advise It's not clear what you mean here; I'll guess that by "iterations" you mean "changes" by "database" you mean the db or ndb datastore and by "info" you mean "data stored in the datastore". Apologies if this isn't so. Appengine doesn't document any migration utilities to handle changes in your datastore schema, so you need to manage the effects of such changes yourself. To ensure that you do not lose data when changing your model code, avoid making destructive changes to your models, i.e. - don't delete properties from a model - don't rename properties on a model If you must make these changes for some reason, you'll need to migrate the data somehow. In my experience with Appengine, data is not actaully lost if you make destructive changes to your models, it becomes inaccessible becuae the property names it was stored under no longer exist on the model. In theory you could access the data by adding the proprties back to the model or (maybe) by loading a different model definition in the remote shell, but this is not something that you would want to rely on in a production environment. tl,dr: it's ok to add new properties to you models, but don't remove or rename properties. Hope that helps, Kev From twizansk at gmail.com Sun Feb 23 05:17:03 2014 From: twizansk at gmail.com (twiz) Date: Sun, 23 Feb 2014 02:17:03 -0800 (PST) Subject: Mac vs. Linux for Python Development In-Reply-To: References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: <966f68f1-a50a-496e-8126-691c4eeab258@googlegroups.com> Hi Chris, thanks for the reply. Yes, I agree. The main consideration is always the development experience. However, I do know that python has had some problems with other OSs (notoriously windows) and I want to avoid unnecessary compatibility issues. Can you elaborate on some of the problems running python on OSX (or point me to a relavant link)? Thanks Tommer From rosuav at gmail.com Sun Feb 23 05:24:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 21:24:11 +1100 Subject: Mac vs. Linux for Python Development In-Reply-To: <966f68f1-a50a-496e-8126-691c4eeab258@googlegroups.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> <966f68f1-a50a-496e-8126-691c4eeab258@googlegroups.com> Message-ID: On Sun, Feb 23, 2014 at 9:17 PM, twiz wrote: > Can you elaborate on some of the problems running python on OSX (or point me to a relavant link)? You could poke around on the archives of this list and python-dev, but the best link I have handy is this, which has only a brief note: http://www.python.org/download/releases/3.3.4/ ChrisA From rosuav at gmail.com Sun Feb 23 05:32:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 21:32:49 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <877g8mcg1m.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> Message-ID: On Sun, Feb 23, 2014 at 8:52 PM, Marko Rauhamaa wrote: > Steven D'Aprano : > >> The big difference is that in "fixed location" languages, it makes >> sense to talk about the address of a *variable*. > > The address could be a symbol, too. > > The Python statement > > xyz = 3 > > places a number in the address "xyz". > > You can read the value from the address "xyz" with > > locals()["xyz"] No, you cannot. That's the exact line of thinking that leads to problems. You are not placing a number at the address "xyz", you are pointing the name "xyz" to the number 3. That number still exists elsewhere. xyz = 3 abc = xyz Does this copy the 3 from xyz into abc? In C, it would. Those variables might not "exist" anywhere, but they must, by definition, be storing the integer 3. And that integer has been copied. But in Python, no it does not. It doesn't *copy* anything. And if you fiddle with the integer 3 in some way, making it different, it'll be different whether you look at xyz or abc, because they're the same 3. You can't see that with integers because Python's int is immutable, but this is where the confusion about mutable vs immutable objects comes from. Immutable objects behave *sufficiently similarly* to the C/Pascal model that it's possible to think Python works the same way, but it doesn't. The nearest C equivalent to what I'm talking about is pointers. (CPython objects are basically used with pointers anyway. When you get back an object reference from a CPython API function, you get a pointer, optionally with the responsibility for one of its references.) This is broadly how Python objects work: /* Python strings are immutable, so the equivalent would be a list. */ /* I'm using a string because C doesn't have a list type. */ char *xyz = strcpy(malloc(20),"Hello, world!"); char *abc = xyz; xyz[1] = 'a'; printf("abc has: %s\n", abc); That'll show that abc has "Hallo, world!", even though it was through xyz that the change was made. The "thing" that is that string is the puddle of bytes on the heap (allocated with the malloc(20) up above). The name just has a reference to that. Creating another reference to the same object doesn't change anything. ChrisA From steve+comp.lang.python at pearwood.info Sun Feb 23 05:30:34 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Feb 2014 10:30:34 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> Message-ID: <5309cdc9$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 23 Feb 2014 11:52:05 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> The big difference is that in "fixed location" languages, it makes >> sense to talk about the address of a *variable*. > > The address could be a symbol, too. > > The Python statement > > xyz = 3 > > places a number in the address "xyz". It doesn't matter whether addresses are numeric or symbolic, Python does not use that model for variables. Consider this example. There are a few steps, so let's go through them. First we prove that so-called address "abc" and "xyz" are distinct. If they were the same address, then they would logically have to contain the same value, but that is not the case: abc = 23 xyz = 42 assert abc != xyz This proves that the two addresses are different. Now we prove that they are the same address: abc = xyz = [] xyz.append(42) assert abc == [42] If they were different, then modifying the object at xyz cannot modify the object at abc. So we have a contradiction: "addresses" abc and xyz are both the same address, and different addresses. There is a way to wiggle out of the contradiction: accept that the addresses are distinct, but claim that a single object can be in two different locations at once. But if we make that argument, we are stretching the metaphor of location quite considerably. Absent time- travel, objects cannot be in two locations at once. Claiming that they can be requires stretching the metaphor of location past breaking point. Self-confession time: some years ago, I used to make exactly that argument. I used to argue that the right way to visualise Python's variable model was to consider that objects were stored in variables in exactly the way you are suggesting. I didn't describe them as symbolic addresses, but otherwise the model was the same. In order to make the model work, I argued that objects could be in more than one place at once, including *inside* itself: L = [] L.append(L) and explicitly argued that this didn't matter. After all, if I can watch Doctor Who and accept the concept of his TARDIS materialising inside itself, I can understand the idea of a list being inside itself. That was before I really grasped the difference between the name binding and fixed location variable models. While I'm still fond of the concept of a box being inside itself, I've come to understand that having to stretch the metaphor of location so far simply indicates that the metaphor does not work with Python's semantics. Python's actual behaviour is not a good fit for the "variables are locations" model, not even if you think of locations in the abstract with symbolic names rather the numeric addresses. -- Steven From marko at pacujo.net Sun Feb 23 06:01:25 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 23 Feb 2014 13:01:25 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> Message-ID: <87ob1yay9m.fsf@elektro.pacujo.net> Chris Angelico : > That's the exact line of thinking that leads to problems. You are not > placing a number at the address "xyz", you are pointing the name "xyz" > to the number 3. That number still exists elsewhere. And? In C, I can say: Number *o = malloc(sizeof *o); o->value = 3; Your statement is valid: the number 3 resides elsewhere than the variable o. As for Python, there's nothing in the Python specification that would prevent you from having, say, 63-bit integers as representing themselves. IOW, you could physically place such integers as themselves as the reference and the number would not physically exist elsewhere. Bottom line, there's no fundamental difference between C and Python variables. Marko From rosuav at gmail.com Sun Feb 23 06:12:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 23 Feb 2014 22:12:26 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87ob1yay9m.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> Message-ID: On Sun, Feb 23, 2014 at 10:01 PM, Marko Rauhamaa wrote: > As for Python, there's nothing in the Python specification that would > prevent you from having, say, 63-bit integers as representing > themselves. IOW, you could physically place such integers as themselves > as the reference and the number would not physically exist elsewhere. What would id(5) be? Some constant? What would id(id([])) be? ChrisA From gd.usenet at spamfence.net Sun Feb 23 06:34:26 2014 From: gd.usenet at spamfence.net (=?ISO-8859-1?Q?G=FCnther?= Dietrich) Date: Sun, 23 Feb 2014 12:34:26 +0100 Subject: Mac vs. Linux for Python Development References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: twiz wrote: >I've been developing with python recreationally for a while on Ubuntu but will >soon be transitioning to full-time python development. I have the option of >using a Mac or Ubuntu environment and I'd like to hear any thoughts on the >pros and cons of each. I've been working with Windows, Unix/Linux (X) and Max OS since 1989. In my experience the GUI of Mac OS is the most user friendly of the the three. >Specifically, how's the support for numpy and scipy? >How are the IDEs? > >Since I generally like working with a Mac, I'd like to hear if there are any >significant downsides to python dev on OsX. Eclipse and the PyDev and MercurialEclipse plug-ins are available for Windows, Linux and Mac OS. So, if I had the choice, I would go with the Mac. Best regards, G?nther From nad at acm.org Sun Feb 23 06:49:22 2014 From: nad at acm.org (Ned Deily) Date: Sun, 23 Feb 2014 03:49:22 -0800 Subject: Mac vs. Linux for Python Development References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> <966f68f1-a50a-496e-8126-691c4eeab258@googlegroups.com> Message-ID: In article , Chris Angelico wrote: > On Sun, Feb 23, 2014 at 9:17 PM, twiz wrote: > > Can you elaborate on some of the problems running python on OSX (or point > > me to a relavant link)? > > You could poke around on the archives of this list and python-dev, but > the best link I have handy is this, which has only a brief note: > > http://www.python.org/download/releases/3.3.4/ The primary issue for 10.9 was an incompatible change in the system libedit's readline compatibility API which could cause Pythons built on earlier versions of OS X to crash on 10.9 when used interactively. Fixed in the current 2.7.6 and 3.3.4 and 3.4.0rc python.org installers. Also, if you are going to use IDLE or Tkinter with a python.org Python, make sure you have the latest ActiveTcl 8.5.15.0 (actually .1) installed, if possible. http://www.python.org/download/mac/tcltk/ -- Ned Deily, nad at acm.org From terminator at of.talk.origins.thrinaxodon Sun Feb 23 08:35:59 2014 From: terminator at of.talk.origins.thrinaxodon (TERMINATOR OF TALK.ORIGINS) Date: Sun, 23 Feb 2014 08:35:59 -0500 Subject: WORLD FAMOUS EVOLUTIONIST IN PRISON -- THE THRINAXODON TIMES Message-ID: ================== > BREAKING NEWS!!!! ================== > RICHARD LEAKEY RECENTLY SENT TO PRISON AFTER BEING CAUGHT SCAMMING MILLIONS OF YOUNG PEOPLE INTO THE SCAM OF EVOLUTION. > THRINAXODON, WHO WAS THE LEAD PROSECUTOR SAID THIS TO THE NY TIMES: It strikes me silly that one of the world's leading evolutionary charlatans finally get put into the place they deserve: PRISON I've been trying FOR YEARS TO GET THESE BASTARDS (LEAKEY, DAWKINS, ETC.) FOR YEARS INTO TOP-MAX PRISONS. ONE HAS FINALLY BEEN SENT, RICHARD LEAKEY. May the rest of the charlatans fall? Who knows. But, this is a warning to all con artists making a buck out of taking peoples souls (e.g. evolutionary bullshit). > LEAKEY WAS SENTENCED TO THREE LIFE SENTENCES AND NO CHANCE OF BAIL. THRINAXODON LED A MOB OF 3,000,000 PEOPLE TO THE PRISON, AND WE ALL CHEERED WITH HAPPINESS THAT OUR KIDS WILL NO LONGER BE FORCED-FED BULLSHIT! > ====================================== EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER -- Thrinaxodon, the ultimate defender of USENET. From exarkun at twistedmatrix.com Sun Feb 23 08:56:40 2014 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sun, 23 Feb 2014 13:56:40 -0000 Subject: [ANN] pyOpenSSL 0.14 Message-ID: <20140223135640.6218.615676796.divmod.xquotient.17@top> Greetings fellow Pythoneers, I'm happy to announce that pyOpenSSL 0.14 is now available. pyOpenSSL is a set of Python bindings for OpenSSL. It includes some low-level cryptography APIs but is primarily focused on providing an API for using the TLS protocol from Python. Check out the PyPI page () for downloads. This release of pyOpenSSL adds: * Support for TLSv1.1 and TLSv1.2 * First-class support for PyPy * New flags, such as MODE_RELEASE_BUFFERS and OP_NO_COMPRESSION * Some APIs to access to the SSL session cache * A variety of bug fixes for error handling cases Additionally, there are three major changes to the project: First, the documentation has been converted from LaTeX (CPython's previous documentation system) to Sphinx (CPython's "new" documentation system ;). You can find the new documentation on the PyPI documentation site () or ). Second, pyOpenSSL is no longer implemented in C as a collection of extension modules using the Python/C API. Instead, pyOpenSSL is now a pure-Python project with a dependency on a new project, cryptography (), which provides (among other things) a cffi-based interface to OpenSSL. This change means that pyOpenSSL development is now more accessible to Python programmers with little or no experience with C. This is also how pyOpenSSL is now able to support PyPy. Finally, the project's code hosting has moved from Launchpad to Github. Many branches remain only on Launchpad along with their associated bug reports. Over the coming releases I hope that the fixes and features in these branches will be ported to Python and incorporated into the pyOpenSSL master development branch. Bug tracking has been disabled on Launchpad so that the amount of useful information hosted there can gradually dwindle to nothing. Please use Github () for further development and bug reporting. Thanks and enjoy, Jean-Paul From marko at pacujo.net Sun Feb 23 10:24:42 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 23 Feb 2014 17:24:42 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> Message-ID: <87k3clc0n9.fsf@elektro.pacujo.net> Chris Angelico : > On Sun, Feb 23, 2014 at 10:01 PM, Marko Rauhamaa wrote: >> As for Python, there's nothing in the Python specification that would >> prevent you from having, say, 63-bit integers as representing >> themselves. IOW, you could physically place such integers as >> themselves as the reference and the number would not physically exist >> elsewhere. > > What would id(5) be? Some constant? What would id(id([])) be? Any suitable scheme would do. For example, id(n) == n for 63-bit integers; other objects are dynamically sequence-numbered starting from a high base (here, 2 ** 64): >>> id(5) 5 >>> id([]) 18446744073709551620 >>> id(id([])) 18446744073709551624 Or id(n) == 2 * n for 63-bit integers; other objects are dynamically sequence-numbered using only odd integers starting from 1: >>> id(5) 10 >>> id([]) 7 >>> id(id([])) 18 Or id(n) == 2 ** 64 + n for 63-bit integers; other objects get the RAM address of the internal ?emory block: >>> id(5) 18446744073709551621 >>> id([]) 3074657068 >>> id(id([])) 18446744076784207372 The possibilities are endless. Marko From rosuav at gmail.com Sun Feb 23 10:41:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 24 Feb 2014 02:41:46 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87k3clc0n9.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <87k3clc0n9.fsf@elektro.pacujo.net> Message-ID: On Mon, Feb 24, 2014 at 2:24 AM, Marko Rauhamaa wrote: > Or id(n) == 2 ** 64 + n for 63-bit integers; other objects get the > RAM address of the internal ?emory block: > > >>> id(5) > 18446744073709551621 > >>> id([]) > 3074657068 > >>> id(id([])) > 18446744076784207372 Assuming you define "63-bit integers" either as 0<=n<2**63 or as -2**62<=n<2**62, this could work, but it would depend on never using memory with addresses with bit 63 set, as id() is (if I recall correctly) supposed to return an integer in the native range. I'm not sure you can depend on that sort of pattern of memory usage. In any case, you'd need some way to pretend that every integer is really an object, so you'd need to define id(), the 'is' operator, and everything else that can work with objects, to ensure that they correctly handle this. It would be a reasonable performance improvement to use native integers for the small ones (where "small" integers might still be fairly large by human standards), but unlike in languages like Pike (which does something like what you're saying), Python has a concept of "object identity" which can't be broken. (Pike's integers simply _are_, they aren't considered separate objects. You can't test them for identity. Its strings, also, simply are, although since Pike strings are guaranteed to be interned, their values and identities really are the same. To Pike, it's only more complex types that need to distinguish value from identity.) So this optimization, which certainly does make sense on the face of it, would potentially make a mess of things elsewhere. I'm sure PyPy optimizes small integers somewhat, though. ChrisA From georg at python.org Sun Feb 23 11:25:21 2014 From: georg at python.org (Georg Brandl) Date: Sun, 23 Feb 2014 17:25:21 +0100 Subject: [RELEASED] Python 3.3.5 release candidate 1 Message-ID: <530A20F1.3030400@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.3.5, release candidate 1. Python 3.3.5 includes a fix for a regression in zipimport in 3.3.4 (see http://bugs.python.org/issue20621) and a few other bugs. Python 3.3 includes a range of improvements of the 3.x series, as well as easier porting between 2.x and 3.x. In total, almost 500 API items are new or improved in Python 3.3. For a more extensive list of changes in the 3.3 series, see http://docs.python.org/3.3/whatsnew/3.3.html To download Python 3.3.5 visit: http://www.python.org/download/releases/3.3.5/ This is a preview release, please report any bugs to http://bugs.python.org/ The final release is scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.3's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) iEYEARECAAYFAlMKIPEACgkQN9GcIYhpnLCjXACfQwbC/eD/lhKAZ+XCwTwYPVWj GMwAnjWkbdk7hqsKoh12EiagpGApEPSA =2BCx -----END PGP SIGNATURE----- From tjreedy at udel.edu Sun Feb 23 12:06:16 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Feb 2014 12:06:16 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <87ob1yay9m.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> Message-ID: On 2/23/2014 6:01 AM, Marko Rauhamaa wrote: > As for Python, there's nothing in the Python specification that would > prevent you from having, say, 63-bit integers as representing > themselves. IOW, you could physically place such integers as themselves > as the reference and the number would not physically exist elsewhere. The Python spec requires that ints act as if they are independent objects with about 20 attributes and methods. The language spec is based on duck typing everything as an object with a class and attributes. Revised code would have to either turn the reference int into a real object on every access (which would be tremendously inefficient), or code special case treatment of reference ints into *every* piece code that might act on ints (which is all over the interpreter) so as to simulate the int object behavior. id(someint) is the least of the problems. Special-casing ints to store the value in the reference has been proposed and rejected. I do not remember how far anyone went in trying to code the idea, but I doubt that anyone got as far as getting the test suite to pass. > Bottom line, there's no fundamental difference between C and Python > variables. Hogwash. Int variables are not all variables. And as I explained above, even if one stored Python ints much like C ints, one would have to add code to hide the fact that one had done so. -- Terry Jan Reedy From pierre.quentel at gmail.com Sun Feb 23 13:20:15 2014 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Sun, 23 Feb 2014 10:20:15 -0800 (PST) Subject: Problem with the console on the new python.org site Message-ID: <1b733c7f-7291-428c-8086-f57f8b14a4fc@googlegroups.com> The new home page of python.org is very nice, congratulations ! But there is a problem with the online console provided by PythonAnywhere : with my azerty keyboard, I can't enter characters such as ) or ] - very annoying ! It this going to be fixed soon ? - Pierre From dihedral88888 at gmail.com Sun Feb 23 14:45:42 2014 From: dihedral88888 at gmail.com (88888 Dihedral) Date: Sun, 23 Feb 2014 11:45:42 -0800 (PST) Subject: Can tuples be replaced with lists all the time? In-Reply-To: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: On Sunday, February 23, 2014 12:06:13 PM UTC+8, Sam wrote: > My understanding of Python tuples is that they are like immutable lists. If this is the cause, why can't we replace tuples with lists all the time (just don't reassign the lists)? Correct me if I am wrong. ====== OK, lets be serious about high-level programming lnguages. Python is a dynamical typed ( name binding mechnism implicitly), imperative language with the built in auto GC and the heap plus stack managements in the bundled scriptor. A tuple is treated immutable and a list is mutable in Python. I suggest one can read the introductions about Erlang which is a non-imperative high level language in the 5 to 6 th gen programming languages in back-end server applictions for the robustness and maintainence costs. Neverthless, Python is regarded as a programming firendly language when comparing with other high level languages. From marko at pacujo.net Sun Feb 23 16:04:34 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 23 Feb 2014 23:04:34 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <87k3clc0n9.fsf@elektro.pacujo.net> Message-ID: <87eh2t1qxp.fsf@elektro.pacujo.net> Chris Angelico : > id() is (if I recall correctly) supposed to return an integer in the > native range That restriction seems beyond the scope of the language definition. Still, it can be trivially provided for. > In any case, you'd need some way to pretend that every integer is > really an object, so you'd need to define id(), the 'is' operator, and > everything else that can work with objects, to ensure that they > correctly handle this. Trivial, I should say. > It would be a reasonable performance improvement to use native > integers for the small ones Maybe. Point is, whether it's done this way or that is irrelevant from the point of view of functional correctness. Whether an integer is an object or not has absolutely nothing to do with the implementation of the interpreter. And thus, Python variables are barely distinguishable from C variables. Marko From marko at pacujo.net Sun Feb 23 16:10:36 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 23 Feb 2014 23:10:36 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> Message-ID: <87a9dh1qnn.fsf@elektro.pacujo.net> Terry Reedy : > Special-casing ints to store the value in the reference has been > proposed and rejected. I do not remember how far anyone went in trying > to code the idea, but I doubt that anyone got as far as getting the > test suite to pass. FWIW, elisp essentially does that. Anyway, we are discussing this to make it clear that the language definition is abstract. All compliant implementations are equally correct. It doesn't make any difference whatsoever for a Python programmer how this or that object type has been implemented under the hood. > Hogwash. Int variables are not all variables. And as I explained > above, even if one stored Python ints much like C ints, one would have > to add code to hide the fact that one had done so. The only difference between me and a madman is that I'm not mad. Marko From breamoreboy at yahoo.co.uk Sun Feb 23 16:18:28 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 23 Feb 2014 21:18:28 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <87eh2t1qxp.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <87k3clc0n9.fsf@elektro.pacujo.net> <87eh2t1qxp.fsf@elektro.pacujo.net> Message-ID: On 23/02/2014 21:04, Marko Rauhamaa wrote: > > And thus, Python variables are barely distinguishable from C variables. > To repeat what Terry Reedy said earlier, hogwash. Looks as if I've another member of my dream team, who can proudly sit alongside our self appointed resident unicode expert. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From skip at pobox.com Sun Feb 23 17:36:56 2014 From: skip at pobox.com (Skip Montanaro) Date: Sun, 23 Feb 2014 16:36:56 -0600 Subject: Looking for someone who can build a 64-bit version of SpamBayes installer for Windows Message-ID: SpamBayes development has been dormant for several years, however it still has a reasonably good following among the Outlook crowd. (I guess Microsoft has still not provided good spam filtering tools for Outlook?) Anyway, though all of SpamBayes is written in pure Python, there is still a small amount of glue code (Microsoft Visual C++-generated dialogs, I think) which is written in C++. As more and more Windows users have moved to 64-bit versions of Windows and Outlook, we've had more and more reports of failures. I think all that's necessary (speaking as someone who knows nothing about Windows) is for someone to build a 64-bit version of the SpamBayes installer for Windows. I don't know how hard that would be, but I presume that for someone with some experience in this area it probably wouldn't be difficult. The current SpamBayes code base should run with Python 2.7. Anybody available to help? Thanks, Skip Montanaro From steve+comp.lang.python at pearwood.info Sun Feb 23 19:37:42 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Feb 2014 00:37:42 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <87a9dh1qnn.fsf@elektro.pacujo.net> Message-ID: <530a9455$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 23 Feb 2014 23:10:36 +0200, Marko Rauhamaa wrote: > Terry Reedy : > >> Special-casing ints to store the value in the reference has been >> proposed and rejected. I do not remember how far anyone went in trying >> to code the idea, but I doubt that anyone got as far as getting the >> test suite to pass. > > FWIW, elisp essentially does that. Anyway, we are discussing this to > make it clear that the language definition is abstract. No. The language definition is concrete: it describes a concrete interface. You are confusing the interface with the implementation: the language definition is only abstract with regard to the implementation, which is free to vary, so long as the interface remains the same. Regardless of the implementation, Python code must behave in certain ways, and the reference implementation CPython defines the semantics of variable as name binding, not fixed locations. Can this by implemented using fixed locations? Of course it can, and is: the proof is that CPython's name binding variables are implemented in C, which uses fixed location variables. > All compliant > implementations are equally correct. It doesn't make any difference > whatsoever for a Python programmer how this or that object type has been > implemented under the hood. Performance can matter :-) But you are correct, as far as it goes. Where you are going wrong is by confusing the semantics of Python code with the underlying implementation of the Python virtual machine. -- Steven From wuwei23 at gmail.com Sun Feb 23 19:55:20 2014 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Feb 2014 10:55:20 +1000 Subject: Functions help In-Reply-To: References: Message-ID: On 23/02/2014 3:43 PM, Scott W Dunning wrote: > I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? The same way you repeat anything in Python: with a loop construct. for _ in range(5): func() From rhodri at wildebst.org.uk Sun Feb 23 20:01:15 2014 From: rhodri at wildebst.org.uk (Rhodri James) Date: Mon, 24 Feb 2014 01:01:15 -0000 Subject: Functions help References: Message-ID: On Sun, 23 Feb 2014 05:43:17 -0000, Scott W Dunning wrote: > I had a question regarding functions. Is there a way to call a function > multiple times without recalling it over and over. Meaning is there a > way I can call a function and then add *5 or something like that? The usual way to call a function several times is to use a loop, like this: for i in range(5): my_function() The function "range" returns the sequence of numbers 1, 2, 3, 4 and 5 [*], so this has the same effect as if you had typed: my_function() my_function() my_function() my_function() my_function() This isn't a great advantage if you just want to call the function two or three times, but when you want to call it two or three hundred times it matters a lot more! You can still use the same technique if you want to pass different parameters to the function each time you call it: for i in range(6): print(i*i) for day in ("Mon", "Tue", "Wed", "Thu", "Fri"): do_stuff_for_day(day) -- Rhodri James *-* Wildebeest Herder to the Masses From breamoreboy at yahoo.co.uk Sun Feb 23 20:09:16 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 01:09:16 +0000 Subject: Functions help In-Reply-To: References: Message-ID: On 24/02/2014 00:55, alex23 wrote: > On 23/02/2014 3:43 PM, Scott W Dunning wrote: >> I had a question regarding functions. Is there a way to call a >> function multiple times without recalling it over and over. Meaning >> is there a way I can call a function and then add *5 or something like >> that? > > The same way you repeat anything in Python: with a loop construct. > > for _ in range(5): > func() For the benefit of newbies, besides the obvious indentation error above, the underscore basically acts as a dummy variable. I'll let the language lawyers give a very detailed, precise description :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From cs at zip.com.au Sun Feb 23 20:19:02 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 24 Feb 2014 12:19:02 +1100 Subject: Remove comma from tuples in python. In-Reply-To: References: Message-ID: <20140224011902.GA41642@cskk.homeip.net> On 21Feb2014 09:32, Roy Smith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > > [x*x for (x,) in lst] > > > > [paraphrasing...] can be better written as: > > > > [x*x for [x] in items] > > I'm torn between, "Yes, the second form is distinctly easier to read" > and, "If you think the second form is easier to read, you're admitting > you're not really fluent in Python". +1 QOTW -- Cameron Simpson It is a tale told by an idiot, full of sound and fury, signifying nothing. - William Shakespeare From swdunning at cox.net Sun Feb 23 20:24:44 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 18:24:44 -0700 Subject: Functions help In-Reply-To: References: Message-ID: <79B85A42-ABE1-4CC6-922B-A8AAAD26C80B@cox.net> On Feb 23, 2014, at 1:44 AM, Steven D'Aprano wrote: > > Sorry, I don't really understand your question. Could you show an example > of what you are doing? > > Do you mean "add 5" or "*5"? "Add *5 doesn't really mean anything to me. Sorry I forgot to add the code that I had to give an example of what I was talking about. I?ll put it below, sorry that it?s so long. A couple of people have basically answered my question though. I take it was I was talking about was a loop, which I haven?t learned in school yet but, it seems semi self-explanatory. As you can see I added a loop in there about half way down the code (i put it in bold) and it seemed to do what I want. Now I?m going to try and do what Rhodri suggested, a range function? I?m not sure exactly what that?ll do but I think it?ll clean up my code more and make things easier to call? from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() row(25) for i in range (5): fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) -------------- next part -------------- An HTML attachment was scrubbed... URL: From travisgriggs at gmail.com Sun Feb 23 20:27:49 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Sun, 23 Feb 2014 17:27:49 -0800 Subject: Functions help In-Reply-To: References: Message-ID: <156E7C94-A02B-48F7-BB8E-3CD133F3CAB6@gmail.com> > On Feb 23, 2014, at 17:09, Mark Lawrence wrote: > > For the benefit of newbies, besides the obvious indentation error above, the underscore basically acts as a dummy variable. I'll let the language lawyers give a very detailed, precise description :) You mean a dummy name binding, right? If we say "variable" we might confuse those newly arrived pilgrims from other language kingdom. (If you squint hard, I think there's some tags in there :) ) From wuwei23 at gmail.com Sun Feb 23 20:39:16 2014 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Feb 2014 11:39:16 +1000 Subject: Functions help In-Reply-To: References: Message-ID: On 24/02/2014 11:09 AM, Mark Lawrence wrote: > On 24/02/2014 00:55, alex23 wrote: >> >> for _ in range(5): >> func() > > the obvious indentation error above Stupid cut&paste :( From swdunning at cox.net Sun Feb 23 20:49:01 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 18:49:01 -0700 Subject: Functions help In-Reply-To: References: <9E019BD7-4C9D-4DED-A626-22BF474CC7F8@cox.net> Message-ID: <0E310661-7634-4DA6-868B-625F184E34CE@cox.net> On Feb 23, 2014, at 12:59 AM, Ben Finney wrote: > > You should ask question like this on the ?python-tutor? forum. Thanks Ben, I wasn?t aware of PythonTutor. From steve+comp.lang.python at pearwood.info Sun Feb 23 20:45:42 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Feb 2014 01:45:42 GMT Subject: Problem with the console on the new python.org site References: <1b733c7f-7291-428c-8086-f57f8b14a4fc@googlegroups.com> Message-ID: <530aa445$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote: > The new home page of python.org is very nice, congratulations ! The best I can say about it is that I'm extremely underwhelmed by the design, which is far more "busy" and colourful than the old design (this is not a complement), and not happy that it doesn't work correctly without Javascript. > But there is a problem with the online console provided by > PythonAnywhere : with my azerty keyboard, I can't enter characters such > as ) or ] - very annoying ! > > It this going to be fixed soon ? Not unless somebody raises it as a bug, or uses the feedback form to notify the web developers. -- Steven From swdunning at cox.net Sun Feb 23 20:43:40 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 18:43:40 -0700 Subject: Functions help In-Reply-To: References: Message-ID: <8706C951-455E-48E8-9213-FCFA272DE8AF@cox.net> I understood what you meant because I looked up loops in the python documentation since we haven?t got there yet in school. On Feb 23, 2014, at 6:39 PM, alex23 wrote: > On 24/02/2014 11:09 AM, Mark Lawrence wrote: >> On 24/02/2014 00:55, alex23 wrote: >>> >>> for _ in range(5): >>> func() >> >> the obvious indentation error above > > Stupid cut&paste :( > -- > https://mail.python.org/mailman/listinfo/python-list From ecomm.61743 at sinergia.bcc.it Sun Feb 23 21:12:06 2014 From: ecomm.61743 at sinergia.bcc.it (www.cartabcc.it) Date: 23 Feb 2014 21:12:06 -0500 Subject: la tua carta è stata limitata - cliente 83114749 Message-ID: <20140223211206.378F1F078D35F61E@sinergia.bcc.it> An HTML attachment was scrubbed... URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun Feb 23 21:55:28 2014 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 23 Feb 2014 18:55:28 -0800 Subject: Functions help In-Reply-To: References: Message-ID: On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: > On 24/02/2014 11:09 AM, Mark Lawrence wrote: >> >> On 24/02/2014 00:55, alex23 wrote: >>> >>> >>> for _ in range(5): >>> func() >> >> >> the obvious indentation error above > > > Stupid cut&paste :( > -- Your message came through fine for me (viewing as mailing list in gmail). Mark's client must be dropping spaces. From breamoreboy at yahoo.co.uk Sun Feb 23 22:21:32 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 03:21:32 +0000 Subject: Functions help In-Reply-To: References: Message-ID: On 24/02/2014 02:55, Benjamin Kaplan wrote: > On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>> >>> On 24/02/2014 00:55, alex23 wrote: >>>> >>>> >>>> for _ in range(5): >>>> func() >>> >>> >>> the obvious indentation error above >> >> >> Stupid cut&paste :( >> -- > > Your message came through fine for me (viewing as mailing list in > gmail). Mark's client must be dropping spaces. > I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From python at mrabarnett.plus.com Sun Feb 23 22:36:38 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 Feb 2014 03:36:38 +0000 Subject: Functions help In-Reply-To: References: Message-ID: <530ABE46.40103@mrabarnett.plus.com> On 2014-02-24 03:21, Mark Lawrence wrote: > On 24/02/2014 02:55, Benjamin Kaplan wrote: >> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>> >>>> On 24/02/2014 00:55, alex23 wrote: >>>>> >>>>> >>>>> for _ in range(5): >>>>> func() >>>> >>>> >>>> the obvious indentation error above >>> >>> >>> Stupid cut&paste :( >>> -- >> >> Your message came through fine for me (viewing as mailing list in >> gmail). Mark's client must be dropping spaces. >> > > I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. > It looked OK to me (also using Thunderbird). However, examining the source, I can see that the first line is indented with 5 spaces and the second line with 1 tab. From davecook at nowhere.net Sun Feb 23 22:37:00 2014 From: davecook at nowhere.net (Dave Cook) Date: 24 Feb 2014 03:37:00 GMT Subject: Mac vs. Linux for Python Development References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: <530abe5c$0$33582$c3e8da3$9deca2c3@news.astraweb.com> On 2014-02-23, twiz wrote: > I've been developing with python recreationally for a while on > Ubuntu but will soon be transitioning to full-time python development. > I have the option of using a Mac or Ubuntu environment and I'd like to > hear any thoughts on the pros and cons of each. Specifically, how's > the support for numpy and scipy? I had problems trying to build my own scipy stack on Maverick, but installing Anaconda's Python distribution solved that. Overall, Python works very well on OS X, but feels better integrated to me under Linux. I'll note that Macs are very popular among the members of pythonsd. I think this is particularly true of the Django developers. Dave Cook From larry at hastings.org Sun Feb 23 23:01:20 2014 From: larry at hastings.org (Larry Hastings) Date: Sun, 23 Feb 2014 22:01:20 -0600 Subject: [RELEASED] Python 3.4.0 release candidate 2 is now available Message-ID: <530AC410.4020600@hastings.org> On behalf of the Python development team, I'm delighted to announce the second and final release candidate of Python 3.4. This is a preview release, and its use is not recommended for production settings. Python 3.4 includes a range of improvements of the 3.x series, including hundreds of small improvements and bug fixes. Major new features and changes in the 3.4 release series include: * PEP 428, a "pathlib" module providing object-oriented filesystem paths * PEP 435, a standardized "enum" module * PEP 436, a build enhancement that will help generate introspection information for builtins * PEP 442, improved semantics for object finalization * PEP 443, adding single-dispatch generic functions to the standard library * PEP 445, a new C API for implementing custom memory allocators * PEP 446, changing file descriptors to not be inherited by default in subprocesses * PEP 450, a new "statistics" module * PEP 451, standardizing module metadata for Python's module import system * PEP 453, a bundled installer for the *pip* package manager * PEP 454, a new "tracemalloc" module for tracing Python memory allocations * PEP 456, a new hash algorithm for Python strings and binary data * PEP 3154, a new and improved protocol for pickled objects * PEP 3156, a new "asyncio" module, a new framework for asynchronous I/O Python 3.4 is now in "feature freeze", meaning that no new features will be added. The final release is projected for mid-March 2014. The python.org web site has recently been updated to something completely new, and I'm having some difficulty updating it. For now I've made Python 3.4.0rc2 available on the legacy web site: http://legacy.python.org/download/releases/3.4.0/ Once I can update the new web site, Python 3.4.0rc2 will be available here: http://python.org/download/releases/ (I'm not sure what the final URL will be, but you'll see it listed on that page.) Please consider trying Python 3.4.0rc2 with your code and reporting any new issues you notice to: http://bugs.python.org/ Enjoy! -- Larry Hastings, Release Manager larry at hastings.org (on behalf of the entire python-dev team and 3.4's contributors) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Sun Feb 23 23:01:23 2014 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 23 Feb 2014 20:01:23 -0800 (PST) Subject: Functions help In-Reply-To: References: Message-ID: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> On 02/23/2014 08:21 PM, Mark Lawrence wrote: > On 24/02/2014 02:55, Benjamin Kaplan wrote: >> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>> On 24/02/2014 00:55, alex23 wrote: >>>>> for _ in range(5): >>>>> func() >>>> the obvious indentation error above >>> >>> Stupid cut&paste :( >> >> Your message came through fine for me (viewing as mailing list in >> gmail). Mark's client must be dropping spaces. > > I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. The original message was properly indented on Google Groups. Perhaps you should switch to GG or some non-broken client that doesn't mangle whitespace. From greg.ewing at canterbury.ac.nz Mon Feb 24 03:07:42 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 24 Feb 2014 21:07:42 +1300 Subject: Can global variable be passed into Python function? In-Reply-To: <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Yes, Pascal has pointers as a first-class data type. Syntax is similar to > C, ^x is a pointer to x, p^ dereferences the pointer p. Actually, the prefix ^ is only used for declaring pointer *types*. Standard Pascal has no way of getting a pointer to an arbitrary variable; the only way to get a pointer is new(p) (which is the equivalent of p = malloc(sizeof(*p))). -- Greg From challakarthik at gmail.com Mon Feb 24 03:31:11 2014 From: challakarthik at gmail.com (Karthik Reddy) Date: Mon, 24 Feb 2014 00:31:11 -0800 (PST) Subject: python Message-ID: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... From wxjmfauth at gmail.com Mon Feb 24 04:35:40 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 24 Feb 2014 01:35:40 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <530a9455$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <87a9dh1qnn.fsf@elektro.pacujo.net> <530a9455$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <99e1e365-e246-49bc-913a-ac62ba7aaf80@googlegroups.com> Le lundi 24 f?vrier 2014 01:37:42 UTC+1, Steven D'Aprano a ?crit?: > > > > Performance can matter :-) > > > >>> timeit.timeit("'abc' * 1000 + 'z'") 0.991999136702321 >>> timeit.timeit("'abc' * 1000 + '\N{EURO SIGN}'") 2.5462559386176444 >>> Two points to notice - Even with utf-8, the worse performance case, such a difference reaches [0.x - a few] percent. - Indexing? Very well preserved for the "abc part" jmf From graeme.pietersz at gmail.com Mon Feb 24 04:45:15 2014 From: graeme.pietersz at gmail.com (graeme.pietersz at gmail.com) Date: Mon, 24 Feb 2014 01:45:15 -0800 (PST) Subject: insert html into ElementTree without parsing it Message-ID: I am building HTML pages using ElementTree. I need to insert chunks of untrusted HTML into the page. I do not need or want to parse this, just insert it at a particular point as is. The best solutions I can think of are rather ugly ones: manipulating the string created by tostring. Is there a nicer way of doing this? Is it possible, for example, to customise how an element is converted to a string representation? I am open to using something else (e.g. lxml) if necessary. From sffjunkie at gmail.com Mon Feb 24 05:15:19 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Mon, 24 Feb 2014 02:15:19 -0800 (PST) Subject: Functions help In-Reply-To: References: Message-ID: <3b84db4a-a8d5-48d9-9ead-da1f238c4ee8@googlegroups.com> On Sunday, 23 February 2014 05:43:17 UTC, Scott W Dunning wrote: > I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? > The following answers your question but is probably not a method you want to employ. from functools import partial def a(ch): print(ch) def b(x): print(x + 10) [x() for x in [partial(a, 'd'), partial(b, 10)]*5] Produces d 14 d 14 d 14 d 14 d 14 --Simon From sffjunkie at gmail.com Mon Feb 24 05:32:07 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Mon, 24 Feb 2014 02:32:07 -0800 (PST) Subject: Functions help In-Reply-To: References: Message-ID: <1e5c02e3-010a-4eec-b0b4-b147492fb9fe@googlegroups.com> On Sunday, 23 February 2014 05:43:17 UTC, Scott W Dunning wrote: > I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? The following answers your question but is probably not a method you want to employ. from functools import partial def a(ch): print(ch) def b(x): print(x + 4) [x() for x in [partial(a, 'd'), partial(b, 10)]*5] Produces d 14 d 14 d 14 d 14 d 14 --Simon From patil.jay2009 at gmail.com Mon Feb 24 06:35:08 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 24 Feb 2014 03:35:08 -0800 (PST) Subject: Python powerpoint automation using pywin32 Message-ID: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> I need to create a new powerpoint presentation. I need to add images, paste some graphs, add texts, tables into powerpoint. Is any link or document available which help me to do this work more effectivey & faster. Regards Jay From sffjunkie at gmail.com Mon Feb 24 06:48:23 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Mon, 24 Feb 2014 03:48:23 -0800 (PST) Subject: The sum of numbers in a line from a file In-Reply-To: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: On Thursday, 20 February 2014 16:22:00 UTC, kxjakkk wrote: > Let's say I have a sample file like this: > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. The following solution works for Python3 (due to the unpacking using the * syntax) ---- from collections import defaultdict, namedtuple info = namedtuple('info', 'sum avg') interesting_data = (x.strip(' \n') for idx, x in enumerate(open('file').readlines()) if idx > 1 and len(x.strip(' \n')) > 0) split_points = [2, 4, 5] results = defaultdict(list) for line in interesting_data: name, _, _, _, *rest = line.split() last_point = 0 for point in split_points: s = sum(map(int, rest[last_point:point])) i = info(s, s / (point - last_point)) results[name].append(i) last_point = point print(results) print(results['name3'][0].avg) --Simon Kennedy From sffjunkie at gmail.com Mon Feb 24 06:57:23 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Mon, 24 Feb 2014 03:57:23 -0800 (PST) Subject: Python powerpoint automation using pywin32 In-Reply-To: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> References: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> Message-ID: <282c7cfe-b6c4-47a9-a9c6-6a4912a81bd0@googlegroups.com> On Monday, 24 February 2014 11:35:08 UTC, Jaydeep Patil wrote: > I need to create a new powerpoint presentation. I need to add images, paste some graphs, add texts, tables into powerpoint. > > Is any link or document available which help me to do this work more effectivey & faster. Always remember, PyPi is your friend. I've not used it but the following is available which works with Microsoft's XML based document types. It is not automation per se (and doesn't use pywin32) but a library for pptx document manipulation. https://pypi.python.org/pypi/python-pptx/ Docs are here https://python-pptx.readthedocs.org/en/latest/ --Simon From sffjunkie at gmail.com Mon Feb 24 07:02:29 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Mon, 24 Feb 2014 04:02:29 -0800 (PST) Subject: The sum of numbers in a line from a file In-Reply-To: References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> Message-ID: <638bd989-e610-4629-92ab-40045f564af2@googlegroups.com> On Monday, 24 February 2014 11:48:23 UTC, sffj... at gmail.com wrote: > split_points = [2, 4, 5] Change this to `split_points = [3, 5]` for your requirements --Simon Kennedy From breamoreboy at yahoo.co.uk Mon Feb 24 08:59:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 13:59:48 +0000 Subject: Functions help In-Reply-To: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> References: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> Message-ID: On 24/02/2014 04:01, rurpy at yahoo.com wrote: > On 02/23/2014 08:21 PM, Mark Lawrence wrote: >> On 24/02/2014 02:55, Benjamin Kaplan wrote: >>> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>>> On 24/02/2014 00:55, alex23 wrote: >>>>>> for _ in range(5): >>>>>> func() >>>>> the obvious indentation error above >>>> >>>> Stupid cut&paste :( >>> >>> Your message came through fine for me (viewing as mailing list in >>> gmail). Mark's client must be dropping spaces. >> >> I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. > > The original message was properly indented on Google Groups. > Perhaps you should switch to GG or some non-broken client that > doesn't mangle whitespace. > MRAB has confirmed that as always Thunderbird is working perfectly, thank you. But you can stick with your bug ridden, badly flawed tool as long as you like, just expect me to keep complaining until google fixes it, or people stop using it, or people follow the instructions that were put up on a Python web site to prevent the bugs showing up. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From jeanmichel at sequans.com Mon Feb 24 10:01:38 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Feb 2014 16:01:38 +0100 (CET) Subject: Functions help In-Reply-To: <79B85A42-ABE1-4CC6-922B-A8AAAD26C80B@cox.net> Message-ID: <1800433431.5160647.1393254098105.JavaMail.root@sequans.com> ----- Original Message ----- > On Feb 23, 2014, at 1:44 AM, Steven D'Aprano < > steve+comp.lang.python at pearwood.info > wrote: > > Sorry, I don't really understand your question. Could you show an > > example > > > of what you are doing? > > > Do you mean "add 5" or "*5"? "Add *5 doesn't really mean anything > > to > > me. > > Sorry I forgot to add the code that I had to give an example of what > I was talking about. I?ll put it below, sorry that it?s so long. A Here's an example of how your star() function could be rewritten. Note that it does not exactly do what it does in your example regarding the start and end position of the turtle. So use it for inspiration only ;) from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) # record the initial position position = getturtle().pos() heading = getturtle().heading() penup() left(36) # initial angle forward(R) pendown() for arms in range(5): left(144) forward(A) right(72) forward(A) penup() # go back to the initial position getturtle().setpos(position) getturtle().setheading(heading) showturtle() clear() star(50) -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From jeanmichel at sequans.com Mon Feb 24 08:19:12 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Feb 2014 14:19:12 +0100 (CET) Subject: Problem with the console on the new python.org site In-Reply-To: <530aa445$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <466310612.5151989.1393247952167.JavaMail.root@sequans.com> ----- Original Message ----- > On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote: > > > The new home page of python.org is very nice, congratulations ! > > The best I can say about it is that I'm extremely underwhelmed by the > design, which is far more "busy" and colourful than the old design > (this > is not a complement), and not happy that it doesn't work correctly > without Javascript. Steven, you must have been the grumpy smurf in another life ;) > > But there is a problem with the online console provided by > > PythonAnywhere : with my azerty keyboard, I can't enter characters > > such > > as ) or ] - very annoying ! I have an azerty keyboard and it works just fine, your problem must be something else. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From steve+comp.lang.python at pearwood.info Mon Feb 24 10:57:38 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Feb 2014 15:57:38 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530b6bf2$0$29985$c3e8da3$5496439d@news.astraweb.com> On Mon, 24 Feb 2014 21:07:42 +1300, Gregory Ewing wrote: > Steven D'Aprano wrote: >> Yes, Pascal has pointers as a first-class data type. Syntax is similar >> to C, ^x is a pointer to x, p^ dereferences the pointer p. > > Actually, the prefix ^ is only used for declaring pointer *types*. > Standard Pascal has no way of getting a pointer to an arbitrary > variable; the only way to get a pointer is new(p) (which is the > equivalent of p = malloc(sizeof(*p))). Standard Pascal? Who uses standard Pascal? I'm talking about MacPascal :-) Actually, it's possible that I've forgotten the details, it's been over twenty years since I last dereferences a Pascal pointer in anger, so you might be right... a quick glance at some of my text books suggest that you probably are. Thanks for the correction! -- Steven From wrw at mac.com Mon Feb 24 10:33:35 2014 From: wrw at mac.com (William Ray Wing) Date: Mon, 24 Feb 2014 10:33:35 -0500 Subject: Mac vs. Linux for Python Development In-Reply-To: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: <4D797B76-567C-436E-82B0-C1A1487596E9@mac.com> On Feb 23, 2014, at 3:43 AM, twiz wrote: > Hello, > > I'm sure this is a common question but I can't seem to find a previous thread that addresses it. If one one exists, please point me to it. > > I've been developing with python recreationally for a while on Ubuntu but will soon be transitioning to full-time python development. I have the option of using a Mac or Ubuntu environment and I'd like to hear any thoughts on the pros and cons of each. Specifically, how's the support for numpy and scipy? How are the IDEs? > > Since I generally like working with a Mac, I'd like to hear if there are any significant downsides to python dev on OsX. > > Thanks > > -- > https://mail.python.org/mailman/listinfo/python-list In addition to the other excellent answers you've received, I'd point you to http://stackoverflow.com/questions/81584/what-ide-to-use-for-python where there is a fairly extensive comparison chart of IDEs, features, and supported OSes. And, by the way, I'm a very happy camper using BBEdit and WingIDE (the name collision is purely coincidental). Thanks, Bill From torriem at gmail.com Mon Feb 24 12:34:37 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 24 Feb 2014 10:34:37 -0700 Subject: Mac vs. Linux for Python Development In-Reply-To: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: <530B82AD.8020801@gmail.com> On 02/23/2014 01:43 AM, twiz wrote: > I've been developing with python recreationally for a while on Ubuntu > but will soon be transitioning to full-time python development. I > have the option of using a Mac or Ubuntu environment and I'd like to > hear any thoughts on the pros and cons of each. Specifically, how's > the support for numpy and scipy? How are the IDEs? I know a lot of Mac developers that love the Sublime text editor. And if you combine it with https://github.com/lunixbochs/actualvim, it's even better. Personally OS X's focus policy drives me absolutely bonkers as a developer. And I can't function without alt-middle clicking to size windows and alt-click to move windows. > Since I generally like working with a Mac, I'd like to hear if there > are any significant downsides to python dev on OsX. You can always run a virtual machine on OS X and have the best of both worlds. From torriem at gmail.com Mon Feb 24 12:42:53 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 24 Feb 2014 10:42:53 -0700 Subject: Mac vs. Linux for Python Development In-Reply-To: <530B82AD.8020801@gmail.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> <530B82AD.8020801@gmail.com> Message-ID: <530B849D.5060604@gmail.com> On 02/24/2014 10:34 AM, Michael Torrie wrote: > I know a lot of Mac developers that love the Sublime text editor. And > if you combine it with https://github.com/lunixbochs/actualvim, it's > even better. Sublime is actually on all platforms, and lots of people like it. http://www.sublimetext.com/ Personally I just use vim on any platform. From j.e.haque at gmail.com Mon Feb 24 13:05:49 2014 From: j.e.haque at gmail.com (j.e.haque at gmail.com) Date: Mon, 24 Feb 2014 10:05:49 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <87ob1yay9m.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> Message-ID: <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> On Sunday, February 23, 2014 5:01:25 AM UTC-6, Marko Rauhamaa wrote: > Chris Angelico : > > > That's the exact line of thinking that leads to problems. You are not > > > placing a number at the address "xyz", you are pointing the name "xyz" > > > to the number 3. That number still exists elsewhere. > > > > And? > > > > In C, I can say: > > > > Number *o = malloc(sizeof *o); > > o->value = 3; > > > > Your statement is valid: the number 3 resides elsewhere than the > > variable o. typedef struct { int value; } Number; Number *o; o = malloc(sizeof(*o)); o->value=3; printf("o<%p>, o->value<%p>\n", o, &o->value); o<0x9fe5008>, o->value<0x9fe5008> Is the compiler borked? From torriem at gmail.com Mon Feb 24 13:19:28 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 24 Feb 2014 11:19:28 -0700 Subject: [OT] Can global variable be passed into Python function? In-Reply-To: <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> Message-ID: <530B8D30.9050706@gmail.com> On 02/24/2014 11:05 AM, j.e.haque at gmail.com wrote: > typedef struct { > int value; > } Number; > > Number *o; > o = malloc(sizeof(*o)); > o->value=3; > printf("o<%p>, o->value<%p>\n", o, &o->value); > > o<0x9fe5008>, o->value<0x9fe5008> > > Is the compiler borked? Why would you think that? The address of the start of your malloc'ed structure is the same as the address of the first element. Surely this is logical? And of course all this is quite off topic. From random832 at fastmail.us Mon Feb 24 13:20:14 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Mon, 24 Feb 2014 13:20:14 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> Message-ID: <1393266014.6099.87210377.38F84560@webmail.messagingengine.com> On Mon, Feb 24, 2014, at 13:05, j.e.haque at gmail.com wrote: > typedef struct { > int value; > } Number; > > Number *o; > o = malloc(sizeof(*o)); > o->value=3; > printf("o<%p>, o->value<%p>\n", o, &o->value); > > o<0x9fe5008>, o->value<0x9fe5008> > > Is the compiler borked? That's cheating. Try printf("o<%p>", &o); From random832 at fastmail.us Mon Feb 24 13:21:41 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Mon, 24 Feb 2014 13:21:41 -0500 Subject: [OT] Can global variable be passed into Python function? In-Reply-To: <530B8D30.9050706@gmail.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> <530B8D30.9050706@gmail.com> Message-ID: <1393266101.6897.87210893.5F29BB7B@webmail.messagingengine.com> On Mon, Feb 24, 2014, at 13:19, Michael Torrie wrote: > Why would you think that? The address of the start of your malloc'ed > structure is the same as the address of the first element. Surely this > is logical? And of course all this is quite off topic. That's not helpful - the problem, in context, is that he doesn't understand that the fact that the structure exists at that address is not the same thing as the variable "o" existing at that address. From rosuav at gmail.com Mon Feb 24 13:22:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 05:22:25 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> Message-ID: On Tue, Feb 25, 2014 at 5:05 AM, wrote: > typedef struct { > int value; > } Number; > > Number *o; > o = malloc(sizeof(*o)); > o->value=3; > printf("o<%p>, o->value<%p>\n", o, &o->value); > > o<0x9fe5008>, o->value<0x9fe5008> > > Is the compiler borked? No, because a structure in C is simply a laying-out of its members. A pointer to the structure is exactly the same as a pointer to its first member, same as a pointer to an array is really just a pointer to its first element (with other elements laid out sequentially, possibly with padding for alignment). In Python, a complex object is a thing in its own right; it has an identity and a set of members, each of which has its own identity. In C, the structure is an invisible piece of nothingness that surrounds an aggregation of other objects. For instance: typedef struct { int val1; int val2; } NumberPair; NumberPair five_pairs[5]; int *ten_ints = (int *)five_pairs; This is considered naughty (pointer aliasing), and can make a mess of optimization, but as far as I know, it's never going to be a problem (I don't think it's possible for there to be any padding between two ints; it's possible the struct will demand coarser alignment than the ints would, which is why I've written them in that order). You can access ten integers from the aliased pointer, and five pairs of integers through the original structure array, and they're all exactly the same. If you print out those two pointers, they will have the same value in them, and &five_pairs[3]->val2 will be the same as &ten_ints[7] (and the same as ten_ints+7). For in C, neither the structure nor the non-structure is anything. The only thing that counts is code expressing itself through love. (Galatians 5:6, K&R translation. Or something like that.) ChrisA From jeanmichel at sequans.com Mon Feb 24 13:25:19 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Feb 2014 19:25:19 +0100 (CET) Subject: Mac vs. Linux for Python Development In-Reply-To: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: <164260540.5194858.1393266319716.JavaMail.root@sequans.com> ----- Original Message ----- > Hello, > > I'm sure this is a common question but I can't seem to find a > previous thread that addresses it. If one one exists, please point > me to it. > > I've been developing with python recreationally for a while on Ubuntu > but will soon be transitioning to full-time python development. I > have the option of using a Mac or Ubuntu environment and I'd like to > hear any thoughts on the pros and cons of each. Specifically, how's > the support for numpy and scipy? How are the IDEs? > > Since I generally like working with a Mac, I'd like to hear if there > are any significant downsides to python dev on OsX. > > Thanks > I'd rather go for linux, I have the feeling that the dev community is larger, though I have no numbers to provide, so I may be wrong. One would successfully argue that most python dev are cross-platform anyway. IDEs in Linux are great, and you'll get the best of them for free. However vim / emacs are available for free on OsX as well... If you go for Linux, know that ubuntu would not be the first choice, ubuntu prefers user experience over stability. Debian for instance is a distribution largely used in the industry. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From rosuav at gmail.com Mon Feb 24 13:25:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 05:25:25 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <1393266014.6099.87210377.38F84560@webmail.messagingengine.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> <1393266014.6099.87210377.38F84560@webmail.messagingengine.com> Message-ID: On Tue, Feb 25, 2014 at 5:20 AM, wrote: > On Mon, Feb 24, 2014, at 13:05, j.e.haque at gmail.com wrote: >> typedef struct { >> int value; >> } Number; >> >> Number *o; >> o = malloc(sizeof(*o)); >> o->value=3; >> printf("o<%p>, o->value<%p>\n", o, &o->value); >> >> o<0x9fe5008>, o->value<0x9fe5008> >> >> Is the compiler borked? > > That's cheating. Try printf("o<%p>", &o); It's not cheating, but it's showing something different. Comparing o and &o->value shows that the structure itself and its first member are at the same location in memory. Comparing o and &o shows that the structure and the pointer to the structure are at different locations in memory. ChrisA From emile at fenx.com Mon Feb 24 13:31:47 2014 From: emile at fenx.com (Emile van Sebille) Date: Mon, 24 Feb 2014 10:31:47 -0800 Subject: python In-Reply-To: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> Message-ID: On 2/24/2014 12:31 AM, Karthik Reddy wrote: > I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... A good place to start: https://wiki.python.org/moin/BeginnersGuide Emile From rosuav at gmail.com Mon Feb 24 13:37:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 05:37:24 +1100 Subject: Mac vs. Linux for Python Development In-Reply-To: <164260540.5194858.1393266319716.JavaMail.root@sequans.com> References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> <164260540.5194858.1393266319716.JavaMail.root@sequans.com> Message-ID: On Tue, Feb 25, 2014 at 5:25 AM, Jean-Michel Pichavant wrote: > If you go for Linux, know that ubuntu would not be the first choice, ubuntu prefers user experience over stability. Debian for instance is a distribution largely used in the industry. > What you'll generally find, actually, is that there's very little effective difference between one distro and another - there's a lot of usability difference between, say, Xfce and GNOME3 and Mate and Unity and so on, but you can get each of those on any Linux that supports them (personally, I like Xfce, which I use with Debian; you can get Xubuntu which comes with it). There's also a huge difference between Python 2.4 and Python 2.7, but beyond the fact that Red Hat 5 happens to ship with 2.4 and Debian Wheezy happens to ship with 2.7, there's no connection between that and your distro. Especially among the families of related distros (Debian and Red Hat being the patriarchs of huge family trees, and Ubuntu being head of a major sub-tree under Debian), you'll usually find there's not a huge amount of fundamental difference. So pick any distro that strikes your fancy! Try it out! If it doesn't work out, pick a different one. Start with one that your friends use (if you have any), that way you can get immediate help. ChrisA From mail at timgolden.me.uk Mon Feb 24 14:26:40 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Feb 2014 19:26:40 +0000 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <52FF4E9F.7070209@shopzeus.com> References: <52FCB228.5040301@shopzeus.com> <52FCB389.3070402@timgolden.me.uk> <52FF4E9F.7070209@shopzeus.com> Message-ID: <530B9CF0.9080108@timgolden.me.uk> On 15/02/2014 11:25, Nagy L?szl? Zsolt wrote: > >> From a cmd window: >> >> ftype python.file="C:\Windows\py.exe" "%1" %* >> >> ftype python.noconfile="C:\Windows\pyw.exe" "%1" %* > There is a serious problem with this! Example code test.py: > > #!/usr/bin/env python3 > import sys > print(sys.argv) > > Test run: > > C:\Temp>test.py 1 2 3 > ['C:\\Temp\\test.py'] > > This is too bad! Can somebody tell me what would be the good setup for > py.exe? Do I have to reinstall Python3 with all libs? :-s Nagy, are you still seeing this behaviour? Because my system, with the exact ftype confiiguration you're describing, behaves as you would expect. c:\Users\tim>assoc .py .py=Python.File c:\Users\tim>ftype python.file python.file="C:\Windows\py.exe" "%1" %* c:\Users\tim>t.py 1 2 3 ['C:\\Users\\tim\\t.py', '1', '2', '3'] I have 2.7 & 3.3 installed (and about half a dozen other versions, too). TJG From cmpython at gmail.com Mon Feb 24 14:28:15 2014 From: cmpython at gmail.com (CM) Date: Mon, 24 Feb 2014 11:28:15 -0800 (PST) Subject: python In-Reply-To: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> Message-ID: On Monday, February 24, 2014 3:31:11 AM UTC-5, Karthik Reddy wrote: > I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... I recommend you look at job advertisements in areas you'd like to work (both areas of the world and areas within IT) and see what they seem to want. Also, consider more informative subject lines to future posts. :D From ed352 at cornell.edu Mon Feb 24 14:40:35 2014 From: ed352 at cornell.edu (ed352 at cornell.edu) Date: Mon, 24 Feb 2014 11:40:35 -0800 (PST) Subject: Python Distributors Message-ID: I am researching the best Python Distributors based on mainly on convenience and performance and I am wondering if anyone has any opinions on which are the best to use. Thanks! From ethan at stoneleaf.us Mon Feb 24 14:54:54 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 24 Feb 2014 11:54:54 -0800 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) Message-ID: <530BA38E.2060909@stoneleaf.us> Greetings! A PEP is under discussion to add %-interpolation back to the bytes type in Python 3.5. Assuming the PEP is accepted, what *will* be added back is: Numerics: b'%d' % 10 --> b'10' b'%02x' % 10 --> b'0a' Single byte: b'%c' % 80 --> b'P' and generic: b'%s' % some_binary_blob --> b'tHE*&92h4' (or whatever) What is under debate is whether we should also add %a: b'%a' % some_obj --> b'some_obj_repr' What %a would do: get the repr of some_obj convert it to ascii using backslashreplace (to handle any code points over 127) encode to bytes using 'ascii' Can anybody think of a use-case for this particular feature? -- ~Ethan~ From gamesbrainiac at gmail.com Mon Feb 24 14:54:22 2014 From: gamesbrainiac at gmail.com (Nafiul Islam) Date: Mon, 24 Feb 2014 11:54:22 -0800 (PST) Subject: Python Distributors In-Reply-To: References: Message-ID: <2c972c73-c10d-4618-a71e-1a305229196b@googlegroups.com> On Tuesday, February 25, 2014 1:40:35 AM UTC+6, ed... at cornell.edu wrote: > I am researching the best Python Distributors based on mainly on convenience and performance and I am wondering if anyone has any opinions on which are the best to use. Thanks! I don't know if you're looking for distributors, as in companies that ship commercial versions of Python or different python distributions, so I'll go ahead and give you some advice on both. Regarding commercial distributors, you I feel that both enthought and ActiveState provide good packages. However, if you're looking towards a python distribution geared towards performance, why not give pypy a shot? It supports most major frameworks out there, and I can say from experience that the performance gains are quite handsome. From breamoreboy at yahoo.co.uk Mon Feb 24 15:04:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 20:04:01 +0000 Subject: Python Distributors In-Reply-To: References: Message-ID: On 24/02/2014 19:40, ed352 at cornell.edu wrote: > I am researching the best Python Distributors based on mainly on convenience and performance and I am wondering if anyone has any opinions on which are the best to use. Thanks! > Given in no particular order I'd have said Peter Otten, Steven D'Aprano, Chris Angelico and MRAB. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Mon Feb 24 15:00:13 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 20:00:13 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> Message-ID: On 24/02/2014 18:05, j.e.haque at gmail.com wrote: > On Sunday, February 23, 2014 5:01:25 AM UTC-6, Marko Rauhamaa wrote: >> Chris Angelico : >> >>> That's the exact line of thinking that leads to problems. You are not >> >>> placing a number at the address "xyz", you are pointing the name "xyz" >> >>> to the number 3. That number still exists elsewhere. >> >> >> >> And? >> >> >> >> In C, I can say: >> >> >> >> Number *o = malloc(sizeof *o); >> >> o->value = 3; >> >> >> >> Your statement is valid: the number 3 resides elsewhere than the >> >> variable o. > > typedef struct { > int value; > } Number; > > Number *o; > o = malloc(sizeof(*o)); > o->value=3; > printf("o<%p>, o->value<%p>\n", o, &o->value); > > o<0x9fe5008>, o->value<0x9fe5008> > > Is the compiler borked? > I can't be bothered to check. OTOH google groups is so please read and action this https://wiki.python.org/moin/GoogleGroupsPython, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From marko at pacujo.net Mon Feb 24 15:46:37 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 24 Feb 2014 22:46:37 +0200 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) References: Message-ID: <87ha7o9r2q.fsf@elektro.pacujo.net> Ethan Furman : > Can anybody think of a use-case for this particular feature? Internet protocol entities constantly have to format (and parse) ASCII-esque octet strings: headers.append(b'Content-length: %d\r\n' % len(blob)) headers.append(b'Content-length: {}\r\n'.format(len(blob))) Now you must do: headers.append(('Content-length: %d\r\n' % len(blob)).encode()) headers.append('Content-length: {}\r\n'.format(len(blob)).encode()) That is: 1. ineffient (encode/decode shuffle) 2. unnatural (strings usually have no place in protocols) 3. confusing (what is stored as bytes, what is stored as strings?) 4. error-prone (UTF-8 decoding exceptions etc) To be sure, %s will definitely be needed as well: uri = b'http://%s/robots.txt' % host Marko From random832 at fastmail.us Mon Feb 24 16:04:48 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Mon, 24 Feb 2014 16:04:48 -0500 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) In-Reply-To: <87ha7o9r2q.fsf@elektro.pacujo.net> References: <87ha7o9r2q.fsf@elektro.pacujo.net> Message-ID: <1393275888.21136.87279633.092F472A@webmail.messagingengine.com> On Mon, Feb 24, 2014, at 15:46, Marko Rauhamaa wrote: > That is: > > 1. ineffient (encode/decode shuffle) > > 2. unnatural (strings usually have no place in protocols) That's not at all clear. Why _aren't_ these protocols considered text protocols? Why can't you add a string directly to headers? From marko at pacujo.net Mon Feb 24 17:18:53 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 25 Feb 2014 00:18:53 +0200 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) References: <87ha7o9r2q.fsf@elektro.pacujo.net> Message-ID: <87d2ic2lyq.fsf@elektro.pacujo.net> random832 at fastmail.us: > On Mon, Feb 24, 2014, at 15:46, Marko Rauhamaa wrote: >> That is: >> >> 1. ineffient (encode/decode shuffle) >> >> 2. unnatural (strings usually have no place in protocols) > > That's not at all clear. Why _aren't_ these protocols considered text > protocols? Why can't you add a string directly to headers? Text expresses a written human language. In prosaic terms, a Python string is a sequence of ISO 10646 characters, whose codepoints are not octets. Most network protocols are defined in terms of octets, although many of them can carry textual, audio or video payloads (among others). So when RFC 3507 (ICAP) shows an example starting: RESPMOD icap://icap.example.org/satisf ICAP/1.0 Host: icap.example.org Encapsulated: req-hdr=0, res-hdr=137, res-body=296 it consists of 8-bit octets and not some human language. In practical terms, you get the bytes off the socket as, well, bytes. It makes little sense to "decode" those bytes into a string for manipulation. Manipulating bytes directly is both more efficient and more natural from the point of view of the standard. Many internet protocols happen to look like text. It makes it nicer for human network programmers to work with them. However, they are primarily meant for computers, and the message formats are really a form of binary code. Marko From ethan at stoneleaf.us Mon Feb 24 16:53:03 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 24 Feb 2014 13:53:03 -0800 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) In-Reply-To: <1393275888.21136.87279633.092F472A@webmail.messagingengine.com> References: <87ha7o9r2q.fsf@elektro.pacujo.net> <1393275888.21136.87279633.092F472A@webmail.messagingengine.com> Message-ID: <530BBF3F.1010806@stoneleaf.us> On 02/24/2014 01:04 PM, random832 at fastmail.us wrote: > On Mon, Feb 24, 2014, at 15:46, Marko Rauhamaa wrote: >> That is: >> >> 1. ineffient (encode/decode shuffle) >> >> 2. unnatural (strings usually have no place in protocols) > > That's not at all clear. Why _aren't_ these protocols considered text > protocols? Why can't you add a string directly to headers? Because text is a high-order abstraction. You don't store text in files, you don't transmit text over the wire or through the air -- those actions are done with a lower abstraction, that of bytes. You're framework may allow you to add a string, but under the covers it's converting to bytes -- at which point is up to the framework. -- ~Ethan~ From steve+comp.lang.python at pearwood.info Mon Feb 24 18:55:14 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Feb 2014 23:55:14 GMT Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) References: Message-ID: <530bdbe2$0$29985$c3e8da3$5496439d@news.astraweb.com> On Mon, 24 Feb 2014 11:54:54 -0800, Ethan Furman wrote: > Greetings! > > A PEP is under discussion to add %-interpolation back to the bytes type > in Python 3.5. > > Assuming the PEP is accepted, what *will* be added back is: > > Numerics: > > b'%d' % 10 --> b'10' > b'%02x' % 10 --> b'0a' > > Single byte: > > b'%c' % 80 --> b'P' Will %c also accept a length-1 bytes object? b'%c' % b'x' => b'x' > and generic: > > b'%s' % some_binary_blob --> b'tHE*&92h4' (or whatever) Will b'%s' take any arbitrary object, as in: b'Key: %s' % [1, 2, 3, 4] => b'Key: [1, 2, 3, 4]' or only something which is already bytes (i.e. a bytes or bytearray object)? > What is under debate is whether we should also add %a: > > b'%a' % some_obj --> b'some_obj_repr' > > What %a would do: > > get the repr of some_obj > > convert it to ascii using backslashreplace (to handle any code points > over 127) > > encode to bytes using 'ascii' > > Can anybody think of a use-case for this particular feature? Not me. -- Steven From steve+comp.lang.python at pearwood.info Mon Feb 24 18:55:36 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 24 Feb 2014 23:55:36 GMT Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) References: <87ha7o9r2q.fsf@elektro.pacujo.net> <87d2ic2lyq.fsf@elektro.pacujo.net> Message-ID: <530bdbf8$0$29985$c3e8da3$5496439d@news.astraweb.com> On Tue, 25 Feb 2014 00:18:53 +0200, Marko Rauhamaa wrote: > random832 at fastmail.us: > >> On Mon, Feb 24, 2014, at 15:46, Marko Rauhamaa wrote: >>> That is: >>> >>> 1. ineffient (encode/decode shuffle) >>> >>> 2. unnatural (strings usually have no place in protocols) >> >> That's not at all clear. Why _aren't_ these protocols considered text >> protocols? Why can't you add a string directly to headers? You cannot mix text strings and byte strings in Python 3. Python 2 allows you to do so, and it leads to hard-to-diagnose bugs and confusing behaviour. This is why Python 3 insists on a strict separation between the two. But of course you can add *byte* strings directly to byte headers. Just prefix your strings with a b, as in b'Header' instead of 'Header', and it will work fine. However, you don't really want to be adding large numbers of byte strings together, due to efficiency. Better to use % interpolation to insert them all at once. Hence the push to add % to bytes in Python 3. Marko replied: > Text expresses a written human language. In prosaic terms, a Python > string is a sequence of ISO 10646 characters, whose codepoints are not > octets. Almost correct, but not quite. Python strings are Unicode, not ISO-10646. The two are not the same. http://www.unicode.org/faq/unicode_iso.html > Most network protocols are defined in terms of octets, although many of > them can carry textual, audio or video payloads (among others). So when > RFC 3507 (ICAP) shows an example starting: > > RESPMOD icap://icap.example.org/satisf ICAP/1.0 Host: > icap.example.org > Encapsulated: req-hdr=0, res-hdr=137, res-body=296 > > it consists of 8-bit octets and not some human language. Not really relevant. In practical terms, whether they are implemented as octets or not, the sequence "Host" *is* human language, specifically it is the English word Host that just happens to be encoded in ASCII. Likewise the sequence "Encapsulated" *is* the English word Encapsulated encoded in ASCII. > In practical terms, you get the bytes off the socket as, well, bytes. It > makes little sense to "decode" those bytes into a string for > manipulation. Manipulating bytes directly is both more efficient and > more natural from the point of view of the standard. But not necessarily more natural from the point of the programmer, which is what matters. I agree that if you don't need to interpret the data as Unicode text, then there's no real benefit to decoding to text. (In fact, if your data can contain arbitrary bytes, you may not be able to decode to text, since not all byte sequences are legal UTF-8.) > Many internet protocols happen to look like text. It makes it nicer for > human network programmers to work with them. However, they are primarily > meant for computers, and the message formats are really a form of binary > code. The reason that, say, the subject header line in emails starts with the word "Subject" rather than some arbitrary binary code is because it is intended to be human-readable. Not just human-readable, but *semantically meaningful*. That's why the subject line is labelled "Subject" rather than "Field 23" or "SJT". Fortunately, such headers are usually (always?) ASCII, and byte strings in Python privilege ASCII-encoded text. When you write b'Subject', you get the same sequence of bytes as 'Subject'.encode('ascii'). -- Steven From ethan at stoneleaf.us Mon Feb 24 19:10:53 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 24 Feb 2014 16:10:53 -0800 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) In-Reply-To: <530bdbe2$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <530bdbe2$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530BDF8D.8020804@stoneleaf.us> On 02/24/2014 03:55 PM, Steven D'Aprano wrote: > On Mon, 24 Feb 2014 11:54:54 -0800, Ethan Furman wrote: > >> Greetings! >> >> A PEP is under discussion to add %-interpolation back to the bytes type >> in Python 3.5. >> >> Assuming the PEP is accepted, what *will* be added back is: >> >> Numerics: >> >> b'%d' % 10 --> b'10' >> b'%02x' % 10 --> b'0a' >> >> Single byte: >> >> b'%c' % 80 --> b'P' > > Will %c also accept a length-1 bytes object? > > b'%c' % b'x' > => b'x' Yes. >> and generic: >> >> b'%s' % some_binary_blob --> b'tHE*&92h4' (or whatever) > > Will b'%s' take any arbitrary object, as in: > > b'Key: %s' % [1, 2, 3, 4] > => b'Key: [1, 2, 3, 4]' No. > or only something which is already bytes (i.e. a bytes or bytearray > object)? It must already be bytes, or have __bytes__ method (that returns bytes, obviously ;) . >> What is under debate is whether we should also add %a: >> >> b'%a' % some_obj --> b'some_obj_repr' >> >> What %a would do: >> >> get the repr of some_obj >> >> convert it to ascii using backslashreplace (to handle any code points >> over 127) >> >> encode to bytes using 'ascii' >> >> Can anybody think of a use-case for this particular feature? > > Not me. I find that humorous, as %a would work with your list example above. :) -- ~Ethan~ From abhishek1899 at gmail.com Mon Feb 24 20:30:26 2014 From: abhishek1899 at gmail.com (Ronaldo) Date: Mon, 24 Feb 2014 17:30:26 -0800 (PST) Subject: Coding a simple state machine in python Message-ID: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code: if state == "ABC": do_something() change state to DEF if state == "DEF" perform_the_next_function() ... I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm: class TestClass(): def __init__(self, var1, var2): #var1 and var2 are received from a GUI self.var1 = var1 ... if state == "ABC" doSomething(var1, var2) .. Could someone point me in the right direction? Thank you! From tundra at tundraware.com Mon Feb 24 20:46:13 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 24 Feb 2014 19:46:13 -0600 Subject: Coding a simple state machine in python In-Reply-To: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: <589tta-krl.ln1@ozzie.tundraware.com> On 02/24/2014 07:30 PM, Ronaldo wrote: > How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code: > > if state == "ABC": > do_something() > change state to DEF > > if state == "DEF" > perform_the_next_function() > ... > > I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm: > > class TestClass(): > def __init__(self, var1, var2): #var1 and var2 are received from a GUI > self.var1 = var1 > ... > if state == "ABC" > doSomething(var1, var2) > .. > > Could someone point me in the right direction? Thank you! > > There are probably lots of ways to do it, but I'd use a dictionary and a variable to hold the current state: CURRENT_STATE = "Start" DFA_STATE_MACHINE = {"Start" : start_fn, "State1" : state1_fn, "State2" : state2_fn ....} ##### # Functions for each state go here. They end by setting CURRENT_STATE to some value ##### def start_fn(): . . . def state1_fn(): . . . # And so on # Now run the state machine while ( CURRENT_STATE != "Done"): # Execute the function for the current state DFA_STATE_MACHINE[CURRENT_STATE]() Like I said, there are other - more compact ways - to do this, but this is the general idea. Now - go do your own homework :) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From aleax at google.com Mon Feb 24 21:24:52 2014 From: aleax at google.com (Alex Martelli) Date: Mon, 24 Feb 2014 18:24:52 -0800 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: Off the cuff, I'd make saveme into a function, not a class; the saveme function would alter the class passed in as its only argument (saving __init__ and/or __del__ methods it may have and replacing them with other -- nested -- functions that call them and do the rest of the job) and return the same class object it received. No time to actually write the code but this seems a much sounder architecture. Alex On Mon, Feb 24, 2014 at 4:49 PM, Sangeeth Saravanaraj < sangeeth.saravanaraj at gmail.com> wrote: > This question was initially asked in tutor at python.org; Now I am widening > the audience to gain attention. > > I want to create a decorator which should do the following things: > => When an object of the decorated class is created, the objects name > (say the value of the incoming "id" argument) should be stored as a record > in a table in a database. > => When an object of the decorated class is deleted, the record with this > deleted objects name (i.e. object.id) should be removed from the table. > > Now, for example - consider the following snippet: > > @saveme > class A(object): > def __init__(self, id): > self.id = id > > @saveme > class B(object): > def __init__(self, id): > self.id = id > > "saveme" should do what I have explained earlier. > > a1 = A("A1") > a2 = A("A2") > a3 = A("A3") > b1 = B("B1") > b2 = B("B2") > > At this point if I query and print all the records in a table, I should > get the following output: > ["A1", "A2", "A3", "B1", "B2"] > > del a1 > del a2 > del a3 > del b1 > del b2 > > At this point, all entries in the table should be deleted; query should > return an empty list! > > And, I want to highlight that the classes that are being decorated with > "saveme" can de derived classes too [which initialises its base classes > using super() method]! > > Now the following is what I have tried: > > class saveme(object): > def __init__(self, klass): > print "saveme::__init__()" > self._klass = klass > > def __call__(self, *args, **kwargs): > print "saveme::__call__()" > obj = self._klass(*args, **kwargs) > # creation of DB record will happen here! > # i.e. something like add_to_db(kwargs.get("id")) > return obj > > def __del__(self): > # deletion of DB record will happen here! > # i.e. something like remove_from_db(id) > # TODO: how to retrieve the "id" here?! > print "saveme::__del__()" > > > class Parent1(object): > def __init__(self): > print "Parent1:: __init__()" > super(Parent1, self).__init__() > > > class Parent2(object): > def __init__(self): > print "Parent2:: __init__()" > super(Parent2, self).__init__() > > > @saveme > class A(Parent1, Parent2): > def __init__(self, id): > print "A::__init__()" > self.id = id > #super(A, self).__init__() > > > #@saveme > #class B(object): > # def __init__(self, id): > # print "B::__init__()" > # self.id = id > > > def main(): > a1 = A(id="A1") > # b1 = B(id="B1") > > if __name__ == "__main__": > main() > > > When executed the above, I ran in to the following: > > saveme::__init__() > saveme::__call__() > A::__init__() > Traceback (most recent call last): > File "1.py", line 54, in > main() > File "1.py", line 50, in main > a1 = A(id="A1") > File "1.py", line 10, in __call__ > obj = self._klass(*args, **kwargs) > File "1.py", line 39, in __init__ > super(A, self).__init__() > TypeError: must be type, not saveme > saveme::__del__() > > > When I commented "super(A, self).__init__()" in the class A :: __init__() > method, it returned an object of type A and I was able to see the prints in > the __call__ and __del__ methods but the __init__() methods of the base > classes (Parent1 & Parent2) were not called! > > From the error message, what I could understand is - the object returned > by saveme::__call__() is not of type A but of type saveme. But when I put a > print in the saveme::__call__() I could see it returns an object of type A > and not saveme. > > Now the question is - with this approach to capture the initiation and > deletion events of an object, how do I initialise the base classes using > super()? > > Or, is there any other better way to capture the __call__ and __del__ > events for an object of a certain class - if so, how?! > > Thank you, > > Sangeeth > > > PS: > http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class > > > _______________________________________________ > Baypiggies mailing list > Baypiggies at python.org > To change your subscription options or unsubscribe: > https://mail.python.org/mailman/listinfo/baypiggies > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Feb 24 21:34:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 13:34:55 +1100 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 1:24 PM, Alex Martelli wrote: > del a1 > del a2 > del a3 > del b1 > del b2 > > At this point, all entries in the table should be deleted; query should > return an empty list! > You can't actually depend on del resulting in __del__ being called. The two are tangentially related, but Python doesn't guarantee that unbinding a name will result in the destruction of the object. I recommend that, instead, you have some kind of explicit removal system. ChrisA From wrw at mac.com Mon Feb 24 21:55:31 2014 From: wrw at mac.com (William Ray Wing) Date: Mon, 24 Feb 2014 21:55:31 -0500 Subject: Coding a simple state machine in python In-Reply-To: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: <41DAA444-F51A-458D-8F79-8CD3117A4879@mac.com> On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: > How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code: > > if state == "ABC": > do_something() > change state to DEF > > if state == "DEF" > perform_the_next_function() > ... > > I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm: > > class TestClass(): > def __init__(self, var1, var2): #var1 and var2 are received from a GUI > self.var1 = var1 > ... > if state == "ABC" > doSomething(var1, var2) > .. > > Could someone point me in the right direction? Thank you! > > -- > https://mail.python.org/mailman/listinfo/python-list And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table. That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state. Stackoverflow has a couple of compact examples here: http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice Bill From tundra at tundraware.com Mon Feb 24 22:27:30 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 24 Feb 2014 21:27:30 -0600 Subject: Coding a simple state machine in python In-Reply-To: References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: <530C0DA2.7020202@tundraware.com> On 02/24/2014 08:55 PM, William Ray Wing wrote: > > On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: > >> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code: >> >> if state == "ABC": >> do_something() >> change state to DEF >> >> if state == "DEF" >> perform_the_next_function() >> ... >> >> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm: >> >> class TestClass(): >> def __init__(self, var1, var2): #var1 and var2 are received from a GUI >> self.var1 = var1 >> ... >> if state == "ABC" >> doSomething(var1, var2) >> .. >> >> Could someone point me in the right direction? Thank you! >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table. That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state. > > Stackoverflow has a couple of compact examples here: > > http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice > > Bill > Now you're making it TOO easy Bill ;) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From tundra at tundraware.com Mon Feb 24 22:27:30 2014 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 24 Feb 2014 21:27:30 -0600 Subject: Coding a simple state machine in python In-Reply-To: References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: <530C0DA2.7020202@tundraware.com> On 02/24/2014 08:55 PM, William Ray Wing wrote: > > On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: > >> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code: >> >> if state == "ABC": >> do_something() >> change state to DEF >> >> if state == "DEF" >> perform_the_next_function() >> ... >> >> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm: >> >> class TestClass(): >> def __init__(self, var1, var2): #var1 and var2 are received from a GUI >> self.var1 = var1 >> ... >> if state == "ABC" >> doSomething(var1, var2) >> .. >> >> Could someone point me in the right direction? Thank you! >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table. That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state. > > Stackoverflow has a couple of compact examples here: > > http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice > > Bill > Now you're making it TOO easy Bill ;) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From patil.jay2009 at gmail.com Mon Feb 24 22:52:29 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 24 Feb 2014 19:52:29 -0800 (PST) Subject: Python powerpoint automation using pywin32 In-Reply-To: <282c7cfe-b6c4-47a9-a9c6-6a4912a81bd0@googlegroups.com> References: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> <282c7cfe-b6c4-47a9-a9c6-6a4912a81bd0@googlegroups.com> Message-ID: On Monday, 24 February 2014 17:27:23 UTC+5:30, sffj... at gmail.com wrote: > On Monday, 24 February 2014 11:35:08 UTC, Jaydeep Patil wrote: > > > I need to create a new powerpoint presentation. I need to add images, paste some graphs, add texts, tables into powerpoint. > > > > > > Is any link or document available which help me to do this work more effectivey & faster. > > > > Always remember, PyPi is your friend. > > > > I've not used it but the following is available which works with Microsoft's XML based document types. It is not automation per se (and doesn't use pywin32) but a library for pptx document manipulation. > > > > https://pypi.python.org/pypi/python-pptx/ > > > > Docs are here > > > > https://python-pptx.readthedocs.org/en/latest/ > > > > --Simon Hi Simon, I need to use COM interface for PowerPoint generation. So let me know any related docs? Regards Jaydeep From david at bitcasa.com Mon Feb 24 22:46:07 2014 From: david at bitcasa.com (David Lawrence) Date: Mon, 24 Feb 2014 19:46:07 -0800 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: If as according to the docs, there is no guarantee of __del__ being called, anything that relies on that seems unsafe (depending on how robust one needs the solutions to be). Solutions I've seen elsewhere suggest creating something like a *release()* method on your objects and calling it explicitly before calling *del my_obj *(if you even call del, rather than just relying on GC). Alternatively, if it suits the scenario, use a context manager. All suggestions lifted from (a SO that informed me in the past): http://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour On Mon, Feb 24, 2014 at 6:24 PM, Alex Martelli wrote: > Off the cuff, I'd make saveme into a function, not a class; > the saveme function would alter the class passed in as its only argument > (saving __init__ and/or __del__ methods it may have and replacing them with > other -- nested -- functions that call them and do the rest of the job) and > return the same class object it received. > > No time to actually write the code but this seems a much sounder > architecture. > > > Alex > > > > On Mon, Feb 24, 2014 at 4:49 PM, Sangeeth Saravanaraj < > sangeeth.saravanaraj at gmail.com> wrote: > >> This question was initially asked in tutor at python.org; Now I am widening >> the audience to gain attention. >> >> I want to create a decorator which should do the following things: >> => When an object of the decorated class is created, the objects name >> (say the value of the incoming "id" argument) should be stored as a record >> in a table in a database. >> => When an object of the decorated class is deleted, the record with >> this deleted objects name (i.e. object.id) should be removed from the >> table. >> >> Now, for example - consider the following snippet: >> >> @saveme >> class A(object): >> def __init__(self, id): >> self.id = id >> >> @saveme >> class B(object): >> def __init__(self, id): >> self.id = id >> >> "saveme" should do what I have explained earlier. >> >> a1 = A("A1") >> a2 = A("A2") >> a3 = A("A3") >> b1 = B("B1") >> b2 = B("B2") >> >> At this point if I query and print all the records in a table, I should >> get the following output: >> ["A1", "A2", "A3", "B1", "B2"] >> >> del a1 >> del a2 >> del a3 >> del b1 >> del b2 >> >> At this point, all entries in the table should be deleted; query should >> return an empty list! >> >> And, I want to highlight that the classes that are being decorated with >> "saveme" can de derived classes too [which initialises its base classes >> using super() method]! >> >> Now the following is what I have tried: >> >> class saveme(object): >> def __init__(self, klass): >> print "saveme::__init__()" >> self._klass = klass >> >> def __call__(self, *args, **kwargs): >> print "saveme::__call__()" >> obj = self._klass(*args, **kwargs) >> # creation of DB record will happen here! >> # i.e. something like add_to_db(kwargs.get("id")) >> return obj >> >> def __del__(self): >> # deletion of DB record will happen here! >> # i.e. something like remove_from_db(id) >> # TODO: how to retrieve the "id" here?! >> print "saveme::__del__()" >> >> >> class Parent1(object): >> def __init__(self): >> print "Parent1:: __init__()" >> super(Parent1, self).__init__() >> >> >> class Parent2(object): >> def __init__(self): >> print "Parent2:: __init__()" >> super(Parent2, self).__init__() >> >> >> @saveme >> class A(Parent1, Parent2): >> def __init__(self, id): >> print "A::__init__()" >> self.id = id >> #super(A, self).__init__() >> >> >> #@saveme >> #class B(object): >> # def __init__(self, id): >> # print "B::__init__()" >> # self.id = id >> >> >> def main(): >> a1 = A(id="A1") >> # b1 = B(id="B1") >> >> if __name__ == "__main__": >> main() >> >> >> When executed the above, I ran in to the following: >> >> saveme::__init__() >> saveme::__call__() >> A::__init__() >> Traceback (most recent call last): >> File "1.py", line 54, in >> main() >> File "1.py", line 50, in main >> a1 = A(id="A1") >> File "1.py", line 10, in __call__ >> obj = self._klass(*args, **kwargs) >> File "1.py", line 39, in __init__ >> super(A, self).__init__() >> TypeError: must be type, not saveme >> saveme::__del__() >> >> >> When I commented "super(A, self).__init__()" in the class A :: __init__() >> method, it returned an object of type A and I was able to see the prints in >> the __call__ and __del__ methods but the __init__() methods of the base >> classes (Parent1 & Parent2) were not called! >> >> From the error message, what I could understand is - the object returned >> by saveme::__call__() is not of type A but of type saveme. But when I put a >> print in the saveme::__call__() I could see it returns an object of type A >> and not saveme. >> >> Now the question is - with this approach to capture the initiation and >> deletion events of an object, how do I initialise the base classes using >> super()? >> >> Or, is there any other better way to capture the __call__ and __del__ >> events for an object of a certain class - if so, how?! >> >> Thank you, >> >> Sangeeth >> >> >> PS: >> http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class >> >> >> _______________________________________________ >> Baypiggies mailing list >> Baypiggies at python.org >> To change your subscription options or unsubscribe: >> https://mail.python.org/mailman/listinfo/baypiggies >> > > > _______________________________________________ > Baypiggies mailing list > Baypiggies at python.org > To change your subscription options or unsubscribe: > https://mail.python.org/mailman/listinfo/baypiggies > -------------- next part -------------- An HTML attachment was scrubbed... URL: From patil.jay2009 at gmail.com Mon Feb 24 23:21:33 2014 From: patil.jay2009 at gmail.com (Jaydeep Patil) Date: Mon, 24 Feb 2014 20:21:33 -0800 (PST) Subject: Docs related python powerpoint automation using pywin32 Message-ID: <951c42c6-0ad1-4975-b36d-61cdc2392fe8@googlegroups.com> Hi, Required help regarding python powerpoint automation using pywin32. provide some reference or guides? Regards Jaydeep From shakefu at gmail.com Mon Feb 24 23:55:32 2014 From: shakefu at gmail.com (Jacob Alheid) Date: Mon, 24 Feb 2014 20:55:32 -0800 (PST) Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: <1393304131851.7914595c@Nodemailer> ? Sent from Mailbox for iPad On Mon, Feb 24, 2014 at 8:49 PM, David Lawrence wrote: > If as according to the docs, there is no guarantee of __del__ being called, > anything that relies on that seems unsafe (depending on how robust one > needs the solutions to be). Solutions I've seen elsewhere suggest creating > something like a *release()* method on your objects and calling it > explicitly before calling *del my_obj *(if you even call del, rather than > just relying on GC). > Alternatively, if it suits the scenario, use a context manager. > All suggestions lifted from (a SO that informed me in the past): > http://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour > On Mon, Feb 24, 2014 at 6:24 PM, Alex Martelli wrote: >> Off the cuff, I'd make saveme into a function, not a class; >> the saveme function would alter the class passed in as its only argument >> (saving __init__ and/or __del__ methods it may have and replacing them with >> other -- nested -- functions that call them and do the rest of the job) and >> return the same class object it received. >> >> No time to actually write the code but this seems a much sounder >> architecture. >> >> >> Alex >> >> >> >> On Mon, Feb 24, 2014 at 4:49 PM, Sangeeth Saravanaraj < >> sangeeth.saravanaraj at gmail.com> wrote: >> >>> This question was initially asked in tutor at python.org; Now I am widening >>> the audience to gain attention. >>> >>> I want to create a decorator which should do the following things: >>> => When an object of the decorated class is created, the objects name >>> (say the value of the incoming "id" argument) should be stored as a record >>> in a table in a database. >>> => When an object of the decorated class is deleted, the record with >>> this deleted objects name (i.e. object.id) should be removed from the >>> table. >>> >>> Now, for example - consider the following snippet: >>> >>> @saveme >>> class A(object): >>> def __init__(self, id): >>> self.id = id >>> >>> @saveme >>> class B(object): >>> def __init__(self, id): >>> self.id = id >>> >>> "saveme" should do what I have explained earlier. >>> >>> a1 = A("A1") >>> a2 = A("A2") >>> a3 = A("A3") >>> b1 = B("B1") >>> b2 = B("B2") >>> >>> At this point if I query and print all the records in a table, I should >>> get the following output: >>> ["A1", "A2", "A3", "B1", "B2"] >>> >>> del a1 >>> del a2 >>> del a3 >>> del b1 >>> del b2 >>> >>> At this point, all entries in the table should be deleted; query should >>> return an empty list! >>> >>> And, I want to highlight that the classes that are being decorated with >>> "saveme" can de derived classes too [which initialises its base classes >>> using super() method]! >>> >>> Now the following is what I have tried: >>> >>> class saveme(object): >>> def __init__(self, klass): >>> print "saveme::__init__()" >>> self._klass = klass >>> >>> def __call__(self, *args, **kwargs): >>> print "saveme::__call__()" >>> obj = self._klass(*args, **kwargs) >>> # creation of DB record will happen here! >>> # i.e. something like add_to_db(kwargs.get("id")) >>> return obj >>> >>> def __del__(self): >>> # deletion of DB record will happen here! >>> # i.e. something like remove_from_db(id) >>> # TODO: how to retrieve the "id" here?! >>> print "saveme::__del__()" >>> >>> >>> class Parent1(object): >>> def __init__(self): >>> print "Parent1:: __init__()" >>> super(Parent1, self).__init__() >>> >>> >>> class Parent2(object): >>> def __init__(self): >>> print "Parent2:: __init__()" >>> super(Parent2, self).__init__() >>> >>> >>> @saveme >>> class A(Parent1, Parent2): >>> def __init__(self, id): >>> print "A::__init__()" >>> self.id = id >>> #super(A, self).__init__() >>> >>> >>> #@saveme >>> #class B(object): >>> # def __init__(self, id): >>> # print "B::__init__()" >>> # self.id = id >>> >>> >>> def main(): >>> a1 = A(id="A1") >>> # b1 = B(id="B1") >>> >>> if __name__ == "__main__": >>> main() >>> >>> >>> When executed the above, I ran in to the following: >>> >>> saveme::__init__() >>> saveme::__call__() >>> A::__init__() >>> Traceback (most recent call last): >>> File "1.py", line 54, in >>> main() >>> File "1.py", line 50, in main >>> a1 = A(id="A1") >>> File "1.py", line 10, in __call__ >>> obj = self._klass(*args, **kwargs) >>> File "1.py", line 39, in __init__ >>> super(A, self).__init__() >>> TypeError: must be type, not saveme >>> saveme::__del__() >>> >>> >>> When I commented "super(A, self).__init__()" in the class A :: __init__() >>> method, it returned an object of type A and I was able to see the prints in >>> the __call__ and __del__ methods but the __init__() methods of the base >>> classes (Parent1 & Parent2) were not called! >>> >>> From the error message, what I could understand is - the object returned >>> by saveme::__call__() is not of type A but of type saveme. But when I put a >>> print in the saveme::__call__() I could see it returns an object of type A >>> and not saveme. >>> >>> Now the question is - with this approach to capture the initiation and >>> deletion events of an object, how do I initialise the base classes using >>> super()? >>> >>> Or, is there any other better way to capture the __call__ and __del__ >>> events for an object of a certain class - if so, how?! >>> >>> Thank you, >>> >>> Sangeeth >>> >>> >>> PS: >>> http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class >>> >>> >>> _______________________________________________ >>> Baypiggies mailing list >>> Baypiggies at python.org >>> To change your subscription options or unsubscribe: >>> https://mail.python.org/mailman/listinfo/baypiggies >>> >> >> >> _______________________________________________ >> Baypiggies mailing list >> Baypiggies at python.org >> To change your subscription options or unsubscribe: >> https://mail.python.org/mailman/listinfo/baypiggies >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Tue Feb 25 00:19:57 2014 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Feb 2014 15:19:57 +1000 Subject: Coding a simple state machine in python In-Reply-To: References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: On 25/02/2014 1:27 PM, Tim Daneliuk wrote: > On 02/24/2014 08:55 PM, William Ray Wing wrote: >> On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: >>> How do I write a state machine in python? >> >> Stackoverflow has a couple of compact examples here: > > Now you're making it TOO easy Bill ;) No, the _easy_ solution is: https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search From wuwei23 at gmail.com Tue Feb 25 00:26:43 2014 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Feb 2014 15:26:43 +1000 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: On 25/02/2014 12:34 PM, Chris Angelico wrote: > On Tue, Feb 25, 2014 at 1:24 PM, Alex Martelli wrote: >> At this point, all entries in the table should be deleted; query should >> return an empty list! > > You can't actually depend on del resulting in __del__ being called. Mind those attributions, Chris, it was actually Sangeeth Saravanaraj who wrote what you quoted. I'm preeeeetty sure Alex knows all about __del__ :) From quequegg at gmail.com Tue Feb 25 00:28:13 2014 From: quequegg at gmail.com (quequegg at gmail.com) Date: Mon, 24 Feb 2014 21:28:13 -0800 (PST) Subject: Help father help son / Install Version 2.6 on Mac OSX 10.9 Message-ID: <69b4887c-afea-46d0-b336-f4a34c78cbbe@googlegroups.com> I just want to help him get the environment set up. Running Mac Maverick, OSX 10.9 Trying to install Python 2.6 because PyGames says it will only install if Python 2.6 is present. When I run make framework install I am treated to: gcc -c -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -DSVNVERSION=\"`LC_ALL=C svnversion .`\" -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c clang: error: no such file or directory: 'directory"' make: *** [Modules/getbuildinfo.o] Error 1 Hint? From rosuav at gmail.com Tue Feb 25 00:43:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 16:43:33 +1100 Subject: Help father help son / Install Version 2.6 on Mac OSX 10.9 In-Reply-To: <69b4887c-afea-46d0-b336-f4a34c78cbbe@googlegroups.com> References: <69b4887c-afea-46d0-b336-f4a34c78cbbe@googlegroups.com> Message-ID: On Tue, Feb 25, 2014 at 4:28 PM, wrote: > Trying to install Python 2.6 because PyGames says it will only install if Python 2.6 is present. Are you sure you need 2.6 and not 2.7? This suggests 2.7 works: http://pygame.org/wiki/MacCompile ChrisA From nad at acm.org Tue Feb 25 00:57:00 2014 From: nad at acm.org (Ned Deily) Date: Mon, 24 Feb 2014 21:57:00 -0800 Subject: Help father help son / Install Version 2.6 on Mac OSX 10.9 References: <69b4887c-afea-46d0-b336-f4a34c78cbbe@googlegroups.com> Message-ID: In article , Chris Angelico wrote: > On Tue, Feb 25, 2014 at 4:28 PM, wrote: > > Trying to install Python 2.6 because PyGames says it will only install if > > Python 2.6 is present. > > Are you sure you need 2.6 and not 2.7? This suggests 2.7 works: > > http://pygame.org/wiki/MacCompile And, in any case, Apple ships OS X 10.9 with copies of both Python 2.7 and 2.6: /usr/bin/python2.7 /usr/bin/python2.6 -- Ned Deily, nad at acm.org From rosuav at gmail.com Tue Feb 25 01:34:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 25 Feb 2014 17:34:00 +1100 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 4:26 PM, alex23 wrote: > On 25/02/2014 12:34 PM, Chris Angelico wrote: >> >> On Tue, Feb 25, 2014 at 1:24 PM, Alex Martelli wrote: >>> >>> At this point, all entries in the table should be deleted; query should >>> return an empty list! >> >> >> You can't actually depend on del resulting in __del__ being called. > > > Mind those attributions, Chris, it was actually Sangeeth Saravanaraj who > wrote what you quoted. I'm preeeeetty sure Alex knows all about __del__ :) Whoops, yes. I deleted a header by mistake. Sorry Alex! And thanks Alex for pulling me up on it. (We have a few of those situations. Fortunately we have Steven and Stephen, otherwise we'd have a lot more of it.) ChrisA From pierre.quentel at gmail.com Tue Feb 25 02:28:51 2014 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Mon, 24 Feb 2014 23:28:51 -0800 (PST) Subject: Problem with the console on the new python.org site In-Reply-To: References: <530aa445$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5125ee9a-4180-4b17-bba8-0dee8c0850e2@googlegroups.com> Le lundi 24 f?vrier 2014 14:19:12 UTC+1, Jean-Michel Pichavant a ?crit?: > ----- Original Message ----- > > On Sun, 23 Feb 2014 10:20:15 -0800, Pierre Quentel wrote: > > > > > The new home page of python.org is very nice, congratulations ! > > > > The best I can say about it is that I'm extremely underwhelmed by the > > design, which is far more "busy" and colourful than the old design > > (this > > is not a complement), and not happy that it doesn't work correctly > > without Javascript. > > Steven, you must have been the grumpy smurf in another life ;) > > > > But there is a problem with the online console provided by > > > PythonAnywhere : with my azerty keyboard, I can't enter characters > > > such > > > as ) or ] - very annoying ! > > I have an azerty keyboard and it works just fine, your problem must be something else. It seems to depend on the browser. I had the problem with Firefox 27.0.1 on Windows XP ; the link "Feedback" didn't work with this browser, this is why I posted here With Chrome 33.0.1750.117 m and Opera 12.12 the characters are recognised I reported the issue on the feedback form, and discovered it was already known by the PythonAnywhere team (https://www.pythonanywhere.com/forums/topic/213/). Hope it will be fixed quickly, it doesn't give a good impression for newcomers to Python whose first contact with the language is this console > > JM > > > -- IMPORTANT NOTICE: > > The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From steve at pearwood.info Tue Feb 25 02:29:49 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 25 Feb 2014 07:29:49 GMT Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) References: <530bdbe2$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530c466c$0$29980$c3e8da3$5496439d@news.astraweb.com> On Mon, 24 Feb 2014 16:10:53 -0800, Ethan Furman wrote: > On 02/24/2014 03:55 PM, Steven D'Aprano wrote: >> Will b'%s' take any arbitrary object, as in: >> >> b'Key: %s' % [1, 2, 3, 4] >> => b'Key: [1, 2, 3, 4]' > > No. Very glad to hear it. [...] >>> Can anybody think of a use-case for this particular feature? >> >> Not me. > > I find that humorous, as %a would work with your list example above. :) I know. But why would I want to do it? "It won't fail" is not a use-case. I can subclass int and give it a __getitem__ method that raise SystemExit, but that's not a use-case for doing so :-) I cannot think of any reason to want to ASCII-ise the repr of arbitrary objects, and on the rare occasion that I did, I could say repr(obj).encode('ascii', 'backslashescape') I don't object to this feature, but nor do I want it. -- Steven From sangeeth.saravanaraj at gmail.com Mon Feb 24 19:49:51 2014 From: sangeeth.saravanaraj at gmail.com (Sangeeth Saravanaraj) Date: Tue, 25 Feb 2014 06:19:51 +0530 Subject: Class decorator to capture the creation and deletion of objects Message-ID: This question was initially asked in tutor at python.org; Now I am widening the audience to gain attention. I want to create a decorator which should do the following things: => When an object of the decorated class is created, the objects name (say the value of the incoming "id" argument) should be stored as a record in a table in a database. => When an object of the decorated class is deleted, the record with this deleted objects name (i.e. object.id) should be removed from the table. Now, for example - consider the following snippet: @saveme class A(object): def __init__(self, id): self.id = id @saveme class B(object): def __init__(self, id): self.id = id "saveme" should do what I have explained earlier. a1 = A("A1") a2 = A("A2") a3 = A("A3") b1 = B("B1") b2 = B("B2") At this point if I query and print all the records in a table, I should get the following output: ["A1", "A2", "A3", "B1", "B2"] del a1 del a2 del a3 del b1 del b2 At this point, all entries in the table should be deleted; query should return an empty list! And, I want to highlight that the classes that are being decorated with "saveme" can de derived classes too [which initialises its base classes using super() method]! Now the following is what I have tried: class saveme(object): def __init__(self, klass): print "saveme::__init__()" self._klass = klass def __call__(self, *args, **kwargs): print "saveme::__call__()" obj = self._klass(*args, **kwargs) # creation of DB record will happen here! # i.e. something like add_to_db(kwargs.get("id")) return obj def __del__(self): # deletion of DB record will happen here! # i.e. something like remove_from_db(id) # TODO: how to retrieve the "id" here?! print "saveme::__del__()" class Parent1(object): def __init__(self): print "Parent1:: __init__()" super(Parent1, self).__init__() class Parent2(object): def __init__(self): print "Parent2:: __init__()" super(Parent2, self).__init__() @saveme class A(Parent1, Parent2): def __init__(self, id): print "A::__init__()" self.id = id #super(A, self).__init__() #@saveme #class B(object): # def __init__(self, id): # print "B::__init__()" # self.id = id def main(): a1 = A(id="A1") # b1 = B(id="B1") if __name__ == "__main__": main() When executed the above, I ran in to the following: saveme::__init__() saveme::__call__() A::__init__() Traceback (most recent call last): File "1.py", line 54, in main() File "1.py", line 50, in main a1 = A(id="A1") File "1.py", line 10, in __call__ obj = self._klass(*args, **kwargs) File "1.py", line 39, in __init__ super(A, self).__init__() TypeError: must be type, not saveme saveme::__del__() When I commented "super(A, self).__init__()" in the class A :: __init__() method, it returned an object of type A and I was able to see the prints in the __call__ and __del__ methods but the __init__() methods of the base classes (Parent1 & Parent2) were not called! >From the error message, what I could understand is - the object returned by saveme::__call__() is not of type A but of type saveme. But when I put a print in the saveme::__call__() I could see it returns an object of type A and not saveme. Now the question is - with this approach to capture the initiation and deletion events of an object, how do I initialise the base classes using super()? Or, is there any other better way to capture the __call__ and __del__ events for an object of a certain class - if so, how?! Thank you, Sangeeth PS: http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class -------------- next part -------------- An HTML attachment was scrubbed... URL: From wxjmfauth at gmail.com Tue Feb 25 03:07:17 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Tue, 25 Feb 2014 00:07:17 -0800 (PST) Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) In-Reply-To: <530bdbf8$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <87ha7o9r2q.fsf@elektro.pacujo.net> <87d2ic2lyq.fsf@elektro.pacujo.net> <530bdbf8$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Le mardi 25 f?vrier 2014 00:55:36 UTC+1, Steven D'Aprano a ?crit?: > > > > However, you don't really want to be adding large numbers of byte strings > > together, due to efficiency. Better to use % interpolation to insert them > > all at once. Hence the push to add % to bytes in Python 3. > > >>> timeit.timeit("'abc' * 1000 + '\u20ac'") 2.3244550589543564 >>> timeit.timeit("x * 1000 + y", "x = 'abc'.encode('utf-8'); y = '\u20ac'.encode('utf-8')") 0.9365105183684364 >>> timeit.timeit("'\u0153' + 'abc' * 1000 + '\u20ac'") 3.0469319226397715 >>> timeit.timeit("z + x * 1000 + y", "x = 'abc'.encode('utf-8'); y = '\u20ac'.encode('utf-8'); z = '\u0153'.encode('utf-8')") 1.9215464486771339 >>> Interpolation will not help. What is wrong by design will always stay wrong by design. jmf >>> From breamoreboy at yahoo.co.uk Tue Feb 25 03:29:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 08:29:49 +0000 Subject: Python 3.5, bytes, and %-interpolation (aka PEP 461) In-Reply-To: References: <87ha7o9r2q.fsf@elektro.pacujo.net> <87d2ic2lyq.fsf@elektro.pacujo.net> <530bdbf8$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 25/02/2014 08:07, wxjmfauth at gmail.com wrote: > > What is wrong by design will always stay wrong by design. > Why are you making the statement that PEP 461 is wrong by design? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Tue Feb 25 03:35:52 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 08:35:52 +0000 Subject: Coding a simple state machine in python In-Reply-To: References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: On 25/02/2014 05:19, alex23 wrote: > On 25/02/2014 1:27 PM, Tim Daneliuk wrote: >> On 02/24/2014 08:55 PM, William Ray Wing wrote: >>> On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: >>>> How do I write a state machine in python? > >> >>> Stackoverflow has a couple of compact examples here: >> >> Now you're making it TOO easy Bill ;) > > No, the _easy_ solution is: > > https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search > Or several recipes on Activestate. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Tue Feb 25 03:38:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 08:38:49 +0000 Subject: Python powerpoint automation using pywin32 In-Reply-To: References: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> <282c7cfe-b6c4-47a9-a9c6-6a4912a81bd0@googlegroups.com> Message-ID: On 25/02/2014 03:52, Jaydeep Patil wrote: > On Monday, 24 February 2014 17:27:23 UTC+5:30, sffj... at gmail.com wrote: >> On Monday, 24 February 2014 11:35:08 UTC, Jaydeep Patil wrote: >> >>> I need to create a new powerpoint presentation. I need to add images, paste some graphs, add texts, tables into powerpoint. >> >>> >> >>> Is any link or document available which help me to do this work more effectivey & faster. >> >> >> >> Always remember, PyPi is your friend. >> >> >> >> I've not used it but the following is available which works with Microsoft's XML based document types. It is not automation per se (and doesn't use pywin32) but a library for pptx document manipulation. >> >> >> >> https://pypi.python.org/pypi/python-pptx/ >> >> >> >> Docs are here >> >> >> >> https://python-pptx.readthedocs.org/en/latest/ >> >> >> >> --Simon > > > Hi Simon, > > I need to use COM interface for PowerPoint generation. > > So let me know any related docs? > > > Regards > Jaydeep > I don't need to read double spaced stuff so please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing it, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Tue Feb 25 05:01:24 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 11:01:24 +0100 Subject: Coding a simple state machine in python References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: alex23 wrote: > On 25/02/2014 1:27 PM, Tim Daneliuk wrote: >> On 02/24/2014 08:55 PM, William Ray Wing wrote: >>> On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: >>>> How do I write a state machine in python? > >> >>> Stackoverflow has a couple of compact examples here: >> >> Now you're making it TOO easy Bill ;) > > No, the _easy_ solution is: > > https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search Easy? By the time I have evaluated these I've written my own ;) From __peter__ at web.de Tue Feb 25 05:04:26 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 11:04:26 +0100 Subject: Coding a simple state machine in python References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> <41DAA444-F51A-458D-8F79-8CD3117A4879@mac.com> Message-ID: William Ray Wing wrote: > > On Feb 24, 2014, at 8:30 PM, Ronaldo wrote: > >> How do I write a state machine in python? I have identified the states >> and the conditions. Is it possible to do simple a if-then-else sort of an >> algorithm? Below is some pseudo code: >> >> if state == "ABC": >> do_something() >> change state to DEF >> >> if state == "DEF" >> perform_the_next_function() >> ... >> >> I have a class to which certain values are passed from a GUI and the >> functions above have to make use of those variables. How do I go about >> doing this? I have the following algorithm: >> >> class TestClass(): >> def __init__(self, var1, var2): #var1 and var2 are received from a GUI >> self.var1 = var1 >> ... >> if state == "ABC" >> doSomething(var1, var2) >> .. >> >> Could someone point me in the right direction? Thank you! >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > And, to extend Tim's suggestion of a dictionary just a bit, note that > since Python functions are happy to pass function names as arguments, you > can use a dictionary to make a really nice compact dispatch table. That > is, function A does its thing, gets to a new state, and returns as one of > its return arguments the key into the dictionary that points to the next > function_name to be called based on that new state. > > Stackoverflow has a couple of compact examples here: > > http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch- table-in-your-language-of-choice Why have the function return a name? Why not just another function? From marko at pacujo.net Tue Feb 25 06:20:23 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 25 Feb 2014 13:20:23 +0200 Subject: Coding a simple state machine in python References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> <41DAA444-F51A-458D-8F79-8CD3117A4879@mac.com> Message-ID: <87lhwz1ls8.fsf@elektro.pacujo.net> Peter Otten <__peter__ at web.de>: > Why have the function return a name? Why not just another function? As people have said, there are many ways to skin the cat. A function can represent a state if it is the only type of event the state machine must process. A regular expression parser would be an example. In the general case, a state machine is a matrix of M states by N types of event. Then, one natural manner of representing a state is a nested class: class Lackey: def __init__(self): lackey = self class Idle: def handle_ding(self): lackey.start_timer(10) lackey.set_state(Dinged) class Dinged: def handle_dong(self): lackey.cancel_timer() lackey.open_door() lackey.ask_for_name() lackey.start_timer(20) lackey.set_state(AwaitingName) def handle_timeout(self): lackey.open_door() lackey.shoo_visitor_away() lackey.set_state(Annoyed) # other state classes here... self.set_state(Idle) def set_state(self, state): log("Lackey(): New state: {}".format( id(self), state.__class__.__name__)) self.state = state() def handle_ding(self): self.state.handle_ding() def handle_dong(self): self.state.handle_dong() def handle_timeout(self): self.state.handle_timeout() def start_timer(self): # etc etc Marko From sffjunkie at gmail.com Tue Feb 25 06:33:59 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Tue, 25 Feb 2014 03:33:59 -0800 (PST) Subject: Python powerpoint automation using pywin32 In-Reply-To: References: <18ed1faa-fe64-4d40-8ade-2f1cac89ae51@googlegroups.com> <282c7cfe-b6c4-47a9-a9c6-6a4912a81bd0@googlegroups.com> Message-ID: <7db15795-2bbe-4ff1-b4be-9a918d08c7de@googlegroups.com> On Tuesday, 25 February 2014 03:52:29 UTC, Jaydeep Patil wrote: > I need to use COM interface for PowerPoint generation. The following will get you started http://nbviewer.ipython.org/github/sanand0/ipython-notebooks/blob/master/Office.ipynb Then you'll need to interpret the Microsoft MSDN docs for anything else http://msdn.microsoft.com/en-us/library/microsoft.office.interop.powerpoint.aspx --Simon Kennedy From sffjunkie at gmail.com Tue Feb 25 07:30:50 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Tue, 25 Feb 2014 04:30:50 -0800 (PST) Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: References: <52FCB228.5040301@shopzeus.com> Message-ID: On Sunday, 16 February 2014 08:13:14 UTC, Nagy L?szl? Zsolt wrote: > > Though I don't see anything in the ActiveState builds (which are all > > I've ever used) to handle the #! type selection of the desired version. > > Just got done updating my 2.7, replacing 3.2 with 3.3, and then having to > > edit my path to make 2.7 primary... No "py.exe" > I need both 2.7 and 3.3. And apparently, py.exe does not work the way it > should be. Is the following any help http://www.perlmonks.org/?node_id=998428 From breamoreboy at yahoo.co.uk Tue Feb 25 08:38:22 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 13:38:22 +0000 Subject: Install python 2 and 3 in the "wrong" order In-Reply-To: <5300731A.7010001@shopzeus.com> References: <52FCB228.5040301@shopzeus.com> <5300731A.7010001@shopzeus.com> Message-ID: On 16/02/2014 08:13, Nagy L?szl? Zsolt wrote: > > And apparently, py.exe does not work the way it should be. What does this mean? Have you raised an issue on the bug tracker? > > I would happily reinstall 3.3 to solve the problem, but before I do that > I would like to check all other related settings. So that after I > reinstall 3.3, I will exactly know what was happening. > > It might be a good idea to change the installer of the 2.x series to > detect if 3.x is already installed, and handle assignments of py and pyw > files gracefully. It might be a good idea but I can't see it happening as (at least as far as I'm concerned) 2.7 is past its sell by date. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From ganesh1pal at gmail.com Tue Feb 25 10:31:20 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Tue, 25 Feb 2014 21:01:20 +0530 Subject: Python : parsing the command line options using optparse Message-ID: Hi Folks , Iam newbie to Python, Iam trying to use optparse module and write a script that will parse the command line options ..I had to use opt parse instead of argparse because by host Operating system is still using python 2.6 Below is the simple program ( Feel free to correct the error ) and 3 quick questions on the same. /* sample Program "/ import optparse parser = optparse.OptionParser() parser.add_option("-p", "--path", action="store", metavar="/ifs/|/ifs/", dest="path_name", type="string", help = "The file or directory path of the object in /ifs",) parser.add_option("-q", "--operation", action="store", metavar="XOR|ADD|SET", dest="operation_type", default='SET', type='choice', choices=['XOR', 'ADD', 'SET'], help = "The corruption operation on the object [default : %default]",) parser.add_option("-f", "--offset", action="store", metavar="HEX", dest="offset_value", default=0x41306141, type="long", help= "The valid offset value [default : %default]" ) parser.add_option("-n", "--node", action="store",metavar="id", dest="node_value", default= 1, type='int', help = "The node id [default : %default]") parser.add_option("-l", "--log", action="store_true",dest="log_file", help = "log the isi_corrupt execution result ") parser.add_option("-c", "--fixcrc", action="store_true",dest="fix_crc", help = "The CRC fix of the corrupted objects ") # instruct optparse to parse the program's command line: (options, args) = parser.parse_args() print options.path_name Questions (1) #python python-5.py --path=/ifs/1.txt --operation=XOR --node=11 --log -fixcrc >> Looks like the dest variable stores it in a dictionary , >> print options.path_name ( gives the option entered in the command line) /ifs/1.txt I wanted to store all the options in a list like [/ifs/1.txt,XOR,11,log_file,fix_crc] please suggest on the same ? Question(2) Why does this program work only with - option and not - in the above code ? I think its not working when the type= 'choice' or its somethimf else ? # python-5.py -p=/ifs/1.txt -q=XOR -f=1234 -n=1 -l Usage: python-5.py [options] python-5.py: error: option -q: invalid choice: '=XOR' (choose from 'XOR', 'ADD', 'SET', 'MODIFY', 'RENAME', 'DELETE', 'KILL') This Works ( --) C:\Users\bahadg\Desktop>python python-5.py --path=/ifs/1.txt --operation=XOR -- offset=1234 --node=1 --log --fixcrc /ifs/1.txt Question (3) If I have really long metavar and the help looks very messy ,is there a way to make it look elegant. Example : parser.add_option("-q", "--operation", action="store", metavar="XOR|ADD|SET|MODIFY|RENAME|DELETE|KILL|", dest="operation_type", default='SET', type='choice', choices=['XOR', 'ADD', 'SET' |'MODIFY'|'RENAME'|'DELETE'|'KILL'], help = "The corruption operation on the object [default : %default]",) #python-5.py --help Usage: python-5.py [options] Options: -h, --help show this help message and exit -p /ifs/|/ifs/, --path=/ifs/|/ifs/ The file or directory path of the object in /ifs -q XOR|ADD|SET|MODIFY|RENAME|DELETE|KILL|, --operation=XOR|ADD|SET|MODIFY|RENA ME|DELETE|KILL| The corruption operation on the object [default : SET] -f HEX, --offset=HEX The valid offset value [default : 1093689665] -n id, --node=id The node id [default : 1] -l, --log log the isi_corrupt execution result -c, --fixcrc The CRC fix of the corrupted objects Thanks is advance !! -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 25 11:25:18 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 17:25:18 +0100 Subject: Python : parsing the command line options using optparse References: Message-ID: Ganesh Pal wrote: > Iam newbie to Python, Iam trying to use optparse module and write a script > that will parse the command line options ..I had to use opt parse instead > of argparse because by host Operating system is still using python 2.6 As you are just starting I recommend that you use argparse instead of optparse. > Questions (1) > > > #python python-5.py --path=/ifs/1.txt --operation=XOR --node=11 --log > -fixcrc >>> Looks like the dest variable stores it in a dictionary , It's an instance of optparse.Values. > >> print options.path_name ( gives the option entered in the command > line) > > > /ifs/1.txt > > > I wanted to store all the options in a list like > [/ifs/1.txt,XOR,11,log_file,fix_crc] > > please suggest on the same ? While you can create such a list with [getattr(options, name) for name in ["path_name", "operation_type", ...]] I don't see what the advantage over the default format would be. In fact you are making it harder to access a specific option that way. > Question(2) > Why does this program work only with - option and not - in the above > code ? > I think its not working when the type= 'choice' or its somethimf else ? > > > # python-5.py -p=/ifs/1.txt -q=XOR -f=1234 -n=1 -l If you are asking why short options don't work in conjunction with = -- I don't know, it is probably a design choice of the optparse author. argparse accepts short options with like -f=1234 > Question (3) > If I have really long metavar and the help looks very messy ,is there > a > way to make it look elegant. > > > Example : > > parser.add_option("-q", "--operation", action="store", > metavar="XOR|ADD|SET|MODIFY|RENAME|DELETE|KILL|", dest="operation_type", > default='SET', > > type='choice', choices=['XOR', 'ADD', 'SET' > |'MODIFY'|'RENAME'|'DELETE'|'KILL'], > > help = "The corruption operation on the object [default > : > %default]",) You can move the choices into the help. Example using argparse : parser.add_argument( "-q", "--operation", metavar="OP", default='SET', choices=['XOR', 'ADD', 'SET'], help="The corruption operation on the object [choose from %(choices)s; default: %(default)s]") This becomes -q OP, --operation OP The corruption operation on the object [choose from XOR, ADD, SET; default: SET] in the help. From breamoreboy at yahoo.co.uk Tue Feb 25 11:46:54 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 16:46:54 +0000 Subject: Python : parsing the command line options using optparse In-Reply-To: References: Message-ID: On 25/02/2014 15:31, Ganesh Pal wrote: > Hi Folks , > > Iam newbie to Python, Iam trying to use optparse module and write a > script that will parse the command line options ..I had to use opt parse > instead of argparse because by host Operating system is still using > python 2.6 > Do you have the needed permissions to simply drop the argparse code into the 2.6 stdlib? Could you use the third party docopt instead? It's on pypi and I think it's awesome :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From nowebdevmyrrh at gmail.com Tue Feb 25 12:37:07 2014 From: nowebdevmyrrh at gmail.com (nowebdevmyrrh at gmail.com) Date: Tue, 25 Feb 2014 09:37:07 -0800 (PST) Subject: ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'S SIZE 11.5 NEW IN BOX', '$49.99')' at line 1") In-Reply-To: <6b73a879-b490-48cb-a896-4d4abee90bf5@googlegroups.com> References: <6b73a879-b490-48cb-a896-4d4abee90bf5@googlegroups.com> Message-ID: <84e95932-524c-474e-8a9d-052b08611bc5@googlegroups.com> HI, I'm also getting this kind of error. This will show when I do the edit function http://screencast.com/t/hGSbe1vt and this when performing the delete "Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" What confused me more is that my website works fine on my live server and will only throws error when running on my wampserver. From aleax at google.com Tue Feb 25 12:44:08 2014 From: aleax at google.com (Alex Martelli) Date: Tue, 25 Feb 2014 09:44:08 -0800 Subject: [Baypiggies] Class decorator to capture the creation and deletion of objects In-Reply-To: References: Message-ID: The best way to avoid relying on __del__ in this particular case may be to hold, rather than a plain list of the IDs, a list of weak references to instances. When the "list of IDs" is asked for, it goes through a property that cleans up those weak refs that correspond to now-disappeared instances, before returning the requested list of IDs. Now __del__ can usefully be removed (as its existence may interfere with GC of cyclical garbage), yet the list of IDs is guaranteed to return the list of still-existing instances' IDs, no matter what constructs or idioms have been used to create and remove instances. This avoid relying on creators/destroyers of instances properly calling release and/or using the appropriate context manager; such reliance is sometimes inevitable, but for this particular spec it does not appear to be, thus, it might best be avoided. Alex On Mon, Feb 24, 2014 at 7:46 PM, David Lawrence wrote: > If as according to the docs, there is no guarantee of __del__ being > called, anything that relies on that seems unsafe (depending on how robust > one needs the solutions to be). Solutions I've seen elsewhere suggest > creating something like a *release()* method on your objects and calling > it explicitly before calling *del my_obj *(if you even call del, rather > than just relying on GC). > > Alternatively, if it suits the scenario, use a context manager. > > All suggestions lifted from (a SO that informed me in the past): > http://stackoverflow.com/questions/6104535/i-dont-understand-this-python-del-behaviour > > > On Mon, Feb 24, 2014 at 6:24 PM, Alex Martelli wrote: > >> Off the cuff, I'd make saveme into a function, not a class; >> the saveme function would alter the class passed in as its only argument >> (saving __init__ and/or __del__ methods it may have and replacing them with >> other -- nested -- functions that call them and do the rest of the job) and >> return the same class object it received. >> >> No time to actually write the code but this seems a much sounder >> architecture. >> >> >> Alex >> >> >> >> On Mon, Feb 24, 2014 at 4:49 PM, Sangeeth Saravanaraj < >> sangeeth.saravanaraj at gmail.com> wrote: >> >>> This question was initially asked in tutor at python.org; Now I am >>> widening the audience to gain attention. >>> >>> I want to create a decorator which should do the following things: >>> => When an object of the decorated class is created, the objects name >>> (say the value of the incoming "id" argument) should be stored as a record >>> in a table in a database. >>> => When an object of the decorated class is deleted, the record with >>> this deleted objects name (i.e. object.id) should be removed from the >>> table. >>> >>> Now, for example - consider the following snippet: >>> >>> @saveme >>> class A(object): >>> def __init__(self, id): >>> self.id = id >>> >>> @saveme >>> class B(object): >>> def __init__(self, id): >>> self.id = id >>> >>> "saveme" should do what I have explained earlier. >>> >>> a1 = A("A1") >>> a2 = A("A2") >>> a3 = A("A3") >>> b1 = B("B1") >>> b2 = B("B2") >>> >>> At this point if I query and print all the records in a table, I should >>> get the following output: >>> ["A1", "A2", "A3", "B1", "B2"] >>> >>> del a1 >>> del a2 >>> del a3 >>> del b1 >>> del b2 >>> >>> At this point, all entries in the table should be deleted; query should >>> return an empty list! >>> >>> And, I want to highlight that the classes that are being decorated with >>> "saveme" can de derived classes too [which initialises its base classes >>> using super() method]! >>> >>> Now the following is what I have tried: >>> >>> class saveme(object): >>> def __init__(self, klass): >>> print "saveme::__init__()" >>> self._klass = klass >>> >>> def __call__(self, *args, **kwargs): >>> print "saveme::__call__()" >>> obj = self._klass(*args, **kwargs) >>> # creation of DB record will happen here! >>> # i.e. something like add_to_db(kwargs.get("id")) >>> return obj >>> >>> def __del__(self): >>> # deletion of DB record will happen here! >>> # i.e. something like remove_from_db(id) >>> # TODO: how to retrieve the "id" here?! >>> print "saveme::__del__()" >>> >>> >>> class Parent1(object): >>> def __init__(self): >>> print "Parent1:: __init__()" >>> super(Parent1, self).__init__() >>> >>> >>> class Parent2(object): >>> def __init__(self): >>> print "Parent2:: __init__()" >>> super(Parent2, self).__init__() >>> >>> >>> @saveme >>> class A(Parent1, Parent2): >>> def __init__(self, id): >>> print "A::__init__()" >>> self.id = id >>> #super(A, self).__init__() >>> >>> >>> #@saveme >>> #class B(object): >>> # def __init__(self, id): >>> # print "B::__init__()" >>> # self.id = id >>> >>> >>> def main(): >>> a1 = A(id="A1") >>> # b1 = B(id="B1") >>> >>> if __name__ == "__main__": >>> main() >>> >>> >>> When executed the above, I ran in to the following: >>> >>> saveme::__init__() >>> saveme::__call__() >>> A::__init__() >>> Traceback (most recent call last): >>> File "1.py", line 54, in >>> main() >>> File "1.py", line 50, in main >>> a1 = A(id="A1") >>> File "1.py", line 10, in __call__ >>> obj = self._klass(*args, **kwargs) >>> File "1.py", line 39, in __init__ >>> super(A, self).__init__() >>> TypeError: must be type, not saveme >>> saveme::__del__() >>> >>> >>> When I commented "super(A, self).__init__()" in the class A :: >>> __init__() method, it returned an object of type A and I was able to see >>> the prints in the __call__ and __del__ methods but the __init__() methods >>> of the base classes (Parent1 & Parent2) were not called! >>> >>> From the error message, what I could understand is - the object returned >>> by saveme::__call__() is not of type A but of type saveme. But when I put a >>> print in the saveme::__call__() I could see it returns an object of type A >>> and not saveme. >>> >>> Now the question is - with this approach to capture the initiation and >>> deletion events of an object, how do I initialise the base classes using >>> super()? >>> >>> Or, is there any other better way to capture the __call__ and __del__ >>> events for an object of a certain class - if so, how?! >>> >>> Thank you, >>> >>> Sangeeth >>> >>> >>> PS: >>> http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class >>> >>> >>> _______________________________________________ >>> Baypiggies mailing list >>> Baypiggies at python.org >>> To change your subscription options or unsubscribe: >>> https://mail.python.org/mailman/listinfo/baypiggies >>> >> >> >> _______________________________________________ >> Baypiggies mailing list >> Baypiggies at python.org >> To change your subscription options or unsubscribe: >> https://mail.python.org/mailman/listinfo/baypiggies >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Feb 25 13:10:47 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Feb 2014 18:10:47 +0000 Subject: ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'S SIZE 11.5 NEW IN BOX', '$49.99')' at line 1") In-Reply-To: <84e95932-524c-474e-8a9d-052b08611bc5@googlegroups.com> References: <6b73a879-b490-48cb-a896-4d4abee90bf5@googlegroups.com> <84e95932-524c-474e-8a9d-052b08611bc5@googlegroups.com> Message-ID: <530CDCA7.10503@mrabarnett.plus.com> On 2014-02-25 17:37, nowebdevmyrrh at gmail.com wrote: > HI, I'm also getting this kind of error. > > This will show when I do the edit function > http://screencast.com/t/hGSbe1vt > > and this when performing the delete > "Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" > > What confused me more is that my website works fine on my live server and will only throws error when running on my wampserver. > It might have the same cause, but that's just a guess because you haven't provided much information. From tim_grove at sil.org Tue Feb 25 13:07:57 2014 From: tim_grove at sil.org (Timothy W. Grove) Date: Tue, 25 Feb 2014 18:07:57 +0000 Subject: An example of Python in action! Message-ID: <530CDBFD.9080900@sil.org> Here is an example of Python being used with Maya for animation .... http://vimeo.com/72276442 (No prizes for guessing what sport and team I support!!!) Best regards, Tim Grove From quequegg at gmail.com Tue Feb 25 13:28:08 2014 From: quequegg at gmail.com (Robert Schmidt) Date: Tue, 25 Feb 2014 10:28:08 -0800 (PST) Subject: Intalling Python 2.6 on Mac OSX 10.9 Message-ID: I am trying to install Python 2.6 because Pygame will only run on 2.6. The configure gives only warnings. make frameworkinstall gcc -c -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -DSVNVERSION=\"`LC_ALL=C svnversion .`\" -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c clang: error: no such file or directory: 'directory"' I need a hint. Am I foolish to try and install Pygame? Is that dead? From skip at pobox.com Tue Feb 25 13:47:20 2014 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Feb 2014 12:47:20 -0600 Subject: An example of Python in action! In-Reply-To: <530CDBFD.9080900@sil.org> References: <530CDBFD.9080900@sil.org> Message-ID: On Tue, Feb 25, 2014 at 12:07 PM, Timothy W. Grove wrote: > Here is an example of Python being used with Maya for animation .... > http://vimeo.com/72276442 Maya as in MayaVi, the 3D data visualizer built atop VTK? Skip From fmasanori at gmail.com Tue Feb 25 13:57:54 2014 From: fmasanori at gmail.com (Fernando Masanori Ashikaga) Date: Tue, 25 Feb 2014 10:57:54 -0800 (PST) Subject: First Brazilian programming MOOC with 10.000 enrolled Message-ID: Python for Zombies [1] is the first MOOC in portuguese to teach programming. Today we have 10.000 enrolled in 1013 cities from Brazil. We started five months ago. The website is a Django application. [1] http://pycursos.com/python-para-zumbis/ From robert.kern at gmail.com Tue Feb 25 14:52:44 2014 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Feb 2014 19:52:44 +0000 Subject: An example of Python in action! In-Reply-To: References: <530CDBFD.9080900@sil.org> Message-ID: On 2014-02-25 18:47, Skip Montanaro wrote: > On Tue, Feb 25, 2014 at 12:07 PM, Timothy W. Grove wrote: >> Here is an example of Python being used with Maya for animation .... >> http://vimeo.com/72276442 > > Maya as in MayaVi, the 3D data visualizer built atop VTK? Maya as in Maya, the 3D animation software from AutoDesk. -- 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 skip at pobox.com Tue Feb 25 15:25:53 2014 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Feb 2014 14:25:53 -0600 Subject: An example of Python in action! In-Reply-To: References: <530CDBFD.9080900@sil.org> Message-ID: On Tue, Feb 25, 2014 at 1:52 PM, Robert Kern wrote: > Maya as in Maya, the 3D animation software from AutoDesk. Ugh. What an unfortunate almost-name-clash... S From mauro at gmail.com Tue Feb 25 15:32:38 2014 From: mauro at gmail.com (mauro) Date: Tue, 25 Feb 2014 20:32:38 GMT Subject: intersection, union, difference, symmetric difference for dictionaries Message-ID: Dictionaries and sets share a few properties: - Dictionaries keys are unique as well as sets items - Dictionaries and sets are both unordered - Dictionaries and sets are both accessed by key - Dictionaries and sets are both mutables So I wonder why operations such us intersection, union, difference, symmetric difference that are available for sets and are not available for dictionaries without going via key dictviews. From prometheus235 at gmail.com Tue Feb 25 15:37:51 2014 From: prometheus235 at gmail.com (Nick Timkovich) Date: Tue, 25 Feb 2014 14:37:51 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 2:32 PM, mauro wrote: > > So I wonder why operations such us intersection, union, difference, > symmetric difference that are available for sets and are not available > for dictionaries without going via key dictviews. How would the set operations apply to the dictionary values? From skip at pobox.com Tue Feb 25 15:40:54 2014 From: skip at pobox.com (Skip Montanaro) Date: Tue, 25 Feb 2014 14:40:54 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 2:32 PM, mauro wrote: > So I wonder why operations such us intersection, union, difference, > symmetric difference that are available for sets and are not available > for dictionaries without going via key dictviews. What's the correct result of evaluating this expression? {'A': 1} | {'A': 2} I can see (at least) two possible "correct" answers. Skip From tim_grove at sil.org Tue Feb 25 15:42:20 2014 From: tim_grove at sil.org (Timothy W. Grove) Date: Tue, 25 Feb 2014 20:42:20 +0000 Subject: An example of Python in action! In-Reply-To: References: <530CDBFD.9080900@sil.org> Message-ID: <530D002C.7050800@sil.org> I'm sorry, but I don't know much more than this. If you follow the link there is a description of how the animation was created under the video. On 25/02/2014 18:47, Skip Montanaro wrote: > On Tue, Feb 25, 2014 at 12:07 PM, Timothy W. Grove wrote: >> Here is an example of Python being used with Maya for animation .... >> http://vimeo.com/72276442 > Maya as in MayaVi, the 3D data visualizer built atop VTK? > > Skip > From __peter__ at web.de Tue Feb 25 15:53:18 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 21:53:18 +0100 Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: mauro wrote: > Dictionaries and sets share a few properties: > - Dictionaries keys are unique as well as sets items > - Dictionaries and sets are both unordered > - Dictionaries and sets are both accessed by key but sets have no values > - Dictionaries and sets are both mutables but frozensets also have the operations mentioned in the subject. > So I wonder why operations such us intersection, union, difference, > symmetric difference that are available for sets and are not available > for dictionaries without going via key dictviews. How would you define them? E. g. {1, 2} & {2, 3} == {2} but {1:"a", 2:"b", 3:"c"} & {2:"b", 3:"e", 4:"f"} == ??? The most obvious result is probably the empty dict {2:"b"}, i. e. a & b is defined as dict(a.items() & b.items()) Frankly, I don't do that a lot. So what's your use-case? From __peter__ at web.de Tue Feb 25 15:58:30 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 21:58:30 +0100 Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: Peter Otten wrote: > the empty dict {2:"b"} Make that half-empty ;) From python.list at tim.thechases.com Tue Feb 25 16:03:51 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Feb 2014 15:03:51 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: Message-ID: <20140225150351.063fd961@bigbox.christie.dr> On 2014-02-25 14:40, Skip Montanaro wrote: > What's the correct result of evaluating this expression? > > {'A': 1} | {'A': 2} > > I can see (at least) two possible "correct" answers. I would propose at least four: {'A': 1} # choose the LHS {'A': 2} # choose the RHS {'A': (1,2)} # a resulting pair of both set(['A']) # you did set-ops, so you get a set If dicts were to support set ops, the last one would be my preferred result. I just had to perform set operations on a pair of dicts earlier this week, shrugged, and did things the manual/explicit way: a_dict = dict(...) b_dict = dict(...) a_set = set(a_dict) b_set = set(b_dict) added_keys = b_set - a_set removed_keys = a_set - b_set same_keys = a_set & b_set diff_keys = a_set ^ b_set all_keys = a_set | b_set It would save some space if I didn't have to duplicate all the keys into sets (on the order of 10-100k small strings), instead being able to directly perform the set-ops on the dicts. But otherwise, it was pretty readable & straight-forward. -tkc From ben+python at benfinney.id.au Tue Feb 25 16:27:15 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Feb 2014 08:27:15 +1100 Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: <85fvn6q3ws.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > mauro wrote: > > > - Dictionaries and sets are both accessed by key > > but sets have no values Or rather, sets *only* have values. Dictionaries have keys, sets do not have keys. -- \ ?If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea? ?Thomas Jefferson | Ben Finney From davea at davea.name Tue Feb 25 16:35:50 2014 From: davea at davea.name (Dave Angel) Date: Tue, 25 Feb 2014 16:35:50 -0500 (EST) Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: mauro Wrote in message: > Dictionaries and sets share a few properties: > - Dictionaries keys are unique as well as sets items > - Dictionaries and sets are both unordered > - Dictionaries and sets are both accessed by key > - Dictionaries and sets are both mutables > > So I wonder why operations such us intersection, union, difference, > symmetric difference that are available for sets and are not available > for dictionaries without going via key dictviews. > I certainly wouldn't be able to guess what they should be defined to do, since there are several equally obnoxious possibilities. For instance, take union for example. What should be the result when you union two dicts that have the same key but different values for that key? -- DaveA From breamoreboy at yahoo.co.uk Tue Feb 25 16:54:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 21:54:49 +0000 Subject: Intalling Python 2.6 on Mac OSX 10.9 In-Reply-To: References: Message-ID: On 25/02/2014 18:28, Robert Schmidt wrote: > I am trying to install Python 2.6 because Pygame will only run on 2.6. > The configure gives only warnings. > make frameworkinstall > gcc -c -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -DSVNVERSION=\"`LC_ALL=C svnversion .`\" -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c > clang: error: no such file or directory: 'directory"' > > I need a hint. Am I foolish to try and install Pygame? Is that dead? > This same question was answered on another thread 16 hours ago. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Tue Feb 25 16:54:43 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Feb 2014 22:54:43 +0100 Subject: intersection, union, difference, symmetric difference for dictionaries References: <20140225150351.063fd961@bigbox.christie.dr> Message-ID: Tim Chase wrote: > On 2014-02-25 14:40, Skip Montanaro wrote: >> What's the correct result of evaluating this expression? >> >> {'A': 1} | {'A': 2} >> >> I can see (at least) two possible "correct" answers. > > I would propose at least four: > > {'A': 1} # choose the LHS > {'A': 2} # choose the RHS > {'A': (1,2)} # a resulting pair of both > set(['A']) # you did set-ops, so you get a set > > If dicts were to support set ops, They do in 2.7 and 3.x. > the last one would be my preferred > result. > > I just had to perform set operations on a pair of dicts earlier this > week, shrugged, and did things the manual/explicit way: > > a_dict = dict(...) > b_dict = dict(...) > a_set = set(a_dict) > b_set = set(b_dict) > added_keys = b_set - a_set > removed_keys = a_set - b_set > same_keys = a_set & b_set > diff_keys = a_set ^ b_set > all_keys = a_set | b_set >>> a = dict.fromkeys("ab") >>> b = dict.fromkeys("bc") >>> a.viewkeys() - b.viewkeys() set(['a']) >>> a.viewkeys() & b.viewkeys() set(['b']) >>> a.viewkeys() ^ b.viewkeys() set(['a', 'c']) >>> a.viewkeys() | b.viewkeys() set(['a', 'c', 'b']) For 3.x replace viewkeys() with keys(). > It would save some space if I didn't have to duplicate all the keys > into sets (on the order of 10-100k small strings), instead being able > to directly perform the set-ops on the dicts. But otherwise, it was > pretty readable & straight-forward. > > -tkc From mauro at gmail.com Tue Feb 25 17:02:01 2014 From: mauro at gmail.com (mauro) Date: Tue, 25 Feb 2014 22:02:01 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: < CANc-5UwjkYwKJ5cqvu6c1XNG=vBuGimxuueBBFXUyuEbYoVNmw@mail.gmail.com> < mailman.7367.1393362209.18130.python-list@python.org> Message-ID: > > {'A': 1} | {'A': 2} > > I would propose at least four: > > {'A': 1} # choose the LHS > {'A': 2} # choose the RHS > {'A': (1,2)} # a resulting pair of both > set(['A']) # you did set-ops, so you get a set The implementation should define if LHS or RHS and user should change the order of operands depending on what he wants. Your example (as well as a many questions in stackoverflow.com) shows that there is some need for these operations, that implemented in C in python library will be by far more CPU and memory efficient than implemented as you did. From mauro at gmail.com Tue Feb 25 17:03:59 2014 From: mauro at gmail.com (mauro) Date: Tue, 25 Feb 2014 22:03:59 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: Il Tue, 25 Feb 2014 22:02:01 +0000, mauro ha scritto: >> {'A': 1} | {'A': 2} >> >> I would propose at least four: >> >> {'A': 1} # choose the LHS {'A': 2} # choose the RHS {'A': (1,2)} >> # a resulting pair of both set(['A']) # you did set-ops, so you get a >> set > > The implementation should define if LHS or RHS and user should change > the order of operands depending on what he wants. > > Your example (as well as a many questions in stackoverflow.com) shows > that there is some need for these operations, that implemented in C in > python library will be by far more CPU and memory efficient than > implemented as you did. posting error, this entry was supposed to be a reply to Tim Chase's comment. From python.list at tim.thechases.com Tue Feb 25 17:10:34 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Feb 2014 16:10:34 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: <20140225150351.063fd961@bigbox.christie.dr> Message-ID: <20140225161034.4c72977c@bigbox.christie.dr> On 2014-02-25 22:54, Peter Otten wrote: > Tim Chase wrote: > > If dicts were to support set ops, > > They do in 2.7 and 3.x. > > >>> a.viewkeys() - b.viewkeys() > set(['a']) > >>> a.viewkeys() & b.viewkeys() > set(['b']) > >>> a.viewkeys() ^ b.viewkeys() > set(['a', 'c']) > >>> a.viewkeys() | b.viewkeys() > set(['a', 'c', 'b']) > > For 3.x replace viewkeys() with keys(). I missed this getting added in the 2.7 release. Thanks for the introduction to .viewkeys()/.keys() as they could prove quite handy. -tkc From mauro at gmail.com Tue Feb 25 17:11:07 2014 From: mauro at gmail.com (mauro) Date: Tue, 25 Feb 2014 22:11:07 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: <%x8Pu.24267$Th2.3261@tornado.fastwebnet.it> > > {1, 2} & {2, 3} == {2} > In my mind the intersection is evaluated on keys, so the resulting dict should be the empty one > but > > {1:"a", 2:"b", 3:"c"} & {2:"b", 3:"e", 4:"f"} == ??? my output will be {2:"b", 3:"e"} or {2:"b", 3:"c"} depending on the implementation choice. > > The most obvious result is probably the empty dict {2:"b"}, i. e. > > a & b is defined as dict(a.items() & b.items()) > > Frankly, I don't do that a lot. So what's your use-case? I do not have an use case, but I've seen that many people ask for these operations for example in stackoverflow.com From duncan.booth at invalid.invalid Tue Feb 25 17:21:05 2014 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Feb 2014 22:21:05 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: Tim Chase wrote: > a_dict = dict(...) > b_dict = dict(...) > a_set = set(a_dict) > b_set = set(b_dict) > added_keys = b_set - a_set > removed_keys = a_set - b_set > same_keys = a_set & b_set > diff_keys = a_set ^ b_set > all_keys = a_set | b_set > > It would save some space if I didn't have to duplicate all the keys > into sets (on the order of 10-100k small strings), instead being able > to directly perform the set-ops on the dicts. But otherwise, it was > pretty readable & straight-forward. > It doesn't matter whether they were small strings or full-length novels, creating a set from a dict doesn't duplicate any strings. -- Duncan Booth http://kupuguy.blogspot.com From breamoreboy at yahoo.co.uk Tue Feb 25 17:35:00 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 25 Feb 2014 22:35:00 +0000 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: <%x8Pu.24267$Th2.3261@tornado.fastwebnet.it> References: <%x8Pu.24267$Th2.3261@tornado.fastwebnet.it> Message-ID: On 25/02/2014 22:11, mauro wrote: > >> >> {1, 2} & {2, 3} == {2} >> > In my mind the intersection is evaluated on keys, so the resulting dict > should be the empty one >> but >> >> {1:"a", 2:"b", 3:"c"} & {2:"b", 3:"e", 4:"f"} == ??? > my output will be > {2:"b", 3:"e"} > or > {2:"b", 3:"c"} > > depending on the implementation choice. >> >> The most obvious result is probably the empty dict {2:"b"}, i. e. >> >> a & b is defined as dict(a.items() & b.items()) >> >> Frankly, I don't do that a lot. So what's your use-case? > I do not have an use case, but I've seen that many people ask for these > operations for example in stackoverflow.com > Please ask one of the many people on stackoverflow to raise an enhancement request here bugs.python.org complete with a patch that changes code, docs and tests and then everybody will be happy, won't they. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From tim at thechases.com Tue Feb 25 17:35:27 2014 From: tim at thechases.com (Tim Chase) Date: Tue, 25 Feb 2014 16:35:27 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: Message-ID: <20140225163527.25ccc804@bigbox.christie.dr> On 2014-02-25 22:21, Duncan Booth wrote: > > It would save some space if I didn't have to duplicate all the > > keys into sets (on the order of 10-100k small strings), instead > > being able to directly perform the set-ops on the dicts. But > > otherwise, it was pretty readable & straight-forward. > > > It doesn't matter whether they were small strings or full-length > novels, creating a set from a dict doesn't duplicate any strings. pre-my-new-learning-about .viewkeys() it sounds like set(my_dict) would have the overhead of storing an additional reference to a string per set-entry (rather than duplicating every string). With .viewkeys()/.keys(), it sounds like that overhead would go away. -tkc From python.list at tim.thechases.com Tue Feb 25 17:36:08 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Feb 2014 16:36:08 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: References: Message-ID: <20140225163608.4c2fbd5c@bigbox.christie.dr> On 2014-02-25 22:21, Duncan Booth wrote: > > It would save some space if I didn't have to duplicate all the > > keys into sets (on the order of 10-100k small strings), instead > > being able to directly perform the set-ops on the dicts. But > > otherwise, it was pretty readable & straight-forward. > > > It doesn't matter whether they were small strings or full-length > novels, creating a set from a dict doesn't duplicate any strings. pre-my-new-learning-about .viewkeys() it sounds like set(my_dict) would have the overhead of storing an additional reference to a string per set-entry (rather than duplicating every string). With .viewkeys()/.keys(), it sounds like that overhead would go away. -tkc From oscar.j.benjamin at gmail.com Tue Feb 25 17:58:48 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 25 Feb 2014 22:58:48 +0000 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: <20140225163608.4c2fbd5c@bigbox.christie.dr> References: <20140225163608.4c2fbd5c@bigbox.christie.dr> Message-ID: On 25 February 2014 22:36, Tim Chase wrote: > On 2014-02-25 22:21, Duncan Booth wrote: >> > It would save some space if I didn't have to duplicate all the >> > keys into sets (on the order of 10-100k small strings), instead >> > being able to directly perform the set-ops on the dicts. But >> > otherwise, it was pretty readable & straight-forward. >> > >> It doesn't matter whether they were small strings or full-length >> novels, creating a set from a dict doesn't duplicate any strings. > > pre-my-new-learning-about .viewkeys() it sounds like set(my_dict) > would have the overhead of storing an additional reference to a > string per set-entry (rather than duplicating every string). > With .viewkeys()/.keys(), it sounds like that overhead would go away. You lose the redundant hash-table by using the keys view. The set hash table takes 20-40 bytes per entry on this computer (according to sys.getsizeof). On the same system a short string takes a similar amount of memory. The .keys() view object apparently takes 24 bytes in total so yes it's a reasonable memory saving if the dicts or of any significant size. However the .keys() objects are not necessarily as well optimised so it may be faster to convert to sets for some operations. One example I found some time ago is that for sets A & B will iterate over the smaller set but for dicts A.keys() & B.keys() would always go over the left-hand set (or right-hand - I don't remember). This makes a considerable difference if one set is significantly larger than the other. Oscar From python at mrabarnett.plus.com Tue Feb 25 18:07:28 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Feb 2014 23:07:28 +0000 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: <85fvn6q3ws.fsf@benfinney.id.au> References: <85fvn6q3ws.fsf@benfinney.id.au> Message-ID: <530D2230.4060807@mrabarnett.plus.com> On 2014-02-25 21:27, Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> mauro wrote: >> >> > - Dictionaries and sets are both accessed by key >> >> but sets have no values > > Or rather, sets *only* have values. Dictionaries have keys, sets do not > have keys. > But a dictionary can have duplicate values, a set cannot. From ben+python at benfinney.id.au Tue Feb 25 18:14:30 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Feb 2014 10:14:30 +1100 Subject: intersection, union, difference, symmetric difference for dictionaries References: <85fvn6q3ws.fsf@benfinney.id.au> <530D2230.4060807@mrabarnett.plus.com> Message-ID: <85a9depyy1.fsf@benfinney.id.au> MRAB writes: > On 2014-02-25 21:27, Ben Finney wrote: > > Peter Otten <__peter__ at web.de> writes: > > > >> mauro wrote: > >> > >> > - Dictionaries and sets are both accessed by key > >> > >> but sets have no values > > > > Or rather, sets *only* have values. Dictionaries have keys, sets do > > not have keys. > > > But a dictionary can have duplicate values, a set cannot. Yes. Your ?but? implies you think that contradicts my statement; it doesn't. So I'm not sure what point you're making. -- \ ?Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.? ?Victor J. Stenger, 2001-11-05 | Ben Finney From steve+comp.lang.python at pearwood.info Tue Feb 25 18:10:29 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 25 Feb 2014 23:10:29 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: <530d22e5$0$29985$c3e8da3$5496439d@news.astraweb.com> On Tue, 25 Feb 2014 15:03:51 -0600, Tim Chase wrote: > On 2014-02-25 14:40, Skip Montanaro wrote: >> What's the correct result of evaluating this expression? >> >> {'A': 1} | {'A': 2} >> >> I can see (at least) two possible "correct" answers. > > I would propose at least four: > > {'A': 1} # choose the LHS > {'A': 2} # choose the RHS > {'A': (1,2)} # a resulting pair of both Should that value be a tuple, a list or a set? > set(['A']) # you did set-ops, so you get a set Option 5: raise an exception if the values are different. Option 6: "or" the values, so that the LHS value is used only if it is truthy, otherwise the RHS value is used. That is: {'A': leftdict['A'] or rightdict['A']} I don't really understand the use-case behind Option 6, but there is a recent thread on python-ideas at python.org where somebody proposed that as the Obviously One True And Correct behaviour for dict intersection. > If dicts were to support set ops, the last one would be my preferred > result. What, getting a set back? No, I disagree. If you want a set, it's easy to do: dicta.keys() | dictb.keys() (In Python 2, use viewkeys instead.) gives you a set of the intersection of the keys. The only point of having dicts support set-like operations directly is if you get a dict back. All of these operations are quite simple to write, so personally I would recommend people just add their own helper function with the behaviour they prefer. -- Steven From python at mrabarnett.plus.com Tue Feb 25 18:25:06 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Feb 2014 23:25:06 +0000 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: <85a9depyy1.fsf@benfinney.id.au> References: <85fvn6q3ws.fsf@benfinney.id.au> <530D2230.4060807@mrabarnett.plus.com> <85a9depyy1.fsf@benfinney.id.au> Message-ID: <530D2652.20201@mrabarnett.plus.com> On 2014-02-25 23:14, Ben Finney wrote: > MRAB writes: > >> On 2014-02-25 21:27, Ben Finney wrote: >> > Peter Otten <__peter__ at web.de> writes: >> > >> >> mauro wrote: >> >> >> >> > - Dictionaries and sets are both accessed by key >> >> >> >> but sets have no values >> > >> > Or rather, sets *only* have values. Dictionaries have keys, sets do >> > not have keys. >> > >> But a dictionary can have duplicate values, a set cannot. > > Yes. Your ?but? implies you think that contradicts my statement; it > doesn't. So I'm not sure what point you're making. > The keys of a dictionary must be unique, like a set. The values of a dictionary don't have to be unique, unlike a set. From cs at zip.com.au Tue Feb 25 19:20:21 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 26 Feb 2014 11:20:21 +1100 Subject: Help father help son / Install Version 2.6 on Mac OSX 10.9 In-Reply-To: References: Message-ID: <20140226002021.GA89553@cskk.homeip.net> On 24Feb2014 21:57, Ned Deily wrote: > In article > , > Chris Angelico wrote: > > On Tue, Feb 25, 2014 at 4:28 PM, wrote: > > > Trying to install Python 2.6 because PyGames says it will only install if > > > Python 2.6 is present. > > > > Are you sure you need 2.6 and not 2.7? This suggests 2.7 works: > > > > http://pygame.org/wiki/MacCompile > > And, in any case, Apple ships OS X 10.9 with copies of both Python 2.7 > and 2.6: > > /usr/bin/python2.7 > /usr/bin/python2.6 And there's always MacPorts for your multiversion needs: python24 @2.4.6_10 (lang) python25 @2.5.6_4 (lang) python26 @2.6.9 (lang) python27 @2.7.6 (lang) python31 @3.1.5 (lang) python32 @3.2.5 (lang) python33 @3.3.4 (lang) python34 @3.4.0rc1 (lang) Cheers, -- Cameron Simpson The ZZR-1100 remains the big, fast, versatile bike for the rider with a regular pillion passenger or the desire to humiliate just about every other road user who attempted to match its straight line acceleration. - REVS From steve+comp.lang.python at pearwood.info Tue Feb 25 19:37:44 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Feb 2014 00:37:44 GMT Subject: intersection, union, difference, symmetric difference for dictionaries References: <85fvn6q3ws.fsf@benfinney.id.au> Message-ID: <530d3758$0$29985$c3e8da3$5496439d@news.astraweb.com> On Tue, 25 Feb 2014 23:07:28 +0000, MRAB wrote: > On 2014-02-25 21:27, Ben Finney wrote: >> Or rather, sets *only* have values. Dictionaries have keys, sets do not >> have keys. >> > But a dictionary can have duplicate values, a set cannot. It is usual to talk about the things stored in dicts and sets using slightly different terminology: - mappings such as dicts have *key/value pairs* - sets have *elements* The elements of a set are most closely related to the keys of a mapping, not the values. Set elements are unique, just like mapping keys. Specifically, the keys in a mapping make up a set; the values in a mapping do not. When talking specifically about Python dicts and sets, there is an additional restriction: both set elements and dict keys have to be hashable. English being a little sloppy at times, sometimes we also talk about the *values of a set*, but here "value" is being used as a synonym for "element" and not as a technical term for the thing which mappings associate with a key. -- Steven From challakarthik at gmail.com Tue Feb 25 20:27:19 2014 From: challakarthik at gmail.com (Karthik Reddy) Date: Tue, 25 Feb 2014 17:27:19 -0800 (PST) Subject: python In-Reply-To: References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> Message-ID: <087f160d-a8a9-430b-9d3f-3318a04e35ae@googlegroups.com> Thank you, but from by reaserch i got these requirements ...... Python, django, Twisted, MySQL, PyQt, PySide, xPython. *Technical proficiency with Python and Django. *Technical proficiency in JavaScript. *Experience with MySQL / PgSQL. *Unix/Linux expertise. *Experience with MVC design patterns and solid algorithm skills. Core Python, DJango Framework, Web2Py, Google App engine, CherryPy ( Basic Introduction) The problem for me is whether i have to learn all these technologies to work as a python developer...... On Tuesday, February 25, 2014 12:58:15 AM UTC+5:30, CM wrote: > On Monday, February 24, 2014 3:31:11 AM UTC-5, Karthik Reddy wrote: > > > I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... > > > > I recommend you look at job advertisements in areas you'd like to work (both > > areas of the world and areas within IT) and see what they seem to want. > > > > Also, consider more informative subject lines to future posts. :D From cs at zip.com.au Tue Feb 25 21:06:01 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 26 Feb 2014 13:06:01 +1100 Subject: Functions help In-Reply-To: References: Message-ID: <20140226020601.GA4281@cskk.homeip.net> On 24Feb2014 13:59, Mark Lawrence wrote: > On 24/02/2014 04:01, rurpy at yahoo.com wrote: > >On 02/23/2014 08:21 PM, Mark Lawrence wrote: > >>On 24/02/2014 02:55, Benjamin Kaplan wrote: > >>>On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: > >>>>On 24/02/2014 11:09 AM, Mark Lawrence wrote: > >>>>>On 24/02/2014 00:55, alex23 wrote: > >>>>>> for _ in range(5): > >>>>>> func() > >>>>>the obvious indentation error above > >>>> > >>>>Stupid cut&paste :( > >>> > >>>Your message came through fine for me (viewing as mailing list in > >>>gmail). Mark's client must be dropping spaces. > >> > >>I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. > > > >The original message was properly indented on Google Groups. > >Perhaps you should switch to GG or some non-broken client that > >doesn't mangle whitespace. > > MRAB has confirmed that as always Thunderbird is working perfectly, > thank you. He confirmed it worked for him. And yet your copy rendered incorrectly. MRAB pointed at a possible cause (mixed TABs and spaces). > But you can stick with your bug ridden, badly flawed > tool as long as you like, just expect me to keep complaining until > google fixes it, or people stop using it, or people follow the > instructions that were put up on a Python web site to prevent the > bugs showing up. Methinks rurpy's GG suggestion was bait aimed specificly at you. I recognised it as sarcasm (or parody?). Relax. -- Cameron Simpson Scott Fansler wrote: > Give me a break with this thread!! So what if another rider doesn't > wave?? Who the hell cares!?!? I wave to other riders from my HD when the > thought/moment is there. If they wave back cool, if not, so what. Maybe > they didn't see me, maybe they're pissed at their boss or spouse or life > in general and are out for a putt to clear out the BS and don't care to > wave back. Big deal. Have you seen EVERY motorcyle that EVER rode past > you going the other way?? Don't think so. Stop posing & ride, wave or no > wave. > 2 cents Somebody get the pliers, this one's hooked deep. We'll need some more bait too. You might want to fiddle with drag setting on your reel too. - Tim Simpson in rec.moto From python.list at tim.thechases.com Tue Feb 25 21:21:08 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 25 Feb 2014 20:21:08 -0600 Subject: intersection, union, difference, symmetric difference for dictionaries In-Reply-To: <530d22e5$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <530d22e5$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20140225202108.7827d916@bigbox.christie.dr> On 2014-02-25 23:10, Steven D'Aprano wrote: > On Tue, 25 Feb 2014 15:03:51 -0600, Tim Chase wrote: > > > On 2014-02-25 14:40, Skip Montanaro wrote: > >> What's the correct result of evaluating this expression? > >> > >> {'A': 1} | {'A': 2} > >> > >> I can see (at least) two possible "correct" answers. > > > > I would propose at least four: > > > > {'A': 1} # choose the LHS > > {'A': 2} # choose the RHS > > {'A': (1,2)} # a resulting pair of both > > Should that value be a tuple, a list or a set? I'd say a tuple: it has order (thus not a set), and it's a fixed record of (LHS, RHS), not mutable as a list would suggest. > Option 5: raise an exception if the values are different. Inconvenient in many use cases, but certainly another possibility > Option 6: "or" the values, so that the LHS value is used only if it > is truthy, otherwise the RHS value is used. That is: > > {'A': leftdict['A'] or rightdict['A']} > > > I don't really understand the use-case behind Option 6 I can imagine a use case for it, but certainly not the *default* behavior. Yick. > > If dicts were to support set ops, the last one would be my > > preferred result. > > What, getting a set back? > > No, I disagree. If you want a set, it's easy to do: > > dicta.keys() | dictb.keys() > > (In Python 2, use viewkeys instead.) Now that I'm aware of .viewkeys()/.keys() (herein "vk/k" for brevity) thanks to Peter Otten's post, that does what I most commonly want for set-ops-on-dicts. I'd just consider this a promotion, since for k in my_dict: pass is the same as for k in my_dict.keys(): # or .iterkeys() in 2.x pass I'd find it intuitive to have set-ops behave similarly, defaulting to vk/k. > All of these operations are quite simple to write, so personally I > would recommend people just add their own helper function with the > behaviour they prefer. And with vk/k, I now fall pretty firmly in agreement with you (except for the aforementioned possibility of having a dict's currently-unused set-ops use the results of vk/k as well). -tkc From cs at zip.com.au Tue Feb 25 21:00:39 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 26 Feb 2014 13:00:39 +1100 Subject: Functions help In-Reply-To: References: Message-ID: <20140226020039.GA921@cskk.homeip.net> On 23Feb2014 18:55, Benjamin Kaplan wrote: > On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: > > On 24/02/2014 11:09 AM, Mark Lawrence wrote: > >> On 24/02/2014 00:55, alex23 wrote: > >>> for _ in range(5): > >>> func() > >> > >> the obvious indentation error above > > > > Stupid cut&paste :( > > Your message came through fine for me (viewing as mailing list in > gmail). Mark's client must be dropping spaces. My copy was fine too. I'm reading it via the python-list mailing list, with mutt. -- Cameron Simpson Deep into the monitor peering, long I sat there wond'ring, fearing, Doubting, while the disk kept churning, turning yet to churn some more. "Save!" I said, "You cursed mother! Save my data from before!" One thing did the phosphors answer, only this and nothing more, Just, "Abort, Retry, Ignore?" From ethan at stoneleaf.us Tue Feb 25 21:52:56 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 25 Feb 2014 18:52:56 -0800 Subject: Functions help In-Reply-To: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> References: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> Message-ID: <530D5708.7030005@stoneleaf.us> On 02/23/2014 08:01 PM, rurpy at yahoo.com wrote: > On 02/23/2014 08:21 PM, Mark Lawrence wrote: >> On 24/02/2014 02:55, Benjamin Kaplan wrote: >>> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>>> On 24/02/2014 00:55, alex23 wrote: >>>>>> for _ in range(5): >>>>>> func() >>>>> the obvious indentation error above >>>> >>>> Stupid cut&paste :( >>> >>> Your message came through fine for me (viewing as mailing list in >>> gmail). Mark's client must be dropping spaces. >> >> I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. > > The original message was properly indented on Google Groups. > Perhaps you should switch to GG or some non-broken client that > doesn't mangle whitespace. LOL! How long have you waited to say that? ;) -- ~Ethan From rodrick.brown at gmail.com Tue Feb 25 07:53:46 2014 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Tue, 25 Feb 2014 07:53:46 -0500 Subject: SSH/Telnet program to Router/switch In-Reply-To: References: Message-ID: <62EB3E59-CB63-4046-A3FF-5B71C2D3D111@gmail.com> Sent from my iPhone > On Feb 20, 2014, at 5:59 AM, Ferrous Cranus wrote: > > ?? ???????, 19 ??????????? 2014 10:45:53 ?.?. UTC+2, ? ??????? Wojciech ?ysiak ??????: >>> On 19.02.2014 09:14, Sujith S wrote: >>> >>> Hi, >> >> >>> I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. >> >> >>> Do we have expect available in python as well or need to use some other method ? >> >> >> >> Hello, >> >> If you are looking for a way to connect to your netdevices and then >> >> execute some shell commands (with output) via ssh then google for >> >> paramiko module for python. >> >> >> >> It works on windows and linux. >> >> >> >> -- >> >> BR, >> >> Wojtek > > Hello, > > What will benefit the OP to go ahead and use paramiko opposed to just use "Putty" or another perhaps even Chrome based ssh client? > > Is there an advantage to that? This is a Python mailing list so obviously the OP wants to use python to automate logging into his devices and dispatching some commands. Why else would they ask here? > -- > https://mail.python.org/mailman/listinfo/python-list From ganesh1pal at gmail.com Wed Feb 26 04:30:21 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 26 Feb 2014 15:00:21 +0530 Subject: Python : parsing the command line options using optparse In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 9:55 PM, Peter Otten <__peter__ at web.de> wrote: >As you are just starting I recommend that you use argparse instead of optparse. I would love to use argparse but the script that I plan to write has to run on host machines that Python 2.6 I have freebsd clients with python 2.6 dont want to install python new version on all the host machine which will be eventually upgraded to 2.7 . I wanted know if I could use argparse with python 2.6 and is it possible to add something like #pkg_add -r install python-argparse and install python argparse module before I use it. > >If you are asking why short options don't work in conjunction with = -- I > >don't know, it is probably a design choice of the optparse author. > >argparse accepts short options with like -f=1234 > I wanted to know why my sample program does not work with short hand option (-p) and works with long hand option . Here is what is happening ( only short hand with -) # python-5.py -p=/ifs/1.txt -q=XOR -f=1234 -n=1 -l Usage: python-5.py [options] python-5.py: error: option -q: invalid choice: '=XOR' (choose from 'XOR', 'ADD', 'SET', 'MODIFY', 'RENAME', 'DELETE', 'KILL') Result :says invalid choice: '=XOR' Long hand Works ( -- , or double hypen ) fine. C:\Users\bahadg\Desktop>python python-5.py --path=/ifs/1.txt --operation=XOR -- offset=1234 --node=1 --log --fixcrc /ifs/1.txt -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Feb 26 04:38:53 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 Feb 2014 09:38:53 +0000 Subject: Functions help In-Reply-To: <20140226020601.GA4281@cskk.homeip.net> References: <20140226020601.GA4281@cskk.homeip.net> Message-ID: On 26/02/2014 02:06, Cameron Simpson wrote: > On 24Feb2014 13:59, Mark Lawrence wrote: >> On 24/02/2014 04:01, rurpy at yahoo.com wrote: >>> On 02/23/2014 08:21 PM, Mark Lawrence wrote: >>>> On 24/02/2014 02:55, Benjamin Kaplan wrote: >>>>> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>>>>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>>>>> On 24/02/2014 00:55, alex23 wrote: >>>>>>>> for _ in range(5): >>>>>>>> func() >>>>>>> the obvious indentation error above >>>>>> >>>>>> Stupid cut&paste :( >>>>> >>>>> Your message came through fine for me (viewing as mailing list in >>>>> gmail). Mark's client must be dropping spaces. >>>> >>>> I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. >>> >>> The original message was properly indented on Google Groups. >>> Perhaps you should switch to GG or some non-broken client that >>> doesn't mangle whitespace. >> >> MRAB has confirmed that as always Thunderbird is working perfectly, >> thank you. > > He confirmed it worked for him. And yet your copy rendered incorrectly. > MRAB pointed at a possible cause (mixed TABs and spaces). > >> But you can stick with your bug ridden, badly flawed >> tool as long as you like, just expect me to keep complaining until >> google fixes it, or people stop using it, or people follow the >> instructions that were put up on a Python web site to prevent the >> bugs showing up. > > Methinks rurpy's GG suggestion was bait aimed specificly at you. > I recognised it as sarcasm (or parody?). > > Relax. > Frankly I don't give a damn one way or the other, I'm simply cheesed off with seeing garbage coming through from gg, in the same way readers of this list are fed up with me complaining about it :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From sffjunkie at gmail.com Wed Feb 26 05:55:16 2014 From: sffjunkie at gmail.com (sffjunkie at gmail.com) Date: Wed, 26 Feb 2014 02:55:16 -0800 (PST) Subject: Python : parsing the command line options using optparse In-Reply-To: References: Message-ID: On Wednesday, 26 February 2014 09:30:21 UTC, Ganesh Pal wrote: > Here is what is happening ( only short hand with -) > > # python-5.py -p=/ifs/1.txt -q=XOR? -f=1234 -n=1 -l > > Usage: python-5.py [options] > python-5.py: error: option -q: invalid choice: '=XOR' (choose from 'XOR', 'ADD', > > ?'SET', 'MODIFY', 'RENAME', 'DELETE', 'KILL') Short hand options don't use '=' signs. Try python-5.py -p /ifs/1.txt -q XOR? -f 1234 -n 1 -l --Simon From greg.ewing at canterbury.ac.nz Wed Feb 26 05:59:37 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 26 Feb 2014 23:59:37 +1300 Subject: Can global variable be passed into Python function? In-Reply-To: <530b6bf2$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> <530b6bf2$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Standard Pascal? Who uses standard Pascal? I'm talking about MacPascal :-) Mac Pascal used @ for getting a pointer to a variable, if I remember rightly. -- Greg From __peter__ at web.de Wed Feb 26 06:27:17 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Feb 2014 12:27:17 +0100 Subject: Python : parsing the command line options using optparse References: Message-ID: Ganesh Pal wrote: > On Tue, Feb 25, 2014 at 9:55 PM, Peter Otten <__peter__ at web.de> wrote: > >>As you are just starting I recommend that you use argparse instead of > optparse. > > I would love to use argparse but the script that I plan to write has to > run on host machines that Python 2.6 > > I have freebsd clients with python 2.6 dont want to install python new > version on all the host machine which will be eventually upgraded to 2.7 . > > I wanted know if I could use argparse with python 2.6 and is it possible > to > add something like #pkg_add -r install python-argparse and install > python argparse module before I use it. Probably, but I have no experience with freebsd. >> >If you are asking why short options don't work in conjunction with = -- >> >I don't know, it is probably a design choice of the optparse author. >> >argparse accepts short options with like -f=1234 > > I wanted to know why my sample program does not work with short hand > option (-p) and works with long hand option . > > Here is what is happening ( only short hand with -) > > # python-5.py -p=/ifs/1.txt -q=XOR -f=1234 -n=1 -l > > Usage: python-5.py [options] > > python-5.py: error: option -q: invalid choice: '=XOR' (choose from 'XOR', > 'ADD', > > 'SET', 'MODIFY', 'RENAME', 'DELETE', 'KILL') > > > Result :says invalid choice: '=XOR' If you stick with optparse just pass the options without '=' -qXOR and -q XOR should both work. From steve+comp.lang.python at pearwood.info Wed Feb 26 08:15:25 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 26 Feb 2014 13:15:25 GMT Subject: exec and locals Message-ID: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> I have to dynamically generate some code inside a function using exec, but I'm not sure if it is working by accident or if I can rely on it. Here is a trivial example: py> def spam(): ... exec( """x = 23""" ) ... return x ... py> spam() 23 (My real example is more complex than this.) According to the documentation of exec, I don't think this should actually work, and yet it appears to. The documentation says: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns. http://docs.python.org/3.4/library/functions.html#exec I *think* this means that if I want to guarantee that a local variable x is created by exec, I need to do this instead: py> def eggs(): ... mylocals = {} ... exec( """x = 23""", globals(), mylocals) ... x = mylocals['x'] ... return x ... py> eggs() 23 The fact that it works in spam() above is perhaps an accident of implementation? Yes no maybe? -- Steven From rosuav at gmail.com Wed Feb 26 08:40:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Feb 2014 00:40:28 +1100 Subject: exec and locals In-Reply-To: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Feb 27, 2014 at 12:15 AM, Steven D'Aprano wrote: > py> def spam(): > ... exec( """x = 23""" ) > ... return x > ... > py> spam() > 23 > > > (My real example is more complex than this.) > > According to the documentation of exec, I don't think this should > actually work, and yet it appears to. Doesn't work for me, in IDLE in 3.4.0b2, nor in command-line Python on 3.4.0rc1+ (from hg a couple of weeks ago). But it did (happen to?) work in 2.7. What version did you use? ChrisA From ganesh1pal at gmail.com Wed Feb 26 08:42:00 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Wed, 26 Feb 2014 19:12:00 +0530 Subject: Python : parsing the command line options using optparse In-Reply-To: References: Message-ID: On Wed, Feb 26, 2014 at 4:57 PM, Peter Otten <__peter__ at web.de> wrote: > > If you stick with optparse just pass the options without '=' > > -qXOR > > and > > -q XOR > > should both work. > > Thanks Peter and Simon for the hints it worked : ) without ' =' # Python corrupt.py -o INODE -p /ifs/1.txt -q SET -f 1 Current Default Choice : Choice: INODE Choice: SET Choice: 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Feb 26 08:46:39 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Feb 2014 14:46:39 +0100 Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have to dynamically generate some code inside a function using exec, > but I'm not sure if it is working by accident or if I can rely on it. > > Here is a trivial example: > > > py> def spam(): > ... exec( """x = 23""" ) > ... return x > ... > py> spam() > 23 > > > (My real example is more complex than this.) > > According to the documentation of exec, I don't think this should > actually work, and yet it appears to. The documentation says: > > The default locals act as described for function locals() > below: modifications to the default locals dictionary should > not be attempted. Pass an explicit locals dictionary if you > need to see effects of the code on locals after function > exec() returns. > > http://docs.python.org/3.4/library/functions.html#exec > > > I *think* this means that if I want to guarantee that a local variable x > is created by exec, I need to do this instead: > > py> def eggs(): > ... mylocals = {} > ... exec( """x = 23""", globals(), mylocals) > ... x = mylocals['x'] > ... return x > ... > py> eggs() > 23 > > The fact that it works in spam() above is perhaps an accident of > implementation? Yes no maybe? eggs() should work in Python 2 and 3, spam() should work in Python 2, but not in Python 3. Fun fact: Python 2 tweaks the bytecode (LOAD_NAME instead of LOAD_GLOBAL) to make spam() work: >>> def spam(): ... return x ... >>> dis.dis(spam) 2 0 LOAD_GLOBAL 0 (x) 3 RETURN_VALUE >>> def spam(): ... exec "" ... return x ... >>> dis.dis(spam) 2 0 LOAD_CONST 1 ('') 3 LOAD_CONST 0 (None) 6 DUP_TOP 7 EXEC_STMT 3 8 LOAD_NAME 0 (x) 11 RETURN_VALUE From __peter__ at web.de Wed Feb 26 08:55:26 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Feb 2014 14:55:26 +0100 Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: Peter Otten wrote: > Steven D'Aprano wrote: > >> I have to dynamically generate some code inside a function using exec, >> but I'm not sure if it is working by accident or if I can rely on it. >> >> Here is a trivial example: >> >> >> py> def spam(): >> ... exec( """x = 23""" ) >> ... return x >> ... >> py> spam() >> 23 >> >> >> (My real example is more complex than this.) >> >> According to the documentation of exec, I don't think this should >> actually work, and yet it appears to. The documentation says: >> >> The default locals act as described for function locals() >> below: modifications to the default locals dictionary should >> not be attempted. Pass an explicit locals dictionary if you >> need to see effects of the code on locals after function >> exec() returns. >> >> http://docs.python.org/3.4/library/functions.html#exec >> >> >> I *think* this means that if I want to guarantee that a local variable x >> is created by exec, I need to do this instead: >> >> py> def eggs(): >> ... mylocals = {} >> ... exec( """x = 23""", globals(), mylocals) >> ... x = mylocals['x'] >> ... return x >> ... >> py> eggs() >> 23 >> >> The fact that it works in spam() above is perhaps an accident of >> implementation? Yes no maybe? > > eggs() should work in Python 2 and 3, > spam() should work in Python 2, but not in Python 3. > > Fun fact: Python 2 tweaks the bytecode (LOAD_NAME instead of LOAD_GLOBAL) > to make spam() work: > >>>> def spam(): > ... return x > ... >>>> dis.dis(spam) > 2 0 LOAD_GLOBAL 0 (x) > 3 RETURN_VALUE >>>> def spam(): > ... exec "" > ... return x > ... >>>> dis.dis(spam) > 2 0 LOAD_CONST 1 ('') > 3 LOAD_CONST 0 (None) > 6 DUP_TOP > 7 EXEC_STMT > > 3 8 LOAD_NAME 0 (x) > 11 RETURN_VALUE Some more bytcode fun, because it just occured to me that you can optimize away the code that triggered the modification: >>> def spam(): ... return x ... if 0: exec "" ... >>> dis.dis(spam) 2 0 LOAD_NAME 0 (x) 3 RETURN_VALUE From alister.ware at ntlworld.com Wed Feb 26 09:00:59 2014 From: alister.ware at ntlworld.com (Alister) Date: Wed, 26 Feb 2014 14:00:59 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, 26 Feb 2014 13:15:25 +0000, Steven D'Aprano wrote: > I have to dynamically generate some code inside a function using exec, > but I'm not sure if it is working by accident or if I can rely on it. > > Here is a trivial example: > > > py> def spam(): > ... exec( """x = 23""" ) > ... return x ... > py> spam() > 23 > > > (My real example is more complex than this.) > > According to the documentation of exec, I don't think this should > actually work, and yet it appears to. The documentation says: > > The default locals act as described for function locals() below: > modifications to the default locals dictionary should not be > attempted. Pass an explicit locals dictionary if you need to see > effects of the code on locals after function exec() returns. > > http://docs.python.org/3.4/library/functions.html#exec > > > I *think* this means that if I want to guarantee that a local variable x > is created by exec, I need to do this instead: > > py> def eggs(): > ... mylocals = {} > ... exec( """x = 23""", globals(), mylocals) > ... x = mylocals['x'] > ... return x ... > py> eggs() > 23 > > The fact that it works in spam() above is perhaps an accident of > implementation? Yes no maybe? I have no idea but as exec is generally considered to be a bad idea are you absolutely sure this is the correct way to achieve your end goal? perhaps if you detailed your requirement someone may be able to suggest a safer solution. -- "Regardless of the legal speed limit, your Buick must be operated at speeds faster than 85 MPH (140kph)." -- 1987 Buick Grand National owners manual. From d.joshi84 at gmail.com Wed Feb 26 09:00:52 2014 From: d.joshi84 at gmail.com (Unix SA) Date: Wed, 26 Feb 2014 19:45:52 +0545 Subject: Need help in writing some code so i can re-use it in every module or class Message-ID: Hello Experts, I have requirement, like i want to use below command in python script. --username --password now my requirement is i want to write some class so i can re-use " --username --password " part via importing as module or class .. and re-use that in other module or classes .. so i dont have to write that in every module or classes .. Now why i wan to do this is ... currently we are using is going to change in near future to , so i dont have go to every module and change that command if i have written single module or class and re-use it in other ? Hope i am clear enough to describe my issue? any suggestions ? Regards, DJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rodperson at rodperson.com Wed Feb 26 09:32:28 2014 From: rodperson at rodperson.com (rodperson at rodperson.com) Date: Wed, 26 Feb 2014 09:32:28 -0500 Subject: Python : parsing the command line options using optparse In-Reply-To: References: Message-ID: <9794bf8ec388cbedc2b206adc4d09b5a@rodperson.com> On 2014-02-26 04:30, Ganesh Pal wrote: > On Tue, Feb 25, 2014 at 9:55 PM, Peter > Otten <__peter__ at web.de> wrote: > >> As you are just starting I recommend that you use argparse instead of > optparse. > > I would love to use argparse but the script that I plan to write > has to run on host machines that Python 2.6 > > I have freebsd clients with python 2.6 dont want to install > python new version on all the host machine which will be eventually > upgraded to 2.7 . > > I wanted know if I could use argparse with python 2.6 and is it > possible to add something like #pkg_add -r install > python-argparse and install python argparse module before I use it. They must be running an older version of FreeBSD since the default version of python is 2.7. There is a FreeBSD package for argparse, the command would be something like pkg_add -r install py26-argparse Rod From rodrick.brown at gmail.com Wed Feb 26 11:51:51 2014 From: rodrick.brown at gmail.com (Rodrick Brown) Date: Wed, 26 Feb 2014 11:51:51 -0500 Subject: python In-Reply-To: <087f160d-a8a9-430b-9d3f-3318a04e35ae@googlegroups.com> References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> <087f160d-a8a9-430b-9d3f-3318a04e35ae@googlegroups.com> Message-ID: <63E62E89-331C-4D05-94B6-F6FBE81822B9@gmail.com> L > On Feb 25, 2014, at 8:27 PM, Karthik Reddy wrote: > > Thank you, > > but from by reaserch i got these requirements ...... > > Python, django, Twisted, MySQL, PyQt, PySide, xPython. > > *Technical proficiency with Python and Django. > *Technical proficiency in JavaScript. > *Experience with MySQL / PgSQL. > *Unix/Linux expertise. > *Experience with MVC design patterns and solid algorithm skills. > > Core Python, DJango Framework, Web2Py, Google App engine, CherryPy ( Basic Introduction) > > The problem for me is whether i have to learn all these technologies to work as a python developer...... > Learn core python fundamentals and idioms and everything else should come easy over time with a little experience and time. > > >> On Tuesday, February 25, 2014 12:58:15 AM UTC+5:30, CM wrote: >>> On Monday, February 24, 2014 3:31:11 AM UTC-5, Karthik Reddy wrote: >>> >>> I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... >> >> >> >> I recommend you look at job advertisements in areas you'd like to work (both >> >> areas of the world and areas within IT) and see what they seem to want. >> >> >> >> Also, consider more informative subject lines to future posts. :D > -- > https://mail.python.org/mailman/listinfo/python-list From bullshit.artist at thrinaxodon.thrinaxodon Wed Feb 26 11:51:22 2014 From: bullshit.artist at thrinaxodon.thrinaxodon (Thrinaxodon) Date: Wed, 26 Feb 2014 11:51:22 -0500 Subject: EVOLUTIONISTS DESTROYED IN 5 SECONDS Message-ID: ================= >BREAKING NEWS!!! ================= > THRINAXODON FOUND 300 FOSSILS FROM DEVONIAN STRATA FROM GREENLAND LAST TUESDAY, ONE WAS A COMPLETE HUMAN PELVIS! > THRINAXODON ALSO FOUND 6 PRIMITIVE STONE TOOLS FROM THE SITE, AS WELL AS CHARCOAL! > PETER NYIKOS WAS FORCED TO ACCEPT THAT HUMANS HAVE ORIGINS IN THE DEVONIAN AND HUMAN EVOLUTION IS A SCAM. > THE SMITHSONIAN IS GOING NUTS OVER THIS FIND, I WILL HAVE TO PATENT IT BEFORE ANYONE ELSE! > SEE YA FUCKERS! ============================ EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN: https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f# https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82# ==================================== http://thrinaxodon.wordpress.com/ =================================== THRINAXODON ONLY HAD THIS TO SAY: "I..I...I...Can't believe it. This completely disproved Darwinian orthodoxy." =================================== THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING WITH FEAR. =========================== THESE ASSHOLES ARE GOING TO DIE: THOMAS AQUINAS; ALDOUS HUXLEY; BOB CASANVOVA; SkyEyes; DAVID IAIN GRIEG; MARK ISAAK; JOHN HARSHAM; RICHARD NORMAN; DR. DOOLITTLE; CHARLES DARWIN; MARK HORTON; ERIK SIMPSON; HYPATIAB7; PAUL J. GANS; JILLERY; WIKI TRIK; THRINAXODON; PETER NYIKOS; RON OKIMOTO; JOHN S. WILKINS =========================== THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That is a myth, for people to believe in science." THRINAXODON PLANS TO BRING DOOM TO SCIENCE, ITSELF. ============================ THRINAXODON IS NOW ON TWITTER -- ---Thrinaxodon From challakarthik at gmail.com Wed Feb 26 12:44:02 2014 From: challakarthik at gmail.com (Karthik Reddy) Date: Wed, 26 Feb 2014 09:44:02 -0800 (PST) Subject: python In-Reply-To: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> Message-ID: <831b8ad2-f4c2-4f35-8f8a-e35749e0226f@googlegroups.com> On Monday, February 24, 2014 2:01:11 PM UTC+5:30, Karthik Reddy wrote: > I worked as a weblogic administrator and now i am changing to development and i am very much interested in python ......... please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me ......... Thank you for guidance.... From jeanmichel at sequans.com Wed Feb 26 13:50:27 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 26 Feb 2014 19:50:27 +0100 (CET) Subject: Need help in writing some code so i can re-use it in every module or class In-Reply-To: Message-ID: <1475933019.5491287.1393440627468.JavaMail.root@sequans.com> ----- Original Message ----- > Hello Experts, > I have requirement, like i want to use below command in python > script. > --username --password arguments> > now my requirement is i want to write some class so i can re-use > " --username --password " part via > importing as module or class .. and re-use that in other module or > classes .. so i dont have to write that in every module or classes > .. > Now why i wan to do this is ... currently we are using is > going to change in near future to , so i dont have go to > every module and change that command if i have written single module > or class and re-use it in other ? > Hope i am clear enough to describe my issue? > any suggestions ? > Regards, > DJ Hi, Have a look at http://docs.python.org/2/library/argparse.html Then create a module, for instance myParser, that defines the common paser, and in each of your scripts import that module and use the parser. *Untested code* myParser.py import argparse parser = argparse.ArgumentParser(description='Process some integers.') #then define the parser then in a script: script.py import myParser if __name__ == '__main__': args = myParser.parser.parse_args() # and so on... Cheers, JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From breamoreboy at yahoo.co.uk Wed Feb 26 13:53:36 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 26 Feb 2014 18:53:36 +0000 Subject: Issue 7503 Message-ID: I'm not sure where to flag this up so reckon here's as good a place as any. I noticed this afternoon 26/02/2014 between 16:05 and 16:09 four messages on the bug tracker mailing list about the subject issue, but http://bugs.python.org/issue7503 has not been updated yet and it's now 18:50. Technical glitch, people only just signing up or what? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From python at mrabarnett.plus.com Wed Feb 26 13:59:05 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Feb 2014 18:59:05 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <87bny0w9w3.fsf@elektro.pacujo.net> <53084f42$0$29985$c3e8da3$5496439d@news.astraweb.com> <5308614c$0$29985$c3e8da3$5496439d@news.astraweb.com> <530b6bf2$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530E3979.2040902@mrabarnett.plus.com> On 2014-02-26 10:59, Gregory Ewing wrote: > Steven D'Aprano wrote: >> Standard Pascal? Who uses standard Pascal? I'm talking about MacPascal :-) > > Mac Pascal used @ for getting a pointer to > a variable, if I remember rightly. > So did Turbo Pascal. Delphi, which is what Turbo Pascal became, is the same. From nad at acm.org Wed Feb 26 16:01:18 2014 From: nad at acm.org (Ned Deily) Date: Wed, 26 Feb 2014 13:01:18 -0800 Subject: Issue 7503 References: Message-ID: In article , Mark Lawrence wrote: > I'm not sure where to flag this up so reckon here's as good a place as > any. I noticed this afternoon 26/02/2014 between 16:05 and 16:09 four > messages on the bug tracker mailing list about the subject issue, but > http://bugs.python.org/issue7503 has not been updated yet and it's now > 18:50. Technical glitch, people only just signing up or what? Thanks for noticing this. I happened to independently see it before reading your post and we've fixed the problem causing the fail and manually posted the dropped updates. -- Ned Deily, nad at acm.org From steve at pearwood.info Wed Feb 26 19:25:45 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 27 Feb 2014 00:25:45 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530e8608$0$11113$c3e8da3@news.astraweb.com> On Wed, 26 Feb 2014 14:46:39 +0100, Peter Otten wrote: > Steven D'Aprano wrote: > >> I have to dynamically generate some code inside a function using exec, >> but I'm not sure if it is working by accident or if I can rely on it. >> >> Here is a trivial example: >> >> >> py> def spam(): >> ... exec( """x = 23""" ) >> ... return x >> ... >> py> spam() >> 23 >> >> >> (My real example is more complex than this.) >> >> According to the documentation of exec, I don't think this should >> actually work, and yet it appears to. The documentation says: >> >> The default locals act as described for function locals() below: >> modifications to the default locals dictionary should not be >> attempted. Pass an explicit locals dictionary if you need to see >> effects of the code on locals after function exec() returns. >> >> http://docs.python.org/3.4/library/functions.html#exec >> >> >> I *think* this means that if I want to guarantee that a local variable >> x is created by exec, I need to do this instead: >> >> py> def eggs(): >> ... mylocals = {} >> ... exec( """x = 23""", globals(), mylocals) ... x = >> mylocals['x'] >> ... return x >> ... >> py> eggs() >> 23 >> >> The fact that it works in spam() above is perhaps an accident of >> implementation? Yes no maybe? > > eggs() should work in Python 2 and 3, spam() should work in Python 2, > but not in Python 3. Aha! That explains it -- I was reading the 3.x docs and testing in Python 2.7. Thanks everyone for answering. By the way, if anyone cares what my actual use-case is, I have a function that needs to work under Python 2.4 through 3.4, and it uses a with statement. With statements are not available in 2.4 (or 2.5, unless you give a from __future__ import). So after messing about for a while with circular imports and dependency injections, I eventually settled on some code that works something like this: def factory(): blah blah blah try: exec("""def inner(): with something: return something """, globals(), mylocals) inner = mylocals['inner'] except SyntaxError: def inner(): # manually operate the context manager call context manager __enter__ try: try: return something except: # Yes, a bare except. Catch EVERYTHING. blah blah blah finally: call context manager __exit__ blah blah blah return inner (By the way, yes, I have to use a bare except, not just "except BaseException". Python 2.4 and 2.5 still have string exceptions.) -- Steven From steve at pearwood.info Wed Feb 26 19:31:56 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 27 Feb 2014 00:31:56 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <530e877b$0$11113$c3e8da3@news.astraweb.com> On Wed, 26 Feb 2014 14:00:59 +0000, Alister wrote: > On Wed, 26 Feb 2014 13:15:25 +0000, Steven D'Aprano wrote: > >> I have to dynamically generate some code inside a function using exec, >> but I'm not sure if it is working by accident or if I can rely on it. [...] > I have no idea but as exec is generally considered to be a bad idea are > you absolutely sure this is the correct way to achieve your end goal? > > perhaps if you detailed your requirement someone may be able to suggest > a safer solution. Thanks for your concern, but what I'm doing is perfectly safe. The string being exec'ed is a string literal known at compile-time and written by me (see my previous email for details) and the only reason I'm running it with exec at runtime rather than treating it as normal source code is that it relies on a feature that may not be available (with statement). The joys of writing code that has to run under multiple incompatible versions of Python. -- Steven From rurpy at yahoo.com Wed Feb 26 20:06:38 2014 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Feb 2014 17:06:38 -0800 (PST) Subject: Functions help In-Reply-To: References: <65d950e1-6d37-4666-8488-c3d75120b1c1@googlegroups.com> Message-ID: On 02/25/2014 07:52 PM, Ethan Furman wrote: > On 02/23/2014 08:01 PM, rurpy at yahoo.com wrote: >> On 02/23/2014 08:21 PM, Mark Lawrence wrote: >>> On 24/02/2014 02:55, Benjamin Kaplan wrote: >>>> On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >>>>> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>>>>> On 24/02/2014 00:55, alex23 wrote: >>>>>>> for _ in range(5): >>>>>>> func() >>>>>> the obvious indentation error above >>>>> >>>>> Stupid cut&paste :( >>>> >>>> Your message came through fine for me (viewing as mailing list in >>>> gmail). Mark's client must be dropping spaces. >>> >>> I'm reading gmane.comp.python.general using Thunderbird 24.3.0 on Windows 7. >> >> The original message was properly indented on Google Groups. >> Perhaps you should switch to GG or some non-broken client that >> doesn't mangle whitespace. > > LOL! How long have you waited to say that? ;) A while. It was worth the wait though. :-) From greg.ewing at canterbury.ac.nz Wed Feb 26 22:34:33 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 27 Feb 2014 16:34:33 +1300 Subject: exec and locals In-Reply-To: <530e8608$0$11113$c3e8da3@news.astraweb.com> References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > except SyntaxError: > def inner(): > # manually operate the context manager > call context manager __enter__ > try: > try: > return something > except: # Yes, a bare except. Catch EVERYTHING. > blah blah blah > finally: > call context manager __exit__ Why not just use this version all the time? It should work in both 2.x and 3.x. -- Greg From dan at tombstonezero.net Wed Feb 26 22:47:34 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 27 Feb 2014 03:47:34 +0000 (UTC) Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thu, 27 Feb 2014 00:25:45 +0000, Steven D'Aprano wrote: > By the way, if anyone cares what my actual use-case is, I have a > function that needs to work under Python 2.4 through 3.4, and it uses > a with statement. With statements are not available in 2.4 (or 2.5, > unless you give a from __future__ import). So after messing about for > a while with circular imports and dependency injections, I eventually > settled on some code that works something like this: > def factory(): > blah blah blah > try: > exec("""def inner(): > with something: > return something > """, globals(), mylocals) > inner = mylocals['inner'] > except SyntaxError: > def inner(): > # manually operate the context manager > call context manager __enter__ > try: > try: > return something > except: # Yes, a bare except. Catch EVERYTHING. > blah blah blah > finally: > call context manager __exit__ > blah blah blah > return inner So why not something simpler? def factory(): def inner(): '''Manually operate the context manager in order to maintain compatibility with Python 2.4 through 3.4.''' call context manager __enter__ try: try: return something except: # Yes, a bare except. Catch EVERYTHING. blah blah blah finally: call context manager __exit__ blah blah blah return inner I claim that the less unnecessary code you write, the fewer bugs you will have. Does my code misbehave under any of your target versions? From davea at davea.name Wed Feb 26 23:20:10 2014 From: davea at davea.name (Dave Angel) Date: Wed, 26 Feb 2014 23:20:10 -0500 (EST) Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano Wrote in message: > On Wed, 26 Feb 2014 14:46:39 +0100, Peter Otten wrote: > >> Steven D'Aprano wrote: >> >>> I have to dynamically generate some code inside a function using exec, >>> but I'm not sure if it is working by accident or if I can rely on it. >>> >> I eventually settled on some > code that works something like this: > > > def factory(): > blah blah blah > try: > exec("""def inner(): > Before I would use exec, I'd look hard at either generating a source file to import, or using a preprocessor. And if this code was to be installed, make the version choice or the preprocess step happen at install time. I once implemented a system that generated 20k lines of C++ header and sources. And the generated code was properly indented and fairly well commented. -- DaveA From prash.bg at gmail.com Wed Feb 26 23:30:34 2014 From: prash.bg at gmail.com (prashanth B.G) Date: Thu, 27 Feb 2014 10:00:34 +0530 Subject: python In-Reply-To: <8lctg9lokbtop7ofb2t2okc8um1vmt6qgb@4ax.com> References: <0538bec1-7668-4bc2-9b0f-f40efb6a76c8@googlegroups.com> <087f160d-a8a9-430b-9d3f-3318a04e35ae@googlegroups.com> <8lctg9lokbtop7ofb2t2okc8um1vmt6qgb@4ax.com> Message-ID: Hi Karthik, Good that you have interest in switching to dev from admin stuff. Since you are already an admin , you wouldn't have problems with administrating an os (probabally weblogic deployment was on an ux/linux machine) or a database. The requirements that you see are a mix of different technologies for building a web application. But then Python and Javascript are the two major ones which you will have to focus on . Javascript is needed along with html and css for the front end alone . Most of the times the front end is only a consumer of the information from the backend except for the user interaction events where in information flows in the opposite way. The backend has the bussiness logic implemented and could be in any language here it is Python and of course this interacts with the database. So you could ignore the rest of the technologies for a while and learn Python till you become comfortable with - Maybe writing small sysadmin scripts or anything which may be of personal interest to you . There are several tutorials which others have pointed out .. May be you can take a look at http://swaroopch.com/notes/python/ (easy) or http://www.diveintopython.net/ (slightly deeper) . Once you get a hold, you could move on to Django which runs on top of Python to get a feel of webframeworks . This would be the time when you would need to lean javascript to make user interaction possible (JS is also a complete language in itself and would need some weeks to start with). The rest like mysql , html , css are something which you could learn when the need arises since you don't have to go too deep into these and that the basics are not too difficult to understand . Once you start working on web dev stuff you will have to know the design patterns further of with mvc is a part . This would definitely take some time and effort but it would be worth learning . Hope this helps :-) Thanks. On Thu, Feb 27, 2014 at 9:21 AM, Dennis Lee Bieber wrote: > On Tue, 25 Feb 2014 17:27:19 -0800 (PST), Karthik Reddy > declaimed the following: > > >Thank you, > > > >but from by reaserch i got these requirements ...... > > > >Python, django, Twisted, MySQL, PyQt, PySide, xPython. > > > > *Technical proficiency with Python and Django. > > Web application framework > > > *Technical proficiency in JavaScript. > > Client-side web application > > > *Experience with MySQL / PgSQL. > > Relational database -- unless you need to fully administer the > DBMS or > use direct/obscure commands, knowing generic SQL may be enough (note that > Django will likely be using it's own ORM package so even SQL may not be > needed) > > > *Unix/Linux expertise. > > Well... that implies being fluent in the OS (probably at the shell > scripting level). > > > *Experience with MVC design patterns and solid algorithm skills. > > While I know the term, I've not had much experience with the > application... Separation of the data (model) from the user interface > (view) and the logic linking the two (controller). > > Algorithm is another matter (the word basically is equivalent to > "recipe"). > > > > >Core Python, DJango Framework, Web2Py, Google App engine, CherryPy ( > Basic Introduction) > > > >The problem for me is whether i have to learn all these technologies to > work as a python developer...... > > > > Django, Web2Py, GAE, CherryPy are all focused on /web-based/ > (HTTP/HTML) applications. Python is just the implementation language. > > If the goal is just pure Python none of those may be applicable. > For > example, my most recent Python task was to generate UDP data packets to be > fed through "Cross Domain Solution" boxes... I had to generate packets of > various sizes, with some variation of contents [stuff that was supposed to > trigger "drop" or "edit" actions in the CDS box]. Wireshark was used to > capture the out-bound packets and the CDS-passed in-bound packets. Python > was used to match the Wireshark captures to produce an SQLite database. > Another Python program then extracted the latency data [outbound timestamp > vs inbound timestamp] for the packets and create a CSV file for Excel > plotting. > > That's three Python programs, yet none are "web" related. They > required > an understanding of the socket library, threading [the SQLite database > relied on threads to read the two Wireshark capture files, filtering out > all but the packet time-stamp and data ID string, and a third thread to > match the out/in packets for latency -- and reporting any missing packets], > and CSV library. Oh, and development of algorithms to do that processing. > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > https://mail.python.org/mailman/listinfo/python-list > -- *****HAVE A NICE DAY ***** Prashanth -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 26 23:39:26 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 27 Feb 2014 04:39:26 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> Message-ID: <530ec17e$0$11113$c3e8da3@news.astraweb.com> On Thu, 27 Feb 2014 16:34:33 +1300, Gregory Ewing wrote: > Steven D'Aprano wrote: >> except SyntaxError: >> def inner(): >> # manually operate the context manager call context manager >> __enter__ >> try: >> try: >> return something >> except: # Yes, a bare except. Catch EVERYTHING. >> blah blah blah >> finally: >> call context manager __exit__ > > Why not just use this version all the time? It should work in both 2.x > and 3.x. Because that's yucky. It's an aesthetic thing: when supported, I want the Python interpreter to manage the context manager. The exec part is only half a dozen lines, only three lines of source code. It's no burden to keep it for the cases where it works (that is, at least 2.6 onwards). -- Steven From steve at pearwood.info Wed Feb 26 23:47:33 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 27 Feb 2014 04:47:33 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> Message-ID: <530ec365$0$11113$c3e8da3@news.astraweb.com> On Wed, 26 Feb 2014 23:20:10 -0500, Dave Angel wrote: > Before I would use exec, I'd look hard at either generating a > source file to import, Yes, I went through the process of pulling out the code into a separate module, but that just made more complexity and was pretty nasty. If the function was stand-alone, it might have worked, but it needed access to other code in the module, so there were circular dependencies. > or using a preprocessor. I don't think that it's easier/better to write a custom Python preprocessor and run the entire module through it, just to avoid a three- line call to exec. Guys, I know that exec is kinda dangerous and newbies should be discouraged from throwing every string they see at it, but this isn't my second day Python programming, and it's not an accident that Python supports the dynamic compilation and execution of source code at runtime. It's a deliberate language feature. We're allowed to use it :-) > And if this code was > to be installed, make the version choice or the preprocess step happen > at install time. Completely inappropriate in my case. This is a module which can be called from multiple versions of Python from a single installation. -- Steven From rosuav at gmail.com Thu Feb 27 00:05:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Feb 2014 16:05:18 +1100 Subject: exec and locals In-Reply-To: <530ec365$0$11113$c3e8da3@news.astraweb.com> References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> <530ec365$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thu, Feb 27, 2014 at 3:47 PM, Steven D'Aprano wrote: > Guys, I know that exec is kinda dangerous and newbies should be > discouraged from throwing every string they see at it, but this isn't my > second day Python programming, and it's not an accident that Python > supports the dynamic compilation and execution of source code at runtime. > It's a deliberate language feature. We're allowed to use it :-) Code smell means "look at this". It doesn't mean "don't use this feature ever". :) Steven's looked into this thoroughly, I'm sure, and exec is important. ChrisA From nomail at invalid.com Thu Feb 27 01:24:24 2014 From: nomail at invalid.com (ast) Date: Thu, 27 Feb 2014 07:24:24 +0100 Subject: Strange behavior with sort() Message-ID: <530eda1d$0$2061$426a74cc@news.free.fr> Hello box is a list of 3 integer items If I write: box.sort() if box == [1, 2, 3]: the program works as expected. But if I write: if box.sort() == [1, 2, 3]: it doesn't work, the test always fails. Why ? Thx From frank at chagford.com Thu Feb 27 01:30:09 2014 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Feb 2014 08:30:09 +0200 Subject: Deepcopying a byte string is quicker than copying it - problem? Message-ID: Hi all I noticed this a little while ago, but dismissed it as a curiosity. On reflection, I decided to mention it here in case it indicates a problem. This is with python 3.3.2. C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" 100000 loops, best of 3: 6.91 usec per loop C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" 100000 loops, best of 3: 11.8 usec per loop C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" 10000 loops, best of 3: 79.9 usec per loop C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" 100000 loops, best of 3: 11.7 usec per loop As you can see, deepcopying a string is slightly slower than copying it. However, deepcopying a byte string is orders of magnitude quicker than copying it. Actually, looking closer, it is the 'copy' that is slow, not the 'deepcopy' that is quick.. Expected, or odd? Frank Millman From frank at chagford.com Thu Feb 27 01:39:18 2014 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Feb 2014 08:39:18 +0200 Subject: Strange behavior with sort() References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: "ast" wrote in message news:530eda1d$0$2061$426a74cc at news.free.fr... > Hello > > box is a list of 3 integer items > > If I write: > > box.sort() > if box == [1, 2, 3]: > > > the program works as expected. But if I write: > > if box.sort() == [1, 2, 3]: > > it doesn't work, the test always fails. Why ? > Try the following in the interpreter - >>> box = [3, 2, 1] >>> box.sort() >>> box [1, 2, 3] >>> box = [3, 2, 1] >>>print(box.sort()) None >>> box [1, 2, 3] box.sort() sorts box 'in situ', but does not return anything. That is why the second example prints None. In your second example, you are comparing the return value of box.sort() with [1, 2, 3]. As the return value is None, they are unequal. HTH Frank Millman From dualbus at gmail.com Thu Feb 27 01:40:53 2014 From: dualbus at gmail.com (Eduardo =?utf-8?Q?A=2E_Bustamante_L=C3=B3pez?=) Date: Wed, 26 Feb 2014 22:40:53 -0800 Subject: Strange behavior with sort() In-Reply-To: <530eda1d$0$2061$426a74cc@news.free.fr> References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: <20140227064053.GA6532@dualbus.me> On Thu, Feb 27, 2014 at 07:24:24AM +0100, ast wrote: > Hello > > box is a list of 3 integer items > > If I write: > > box.sort() > if box == [1, 2, 3]: > > > the program works as expected. But if I write: > > if box.sort() == [1, 2, 3]: > > it doesn't work, the test always fails. Why ? > > Thx > -- > https://mail.python.org/mailman/listinfo/python-list Because when you call the .sort() method on a list, it does the sort in-place, instead of returning a sorted copy of the list. Check this: >>> [2,1,3].sort() >>> The method does not return a value, that's why the direct comparison fails. What you might want is to use the sorted() method on the list, like this: >>> sorted([2,1,3]) [1, 2, 3] >>> sorted([2,1,3]) == [1,2,3] True -- Eduardo Alan Bustamante L?pez From lele at metapensiero.it Thu Feb 27 01:41:03 2014 From: lele at metapensiero.it (Lele Gaifax) Date: Thu, 27 Feb 2014 07:41:03 +0100 Subject: Strange behavior with sort() References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: <87fvn5rrb4.fsf@nautilus.nautilus> "ast" writes: > If I write: > > box.sort() > if box == [1, 2, 3]: > > the program works as expected. But if I write: > > if box.sort() == [1, 2, 3]: > > it doesn't work, the test always fails. Why ? Because very often methods **dont't** return the object they are applied (self that is). This works though: >>> box = [1,3,2] >>> sorted(box) == [1,2,3] True hth, ciao, lele. -- nickname: Lele Gaifax | Quando vivr? di quello che ho pensato ieri real: Emanuele Gaifas | comincer? ad aver paura di chi mi copia. lele at metapensiero.it | -- Fortunato Depero, 1929. From marko at pacujo.net Thu Feb 27 01:41:57 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 27 Feb 2014 08:41:57 +0200 Subject: Strange behavior with sort() References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: <87vbw12h1m.fsf@elektro.pacujo.net> "ast" : > if I write: > > if box.sort() == [1, 2, 3]: > > it doesn't work, the test always fails. Why ? The list.sort() method returns None. The builtin sorted() function returns a list: if sorted(box) == [1, 2, 3]: would work. Note that the list.sort() method is often preferred because it sorts the list in place while the sorted() function must generate a fresh, sorted list. Marko From nomail at invalid.com Thu Feb 27 02:01:12 2014 From: nomail at invalid.com (ast) Date: Thu, 27 Feb 2014 08:01:12 +0100 Subject: Strange behavior with sort() In-Reply-To: <530eda1d$0$2061$426a74cc@news.free.fr> References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: <530ee2be$0$2183$426a74cc@news.free.fr> Thanks for the very clear explanation From gary.herron at islandtraining.com Thu Feb 27 02:16:27 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Wed, 26 Feb 2014 23:16:27 -0800 Subject: Strange behavior with sort() In-Reply-To: <530eda1d$0$2061$426a74cc@news.free.fr> References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: <530EE64B.3070802@islandtraining.com> On 02/26/2014 10:24 PM, ast wrote: > Hello > > box is a list of 3 integer items > > If I write: > > box.sort() > if box == [1, 2, 3]: > > > the program works as expected. But if I write: > > if box.sort() == [1, 2, 3]: Most such questions can be answered by printing out the values in question and observing first hand what the value is. So, print out box.sort() to see what it is. You might be surprised. Hint: box.sort() does indeed cause box to be sorted, and the sorted list is left in box, but the sorted list is not returned as a function value. > > it doesn't work, the test always fails. Why ? > > Thx From orgnut at yahoo.com Thu Feb 27 02:23:29 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Wed, 26 Feb 2014 23:23:29 -0800 Subject: Strange behavior with sort() In-Reply-To: <530eda1d$0$2061$426a74cc@news.free.fr> References: <530eda1d$0$2061$426a74cc@news.free.fr> Message-ID: On 02/26/2014 10:24 PM, ast wrote: > Hello > > box is a list of 3 integer items > > If I write: > > box.sort() > if box == [1, 2, 3]: > > > the program works as expected. But if I write: > > if box.sort() == [1, 2, 3]: > > it doesn't work, the test always fails. Why ? > > Thx sort() sorts the sequence in place, but it _returns_ None. Your second example becomes the equivalent of: box.sort() if None == [1, 2, 3]: So although your box does become sorted, it is NOT what is compared in your if statement. BTW, the sorted() function won't work here either. It will return the sorted sequence, but it leaves the original unchanged. -=- Larry -=- From ian.g.kelly at gmail.com Thu Feb 27 03:02:01 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 27 Feb 2014 01:02:01 -0700 Subject: Deepcopying a byte string is quicker than copying it - problem? In-Reply-To: References: Message-ID: On Wed, Feb 26, 2014 at 11:30 PM, Frank Millman wrote: > Hi all > > I noticed this a little while ago, but dismissed it as a curiosity. On > reflection, I decided to mention it here in case it indicates a problem. > > This is with python 3.3.2. > > C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" > 100000 loops, best of 3: 6.91 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" > 100000 loops, best of 3: 11.8 usec per loop > > C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" > 10000 loops, best of 3: 79.9 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" > 100000 loops, best of 3: 11.7 usec per loop > > As you can see, deepcopying a string is slightly slower than copying it. > > However, deepcopying a byte string is orders of magnitude quicker than > copying it. > > Actually, looking closer, it is the 'copy' that is slow, not the 'deepcopy' > that is quick.. > > Expected, or odd? This will shed some light: >>> a = 'a' * 1000 >>> b = copy.copy(a) >>> a is b True >>> c = copy.deepcopy(a) >>> a is c True >>> d = b'a' * 1000 >>> e = copy.copy(d) >>> d is e False >>> f = copy.deepcopy(d) >>> d is f True For some reason, calling copy.copy on a bytes object actually copies the bytes, rather than just returning the immutable object passed in. That's probably not intentional and is worth opening a ticket for. The difference between copy and deepcopy is probably just due to the extra overhead of deepcopy. From __peter__ at web.de Thu Feb 27 03:25:22 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Feb 2014 09:25:22 +0100 Subject: Deepcopying a byte string is quicker than copying it - problem? References: Message-ID: Frank Millman wrote: > Hi all > > I noticed this a little while ago, but dismissed it as a curiosity. On > reflection, I decided to mention it here in case it indicates a problem. > > This is with python 3.3.2. > > C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" > 100000 loops, best of 3: 6.91 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" > 100000 loops, best of 3: 11.8 usec per loop > > C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" > 10000 loops, best of 3: 79.9 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" > 100000 loops, best of 3: 11.7 usec per loop > > As you can see, deepcopying a string is slightly slower than copying it. > > However, deepcopying a byte string is orders of magnitude quicker than > copying it. > > Actually, looking closer, it is the 'copy' that is slow, not the > 'deepcopy' that is quick.. > > Expected, or odd? Definitely odd. For some reason deepcopy() special-cases the bytes type while copy() does not. If you fix that: $ python3.4 -m timeit -s 'import copy; b = b"a"*1000' 'copy.copy(b)' 10000 loops, best of 3: 21.2 usec per loop $ python3.4 -m timeit -s 'import copy; copy._copy_dispatch[bytes] = copy._copy_immutable; b = b"a"*1000' 'copy.copy(b)' 1000000 loops, best of 3: 0.971 usec per loop I think this an oversight rather than intentional. Please report to bugs.python.org. From frank at chagford.com Thu Feb 27 04:02:26 2014 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Feb 2014 11:02:26 +0200 Subject: Deepcopying a byte string is quicker than copying it - problem? References: Message-ID: "Frank Millman" wrote in message news:lemm11$18r$1 at ger.gmane.org... > Hi all > > I noticed this a little while ago, but dismissed it as a curiosity. On > reflection, I decided to mention it here in case it indicates a problem. > > This is with python 3.3.2. > > C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" > 100000 loops, best of 3: 6.91 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" > 100000 loops, best of 3: 11.8 usec per loop > > C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" > 10000 loops, best of 3: 79.9 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" > 100000 loops, best of 3: 11.7 usec per loop > > As you can see, deepcopying a string is slightly slower than copying it. > > However, deepcopying a byte string is orders of magnitude quicker than > copying it. > > Actually, looking closer, it is the 'copy' that is slow, not the > 'deepcopy' that is quick.. > > Expected, or odd? > > Frank Millman > Thanks, Ian and Peter, for confirming that this is not expected. I have created an issue on the bug tracker - http://bugs.python.org/issue20791 Frank From alister.ware at ntlworld.com Thu Feb 27 04:59:11 2014 From: alister.ware at ntlworld.com (Alister) Date: Thu, 27 Feb 2014 09:59:11 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e877b$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thu, 27 Feb 2014 00:31:56 +0000, Steven D'Aprano wrote: > On Wed, 26 Feb 2014 14:00:59 +0000, Alister wrote: > >> On Wed, 26 Feb 2014 13:15:25 +0000, Steven D'Aprano wrote: >> >>> I have to dynamically generate some code inside a function using exec, >>> but I'm not sure if it is working by accident or if I can rely on it. > [...] > >> I have no idea but as exec is generally considered to be a bad idea are >> you absolutely sure this is the correct way to achieve your end goal? >> >> perhaps if you detailed your requirement someone may be able to suggest >> a safer solution. > > Thanks for your concern, but what I'm doing is perfectly safe. The > string being exec'ed is a string literal known at compile-time and > written by me (see my previous email for details) and the only reason > I'm running it with exec at runtime rather than treating it as normal > source code is that it relies on a feature that may not be available > (with statement). > > The joys of writing code that has to run under multiple incompatible > versions of Python. I hadn't noticed who had made the original post or a I wouldn't have bothered, you know Python & what is safe far better than I ever will -- The world is not octal despite DEC. From artomishka at yahoo.co.uk Thu Feb 27 05:30:41 2014 From: artomishka at yahoo.co.uk (Peter Clark) Date: Thu, 27 Feb 2014 10:30:41 +0000 (GMT) Subject: end quote help for a newbie In-Reply-To: <1391110020.83595.YahooMailNeo@web133106.mail.ir2.yahoo.com> References: <1391088376.73476.YahooMailNeo@web133103.mail.ir2.yahoo.com> <1391093552.89290.YahooMailNeo@web133104.mail.ir2.yahoo.com> <1391110020.83595.YahooMailNeo@web133106.mail.ir2.yahoo.com> Message-ID: <1393497041.37213.YahooMailNeo@web133105.mail.ir2.yahoo.com> On Thursday, 30 January 2014, 21:27, Peter Clark wrote: ? Thank-you.? Please no-one reply to this post.? I just want to put on record my complete p-offed-ness, that having spent 10 days sorting out and hypertexting a library of documentation, I now have to start all over. Please do not respond, I am sure it is all my fault. Please do not respond - it will only prolong the agony. Long live the Norwegian blue. peter On Thursday, 30 January 2014, 17:31, Zachary Ware wrote: Please reply to the list, rather than to me directly.? You can use "Reply to List" if you have that option, or "Reply to All" to make sure you include the list. On Thu, Jan 30, 2014 at 8:52 AM, Peter Clark wrote: > I do not know how to dump the screen - it will not let me select anything > with the mouse cursor, so here is my (typed in) reproduction: Since it looks like you're probably using Windows Command Prompt, you can right click anywhere in that window, click "Mark", and highlight a rectangle containing what you want and hit the Enter key.? Note that it doesn't go by lines, only the rectangle you highlight will be copied! (Yes, it is horribly annoying :) Thank you for taking the time to type it all out! > Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:18:40)? [MSC v.1600 32 > bit (In > tel) on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> print "xyz" >? ? ? File "(stdin)", line 1 >? ? ? ? print "xyz" >? ? ? ? ? ? ? ? ? ? ? ? ^ > SyntaxError: invalid syntax This right here confirms what I thought: you're using Python 3 with a Python 2 tutorial.? 'print' in Python 3 is a function just like 'input' or 'open', so you have to use it like this instead: ? >>> print("xyz") ? xyz >>>> print '''xyz"? . . .''' >? ? ? File "(stdin)", line 1 >? ? ? ? print '''xyz''' >? ? ? ? ? ? ? ? ? ? ? ? ? ^ > SyntaxError: invalid syntax >>>> print '''xyz"? . . .''? ? ? ? ? ? ? ? ? ? (note - not appearing on >>>> screen - this is 2 single quotes) > ... ''' >? ? File "(stdin)", line 2 >? ? ? ? ''' >? ? ? ? ? ^ > SyntaxError: invalid syntax >>>> > > I do not see anywhere a definition of which version the tutorial relates to, > but I downloaded it from the Python site on 19th January 2014. The Python website provides docs for every current version of Python, and the community is currently in the midst of a very long transition from version 2.7 to 3.x, so both versions are considered "current". In fact, most links to the Python documentation will link to the 2.7 version to maintain compatibility.? Here's a link to the Python 3 version of the tutorial, which should work much better for you! http://docs.python.org/3/tutorial/ You can also find the docs in your Python installation: find Python 3.3 in your start menu, and choose "Python Manuals".? This will open the same docs as are found online, in standard Windows help file format.? Click the "Tutorial" link on the first page of that, and you should have the right tutorial to work from. Hope this helps, and welcome to Python! -- Zach > > peter. > > On Thursday, 30 January 2014, 16:13, Zachary Ware > wrote: > > On Thu, Jan 30, 2014 at 7:26 AM, Peter Clark wrote: > >> There is probably an easy solution to this ? but I have not found it. >> >> Trying to terminate a literal in a print statement (from the tutorial). >> >> The literal should be enclosed in double quotes ? ? >> >> the initial double quote seems to be OK (if I use a different character it >> flags it) but the ending is flagged as invalid syntax.? I have tried >> changing my keyboard from UK to USA, without any effect, and tried adding >> a >> space after the final double quote, > > > Which version of Python are you using?? Make sure you're using the > same version of interpreter and tutorial.? 'print' was one of the big > changes between Python 2 and Python 3 (in Python 2 it was a statement, > while in Python 3 it is a function), so a tutorial written with Python > 2 in mind will have some issues if you're using Python 3. > > If you've already checked that, try copying and pasting your entire > interpreter session into a reply here, and we'll be more able to > figure out what's going on. > > Hope this helps, > > -- > Zach > Hi, I have just started trying to use python version 3, under windows XP, I have got a simple script (attached) to run as I want in Interpreter mode.? It is saved as a .py file. If I double click on the file the python screen opens and appears to be waiting for input but?the cursor just sits there without?doing anything but blink. I haven't found any .py program which does anything except open and close the python window, or occasionally accepting input with no response. I would like to be able to save and run scripts as my usual method of acquiring a new language, but getting python to run a saved script has me beat.? I assume there is something I am missing, or have missed. As an aside, does the fact that python runs at all indicate that I have C installed? Thank you in advance for any assistance. peter clark. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: DandD.py URL: From fleitner.cnio at gmail.com Thu Feb 27 05:36:24 2014 From: fleitner.cnio at gmail.com (Florian Leitner) Date: Thu, 27 Feb 2014 11:36:24 +0100 Subject: Deepcopying a byte string is quicker than copying it - problem? In-Reply-To: References: Message-ID: <530F1528.60009@gmail.com> On 27.02.14, 7:30 , Frank Millman wrote: > Hi all > > I noticed this a little while ago, but dismissed it as a curiosity. > On reflection, I decided to mention it here in case it indicates a > problem. > > This is with python 3.3.2. > > C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" 100000 > loops, best of 3: 6.91 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" > 100000 loops, best of 3: 11.8 usec per loop > > C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" 10000 > loops, best of 3: 79.9 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" > 100000 loops, best of 3: 11.7 usec per loop > > As you can see, deepcopying a string is slightly slower than > copying it. > > However, deepcopying a byte string is orders of magnitude quicker > than copying it. > > Actually, looking closer, it is the 'copy' that is slow, not the 'deepcopy' > that is quick.. > > Expected, or odd? > > Frank Millman > > > Indeed, just tried this: Python 3.3.2 (default, Sep 30 2013, 21:37:29) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.75)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import copy >>> >>> bs = b'a'*1000 id(bs) 140246553640960 >>> id(copy.copy(bs)) # WATCH THIS! 140246578636800 >>> id(copy.deepcopy(bs)) 140246553640960 >>> id(bs[:]) 140246553640960 >>> >>> us = 'a'*1000 id(us) 140246553642496 >>> id(copy.copy(us)) 140246553642496 >>> id(copy.deepcopy(us)) 140246553642496 >>> id(us[:]) 140246553642496 Interesting; copy.copy(b'bytes') creates a "real" copy of an otherwise immutable value... That might actually be some form of a bug. By the way, if you are looking into this as something about speed, you should use slices, not copy.copy/deepcopy, anyways (copy = bc[:]); More than 5x faster: $ python -m timeit -s "import copy; s='a'*1000" "copy.copy(s)" 1000000 loops, best of 3: 0.465 usec per loop $ python -m timeit -s "import copy; s='a'*1000" "cs = s[:]" 10000000 loops, best of 3: 0.0728 usec per loop From harrismh777 at gmail.com Thu Feb 27 05:33:35 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 02:33:35 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <81aa3b17-fcaf-4aea-bef7-429403ac8d27@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <81aa3b17-fcaf-4aea-bef7-429403ac8d27@googlegroups.com> Message-ID: > > Have you looked at the gmpy2 ( https://code.google.com/p/gmpy/ ) module? > > casevh No... was not aware of gmpy2... looks like a great project! I am wondering why it would be sooo much faster? I was hoping that Stefan Krah's C accelerator was using FFT fast fourier transforms for multiplication at least... but, as Oscar pointed out a native python series algorithm runs right along with the built-in (at least for exp() and ln() ) I have not looked at Krah's code, so not sure what he did to speed things up... (something more than just writing it in C I would suppose). Thanks for the heads up on gmpy From florian.leitner at gmail.com Thu Feb 27 05:36:24 2014 From: florian.leitner at gmail.com (Florian Leitner) Date: Thu, 27 Feb 2014 11:36:24 +0100 Subject: Deepcopying a byte string is quicker than copying it - problem? In-Reply-To: References: Message-ID: <530F1528.60009@gmail.com> On 27.02.14, 7:30 , Frank Millman wrote: > Hi all > > I noticed this a little while ago, but dismissed it as a curiosity. > On reflection, I decided to mention it here in case it indicates a > problem. > > This is with python 3.3.2. > > C:\>python -m timeit -s "import copy" "copy.copy('a'*1000)" 100000 > loops, best of 3: 6.91 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy('a'*1000)" > 100000 loops, best of 3: 11.8 usec per loop > > C:\>python -m timeit -s "import copy" "copy.copy(b'a'*1000)" 10000 > loops, best of 3: 79.9 usec per loop > > C:\>python -m timeit -s "import copy" "copy.deepcopy(b'a'*1000)" > 100000 loops, best of 3: 11.7 usec per loop > > As you can see, deepcopying a string is slightly slower than > copying it. > > However, deepcopying a byte string is orders of magnitude quicker > than copying it. > > Actually, looking closer, it is the 'copy' that is slow, not the 'deepcopy' > that is quick.. > > Expected, or odd? > > Frank Millman > > > Indeed, just tried this: Python 3.3.2 (default, Sep 30 2013, 21:37:29) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.75)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import copy >>> >>> bs = b'a'*1000 id(bs) 140246553640960 >>> id(copy.copy(bs)) # WATCH THIS! 140246578636800 >>> id(copy.deepcopy(bs)) 140246553640960 >>> id(bs[:]) 140246553640960 >>> >>> us = 'a'*1000 id(us) 140246553642496 >>> id(copy.copy(us)) 140246553642496 >>> id(copy.deepcopy(us)) 140246553642496 >>> id(us[:]) 140246553642496 Interesting; copy.copy(b'bytes') creates a "real" copy of an otherwise immutable value... That might actually be some form of a bug. By the way, if you are looking into this as something about speed, you should use slices, not copy.copy/deepcopy, anyways (copy = bc[:]); More than 5x faster: $ python -m timeit -s "import copy; s='a'*1000" "copy.copy(s)" 1000000 loops, best of 3: 0.465 usec per loop $ python -m timeit -s "import copy; s='a'*1000" "cs = s[:]" 10000000 loops, best of 3: 0.0728 usec per loop --- news://freenews.netfront.net/ - complaints: news at netfront.net --- From harrismh777 at gmail.com Thu Feb 27 05:37:09 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 02:37:09 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> Message-ID: <1434ec4a-b28d-4309-9be4-0846c755c86d@googlegroups.com> On Wednesday, February 19, 2014 4:29:27 PM UTC-6, Oscar Benjamin wrote: > Actually the performance difference isn't as big as you might think. > > Oscar You're right. At least my own benchmark on my native exp() vs the built-in was about ~same ~same. I was hoping that Stefan had used FFT... but I need to talk with him... Thanks for the reply. From rosuav at gmail.com Thu Feb 27 05:41:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Feb 2014 21:41:53 +1100 Subject: end quote help for a newbie In-Reply-To: <1393497041.37213.YahooMailNeo@web133105.mail.ir2.yahoo.com> References: <1391088376.73476.YahooMailNeo@web133103.mail.ir2.yahoo.com> <1391093552.89290.YahooMailNeo@web133104.mail.ir2.yahoo.com> <1391110020.83595.YahooMailNeo@web133106.mail.ir2.yahoo.com> <1393497041.37213.YahooMailNeo@web133105.mail.ir2.yahoo.com> Message-ID: On Thu, Feb 27, 2014 at 9:30 PM, Peter Clark wrote: > Hi, I have just started trying to use python version 3, under windows XP, I > have got a simple script (attached) to run as I want in Interpreter mode. > It is saved as a .py file. If I double click on the file the python screen > opens and appears to be waiting for input but the cursor just sits there > without doing anything but blink. I haven't found any .py program which does > anything except open and close the python window, or occasionally accepting > input with no response. In future, it'd be easier for us if you include the text inline. It's not particularly long, so I'll just do that for you here. # Dragons and dungeons, based on CP/M program messages from ca. 1966 # This version designed and produced by peter clark beginning in December 2013 def startandload(n): # introduce program and allow messages to be loaded/amended x = str(input("Welcome Adventurer, what is your name?")) if x==('load'): y = str(input("messages, places or things?")) if y in("messages", "places","things"): print("OK") else: print("Wrong") if x==('restart'): y = str(input("game reference")) if y in("messages", "places","things"): print("*** to be done - load and restart game ***") else: print("Wrong") while True: startandload The problem is right at the end: you don't actually call the function. You always need parentheses to call a function. I'm also a bit confused as to your reason for running a function called "startandload" (which seems to be initialization) in an infinite loop; you possibly just want to call it once. Note that input() already returns a string, so passing it through str() doesn't do anything. ChrisA From ganesh1pal at gmail.com Thu Feb 27 05:50:55 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Thu, 27 Feb 2014 16:20:55 +0530 Subject: Python : parsing the command line options using optparse In-Reply-To: <9794bf8ec388cbedc2b206adc4d09b5a@rodperson.com> References: <9794bf8ec388cbedc2b206adc4d09b5a@rodperson.com> Message-ID: > > They must be running an older version of FreeBSD since the default version > of python is 2.7. > > There is a FreeBSD package for argparse, the command would be something > like > pkg_add -r install py26-argparse > > > Rod > > Yes Iam running a older version of FreeBSD ( Iam actually running a derivative of FreeBSD ) Thanks for the suggestion I ran the command but I got the below error # pkg_add -r install py26-argparse Error: Unable to get ftp://ftp.freebsd.org/pub/FreeBSD/ports/amd64/packages-7-stable/Latest/install.tbz: File unavailable (e.g., file not found, no access) pkg_add: unable to fetch ' ftp://ftp.freebsd.org/pub/FreeBSD/ports/amd64/packages-7-stable/Latest/install.tbz' by URL Error: Unable to get ftp://ftp.freebsd.org/pub/FreeBSD/ports/amd64/packages-7-stable/Latest/py26-argparse.tbz: File unavailable (e.g., file not found, no access) pkg_add: unable to fetch ' ftp://ftp.freebsd.org/pub/FreeBSD/ports/amd64/packages-7-stable/Latest/py26-argparse.tbz' by URL Iam now trying to browse the link directly didnt find the patch , will keep you posted -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Thu Feb 27 06:29:35 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 28 Feb 2014 00:29:35 +1300 Subject: exec and locals In-Reply-To: <530ec17e$0$11113$c3e8da3@news.astraweb.com> References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> <530ec17e$0$11113$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 27 Feb 2014 16:34:33 +1300, Gregory Ewing wrote: > >>Why not just use this version all the time? It should work in both 2.x >>and 3.x. > > Because that's yucky. It's an aesthetic thing: when supported, I want the > Python interpreter to manage the context manager. More yucky than wrapping the Py3 version in an exec? To my way of thinking, that cancels out any elegance that might have been gained from using a with-statement. Do you really need to use the context manager at all? Could you just write the try-statement that you would have written in Py2 if you didn't have a context manager? -- Greg From rosuav at gmail.com Thu Feb 27 06:41:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Feb 2014 22:41:13 +1100 Subject: exec and locals In-Reply-To: References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> <530ec17e$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thu, Feb 27, 2014 at 10:29 PM, Gregory Ewing wrote: > Steven D'Aprano wrote: >> >> On Thu, 27 Feb 2014 16:34:33 +1300, Gregory Ewing wrote: >> >>> Why not just use this version all the time? It should work in both 2.x >>> and 3.x. >> >> >> Because that's yucky. It's an aesthetic thing: when supported, I want the >> Python interpreter to manage the context manager. > > > More yucky than wrapping the Py3 version in an > exec? To my way of thinking, that cancels out any > elegance that might have been gained from using > a with-statement. > > Do you really need to use the context manager > at all? Could you just write the try-statement > that you would have written in Py2 if you > didn't have a context manager? If I have to support two vastly different versions, I would prefer (when possible) to write the code so that dropping the old version's support is simply a matter of deleting stuff. Write the code for the new version, then warp it as little as possible to support the old version as well, and keep it clear which bits are for the old. Writing code that avoids 'with' altogether goes against that. ChrisA From harrismh777 at gmail.com Thu Feb 27 07:07:07 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 04:07:07 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> Message-ID: <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> On Wednesday, February 19, 2014 4:10:22 PM UTC-6, Terry Reedy wrote: > Or just dmath. I think this is a better idea than suggesting additions > to decimal itself. For one thing, anything put in decimal would be > subject to change if the function were to be added to the standard. It > is worth noting in such a posting that Krah's speedup make such > functions really feasible. The algorithms could be similar, at least > initially, to the one used for floats > > Terry Jan Reedy I have created a project here: https://code.google.com/p/pythondecimallibrary/ I wrote a dmath.py library module for use with the C accelerated decimal module, that I would like to see merged into the C Python distribution so that folks have it by default... without having to pull it down with GIT, or whatever. Anyway, thanks for responding (everyone) and for your consideration. Oh, and one more thing... whoever is doing the work on IDLE these days, nice job! It is stable, reliable, and just works/ appreciate it! Kind regards, Mark H Harris From harrismh777 at gmail.com Thu Feb 27 07:13:00 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 04:13:00 -0800 (PST) Subject: posting code snippets Message-ID: hi folks, Its been too long... can't remember... are there rules here about posting code snippets, or length considerations, and so forth? Seems like there was a place to share code snips outside of the message area? A related question, is there a python repository for uploading py files, patches, suggestions, etc? What is the correct venue protocol for contributing code source? tnx... happy Thursday! From rosuav at gmail.com Thu Feb 27 07:27:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Feb 2014 23:27:16 +1100 Subject: posting code snippets In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 11:13 PM, Mark H. Harris wrote: > hi folks, > Its been too long... can't remember... are there rules here about posting code snippets, or length considerations, and so forth? > Seems like there was a place to share code snips outside of the message area? The convention is to post it in-line, just have it right there in the body of the email. There's no specific rule on length, but if it goes over a screenful or two, a lot of people won't bother to read it. Keeping the code in the message itself is the best way to carry it around. Not every transmission medium supports attachments, and they don't cut down on size in any way; and a link to an external resource creates a dependency. But if your code really is too long to be practical, you could post it to pastebin or somesuch. It's not as good as keeping it in the email, but it can work. Do try to make your code more consumable, though - posting a link to a thousand-line script is just as useless as embedding it, as nobody will bother to read through it. > tnx... happy Thursday! I never could get the hang of Thursdays. ChrisA From harrismh777 at gmail.com Thu Feb 27 08:24:22 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 05:24:22 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: On Friday, February 21, 2014 12:37:59 AM UTC-6, Sam wrote: > I need to pass a global variable into a python function. However, the global variable does not seem to be assigned after the function ends. Is it because parameters are not passed by reference? How can I get function parameters to be passed by reference in Python? def func(x): global ref_name ref_name = '3.14159' # rest of the code # rest of the code When you call this function the ref_name reference will be set to '3.14159' as a string and your main code will be able to 'see' it, and other funcs will be able to 'see' it too... play with it a bit... if other funcs need to write to it they will also have to use the global ref_name line. As long as other funcs only read the reference, then the global line is not needed to 'see' the reference. As others have noted, python does not have a 'variable' concept (references to objects instead) and so your question is a little ambiguous. Also, using global references within functions is not a good idea... generally speaking. Cheers From oscar.j.benjamin at gmail.com Thu Feb 27 09:42:55 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 27 Feb 2014 14:42:55 +0000 Subject: extend methods of decimal module In-Reply-To: <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> Message-ID: On 27 February 2014 12:07, Mark H. Harris wrote: > > I have created a project here: > > https://code.google.com/p/pythondecimallibrary/ > > I wrote a dmath.py library module for use with the C accelerated decimal module, that I would like to see merged into the C Python distribution so that folks have it by default... without having to pull it down with GIT, or whatever. Hi Mark, Some points: 1) Why have you committed the code as a .tar.gz file? 2) This function is not such a good idea: def D(numform): return Decimal(str(numform)) The Decimal constructor already accepts strings and many types of numbers. Going via str like this reduces accuracy if e.g. someone passes a float in. 3) In many places you've written code like this: prec=dscale(getcontext().prec +7) sqr = (D(x).sqrt()).__round__(prec) retscale=dscale(prec) The preferred way is: with localcontext() as ctx: ctx.prec += 7 sqr = round(D(x).sqrt(), prec) i.e. use a context manager to restore the context even if an error occurs and use the round builtin rather than the dunder method. 4) You shouldn't be using round/__round__ for precision rounding: it uses decimal places rather than significant figures. If you want to round to context precision just use unary +. i.e.: return +sqr 5) The Decimal.sqrt method already rounds to context precision. There's no need to compute in higher precision and then round it yourself (in fact you're invalidating the correctness of the rounding by double-rounding like this). So really it's just: def sqrt(x): return Decimal(x).sqrt() 6) You should organise it in such a way that you're not progressively increasing the precision each time one function calls another. Oscar From mal at python.org Thu Feb 27 09:59:42 2014 From: mal at python.org (M.-A. Lemburg) Date: Thu, 27 Feb 2014 15:59:42 +0100 Subject: ANN: Python Job Board - Call for volunteers Message-ID: <530F52DE.9000704@python.org> [Please help spread the word by forwarding to other relevant mailing lists, user groups, etc. world-wide; thanks :-)] Dear Python Community, for many years, the Python Job board (http://legacy.python.org/community/jobs/) was run by volunteers - most of the time by just one volunteer at a time until they moved on to spend their time on other things. We've now reached such a point again. In these years, the volume on the job board has significantly increased, as it got more and more popular. It is now at around 2-5 postings per day and most of those positions get filled quickly - which is an indication of how useful this service is to the Python community. To scale up and revive the job board, the PSF would now like to setup a *team of volunteers* to run the job board and this is our call for help. How does the job board work ? ----------------------------- At the moment, the job board is maintained on the legacy site (http://legacy.python.org/community/jobs/), but since we've launched our brand new website (http://www.python.org/), we'd like to move the job board over to that site. Instead of the repository based approach used on the old site, the new site has database support to aid in more easily processing and filing job listings. There's a job board mailing list which helps coordinate the task of reviewing and filing job offers. Currently, all job submissions get sent to this mailing list, but with the job board app, the submission process can be moved over to the website's database. What does it take to run the job board ? ---------------------------------------- You have to review the job postings, request changes if they are too long, don't clearly state the need for Python skills, or have quality issues. After review, the job board app will then allow posting the jobs on the website by simply setting the status to published. Communication with the submitters is usually done by email and via the mailing list, so all team members can see the communication and help out if necessary. Please note: This is just a high level overview. The details need to be hashed out by the new team. Does the job board app work already ? ------------------------------------- It does, but is disabled at the moment due to lack of volunteers. Since the site just launched there may also well be some issues with the job board app. On the positive side there's a lot happening around the site at the moment, so if you have change requests, these will usually be implemented quickly - or you can jump in, hack on the job board app and submit a pull request yourself: https://github.com/python/pythondotorg/tree/master/jobs These are exciting times and this is your chance to make a difference ! Ok, I like new challenges - where do I sign up ? ------------------------------------------------ Great :-) Please write to jobs at python.org I have a question... -------------------- If you have questions, you can write me or the PSF board at psf at python.org. Many thanks, -- Marc-Andre Lemburg Director Python Software Foundation http://www.python.org/psf/ From malaclypse2 at gmail.com Thu Feb 27 10:01:50 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 27 Feb 2014 10:01:50 -0500 Subject: posting code snippets In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 7:13 AM, Mark H. Harris wrote: > hi folks, > Its been too long... can't remember... are there rules here about posting code snippets, or length considerations, and so forth? Chris' advice about just posting your code inline with your message is good. If the problem is that you think your code is too long to post inline, you're probably right. That means it's probably also too long for people to give it much attention. If you really want people to help figure out what is going on with code you don't understand, the best thing to do is to post a Short, Self Contained, Correct Example (http://www.sscce.org/). That means cutting the code down to the bare minimum required to demonstrate your issue. Many times, the very act of cutting the code down to a digestible chunk will show you the problem without posting. And if you still don't understand what's going on, you're much more likely to get help when you present a problem that can be read in a single screenful or so of code. > A related question, is there a python repository for uploading py files, patches, suggestions, etc? Assuming this goes beyond posting code for people on the list to look at, yes, there are lots of places to post python code. For short bits, Activestate has a repository of python recipes: http://code.activestate.com/recipes/langs/python/ For publishing full modules and packages, there's the python package index: https://pypi.python.org/pypi Patches, bugs and feature requests for the python language itself belong here: http://bugs.python.org/ attached to an appropriate tracker issue. Feature requests should probably be raised on the python-ideas mailing list (https://mail.python.org/mailman/listinfo/python-ideas) before opening an issue on the bug tracker. -- Jerry From harrismh777 at gmail.com Thu Feb 27 10:23:32 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 07:23:32 -0800 (PST) Subject: posting code snippets In-Reply-To: References: Message-ID: <530bbabb-488b-46e8-82d3-3232baec6f75@googlegroups.com> On Thursday, February 27, 2014 9:01:50 AM UTC-6, Jerry Hill wrote: > -- > > Jerry Thanks guys, perfect. 'preciate it! From hendikoy at gmail.com Thu Feb 27 10:29:28 2014 From: hendikoy at gmail.com (YE SHANG) Date: Thu, 27 Feb 2014 07:29:28 -0800 (PST) Subject: How to run multiple virtualenv in product server Message-ID: I'm starting to learn virtualenv, I wonder how run python project developed in virtualenv. Here is my situation, there is a server we can access with a common user name and password, there are many py scripts wrote by different people on this server. If I develop my python project with virtualenv, could I run it in product server?? From harrismh777 at gmail.com Thu Feb 27 10:42:37 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 07:42:37 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> Message-ID: <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> On Thursday, February 27, 2014 8:42:55 AM UTC-6, Oscar Benjamin wrote: > > Some points: Thanks so much... you have clarified some things I was struggling with... > 1) Why have you committed the code as a .tar.gz file? um, to save space... well, I know its tiny, but its just a habit I have... 5kb instead of 25kb... > 2) This function is not such a good idea: > > def D(numform): > return Decimal(str(numform)) The reason for this is not for strings, but for float literals. All of my functions may take a float literal and things still work, because the D(float) function converts the float literal to a string, which is then passed to the Decimal constructor. so... this works sqrt(0.1) or, sqrt(2.01) Without the D() function float literals may not be passed to the Decimal because it really cannot handle them... 0.1 and others cause it a fit... is there another way to do what I'm looking for here..? > 3) In many places you've written code like this: > > prec=dscale(getcontext().prec +7) > sqr = (D(x).sqrt()).__round__(prec) > retscale=dscale(prec) > The preferred way is: > with localcontext() as ctx: > ctx.prec += 7 > sqr = round(D(x).sqrt(), prec) Thanks... > i.e. use a context manager to restore the context even if an error > occurs and use the round builtin rather than the dunder method. This has confused me, because when I look into the module help text I don't see roun() all I see is __round__(...) how do I know when the round() method exists vs. __round__(...) ?? > 4) You shouldn't be using round/__round__ for precision rounding: it > uses decimal places rather than significant figures. If you want to > round to context precision just use unary +. i.e.: > return +sqr whoohoo! thank you. > 5) The Decimal.sqrt method already rounds to context precision. > There's no need to compute in higher precision and then round it > yourself (in fact you're invalidating the correctness of the rounding > by double-rounding like this). So really it's just: > def sqrt(x): > return Decimal(x).sqrt() ok... > > 6) You should organise it in such a way that you're not progressively > increasing the precision each time one function calls another. right... well, and if you look at the calls to my __atan__ funcs I am assuming that they are still in the context of the calling func atan().... right...? so no need to even have the bump up in prec there. > > Oscar thanks Oscar, I really appreciate your comments marcus From python.list at tim.thechases.com Thu Feb 27 10:56:06 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 Feb 2014 09:56:06 -0600 Subject: posting code snippets In-Reply-To: References: Message-ID: <20140227095606.49a3dde5@bigbox.christie.dr> On 2014-02-27 04:13, Mark H. Harris wrote: > are there rules here about posting code snippets, or length > considerations, and so forth? Seems like there was a place to share > code snips outside of the message area? This is the internet, so you're welcome to post code as you please. However, be aware that - if it's on an external site, lots of potential respondants will shrug with an "I ain't got time for that" or assume that the code-pasting site won't keep the content around (possibly making answers useless/contextless in a couple years) and skip it - if it's inline but too long, lots of potential respondants will shrug with an "I ain't got time for that" and skip it, or flame you for filling their mailbox with junk People here on the list generally enjoy helping where they can, but are more likely to do so if you've made it as easy possible. So SSCCEs (as Chris & Jerry mentioned) are your best hope of getting a useful & friendly reply :-) -tkc From rosuav at gmail.com Thu Feb 27 10:57:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 02:57:53 +1100 Subject: extend methods of decimal module In-Reply-To: <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> Message-ID: On Fri, Feb 28, 2014 at 2:42 AM, Mark H. Harris wrote: >> 1) Why have you committed the code as a .tar.gz file? > > um, to save space... well, I know its tiny, but its just a habit I have... 5kb instead of 25kb... When you commit changes, though, it has to treat it as a completely changed binary file - utterly opaque, and it destroys your space savings too. Normal source code diffs are tiny, and they're readable. Check out the history of this file; you can easily see every change I've made: https://github.com/Rosuav/ExceptExpr/commits/master/find_except_expr.py Click on any commit to see what happened there. It's hard to do that with .tar.gz blobs. ChrisA From eric.jacoboni at gmail.com Thu Feb 27 11:01:39 2014 From: eric.jacoboni at gmail.com (Eric Jacoboni) Date: Thu, 27 Feb 2014 17:01:39 +0100 Subject: Tuples and immutability Message-ID: Hi, I'm using Python 3.3 and i have a problem for which i've still not found any reasonable explanation... >>> a_tuple = ("spam", [10, 30], "eggs") >>> a_tuple[1] += [20] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Ok... I accept this message as += is a reassignment of a_tuple[1] and a tuple is immutable... But, then, why a_tuple is still modified? >>> a_tuple ('spam', [10, 30, 20], 'eggs') I get a TypeError for an illegal operation, but this operation is still completed? From zachary.ware+pylist at gmail.com Thu Feb 27 11:13:30 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 27 Feb 2014 10:13:30 -0600 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 10:01 AM, Eric Jacoboni wrote: > Hi, > > I'm using Python 3.3 and i have a problem for which i've still not found > any reasonable explanation... > >>>> a_tuple = ("spam", [10, 30], "eggs") >>>> a_tuple[1] += [20] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > Ok... I accept this message as += is a reassignment of a_tuple[1] and a > tuple is immutable... > > But, then, why a_tuple is still modified? > >>>> a_tuple > ('spam', [10, 30, 20], 'eggs') > > I get a TypeError for an illegal operation, but this operation is still > completed? You're not the first person to have this question :) http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works -- Zach From rosuav at gmail.com Thu Feb 27 11:14:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 03:14:08 +1100 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Fri, Feb 28, 2014 at 3:01 AM, Eric Jacoboni wrote: > I'm using Python 3.3 and i have a problem for which i've still not found > any reasonable explanation... > >>>> a_tuple = ("spam", [10, 30], "eggs") >>>> a_tuple[1] += [20] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > Ok... I accept this message as += is a reassignment of a_tuple[1] and a > tuple is immutable... > > But, then, why a_tuple is still modified? > >>>> a_tuple > ('spam', [10, 30, 20], 'eggs') > > I get a TypeError for an illegal operation, but this operation is still > completed? This is a common confusion. The += operator does two things. First, it asks the target to please do an in-place addition of the other operand. Then, it takes whatever result the target gives back, and assigns it back into the target. So with a list, it goes like this: >>> foo = [10, 30] >>> foo.__iadd__([20]) [10, 30, 20] >>> foo = _ Note that the second step returned a three-element list. Then the += operator stuffs that back into the source. In the case of a list, it does that addition by extending the list, and then returning itself. The putting-back-into-the-target step fails with a tuple, because a tuple's members can't be reassigned. But the list has already been changed by that point. So, when you go to look at it, you see a changed list. You can call on this behaviour more safely by using the append() or extend() methods. >>> a_tuple = ("spam", [10, 30], "eggs") >>> a_tuple[1].extend([20]) >>> a_tuple ('spam', [10, 30, 20], 'eggs') >>> a_tuple = ("spam", [10, 30], "eggs") >>> a_tuple[1].append(20) >>> a_tuple ('spam', [10, 30, 20], 'eggs') (append will add one more element, extend is roughly the same as you had). Then you're not trying to assign to the tuple, but you're still mutating the list. Hope that helps! ChrisA From marko at pacujo.net Thu Feb 27 11:19:09 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 27 Feb 2014 18:19:09 +0200 Subject: Tuples and immutability References: Message-ID: <87a9dczfya.fsf@elektro.pacujo.net> Eric Jacoboni : >>>> a_tuple[1] += [20] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment > > [...] > > But, then, why a_tuple is still modified? That's because the += operator 1. modifies the list object in place 2. tries to replace the tuple slot with the list (even though the list hasn't changed) It's Step 2 that raises the exception, but the damage has been done already. One may ask why the += operator modifies the list instead of creating a new object. That's just how it is with lists. BTW, try: >>> a_tuple[1].append(20) >>> a_tuple[1].extend([20]) Try also: >>> a_tuple[1] = a_tuple[1] Marko From oscar.j.benjamin at gmail.com Thu Feb 27 11:24:23 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 27 Feb 2014 16:24:23 +0000 Subject: extend methods of decimal module In-Reply-To: <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> Message-ID: On 27 February 2014 15:42, Mark H. Harris wrote: > On Thursday, February 27, 2014 8:42:55 AM UTC-6, Oscar Benjamin wrote: > >> >> Some points: > > Thanks so much... you have clarified some things I was struggling with... > >> 1) Why have you committed the code as a .tar.gz file? > > um, to save space... well, I know its tiny, but its just a habit I have... 5kb instead of 25kb... It made it awkward for me to see the code you were referring to. In a separate thread you asked about how to share code samples. These days it's common practice to host code somewhere it can be viewed from a browser. This means that I can do things like link to a line in Chris' code: https://github.com/Rosuav/ExceptExpr/blob/master/examples.py#L169 There are many other reasons (as mentioned by Chris) why committing a binary archive instead of just the plain old files is a generally bad idea with standard version control systems. A relevant one is that every change you make to your code, even if you only change 2 lines will require an additional 5kb of space to store the new .tar.gz file alongside the old rather than 200 bytes or whatever it is to store the diff of the code files. >> 2) This function is not such a good idea: >> >> def D(numform): >> return Decimal(str(numform)) > > The reason for this is not for strings, but for float literals. All of my functions may take a float literal and things still work, because the D(float) function converts the float literal to a string, which is then passed to the Decimal constructor. so... this works sqrt(0.1) or, sqrt(2.01) Without the D() function float literals may not be passed to the Decimal because it really cannot handle them... 0.1 and others cause it a fit... is there another way to do what I'm looking for here..? I think you're misunderstanding what's going on: >>> from decimal import Decimal as D >>> D(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') There is no binary floating point value that is exactly equal to the mathematical number 0.1. So when you write 0.1 in Python the number is rounded to the nearest binary floating point number. When you create a Decimal from a float it will create a Decimal with the *exact* same value that the float had. That's exactly what you're seeing above. When you print a float normally it pretends to have the value 0.1 but that's really a lie: >>> 0.1 # There is no float with the true value 0.1!!!!! 0.1 >>> 0.1 == D('0.1') False When you convert a float to a string it does not show the exact value of the float but rather a rounded, shortened decimal form. By converting float->str->Decimal you are introducing unnecessary rounding. The Decimal constructor deliberately never rounds its inputs and every float can be represented as a Decimal with a finite number of digits. So Decimal(float) is exact but your D function is not. It is precisely the fact that binary floating point cannot represent seemingly simple non-integer decimal numbers like 0.1 that leads to the creation of the decimal module. But why would anyone pass a float into one of your dmath functions since they're surely much slower than the math module? The main reason that I can imagine is that they would like a really accurate result in which case rounding all floats on input is unacceptable. > This has confused me, because when I look into the module help text I don't see roun() all I see is > __round__(...) how do I know when the round() method exists vs. __round__(...) ?? The round builtin function calls __round__ on any object. Dunder methods are not supposed to be called directly. Oscar From eric.jacoboni at gmail.com Thu Feb 27 11:27:12 2014 From: eric.jacoboni at gmail.com (Eric Jacoboni) Date: Thu, 27 Feb 2014 17:27:12 +0100 Subject: Tuples and immutability In-Reply-To: References: Message-ID: Le 27/02/2014 17:13, Zachary Ware a ?crit : > > You're not the first person to have this question :) > > http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works > Oh yes, i was aware of this explanation (thanks to Chris for his answer, too)... and that's why i wrote "reasonable" :) I know i should use append() or extend() and i understand the tricky implications of += in this context. But, imho, it's far from being a intuitive result, to say the least. From rosuav at gmail.com Thu Feb 27 11:33:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 03:33:20 +1100 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Fri, Feb 28, 2014 at 3:27 AM, Eric Jacoboni wrote: > But, imho, it's far from being a intuitive result, to say the least. It's unintuitive, but it's a consequence of the way += is defined. If you don't want assignment, don't use assignment :) ChrisA From zachary.ware+pylist at gmail.com Thu Feb 27 11:47:09 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 27 Feb 2014 10:47:09 -0600 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 10:27 AM, Eric Jacoboni wrote: > Le 27/02/2014 17:13, Zachary Ware a ?crit : >> >> You're not the first person to have this question :) >> >> http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works >> > > Oh yes, i was aware of this explanation (thanks to Chris for his answer, > too)... and that's why i wrote "reasonable" :) > I know i should use append() or extend() and i understand the tricky > implications of += in this context. But, imho, it's far from being a > intuitive result, to say the least. Well, once you understand what's actually going on, it's the result that you should expect. The FAQ entry I linked to exists to help people get to that point. To answer your specific questions: > But, then, why a_tuple is still modified? It is not. a_tuple is still "('spam', , 'eggs')", exactly the same before and after the attempted "a_tuple[1] += [20]". The change is internal to . > I get a TypeError for an illegal operation, but this operation is still > completed? Half completed. The extension of happened as expected, but the assignment of to a_tuple[1] didn't. It looks like it did, though, because the assignment was just trying to assign the same object to the same index. -- Zach From tjreedy at udel.edu Thu Feb 27 12:07:17 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Feb 2014 12:07:17 -0500 Subject: extend methods of decimal module In-Reply-To: <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> Message-ID: On 2/27/2014 7:07 AM, Mark H. Harris wrote: > Oh, and one more thing... whoever is doing the work on IDLE these > days, nice job! It is stable, reliable, and just works/ > appreciate it! As one of 'them', thank you for the feedback. There are still some bugs, but I hit them seldom enough that I am now looking at enhancement issues. -- Terry Jan Reedy From rosuav at gmail.com Thu Feb 27 12:48:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 04:48:42 +1100 Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> Message-ID: On Fri, Feb 28, 2014 at 4:07 AM, Terry Reedy wrote: > On 2/27/2014 7:07 AM, Mark H. Harris wrote: > >> Oh, and one more thing... whoever is doing the work on IDLE these >> days, nice job! It is stable, reliable, and just works/ >> appreciate it! > > > As one of 'them', thank you for the feedback. There are still some bugs, but > I hit them seldom enough that I am now looking at enhancement issues. Aside from having to be careful not to paste in a non-BMP character (a Tk limitation, I believe, and currently being tracked at issue 13153), I'm pretty happy with IDLE too. It's my standard way to fiddle with Python code. Easier to use than the inbuilt interactive mode, as Alt-P will recall an entire block command, rather than one line at a time. So, I echo that sentiment of thanks. :) ChrisA From ned at nedbatchelder.com Thu Feb 27 12:54:44 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Thu, 27 Feb 2014 12:54:44 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: On 2/27/14 8:24 AM, Mark H. Harris wrote: > > As others have noted, python does not have a 'variable' concept (references to objects instead) and so your question is a little ambiguous. > Mark, thanks for helping to answer the OP's question. We've covered (in depth) in the rest of this thread, that Python *does* have the concept of a variable, it just behaves differently than some other popular programming languages (but exactly the same as some other popular programming languages!) -- Ned Batchelder, http://nedbatchelder.com From davea at davea.name Thu Feb 27 12:59:54 2014 From: davea at davea.name (Dave Angel) Date: Thu, 27 Feb 2014 12:59:54 -0500 (EST) Subject: How to run multiple virtualenv in product server References: Message-ID: YE SHANG Wrote in message: > I'm starting to learn virtualenv, I wonder how run python project developed in virtualenv. > > Here is my situation, there is a server we can access with a common user name and password, there are many py scripts wrote by different people on this server. > > If I develop my python project with virtualenv, could I run it in product server?? > There are many kinds of servers, so we can only guess. Assuming you're logging in with ssh, it would depend on your permissions on your particular account. -- DaveA From jsutar at gmail.com Thu Feb 27 15:07:56 2014 From: jsutar at gmail.com (Jignesh Sutar) Date: Thu, 27 Feb 2014 20:07:56 +0000 Subject: Extracting parts of string between anchor points Message-ID: I've kind of got this working but my code is very ugly. I'm sure it's regular expression I need to achieve this more but not very familiar with use regex, particularly retaining part of the string that is being searched/matched for. Notes and code below to demonstrate what I am trying to achieve. Any help, much appreciated. Examples=["Test1A", "Test2A: Test2B", "Test3A: Test3B -:- Test3C", ""] # Out1 is just itself unless if it is empty # Out2 is everything left of ":" (including ":" i.e. part A) and right of "-:-" (excluding "-:-" i.e. part C) # If text doesn't contain "-:-" then return text itself as it is # Out3 is everything right of "-:-" (excluding "-:-" i.e. part C) # If text doesn't contain "-:-" but does contains ":" then return part B only # If it doesn't contain ":" then return itself (unless if it empty then "None") for i,s in enumerate(Examples,start=1): Out1=s if len(s)>0 else "Empty" Out2=s[:s.find(":")+3] + s[s.find("-:-")+5:] if s.find("-:-")>0 else s.strip() if len(s) else "Empty" Out3=s[s.find("-:-")+4:] if s.find("-:-")>0 else s[s.find(":")+1:].strip() if s.find(":")>0 and len(s)!=s.find(":")+1 else s if len(s) else "Empty" print "Item%(i)s <%(s)s> Out1 = %(Out1)s" % locals() print "Item%(i)s <%(s)s> Out2 = %(Out2)s" % locals() print "Item%(i)s <%(s)s> Out3 = %(Out3)s" % locals() Output: Item1 Out1 = Test1A Item1 Out2 = Test1A Item1 Out3 = Test1A Item2 Out1 = Test2A: Test2B Item2 Out2 = Test2A: Test2B Item2 Out3 = Test2B #INCORRECT - Should be "Test2A: Test2B" Item3 Out1 = Test3A: Test3B -:- Test3C Item3 Out2 = Test3A: Test3C Item3 Out3 = Test3C Item4 <> Out1 = Empty Item4 <> Out2 = Empty Item4 <> Out3 = Empty -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Thu Feb 27 16:40:12 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 28 Feb 2014 08:40:12 +1100 Subject: Extracting parts of string between anchor points In-Reply-To: References: Message-ID: <20140227214012.GA74711@cskk.homeip.net> On 27Feb2014 20:07, Jignesh Sutar wrote: > I've kind of got this working but my code is very ugly. I'm sure it's > regular expression I need to achieve this more but not very familiar with > use regex, particularly retaining part of the string that is being > searched/matched for. Regexps are quite useful for very variable text. You're just splitting on ':' and '-:-', which is very easy and does not need a regexp. Avoid regexps if the code can be written easily and readably without them; they are cryptic and fragile. > Notes and code below to demonstrate what I am trying to achieve. Any help, > much appreciated. > > Examples=["Test1A", > "Test2A: Test2B", > "Test3A: Test3B -:- Test3C", ""] Minor remark. Class names tend to have leading uppercase names, like Foo. ordinary variables tend to have lower case names, like foo. A habit to get into - it maes your code more readable for everyone else. Code suggestions below the code... > # Out1 is just itself unless if it is empty > # Out2 is everything left of ":" (including ":" i.e. part A) and right of > "-:-" (excluding "-:-" i.e. part C) > # If text doesn't contain "-:-" then return text itself as it is > # Out3 is everything right of "-:-" (excluding "-:-" i.e. part C) > # If text doesn't contain "-:-" but does contains ":" then return part B > only > # If it doesn't contain ":" then return itself (unless if it empty then > "None") > > for i,s in enumerate(Examples,start=1): > Out1=s if len(s)>0 else "Empty" > Out2=s[:s.find(":")+3] + s[s.find("-:-")+5:] if s.find("-:-")>0 else > s.strip() if len(s) else "Empty" > Out3=s[s.find("-:-")+4:] if s.find("-:-")>0 else > s[s.find(":")+1:].strip() if s.find(":")>0 and len(s)!=s.find(":")+1 else s > if len(s) else "Empty" > print "Item%(i)s <%(s)s> Out1 = %(Out1)s" % locals() > print "Item%(i)s <%(s)s> Out2 = %(Out2)s" % locals() > print "Item%(i)s <%(s)s> Out3 = %(Out3)s" % locals() I would be parsing the string using "split", progressively. Example (completely untested): # initialise all parts because we will only set the parts # below if they appear in the text out1, out2, out3 = '', '', '' words = s.split(':', 1) if words: # arrays are false if empty, true if non-empty out1 = words.pop(0) # there is a second part - split it on "-:-" if words: words = words[0].split('-:-', 1) out2 = words.pop(0) if words: out3 = words.pop(0) # personally I would leave out1 etc as empty strings and only _print_ the word "Empty" # but if you really want to mangle the variables themselves: if not out1: out1 = "Empty" if not out2: out2 = "Empty" if not out3: out3 = "Empty" Notice that by using split we do not need to do any funny string index arithmetic. Cheers, -- Cameron Simpson You can't have everything... where would you put it? - Charles Robinson, cr0100 at medtronic.com From python.list at tim.thechases.com Thu Feb 27 16:45:35 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 Feb 2014 15:45:35 -0600 Subject: Extracting parts of string between anchor points In-Reply-To: References: Message-ID: <20140227154535.6e921956@bigbox.christie.dr> On 2014-02-27 20:07, Jignesh Sutar wrote: > I've kind of got this working but my code is very ugly. I'm sure > it's regular expression I need to achieve this more but not very > familiar with use regex, particularly retaining part of the string > that is being searched/matched for. While I suppose this could be done with regular expressions, in this case it seems like a bit of overkill. Just to show that it can be done, I give you this monstrosity: >>> examples = ["Test1A", ... "Test2A: Test2B", ... "Test3A: Test3B -:- Test3C", ... ""] >>> import re >>> r = re.compile(r"^([^:]*)(?::((?:(?!-:-).)*)(?:-:-(.*))?)?") >>> [r.match(s).groups() for s in examples] [('Test1A', None, None), ('Test2A', ' Test2B', None), ('Test3A', ' Test3B ', ' Test3C'), ('', None, None)] You'd still have to strip those values that are strings, but that gets you the core of what you're seeking. You do omit several edge cases: to_test = [ "Test4A -:- Test4D", # no ":" "Test4A : Test4B : Test4C -:- Test4D", # 2x ":" "Test4A : Test4B -:- Test4C -:- Test4D", # 2x "-:-" ] what should Out2 and Out3 be in those particular instances? > Notes and code below to demonstrate what I am trying to achieve. > Any help, much appreciated. > > Examples=["Test1A", > "Test2A: Test2B", > "Test3A: Test3B -:- Test3C", ""] > > # Out1 is just itself unless if it is empty > # Out2 is everything left of ":" (including ":" i.e. part A) and > right of "-:-" (excluding "-:-" i.e. part C) > # If text doesn't contain "-:-" then return text itself as it is > # Out3 is everything right of "-:-" (excluding "-:-" i.e. part C) > # If text doesn't contain "-:-" but does contains ":" then > return part B only > # If it doesn't contain ":" then return itself (unless if it > empty then "None") I believe you want something like examples = [ ("", (None, None, None)), ("Test1A", ("Test1A", None, None)), ("Test2A: Test2B", ("Test2A", "Test2B", None)), ("Test3A: Test3B -:- Test3C", ("Test3A", "Test3B", "Test3C")), # three test-cases with no provided expectations ("Test4A -:- Test4B", None), ("Test5A : Test5B : Test5C -:- Test5D", None), ("Test6A : Test6B -:- Test6C -:- Test6D", None), ] def clean(t): return [ s.strip() if s is not None else s for s in t ] for s, expected in examples: out1 = out2 = out3 = None if ":" in s: if "-:-" in s: left, _, out3 = clean(s.partition("-:-")) if ":" in left: out1, _, out2 = clean(left.partition(":")) else: out1 = left else: out1, _, out2 = clean(s.partition(":")) else: if s: out1 = s result = (out1, out2, out3) if expected is not None: if result != expected: print("FAIL: %r got %r, not %r" % (s, result, expected)) else: print("PASS: %r got %r" % (s, result)) else: print("UNKN: %r got %r" % (s, result)) which gives me PASS: '' got (None, None, None) PASS: 'Test1A' got ('Test1A', None, None) PASS: 'Test2A: Test2B' got ('Test2A', 'Test2B', None) PASS: 'Test3A: Test3B -:- Test3C' got ('Test3A', 'Test3B', 'Test3C') UNKN: 'Test4A -:- Test4B' got ('Test4A', None, 'Test4B') UNKN: 'Test5A : Test5B : Test5C -:- Test5D' got ('Test5A', 'Test5B : Test5C', 'Test5D') UNKN: 'Test6A : Test6B -:- Test6C -:- Test6D' got ('Test6A', 'Test6B', 'Test6C -:- Test6D') I find that a good bit more readable than the atrocity of that regular expression. -tkc From prometheus235 at gmail.com Thu Feb 27 16:47:48 2014 From: prometheus235 at gmail.com (Nick Timkovich) Date: Thu, 27 Feb 2014 15:47:48 -0600 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 10:33 AM, Chris Angelico wrote: > On Fri, Feb 28, 2014 at 3:27 AM, Eric Jacoboni > wrote: > > But, imho, it's far from being a intuitive result, to say the least. > > It's unintuitive, but it's a consequence of the way += is defined. If > you don't want assignment, don't use assignment :) > > ChrisA > Where is `.__iadd__()` called outside of `list += X`? If the only difference from `.extend()` is that it returns `self`, but the list was already modified anyway, why bother with reassignment? -------------- next part -------------- An HTML attachment was scrubbed... URL: From balijanosdaniel at gmail.com Thu Feb 27 14:16:58 2014 From: balijanosdaniel at gmail.com (=?ISO-8859-1?Q?D=E1niel_Bali?=) Date: Thu, 27 Feb 2014 19:16:58 +0000 Subject: Python VM university project Message-ID: Hello! I hope this is the right place to ask about this, sorry if it's inappropriate. At our University we have to do a project for a class called Virtual Execution Environments. We decided that it would be great to work with/on the Python VM. The project has to revolve around one of the following topics: Analysis of Internal Mechanisms, Implementation, Relevant Evaluation, Advanced Usage in a Specific Scenario, Extension. Does anybody have an idea for such a project, that would be interesting/beneficial to explore? We have a group of 3 master's students and the project is for a single semester. Best regards, Daniel Bali -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Feb 27 16:52:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 08:52:48 +1100 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Fri, Feb 28, 2014 at 8:47 AM, Nick Timkovich wrote: > On Thu, Feb 27, 2014 at 10:33 AM, Chris Angelico wrote: >> >> On Fri, Feb 28, 2014 at 3:27 AM, Eric Jacoboni >> wrote: >> > But, imho, it's far from being a intuitive result, to say the least. >> >> It's unintuitive, but it's a consequence of the way += is defined. If >> you don't want assignment, don't use assignment :) >> >> ChrisA > > > Where is `.__iadd__()` called outside of `list += X`? If the only > difference from `.extend()` is that it returns `self`, but the list was > already modified anyway, why bother with reassignment? Not everything handles += that way. You can't mutate the integer 5 into 7 because someone had 5 in x and wrote "x += 2". So it has to reassign. Actually, integers just don't define __iadd__, but the principle applies. ChrisA From tjreedy at udel.edu Thu Feb 27 16:57:29 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Feb 2014 16:57:29 -0500 Subject: Deepcopying a byte string is quicker than copying it - problem? In-Reply-To: References: Message-ID: On 2/27/2014 4:02 AM, Frank Millman wrote: >> However, deepcopying a byte string is orders of magnitude quicker than >> copying it. >> >> Actually, looking closer, it is the 'copy' that is slow, not the >> 'deepcopy' that is quick.. > I have created an issue on the bug tracker - > http://bugs.python.org/issue20791 Fixed, 12 hours later. -- Terry Jan Reedy From python.list at tim.thechases.com Thu Feb 27 17:01:51 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 27 Feb 2014 16:01:51 -0600 Subject: Extracting parts of string between anchor points In-Reply-To: <20140227154535.6e921956@bigbox.christie.dr> References: <20140227154535.6e921956@bigbox.christie.dr> Message-ID: <20140227160151.725e0287@bigbox.christie.dr> On 2014-02-27 15:45, Tim Chase wrote: > >>> r = re.compile(r"^([^:]*)(?::((?:(?!-:-).)*)(?:-:-(.*))?)?") If you want to compare both the re method and the string method, here's a test-harness to play with: import re examples = [ ("", (None, None, None)), ("Test1A", ("Test1A", None, None)), ("Test2A: Test2B", ("Test2A", "Test2B", None)), ("Test3A: Test3B -:- Test3C", ("Test3A", "Test3B", "Test3C")), ("Test4A -:- Test4B", None), ("Test5A : Test5B : Test5C -:- Test5D", None), ("Test6A : Test6B -:- Test6C -:- Test6D", None), ] splitter_re = re.compile(r"^([^:]*)(?::((?:(?!-:-).)*)(?:-:-(.*))?)?") def clean(t): return [ s.strip() if s else None for s in t ] def splitter1(s): "using regexp" m = splitter_re.match(s) if m: return tuple(clean(m.groups())) else: return (None, None, None) def splitter2(s): "using string methods" out1 = out2 = out3 = None if ":" in s: if "-:-" in s: left, _, out3 = clean(s.partition("-:-")) if ":" in left: out1, _, out2 = clean(left.partition(":")) else: out1 = left else: out1, _, out2 = clean(s.partition(":")) else: if s: out1 = s return (out1, out2, out3) for method in (splitter1, splitter2): print("") print(method.__doc__) print("=" * len(method.__doc__)) for s, expected in examples: result = method(s) if expected is not None: if result != expected: print("FAIL: %r got %r, not %r" % (s, result, expected)) else: print("PASS: %r got %r" % (s, result)) else: print("UNKN: %r got %r" % (s, result)) Note the differences in Test4. -tkc From ben+python at benfinney.id.au Thu Feb 27 17:15:16 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Feb 2014 09:15:16 +1100 Subject: posting code snippets References: Message-ID: <85ppm8nqx7.fsf@benfinney.id.au> "Mark H. Harris" writes: > Its been too long... can't remember... are there rules here about > posting code snippets, or length considerations, and so forth? Post your code in-line with your message. This is for the sake of the people whose time you're requesting, and of later readers who will find the thread when searching the archives ? URLs to snippets are likely to be invalid later. Since you'll be posting the code in-line, make sure it's short. Since it'll be short, make sure it's complete ? we should need nothing else to run the code and expect to see the same behaviour you're seeing. Since you'll be making it short, complete, and still demonstrating the behaviour, you may even get the result that you understand the cause of the behaviour before posting it. Everyone wins! :-) For these and other reasons, ensure the example you're showing us is a Simple, Self-Contained, Complete Example which demonstrates the issue you're asking about. > A related question, is there a python repository for uploading py > files, patches, suggestions, etc? The place to contribute patches and suggestions is to the project that maintains whatever it is your patch or suggestion is for. What code project are you wanting to contribute to? Look to the home page of that project, and see what resources it has for ?Developers? etc. From ian.g.kelly at gmail.com Thu Feb 27 17:18:01 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 27 Feb 2014 15:18:01 -0700 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Thu, Feb 27, 2014 at 2:47 PM, Nick Timkovich wrote: > On Thu, Feb 27, 2014 at 10:33 AM, Chris Angelico wrote: >> >> On Fri, Feb 28, 2014 at 3:27 AM, Eric Jacoboni >> wrote: >> > But, imho, it's far from being a intuitive result, to say the least. >> >> It's unintuitive, but it's a consequence of the way += is defined. If >> you don't want assignment, don't use assignment :) >> >> ChrisA > > > Where is `.__iadd__()` called outside of `list += X`? If the only > difference from `.extend()` is that it returns `self`, but the list was > already modified anyway, why bother with reassignment? x += y is meant to be equivalent, except possibly in-place and more efficient, than x = x + y. If you skip the assignment, and that assignment is meaningful to whatever the left side may be (e.g. assigning to a descriptor or something that invokes __setitem__ or __setattr__), then the operation is not equivalent. From jcasale at activenetwerx.com Thu Feb 27 17:21:31 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Thu, 27 Feb 2014 22:21:31 +0000 Subject: Descriptor type hinting Message-ID: <65f296fa185943a7af247fd0ae61ab4e@exch.activenetwerx.com> How does one satisfy a lint/type checker with the return value of a class method decorated with a descriptor? It returns a dict, and I want the type hinting to suggest this versus the str|unknown its defaults to. Thanks, jlc From rhodri at wildebst.org.uk Thu Feb 27 17:49:16 2014 From: rhodri at wildebst.org.uk (Rhodri James) Date: Thu, 27 Feb 2014 22:49:16 -0000 Subject: Functions help References: Message-ID: On Tue, 25 Feb 2014 02:18:43 -0000, Dennis Lee Bieber wrote: > On Mon, 24 Feb 2014 01:01:15 -0000, "Rhodri James" > > declaimed the following: > > >> >> The function "range" returns the sequence of numbers 1, 2, 3, 4 and 5 >> [*], >> so this has the same effect as if you had typed: >> > Wrong -- it returns the sequence 0, 1, 2, 3, 4... Duh, yes. I do know better than that... -- Rhodri James *-* Wildebeest Herder to the Masses From harrismh777 at gmail.com Thu Feb 27 18:00:45 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 15:00:45 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> Message-ID: <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> On Thursday, February 27, 2014 10:24:23 AM UTC-6, Oscar Benjamin wrote: >>>> from decimal import Decimal as D > >>> D(0.1) > Decimal('0.1000000000000000055511151231257827021181583404541015625') > hi Oscar, well, that's not what I'm doing with my D()... I'm not just making D() mimic Decimal... look inside it... there's a str() call.... consider the following experiment and you'll see what I'm talking about... Decimal does not keep 0.1 as a floating point format (regardless of size) which is why banking can use Decimal without having to worry about the floating formatting issue... in other words, 0.0 is not stored in Decimal as any kind of floating value... its not rounded.... it really is Decimal('0.1'). Ok, so for the experiment: consider this exchange from IDLE: >>> ==================== RESTART == >>> from dmath import * >>> pi = D(piagm(32)) >>> pi Decimal('3.14159265358979323846264338327950') >>> pi * Decimal(.1) Decimal('0.31415926535897934128560682837111') >>> >>> pi * D(.1) Decimal('0.31415926535897932384626433832795') >>> >>> You will notice that Decimal(.1) and my D(.1) work against PI differently... in fact, Decimal(.1) decimates PI.... The reason is that Decimal(.1) stores the erroneous float in the Decimal object including the float error for .1 and D(.1) works correctly because the D(.1) function in my dmath.py first converts the .1 to a string value before handing it to Decimal's constructor(s) Now, try this experiment: again from IDLE and dmath.py >>> ===================== RESTART = >>> from dmath import * >>> pi = D(piagm(32)) >>> pi Decimal('3.14159265358979323846264338327950') >>> >>> pi * Decimal(str(.1)) Decimal('0.31415926535897932384626433832795') >>> >>> pi * D(.1) Decimal('0.31415926535897932384626433832795') >>> You see? All of my functions make certain that when the Decimal objects are created that the string constructor gets called.... so that, in this case, .1 really is 0.1 precisely, not floating format. and take a look at this: >>> ================ RESTART == >>> from dmath import * >>> D(.1) Decimal('0.1') >>> With my dmath D() function the object holds 0.1 precisely... its not the float 0.1 rounded ... shifting gears a bit.... The real reason I pushed a commit of a gzip tarball to code.google is because I've never used code.google before (thought I'd give it a try) and I didn't realize that its only pull / download is a ZIP... so I am going to take your advice and remove the tarballs and just put the code up there... if I can get my GIT to work ... its GIVing me fits (probably because I don't have it configured right on this system. Thanks for the discussion... its helping me get this stuff into my brain, and its giving me a chance to discuss what's at issue between floats and Decimal. kind regards, marcus From harrismh777 at gmail.com Thu Feb 27 18:13:26 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 15:13:26 -0800 (PST) Subject: posting code snippets In-Reply-To: References: Message-ID: On Thursday, February 27, 2014 4:15:16 PM UTC-6, Ben Finney wrote: > > Post your code in-line with your message. This is for the sake of the > people whose time you're requesting, and of later readers who will find > the thread when searching the archives -- URLs to snippets are likely to > be invalid later. > Thanks everyone for the great responses.... will do. I read this group frequently, but have not posted for quite some time for time and focus reasons. To tell you just how long, well, my isp withdrew the post service (nntp) from their server at end of 2011... and I didn't notice till now! ha! So, I'm not using seamonkey any longer... using google groups/ and that has been a fit to get used to, but I'm making progress. :-} Thanks again From harrismh777 at gmail.com Thu Feb 27 18:29:01 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 15:29:01 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> Message-ID: <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> On Thursday, February 27, 2014 11:54:44 AM UTC-6, Ned Batchelder wrote: > Mark, thanks for helping to answer the OP's question. We've covered (in > depth) in the rest of this thread, that Python *does* have the concept > of a variable, it just behaves differently than some other popular > programming languages (but exactly the same as some other popular > programming languages!) > I do not disagree. I've had the same discussion over the years since using python, and often its a rope soaking contest... some folks get so enamored with the 'way' it works under the covers that they forget how people think about it as they are trying (as normal people) to use the language (instead of BASIC). So, yeah, thinking about variables is just not going away. I finally decided (in my own head) that I would completely give up on the 'variable' concept (intellectually) and help folks try to understand references and reference counting. Knowing that A points to an int, and that B=A, now B points to the VERY SAME int... they are references pointing to the same piece of memory. And of course we want new folks to understand the issue of: A==B True A is B False ..... and WHY that is or isn't.... :) it just helps to get the 'variable' idea out of here... it really is something completely different in python. Thanks for the note, kind regards, marcus From xpysol at gmail.com Thu Feb 27 18:43:48 2014 From: xpysol at gmail.com (Wolfgang) Date: Thu, 27 Feb 2014 15:43:48 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> Message-ID: On Friday, February 28, 2014 12:00:45 AM UTC+1, Mark H. Harris wrote: > On Thursday, February 27, 2014 10:24:23 AM UTC-6, Oscar Benjamin wrote: > >>>> from decimal import Decimal as D > > > >>> D(0.1) > > > Decimal('0.1000000000000000055511151231257827021181583404541015625') > > > > hi Oscar, well, that's not what I'm doing with my D()... I'm not just making D() mimic Decimal... look inside it... there's a str() call.... consider the following experiment and you'll see what I'm talking about... > >>> from dmath import * > >>> pi = D(piagm(32)) > >>> pi > Decimal('3.14159265358979323846264338327950') > >>> pi * Decimal(.1) > Decimal('0.31415926535897934128560682837111') > >>> > >>> pi * D(.1) > Decimal('0.31415926535897932384626433832795') > >>> > >>> > You will notice that Decimal(.1) and my D(.1) work against PI differently... in fact, Decimal(.1) decimates PI.... > The reason is that Decimal(.1) stores the erroneous float in the Decimal object including the float error for .1 and D(.1) works correctly because the D(.1) function in my dmath.py first converts the .1 to a string value before handing it to Decimal's constructor(s) What Oscar tried to make clear is that Decimal(.1) does not store an "erroneous" float in the Decimal object, but an "honest" one. Maybe this becomes clearer with calculations instead of literal values: >>> 1000000000000000055511151231257827021181583404541015625/10**55 0.1 now try: D(1000000000000000055511151231257827021181583404541015625/10**55) vs Decimal(1000000000000000055511151231257827021181583404541015625/10**55) for an example that it is not better, in general, to go through the str()-mediated rounding you are doing. Of course, if the user *intended* that float(.1) to mean exactly 0.1 then your D class does a good job at guessing, but only then. The Decimal class, on the other hand, leaves the choice to the user as you are illustrating perfectly in your own example below: > Now, try this experiment: again from IDLE and dmath.py > > >>> from dmath import * > >>> pi = D(piagm(32)) > >>> pi > Decimal('3.14159265358979323846264338327950') > >>> > >>> pi * Decimal(str(.1)) > Decimal('0.31415926535897932384626433832795') > >>> > >>> pi * D(.1) > Decimal('0.31415926535897932384626433832795') see? Decimal(.1) gives the exact representation of the float, but Decimal('.1') is the way to get your D()'s default behavior. > You see? All of my functions make certain that when the Decimal objects are created that the string constructor gets called.... so that, in this case, .1 really is 0.1 precisely, not floating format. Yes, just that this is almost never what your users will want to happen ... The Decimal constructor is really well designed, so stick to it ! Best, Wolfgang From oscar.j.benjamin at gmail.com Thu Feb 27 18:50:55 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 27 Feb 2014 23:50:55 +0000 Subject: extend methods of decimal module In-Reply-To: <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> Message-ID: On 27 February 2014 23:00, Mark H. Harris wrote: > On Thursday, February 27, 2014 10:24:23 AM UTC-6, Oscar Benjamin wrote: > >>>>> from decimal import Decimal as D >> >>> D(0.1) >> Decimal('0.1000000000000000055511151231257827021181583404541015625') > > hi Oscar, well, that's not what I'm doing with my D()... I'm not just making D() mimic Decimal... look inside it... there's a str() call.... consider the following experiment and you'll see what I'm talking about... I understood what your code is doing but I'm not sure if you do. Calling str on a float performs an inexact binary to decimal conversion. Calling Decimal on a float performs an exact binary to decimal conversion. Your reasoning essentially assumes that every float should be interpreted as an approximate representation for a nearby decimal value. This is probably true if the user wrote "a = 0.1" but is generally not true in the kind of numeric code that is likely to be using the transcendental functions defined in your dmath module. Calling Decimal(str(float)) introduces entirely avoidable inaccuracy in your code when the primary purpose of your code as accuracy! Oscar From denismfmcmahon at gmail.com Thu Feb 27 19:55:01 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 28 Feb 2014 00:55:01 +0000 (UTC) Subject: Extracting parts of string between anchor points References: Message-ID: On Thu, 27 Feb 2014 20:07:56 +0000, Jignesh Sutar wrote: > I've kind of got this working but my code is very ugly. I'm sure it's > regular expression I need to achieve this more but not very familiar > with use regex, particularly retaining part of the string that is being > searched/matched for. > > Notes and code below to demonstrate what I am trying to achieve. Any > help, > much appreciated. It seems you have a string which may be split into between 1 and 3 substrings by the presence of up to 2 delimeters, and that if both delimeters are present, they are in a specified order. You have several possible cases which, broadly speaking, break down into 4 groups: (a) no delimiters present (b) delimiter 1 present (c) delimiter 2 present (d) both delimiters present It is important when coding for such scenarios to consider the possible cases that are not specified, as well as the ones that are. For example, consider the string: "" where you have both delims, in sequence, but no other data elements. I believe there are at least 17 possible combinations, and maybe another 8 if you allow for the delims being out of sequence. The code in the file at the url below processes 17 different cases. It may help, or it may confuse. http://www.sined.co.uk/tmp/strparse.py.txt -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Thu Feb 27 20:25:17 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 28 Feb 2014 01:25:17 +0000 (UTC) Subject: Extracting parts of string between anchor points References: Message-ID: On Fri, 28 Feb 2014 00:55:01 +0000, Denis McMahon wrote: > The code in the file at the url below processes 17 different cases. It > may help, or it may confuse. > http://www.sined.co.uk/tmp/strparse.py.txt I added some more cases to it, and then realised that the code could actually be simplified quite a lot. So now it has been. -- Denis McMahon, denismfmcmahon at gmail.com From steve at pearwood.info Thu Feb 27 20:49:10 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 01:49:10 GMT Subject: exec and locals References: <530de8ed$0$29985$c3e8da3$5496439d@news.astraweb.com> <530e8608$0$11113$c3e8da3@news.astraweb.com> <530ec17e$0$11113$c3e8da3@news.astraweb.com> Message-ID: <530feb16$0$11113$c3e8da3@news.astraweb.com> On Fri, 28 Feb 2014 00:29:35 +1300, Gregory Ewing wrote: > Steven D'Aprano wrote: >> On Thu, 27 Feb 2014 16:34:33 +1300, Gregory Ewing wrote: >> >>>Why not just use this version all the time? It should work in both 2.x >>>and 3.x. >> >> Because that's yucky. It's an aesthetic thing: when supported, I want >> the Python interpreter to manage the context manager. > > More yucky than wrapping the Py3 version in an exec? To my way of > thinking, that cancels out any elegance that might have been gained from > using a with-statement. > > Do you really need to use the context manager at all? Could you just > write the try-statement that you would have written in Py2 if you didn't > have a context manager? I don't *have* to do it any particular way, but the way it works now, the version of the inner function (which does eventually get exposed to the caller) is simple with statement wrapping a function call. So for seven of the eight versions of Python supported (2.5 through 3.4) the function is the simplest it can be. Even if the code creating that function is a tiny bit more complex, since it is wrapped inside an exec. For the other two versions (2.4 and 2.5), I have to fall back on a more complex chunk of code. (And yes, it's deliberate that 2.5 gets counted in both groups.) I'm not saying that I have objective reasons for preferring this way over the manual alternative, or at least not *strong* objective reasons. It's mostly subjective. I don't expect to convince you my way is better, and I doubt that you'll convince me your way is better. But if I were to try, I'd put it this way: At a cost of six (by memory) extra lines of code, including one call to exec, I have an inner function which is *guaranteed* to use the exact same semantics and efficiency of a with-statement when possible, because it *is* a with-statement. Any differences between with-statement and my manual handling will only affect 2.4 and sometimes 2.5, rather than everything. The only differences that I know of are insignificant -- the byte-code will be different, there may be trivial performance differences -- but if it turns out to be some meaningful difference, I have three choices: 1) deny that the difference is meaningful; 2) accept that the difference is meaningful, and fix it; or 3) accept that the difference is meaningful, but say that it won't be fixed for 2.4 and 2.5. If I use the same manual handling for all versions, then I don't have that last option, no matter how unlikely it is that I will need it. But really, it's a subjective choice of what feels right to me in this instance. If the body of the with-statement was bigger, or if the feature in question was something else, I might choose a different approach. -- Steven From steve at pearwood.info Thu Feb 27 21:05:36 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 02:05:36 GMT Subject: Descriptor type hinting References: Message-ID: <530feef0$0$11113$c3e8da3@news.astraweb.com> On Thu, 27 Feb 2014 22:21:31 +0000, Joseph L. Casale wrote: > How does one satisfy a lint/type checker with the return value of a > class method decorated with a descriptor? Surely the answer will depend on the linter you are using. Care to tell us, or shall we guess? -- Steven From steve at pearwood.info Thu Feb 27 21:07:20 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 02:07:20 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> Message-ID: <530fef58$0$11113$c3e8da3@news.astraweb.com> On Thu, 27 Feb 2014 15:29:01 -0800, Mark H. Harris wrote: > Knowing that A points to an int, and > that B=A, now B points to the VERY SAME int... they are references > pointing to the same piece of memory. And of course we want new folks to > understand the issue of: A==B > True > A is B > False > ..... and WHY that is or isn't.... If they point to the same piece of memory -- which, by the way, can be moved around if the garbage collector supports it -- then A is B cannot possibly return False. -- Steven From jcasale at activenetwerx.com Thu Feb 27 21:16:53 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Fri, 28 Feb 2014 02:16:53 +0000 Subject: Descriptor type hinting In-Reply-To: <530feef0$0$11113$c3e8da3@news.astraweb.com> References: <530feef0$0$11113$c3e8da3@news.astraweb.com> Message-ID: <06eca272776f47469dd78497ca2467e9@exch.activenetwerx.com> > Surely the answer will depend on the linter you are using. Care to tell > us, or shall we guess? Hey Steven, I am using PyCharm, I have to admit I feel silly on this one. I had a buried assignment that overrode the inferred type. It wasn't until a fresh set of eyes confirmed something was awry and we looked... Add one to the fail list for me. Thanks for taking the time to respond, jlc From harrismh777 at gmail.com Thu Feb 27 21:15:46 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 18:15:46 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> Message-ID: <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> On Thursday, February 27, 2014 5:50:55 PM UTC-6, Oscar Benjamin wrote: > . . . Calling Decimal on a float performs an exact binary to > decimal conversion. Your reasoning essentially assumes that every > float should be interpreted as an approximate representation for a > nearby decimal value. That is the whole point exactly. Yes, the exact binary to decimal conversion for float is the problem precisely. But my solution does not assume any such thing... because the decimal module is "advertised" to support what I'm doing. In other words, decimal correctly builds from a string literal in any case; even intermediary values. Well, the digits past 16 (for a double) aren't valid anyway... and the ones before that (when passed to decimal as a string) get correctly created as a decimal object. But here is the other point... I am not planning on passing *any* of these functions a float... my system that uses dmath uses strings only, or decimals. str(Decimal) works, as does Decimal(str()). So, I'm not really interested in floats at all... but, and here's the big BUT, I'm expecting folks to use dmath.py from the console (as I plan to) and they are going to punch in *floats*. why? because its natural. Its just easier to type D(2.78) than Deciaml('2.78'). Neither here nor there.... but the frustration is the fact that floats are so 1982. Know what I mean? This is the 21st century, and you know what, we have got to get past this: >>> >>> Decimal(.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> In other words, we need to move to a numeric system of computation (decimal is a good start) that does not keep track of real values as IEEE floats. Back in the day, that was ok... today, its unacceptable. So, Krah has a really nice (and fast) module that will help at least the python community (and users) to move into the 21st century. My hat is off to Stefan, that's for sure. I am going to keep playing with this, and making the changes you have suggested... I'll put the code back up there on code.google and see if I can make the repository work like its supposed to.. Thanks again for your assistance, I really appreciate it, Oscar. From harrismh777 at gmail.com Thu Feb 27 21:29:35 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 18:29:35 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <530fef58$0$11113$c3e8da3@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thursday, February 27, 2014 8:07:20 PM UTC-6, Steven D'Aprano wrote: > If they point to the same piece of memory -- which, by the way, can be > moved around if the garbage collector supports it -- then A is B cannot > possibly return False. > hi Steve, long time, yes, my whole point exactly. And we all know what python is doing under the covers for small ints like 0 - 256 ... in which case consider the following: a=128 b=a b=128 a is b True But...... consider this a=1024 b=a b=1024 a is b False For small ints below a certain value (257) A is B will always be True.... but now for ints above that value, as I've shown, A=257 B=A B=257 A is B False But for the variable discussion (like in BASIC, or even C) A=128, B=A, A and B are two pieces of memory that both happen to be variables containing different pieces of memory. For python, the references to small ints (as above) will almost always point to the same int object for each reference; hence the need for reference counts. Folks that think of assignment in python with a BASIC, or even C, mentality will have trouble understanding the difference between "==" and "is" and why... and they won't get reference counting. Cheers From ben+python at benfinney.id.au Thu Feb 27 21:46:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Feb 2014 13:46:11 +1100 Subject: References, and avoiding use of =?utf-8?B?4oCcdmFyaWFibGXigJ0=?= (was: Can global variable be passed into Python function?) References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> Message-ID: <85ha7knedo.fsf_-_@benfinney.id.au> "Mark H. Harris" writes: > So, yeah, thinking about variables is just not going away. Right. I would like, ideally, for the Python documentation to avoid mentioning that term entirely; and I would hope for that to promote a better understanding of Python's data model. The wider programming community, though, will no doubt continue to use that term to refer to various (incompatible) data models, and I certainly don't expect the Python community to pretend it doesn't exist. I encourage getting rid of it from Python documentation, but not getting rid of it from discussion in the community. > I finally decided (in my own head) that I would completely give up on > the 'variable' concept (intellectually) and help folks try to > understand references and reference counting. Reference counting isn't a concept one needs to present to newcomers, IMO. It is sufficient to explain that the Python runtime is free to discard an object when nothing refers to it any more. There's no need to explain to a newcomer the garbage-collection implementation details, precisely *because* it's an implementation detail. Some Python implementations use reference counting, some don't, and each implementation is free to do what it likes so long as the data model guarantees are preserved. The user normally shouldn't care, because they shouldn't have to depend on any specific garbage-collection behaviour. So: it's good to present the concept of ?references?, and use ?name binding? instead of ?variable?; but there's no need to present ?reference counting?, which is a Python-implementation-detail technical concept that IMO doesn't need to be in the newcomer's head. -- \ ?The trouble with the rat race is that even if you win, you're | `\ still a rat.? ?Jane Wagner, via Lily Tomlin | _o__) | Ben Finney From steve at pearwood.info Thu Feb 27 22:15:36 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 03:15:36 GMT Subject: extend methods of decimal module References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> Message-ID: <530fff58$0$11113$c3e8da3@news.astraweb.com> On Thu, 27 Feb 2014 15:00:45 -0800, Mark H. Harris wrote: > Decimal does not keep 0.1 as a floating point format (regardless of > size) which is why banking can use Decimal without having to worry about > the floating formatting issue... in other words, 0.0 is not stored in > Decimal as any kind of floating value... its not rounded.... it really > is Decimal('0.1'). I'm sorry, but that is incorrect. Decimal is a floating point format, same as float. Decimal uses base 10, so it is a better fit for numbers we write out in base 10 like "0.12345", but otherwise it suffers from the same sort of floating point rounding issues as floats do. py> a = Decimal("1.1e20") py> b = Decimal("1.1e-20") py> assert b != 0 py> a + b == a True In the case of 0.1 (I assume your "0.0" above was a typo), it is a floating point value. You can inspect the fields' values like this: py> x = Decimal("0.1") py> x.as_tuple() DecimalTuple(sign=0, digits=(1,), exponent=-1) There's a sequence of digits, and an exponent that tells you where the decimal point goes. That's practically the definition of "floating point". In Python 3.2 and older, you can even see those fields as non- public attributes: py> x._int '1' py> x._exp -1 (In Python 3.3, the C implementation does not allow access to those attributes from Python.) This is perhaps a better illustrated with a couple of other examples: py> Decimal('1.2345').as_tuple() DecimalTuple(sign=0, digits=(1, 2, 3, 4, 5), exponent=-4) py> Decimal('1234.5').as_tuple() DecimalTuple(sign=0, digits=(1, 2, 3, 4, 5), exponent=-1) [...] > The reason is that Decimal(.1) stores the erroneous float in the Decimal > object including the float error for .1 and D(.1) works correctly > because the D(.1) function in my dmath.py first converts the .1 to a > string value before handing it to Decimal's constructor(s) That *assumes* that when the user types 0.1 as a float value, they actually intend it to have the value of 1/10 rather than the exact value of 3602879701896397/36028797018963968. That's probably a safe bet, with a number like 0.1, typed as a literal. But how about this number? py> x = 3832879701896397/36028797218963967 py> Decimal(x) Decimal('0.10638378180104603176747701809290447272360324859619140625') py> Decimal(str(x)) Decimal('0.10638378180104603') Are you *absolutely* sure that the user intended x to have the second value rather than the first? How do you know? In other words, what you are doing is automatically truncating calculated floats at whatever string display format Python happens to use, regardless of the actual precision of the calculation. That happens to work okay with some values that the user types in by hand, like 0.1. But it is a disaster for *calculated* values. Unfortunately, there is no way for your D function to say "only call str on the argument if it is a floating point literal typed by the user". But what you can do is follow the lead of the decimal module, and leave the decision up to the user. The only safe way to avoid *guessing* what value the caller wanted is to leave the choice of truncating floats up to them. That's what the decimal module does, and it is the right decision. If the user passes a float directly, they should get *exact conversion*, because you have no way of knowing whether they actually wanted the float to be truncated or not. If they do want to truncate, they can pass it to string themselves, or supply a string literal. -- Steven From alec.taylor6 at gmail.com Thu Feb 27 22:49:07 2014 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Fri, 28 Feb 2014 14:49:07 +1100 Subject: Output JSON-schema from bottle application? Message-ID: Are there libraries for doing this? I would like to autogenerate JSON-schema for use inside an API explorer. However whenever there is a schema change; I would only like to change the schema in one place (where possible). E.g.: For use here - https://github.com/salesking/json-schema-browser How do I do this? Thanks for all suggestions, Alec Taylor From rosuav at gmail.com Thu Feb 27 23:26:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 15:26:59 +1100 Subject: extend methods of decimal module In-Reply-To: <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> Message-ID: On Fri, Feb 28, 2014 at 1:15 PM, Mark H. Harris wrote: > Its just easier to type D(2.78) than Deciaml('2.78'). It's easier to type 2.78 than 2.718281828, too, but one of them is just plain wrong. Would you tolerate using 2.78 for e because it's easier to type? I mean, it's gonna be close. Create Decimal values from strings, not from the str() of a float, which first rounds in binary and then rounds in decimal. ChrisA From wuwei23 at gmail.com Thu Feb 27 23:36:22 2014 From: wuwei23 at gmail.com (alex23) Date: Fri, 28 Feb 2014 14:36:22 +1000 Subject: end quote help for a newbie In-Reply-To: References: <1391088376.73476.YahooMailNeo@web133103.mail.ir2.yahoo.com> <1391093552.89290.YahooMailNeo@web133104.mail.ir2.yahoo.com> <1391110020.83595.YahooMailNeo@web133106.mail.ir2.yahoo.com> <1393497041.37213.YahooMailNeo@web133105.mail.ir2.yahoo.com> Message-ID: On 27/02/2014 8:41 PM, Chris Angelico wrote: > On Thu, Feb 27, 2014 at 9:30 PM, Peter Clark wrote: > # Dragons and dungeons, based on CP/M program messages from ca. 1966 > # This version designed and produced by peter clark beginning in December 2013 > def startandload(n): # introduce program and allow messages to be > loaded/amended > x = str(input("Welcome Adventurer, what is your name?")) > if x==('load'): > y = str(input("messages, places or things?")) > if y in("messages", "places","things"): > print("OK") > else: print("Wrong") > if x==('restart'): > y = str(input("game reference")) > if y in("messages", "places","things"): > print("*** to be done - load and restart game ***") > else: print("Wrong") > > while True: > startandload > > > The problem is right at the end: you don't actually call the function. > You always need parentheses to call a function. `startandload` also takes a parameter that doesn't seem to be used. > I'm also a bit > confused as to your reason for running a function called > "startandload" (which seems to be initialization) in an infinite loop; > you possibly just want to call it once. Or perhaps: if __name__ == '__main__': startandload() From rosuav at gmail.com Thu Feb 27 23:43:23 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 15:43:23 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Fri, Feb 28, 2014 at 1:29 PM, Mark H. Harris wrote: > a=1024 > b=a > b=1024 > a is b > False No no no no! They're not pointing to the same integer any more. Now, if you change the "b=1024" from being a mostly-useless assignment (to another int with the same value) into being a comparison, then it'll be safe. But you're assigning "b=a" and then immediately reassigning "b=1024". Simple rule of thumb: Never use 'is' with strings or ints. They're immutable, their identities should be their values. Playing with 'is' will only confuse you, unless you're specifically going for introspection and such. ChrisA From harrismh777 at gmail.com Thu Feb 27 23:41:09 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 20:41:09 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <530fff58$0$11113$c3e8da3@news.astraweb.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Thursday, February 27, 2014 9:15:36 PM UTC-6, Steven D'Aprano wrote: > Decimal uses base 10, so it is a better fit for numbers we > write out in base 10 like "0.12345", but otherwise it suffers from the > same sort of floating point rounding issues as floats do. > > > py> Decimal('1.2345').as_tuple() > DecimalTuple(sign=0, digits=(1, 2, 3, 4, 5), exponent=-4) > > py> Decimal('1234.5').as_tuple() > DecimalTuple(sign=0, digits=(1, 2, 3, 4, 5), exponent=-1) > Steven, thank you, your explanation here is splendid, and has cleared up some of my confusion about Decimal, and given me a tool besides ('preciate it !) I did not investigate .as_tuple() nice. Take a look at this: From IDLE >>> from decimal import * >>> s=Decimal(.1) >>> s.as_tuple() DecimalTuple(sign=0, digits=(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 1, 1, 1, 5, 1, 2, 3, 1, 2, 5, 7, 8, 2, 7, 0, 2, 1, 1, 8, 1, 5, 8, 3, 4, 0, 4, 5, 4, 1, 0, 1, 5, 6, 2, 5), exponent=-55) >>> >>> s=Decimal('.1') <===== .1 as string >>> s.as_tuple() DecimalTuple(sign=0, digits=(1,), exponent=-1) >>> Big difference, yes? You have hit the nail on the head, because as you say, it is very unfortunate that the function does not know whether it has been typed in by hand (a big problem) or whether it comes from an intermediate calculated result (maybe an even bigger problem. rats(). So, I am thinking I need to mods... maybe an idmath.py for interactive sessions, and then dmath.py for for running within my scientific scripts... ?? Thanks for your input. kind regards, From rosuav at gmail.com Fri Feb 28 00:00:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 16:00:10 +1100 Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Fri, Feb 28, 2014 at 3:41 PM, Mark H. Harris wrote: > So, I am thinking I need to mods... maybe an idmath.py for interactive sessions, and then dmath.py for for running within my scientific scripts... ?? No; the solution is to put quotes around your literals in interactive mode, too. There's no difference between interactive and script mode, and adding magic to interactive mode will only cause confusion. Alternatively, there is another solution that's been posited from time to time: Decimal literals. We currently have three forms of numeric literal, which create three different types of object: >>> type(1) >>> type(.1) >>> type(1j) If we had some other tag, like 'd', we could actually construct a Decimal straight from the source code. Since source code is a string, it'll be constructed from that string, and it'll never go via float. Something like this: >>> type(0.1d) which currently is a SyntaxError, so it wouldn't collide with anything. The question is how far Python wants to bless the Decimal type with syntax - after all, if Decimal can get a literal notation, why can't Fraction, and why can't all sorts of other types? And that's a huge can of worms. ChrisA From davea at davea.name Fri Feb 28 00:05:57 2014 From: davea at davea.name (Dave Angel) Date: Fri, 28 Feb 2014 00:05:57 -0500 (EST) Subject: posting code snippets References: Message-ID: "Mark H. Harris" Wrote in message: > my isp withdrew the post service (nntp) from their server at end of 2011... and I didn't notice till now! ha! So, I'm not using seamonkey any longer... using google groups/ and that has been a fit to get used to, but I'm making progress. > > You could still use nntp, if you switch to gmane.comp.python. -- DaveA From research at johnohagan.com Fri Feb 28 00:17:10 2014 From: research at johnohagan.com (John O'Hagan) Date: Fri, 28 Feb 2014 16:17:10 +1100 Subject: Tuples and immutability In-Reply-To: <87a9dczfya.fsf@elektro.pacujo.net> References: <87a9dczfya.fsf@elektro.pacujo.net> Message-ID: <20140228161710.7ebb8f4d@mini.home> On Thu, 27 Feb 2014 18:19:09 +0200 Marko Rauhamaa wrote: > Eric Jacoboni : > > >>>> a_tuple[1] += [20] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: 'tuple' object does not support item assignment > > > > [...] > > > > But, then, why a_tuple is still modified? > > That's because the += operator > > 1. modifies the list object in place > > 2. tries to replace the tuple slot with the list (even though the > list hasn't changed) > > It's Step 2 that raises the exception, but the damage has been done > already. > > One may ask why the += operator modifies the list instead of creating > a new object. That's just how it is with lists. > > BTW, try: > > >>> a_tuple[1].append(20) > >>> a_tuple[1].extend([20]) > > Try also: > > >>> a_tuple[1] = a_tuple[1] > [...] Also try: x = a_tuple[1] #What's in a name? x is a_tuple[1] #Obviously, but: x += [1] #No error a_tuple[1] += [1] #Error Same object, just a different name - but a different result. I get why, but still find that odd. -- John From harrismh777 at gmail.com Fri Feb 28 00:18:49 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 21:18:49 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> Message-ID: On Thursday, February 27, 2014 10:26:59 PM UTC-6, Chris Angelico wrote: > Create Decimal values from strings, not from the str() of a float, > which first rounds in binary and then rounds in decimal. > Thanks Chris... another excellent point... ok, you guys have about convinced me (which is spooky) but, hey, I'm teachable... what is the best strategy then? Many of the functions of my dmath.py are algorithms which calculate infinite series to convergence out there at some number of precision ... do I make the assumption that all functions will take a string as argument and then let interactive users bare the responsibility to enter a string or decimal... avoiding floats... or use try and toss and error if the rules are not followed, or what? I do see that I'm trying to solve a problem the wrong way,... just not sure what is the better approach. If you get a chance, take a look at the dmath.py code on: https://code.google.com/p/pythondecimallibrary/ I got the repository working correctly for me, and the files can be viewed on-line ... its a long script, but not that hard to look through because all the functions pretty much work the same... when you've seen one converging series function in python you've seen them all! Thanks again, Chris. From rosuav at gmail.com Fri Feb 28 00:26:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 16:26:11 +1100 Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> Message-ID: On Fri, Feb 28, 2014 at 4:18 PM, Mark H. Harris wrote: > do I make the assumption that all functions will take a string as argument and then let interactive users bare the responsibility to enter a string or decimal... avoiding floats... Just have your users pass in Decimal objects. They can construct them however they wish. ChrisA From harrismh777 at gmail.com Fri Feb 28 00:39:44 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Thu, 27 Feb 2014 21:39:44 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> Message-ID: <4a7700ed-835c-4e19-8c6d-ab451b696390@googlegroups.com> On Thursday, February 27, 2014 10:43:23 PM UTC-6, Chris Angelico wrote: > Simple rule of thumb: Never use 'is' with strings or ints. They're > immutable, their identities should be their values. Playing with 'is' > will only confuse you, unless you're specifically going for > introspection and such. Right. The only time I use "is" is when I'm trying to explain to someone new to python assignment what is happening inside... what Mark Summerfield calls "python's beautiful heart," in his his recent book, "Programming in Python 3" ... a great resource, by the way. From rosuav at gmail.com Fri Feb 28 00:41:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 16:41:28 +1100 Subject: posting code snippets In-Reply-To: <85ppm8nqx7.fsf@benfinney.id.au> References: <85ppm8nqx7.fsf@benfinney.id.au> Message-ID: On Fri, Feb 28, 2014 at 9:15 AM, Ben Finney wrote: > Since you'll be posting the code in-line, make sure it's short. Since > it'll be short, make sure it's complete ? we should need nothing else to > run the code and expect to see the same behaviour you're seeing. > > Since you'll be making it short, complete, and still demonstrating the > behaviour, you may even get the result that you understand the cause of > the behaviour before posting it. Everyone wins! :-) Which is the scientific basis of the astonishingly successful (that is, it's astonishing to people who don't understand) debugging technique of Rubber Ducking, or talking to your teddy bear, or other variants of the subject. (I have a figurine from American McGee's "Alice: Madness Returns" who is extremely helpful to me. She's pretty, she's smart, and she's pretty smart.) By the time you've explained it to someone, you've boiled the problem down into a manageable form, and that often helps you solve the problem yourself. The problem does have to believe that the rubber duck/teddy bear/figurine is an expert, though. I've had my siblings or parents come to me with problems and, without saying a word or touching the computer or anything, I've solved them. The problem itself respects my skill, and retracts its objection and solves itself. Why this works I am not sure, but just remember to treat your teddy bear as an intelligent partner in the debugging process, not as an idiot who just gets in the way. He's a brilliant programmer from another dimension; he knows all about coding, but not about your code, so you have to explain its little oddities to him. (Or her. Female teddy bears are just as good at debugging as male ones are.) ChrisA From rosuav at gmail.com Fri Feb 28 00:53:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 16:53:35 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <4a7700ed-835c-4e19-8c6d-ab451b696390@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <4a7700ed-835c-4e19-8c6d-ab451b696390@googlegroups.com> Message-ID: On Fri, Feb 28, 2014 at 4:39 PM, Mark H. Harris wrote: > On Thursday, February 27, 2014 10:43:23 PM UTC-6, Chris Angelico wrote: > >> Simple rule of thumb: Never use 'is' with strings or ints. They're >> immutable, their identities should be their values. Playing with 'is' >> will only confuse you, unless you're specifically going for >> introspection and such. > > Right. The only time I use "is" is when I'm trying to explain to someone new to python assignment what is happening inside... what Mark Summerfield calls "python's beautiful heart," in his his recent book, "Programming in Python 3" ... a great resource, by the way. > 'is' can and should be used with mutables, to distinguish between identical values with different identities. It's also appropriate to use 'is' with special singletons like None. Just be careful of ints and strings. ChrisA From steve at pearwood.info Fri Feb 28 02:34:27 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 07:34:27 GMT Subject: extend methods of decimal module References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> Message-ID: <53103c03$0$11113$c3e8da3@news.astraweb.com> On Fri, 28 Feb 2014 16:00:10 +1100, Chris Angelico wrote: > If we had some other tag, like 'd', we could actually construct a > Decimal straight from the source code. Since source code is a string, > it'll be constructed from that string, and it'll never go via float. Now that Python has a fast C implementation of Decimal, I would be happy for Python 4000 to default to decimal floats, and require special syntax for binary floats. Say, 0.1b if you want a binary float, and 0.1 for a decimal. But for now, backwards-compatibility requires that the default floating point type remains binary float. But we could maybe agitate for a 1.234d Decimal literal type. Care to write a PEP? :-) > The question is how far Python wants to bless the Decimal type with > syntax - after all, if Decimal can get a literal notation, why can't > Fraction, and why can't all sorts of other types? And that's a huge can > of worms. I like Fractions, but I don't think they're important enough for the average users to require literal notation. -- Steven From marko at pacujo.net Fri Feb 28 02:43:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 09:43:58 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> Message-ID: <871tynznpd.fsf@elektro.pacujo.net> Chris Angelico : > Simple rule of thumb: Never use 'is' with strings or ints. They're > immutable, their identities should be their values. Playing with 'is' > will only confuse you, unless you're specifically going for > introspection and such. Here's a use case for "is" with strings (or ints): class Connection: IDLE = "IDLE" CONNECTING = "CONNECTING" CONNECTED = "CONNECTED" DISCONNECTING = "DISCONNECTING" DISCONNECTED = "DISCONNECTED" def __init__(self): self.state = IDLE def connect(self, address): ... self.state = CONNECTING ... def disconnect(self): ... if self.state is CONNECTED: ... The state objects could have been defined like this: IDLE = object() CONNECTING = object() CONNECTED = object() DISCONNECTING = object() DISCONNECTED = object() However, strings have the advantage in troubleshooting: sys.stderr.write("state = {}\n".format(self.state)) Marko From marko at pacujo.net Fri Feb 28 02:54:48 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 09:54:48 +0200 Subject: Tuples and immutability References: <87a9dczfya.fsf@elektro.pacujo.net> Message-ID: <87wqgfy8mv.fsf@elektro.pacujo.net> John O'Hagan : > Same object, just a different name - but a different result. I get > why, but still find that odd. The general principle is stated in the language specification: : Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. [...] with the exception of the possible in-place behavior, the binary operation performed by augmented assignment [x += y] is the same as the normal binary operations [x = x + y]. We should call += "dual-use technology." Marko From steve at pearwood.info Fri Feb 28 03:23:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 08:23:53 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> Message-ID: <53104798$0$11113$c3e8da3@news.astraweb.com> On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote: > Chris Angelico : > >> Simple rule of thumb: Never use 'is' with strings or ints. They're >> immutable, their identities should be their values. Playing with 'is' >> will only confuse you, unless you're specifically going for >> introspection and such. > > Here's a use case for "is" with strings (or ints): I don't think this is a use-case for "is". See below. > class Connection: > IDLE = "IDLE" [...] > CONNECTED = "CONNECTED" [...] > def disconnect(self): > ... > if self.state is CONNECTED: > ... Why do you care that the state is *that specific* string, rather than any old string with the value "CONNECTED"? Unless you can explain a good reason why, say, *this* instance "CONNECTED" should fail the test, while *that* instance with the same value passes, it's not a good use-case for "is". -- Steven From ben+python at benfinney.id.au Fri Feb 28 03:46:48 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Feb 2014 19:46:48 +1100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> Message-ID: <857g8foc93.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote: > > class Connection: > > IDLE = "IDLE" > [...] > > CONNECTED = "CONNECTED" > [...] > > def disconnect(self): > > ... > > if self.state is CONNECTED: > > ... > > Why do you care that the state is *that specific* string, rather than > any old string with the value "CONNECTED"? I can think of a reason: * When you publish the API for the ?Connection? class, * and another party writes code that sets ?state? to a string with the value ?"CONNECTED"?, * and you implemented the check as ?self.state == "CONNECTED"?, * and their code works with your class and it goes into production, * you're then not able to change the expected value without breaking that party's code. On the other hand, if the only value which will work is the one which the caller gets via ?Connection.CONNECTED?, then you can change the implementation later without breaking existing code. There are two reasons why I think this is *still* not a justification for using ?is? with string values: First reason: This is better done by making it clear the value is an arbitrary object that won't be compared for equality. Just use ?object()? to creeate each value and be done with it. That's a hack, but it's better than pretending you'll use the string as a string of text and then breaking that expectation. Second reason: This use case is a primary motivation for the Enum pattern. The Enum pattern is implemented in the standard-library ?enum? module, now in Python 3.4 . So, I think Marko's use case is not a justification for comparing string values with ?is?. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but if we didn't have ears, we'd look like weasels.? | _o__) ?_Pinky and The Brain_ | Ben Finney From rosuav at gmail.com Fri Feb 28 03:52:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 19:52:45 +1100 Subject: extend methods of decimal module In-Reply-To: <53103c03$0$11113$c3e8da3@news.astraweb.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Fri, Feb 28, 2014 at 6:34 PM, Steven D'Aprano wrote: > On Fri, 28 Feb 2014 16:00:10 +1100, Chris Angelico wrote: > >> If we had some other tag, like 'd', we could actually construct a >> Decimal straight from the source code. Since source code is a string, >> it'll be constructed from that string, and it'll never go via float. > > Now that Python has a fast C implementation of Decimal, I would be happy > for Python 4000 to default to decimal floats, and require special syntax > for binary floats. Say, 0.1b if you want a binary float, and 0.1 for a > decimal. Maybe, but I believe the cdecimal module is still slower than typical floating point. There'd also be considerations regarding NumPy and how you'd go about working with an array of non-integer values, and so on. Certainly this will be an extremely reasonable topic of discussion once there's any notion of a Py4K on the cards. There'll be arguments on both sides. > But for now, backwards-compatibility requires that the default floating > point type remains binary float. But we could maybe agitate for a 1.234d > Decimal literal type. Care to write a PEP? > > :-) Heh. Strong consideration here: it would mean importing the decimal module on startup. >>> t=time.time(); import decimal; time.time()-t 4.5000159740448 >>> t=time.time(); import decimal; time.time()-t 0.0 A dummy import (when it's already loaded) is so fast that it's immeasurable, but four and a half seconds to load up decimal? This is 3.4.0b2 on Windows, btw. It was a lot quicker on my Linux box, probably because the OS or disk cache had the file. So maybe it wouldn't be too bad in practice; but it's still a cost to consider. >> The question is how far Python wants to bless the Decimal type with >> syntax - after all, if Decimal can get a literal notation, why can't >> Fraction, and why can't all sorts of other types? And that's a huge can >> of worms. > > I like Fractions, but I don't think they're important enough for the > average users to require literal notation. Yeah, but where do you draw the line? Either decimal.Decimal becomes a built-in type, or there needs to be a system for constructing literals of non-built-in types. And if Decimal becomes built-in, then why that and not <>? Also, if Decimal becomes a built-in type, does that affect the numeric tower? ChrisA From wolfgang.maier at biologie.uni-freiburg.de Fri Feb 28 03:54:12 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Fri, 28 Feb 2014 08:54:12 +0000 (UTC) Subject: extend methods of decimal module References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> Message-ID: Mark H. Harris gmail.com> writes: > > On Thursday, February 27, 2014 10:26:59 PM UTC-6, Chris Angelico wrote: > > > Create Decimal values from strings, not from the str() of a float, > > which first rounds in binary and then rounds in decimal. > > > > Thanks Chris... another excellent point... ok, you guys have about convinced me (which is spooky) but, > hey, I'm teachable... what is the best strategy then? > > If you get a chance, take a look at the dmath.py code on: > > https://code.google.com/p/pythondecimallibrary/ > > I got the repository working correctly for me, and the files can be viewed on-line ... its a long script, but > not that hard to look through because all the functions pretty much work the same... when you've seen one > converging series function in python you've seen them all! > > Thanks again, Chris. > Hi Mark, I quickly skimmed through your code and I don't think there is a need for your D() function at all. I thought it was a class adding some extra functionality to Decimal (that's because you used a capital letter for its name), but now I realized that it's just a function returning a Decimal from the string representation of its argument. Since by now, I guess, we all agree that using the string representation is the wrong approach, you can simply use Decimal instead of D() throughout your code. Best, Wolfgang From rosuav at gmail.com Fri Feb 28 04:00:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 20:00:07 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <871tynznpd.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 28, 2014 at 6:43 PM, Marko Rauhamaa wrote: > Here's a use case for "is" with strings (or ints): > > class Connection: > IDLE = "IDLE" > CONNECTING = "CONNECTING" > CONNECTED = "CONNECTED" > DISCONNECTING = "DISCONNECTING" > DISCONNECTED = "DISCONNECTED" > > The state objects could have been defined like this: > > IDLE = object() > CONNECTING = object() > CONNECTED = object() > DISCONNECTING = object() > DISCONNECTED = object() > > However, strings have the advantage in troubleshooting: > > sys.stderr.write("state = {}\n".format(self.state)) As Ben said, strong use-case for enums (either migrate to 3.4, or check PyPI). But here's an alternative that uses object identity safely. (Remember, all it takes is a bit of string interning and two equal strings could become identical.) class enum: def __init__(self, desc): self.desc = desc def __repr__(self): return self.desc IDLE = enum("IDLE") CONNECTING = enum("CONNECTING") CONNECTED = enum("CONNECTED") DISCONNECTING = enum("DISCONNECTING") DISCONNECTED = enum("DISCONNECTED") Now object identity is the right way to do things, and you can still do the formatting just like you say; plus there's no way to accidentally get something that seems to work. Of course, the real enum type is far more sophisticated than that, but the concept is the same. It's an object. ChrisA From alister.ware at ntlworld.com Fri Feb 28 04:52:28 2014 From: alister.ware at ntlworld.com (Alister) Date: Fri, 28 Feb 2014 09:52:28 GMT Subject: Output JSON-schema from bottle application? References: Message-ID: On Fri, 28 Feb 2014 14:49:07 +1100, Alec Taylor wrote: > Are there libraries for doing this? > > I would like to autogenerate JSON-schema for use inside an API explorer. > > However whenever there is a schema change; I would only like to change > the schema in one place (where possible). > > E.g.: For use here - https://github.com/salesking/json-schema-browser > > How do I do this? > > Thanks for all suggestions, > > Alec Taylor A quick trip to google reveals the json module which is part of the std library http://docs.python.org/2/library/json.html -- Two cars in every pot and a chicken in every garage. From marko at pacujo.net Fri Feb 28 05:02:03 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 12:02:03 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> Message-ID: <87ha7jy2qs.fsf@elektro.pacujo.net> Ben Finney : > There are two reasons why I think this is *still* not a justification > for using ?is? with string values: > > First reason: This is better done by making it clear the value is an > arbitrary object that won't be compared for equality. Just use > ?object()? to creeate each value and be done with it. That's a hack, > but it's better than pretending you'll use the string as a string of > text and then breaking that expectation. > > Second reason: This use case is a primary motivation for the Enum > pattern. The Enum pattern is implemented in the standard-library > ?enum? module, now in Python 3.4 > . > > So, I think Marko's use case is not a justification for comparing > string values with ?is?. Yes, enums are long overdue. However, since any distinct objects will do, there is nothing preventing you from using string objects. Marko PS On the topic of enums, when are we getting support for a switch statement? From rosuav at gmail.com Fri Feb 28 05:55:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 21:55:53 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87ha7jy2qs.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 28, 2014 at 9:02 PM, Marko Rauhamaa wrote: > Yes, enums are long overdue. However, since any distinct objects will > do, there is nothing preventing you from using string objects. > String literals will often be interned if they look like (especially, if they *are*) identifiers, so if you want to prevent other strings from happening to match, you can't trust 'is'. >>> class Foo: INIT = "INIT" def __init__(self): self.state = self.INIT def initializing(self): return self.state is self.INIT >>> a=Foo() >>> a.initializing() True >>> a.state="INIT" >>> a.initializing() True So you should use some string value that doesn't look like an identifier: >>> class Foo: INIT = "<>" def __init__(self): self.state = self.INIT def initializing(self): return self.state is self.INIT >>> a=Foo() >>> a.initializing() True >>> a.state="<>" >>> a.initializing() False But even then, chances are you can force the matter by interning explicitly. >>> class Foo: INIT = ">>INIT<<" def __init__(self): self.state = self.INIT def initializing(self): return self.state is self.INIT >>> a=Foo() >>> a.initializing() True >>> sys.intern(a.state) '>>INIT<<' >>> a.state=sys.intern(">>INIT<<") >>> a.initializing() True Note that in no case did I at all tamper with the class definition, either to change its idea of the INIT string or to fetch that particular object. Two equal strings, in Python, might and might not be identical, and you simply cannot rely on interning either way. The third example, incidentally, depends on sys.intern reusing a.state as the "one interned string". This will normally be what happens if it's the first string of that value to be used. So you might be able to first force the strings to be in the interning table, and then force your sentinels to be different objects. But at that point, you really should be using object(), or a proper enum module. If you're using strings as state values, you should be using == to compare them. Nothing else is safe. ChrisA From rosuav at gmail.com Fri Feb 28 06:08:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 22:08:03 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87ha7jy2qs.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 28, 2014 at 9:02 PM, Marko Rauhamaa wrote: > PS On the topic of enums, when are we getting support for a switch > statement? I don't see that they're particularly connected. In my C code, I've used enums frequently as quick constants, often never switching on them. Conversely, I often use switch in C code with either integer or character constants. (ASCII character, of course, as that's all you get.) Take this, for example, from my C++ MUD client: enum {IS=0x00,ECHO=0x01,SEND=0x01,SUPPRESSGA=0x03,TERMTYPE=0x18,NAWS=0x1F,SE=0xF0,GA=0xF9,SB,WILL,WONT,DO=0xFD,DONT,IAC=0xFF}; That one happens to be used in a switch at one point, but it's also used in other ways, like this: static char naws[]={IAC,SB,NAWS,0,0,0,0,IAC,SE}; (The actual window size gets patched in separately, in case you're curious... but I suspect most people here won't be aware that IAC SB NAWS means Interpret-As-Command, Subnegotiation Begin, Negotiate About Window Size, and that this is a TELNET command sequence.) With bit flags, they'll never be used in switch: enum //Bitflags in hackity { HACK_ATAT=1, //Perform @@ -> fill-in translation HACK_AUTOEDIT=2, //Respond to the autoedit markers [now active by default] }; ... if (hackity&HACK_ATAT) ... Sometimes, they're just states, and they're assigned and/or compared for equality: enum {ic, court, citizen, trivia, sports, chancount} lastlinetype; Some things check if (lastlinetype == ic), but nothing ever switches on it. Meanwhile, here's a switch block from Gypsum that will never use enumerations: switch (max(delay,base)) { case 0..59: ... handling for <1 minute ... case 60..3599: ... handling for <1 hour ... default: ... handling for >= 1 hour ... } No, the features are quite independent. Python currently has dispatch tables and if/elif chains, and a strong cultural aversion to switch. You could change that by coming up with some *really* awesome proposal, but you'll be fighting against the tide a bit. ChrisA From marko at pacujo.net Fri Feb 28 06:30:16 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 13:30:16 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: <8738j3xynr.fsf@elektro.pacujo.net> Chris Angelico : > String literals will often be interned if they look like (especially, > if they *are*) identifiers, so if you want to prevent other strings > from happening to match, you can't trust 'is'. > > [...] > > If you're using strings as state values, you should be using == to > compare them. Nothing else is safe. You didn't quite understand the use case. You would never ever do things like: > >>> a.state="<>" You'd only refer to the state names symbolically: a.state = a.INIT Marko From marko at pacujo.net Fri Feb 28 06:38:11 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 13:38:11 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: <87y50vwjq4.fsf@elektro.pacujo.net> Chris Angelico : > Python currently has dispatch tables and if/elif chains, and a strong > cultural aversion to switch. You could change that by coming up with > some *really* awesome proposal, but you'll be fighting against the > tide a bit. It's easy have a "cultural aversion" when the language doesn't provide the facility. Switch statements provide for excellent readability in parsers and state machines, for example. They also allow the Python compiler to optimize the statement internally unlike long if-else chains. Marko From rosuav at gmail.com Fri Feb 28 06:51:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 22:51:28 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <8738j3xynr.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <8738j3xynr.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 28, 2014 at 10:30 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> String literals will often be interned if they look like (especially, >> if they *are*) identifiers, so if you want to prevent other strings >> from happening to match, you can't trust 'is'. >> >> [...] >> >> If you're using strings as state values, you should be using == to >> compare them. Nothing else is safe. > > You didn't quite understand the use case. You would never ever do things > like: > >> >>> a.state="<>" > > You'd only refer to the state names symbolically: > > a.state = a.INIT In theory, yes. If that's all people will ever do, then you can safely use == to check. Why are you using is? To prevent the case where some other random string will happen to compare equal. So I stuffed some other random string in, and it was equal, and I proved that I could make it identical as well. ChrisA From rosuav at gmail.com Fri Feb 28 07:22:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Feb 2014 23:22:00 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87y50vwjq4.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> Message-ID: On Fri, Feb 28, 2014 at 10:38 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> Python currently has dispatch tables and if/elif chains, and a strong >> cultural aversion to switch. You could change that by coming up with >> some *really* awesome proposal, but you'll be fighting against the >> tide a bit. > > It's easy have a "cultural aversion" when the language doesn't provide > the facility. I'm talking about the strong resistance that gets put up any time the suggestion comes up on python-ideas or somesuch. The core devs and Guido especially are against the idea. > Switch statements provide for excellent readability in parsers and state > machines, for example. They also allow the Python compiler to optimize > the statement internally unlike long if-else chains. It's usually possible to turn any concrete example of a switch statement into an equally-readable dispatch table. All you need is for your search terms to be hashable (which is a much less stringent requirement than is usually put on switch blocks, like "must be machine word signed integer"), and you can do something like this: compare_key = { # Same target(s). ast.Assign: lambda node: ' '.join(dump(t) for t in node.targets), # Same target and same operator. ast.AugAssign: lambda node: dump(node.target) + dump(node.op) + "=", # A return statement is always compatible with another. ast.Return: lambda node: "(easy)", # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. ast.Expr: lambda node: "(maybe)", # These ones are never compatible, so return some # object that's never equal to anything. ast.Import: lambda node: float("nan"), ast.ImportFrom: lambda node: float("nan"), ast.Pass: lambda node: float("nan"), ast.Raise: lambda node: float("nan"), ast.If: lambda node: float("nan"), } I then effectively do a big switch block like this: if try_type not in compare_key: print("Unrecognized type",try_type.__name__,file=sys.stderr) compare_key[try_type] = lambda node: float("nan") func = compare_key[try_type] try_node = func(node.body[0]) for handler in node.handlers: if try_node != func(handler.body[0]): return The first check (the "not in" bit) is kinda like a default clause, but it makes the output only once for any given type. For a more 'true' default clause, I could do this: try: func = compare_key[try_type] except KeyError: func = compare_key["default"] but I take advantage of the fact that the dispatch table is a dict and mutate it. Also, if this were done in a switch block, there'd be some redundancy. I call the same function on node.body[0] and on handler.body[0] for each handler in handlers, so there's structure that's common to all the branches there. I'm not sure how, with a classic C-style switch block, I could implement that cleanly. Probably I'd end up using function pointers and basically doing it exactly the same way :) The only major thing C's switch does that a dispatch table doesn't is fall-through. And let's face it, if your big argument in favour of a switch statement is "I need fall-through", you're not just going to have Python devs against you, you're also going to fight against the roughly 50% of C programmers who detest that feature :) (FWIW, I'm in the other 50%. I quite like fall-through, and there are times when it's a very clean way to express something. But even those cases can usually be expressed one way or another with only a little more redundancy - for instance, have one case that sets the key to be the next one, and then have stand-alone if blocks rather than if/elif. Considering that that use of fall-through usually requires an explanatory comment anyway, you're not really losing much.) So, going back to your statement: > Switch statements provide for excellent readability in parsers and state > machines, for example. The best way to start trying to build support for this would be to mock up a syntax for a switch statement, and find a currently-existing parser or state machine to translate. Show us the "before and after" shots. That's what I'm currently doing to justify an exception expression syntax - examples like this: pwd = (os.getcwd() except OSError: None) # Lib/tkinter/filedialog.py:210: try: pwd = os.getcwd() except OSError: pwd = None g = (grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid) u = (pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid) # Lib/tarfile.py:2198: try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid This is real Python code, straight out of the standard library. I don't know if you could find many examples in the stdlib that beg for a switch statement, but pick up some real-world code of your own, or from some open source project, or something. Even if, in practice, it wouldn't be changed for many years (because that project needs to be compatible with previous versions of Python), it'd be worth showing "here's what could be". And then be prepared for a few hundred posts' worth of bikeshedding about the details :) ChrisA From marko at pacujo.net Fri Feb 28 07:25:54 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 14:25:54 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <8738j3xynr.fsf@elektro.pacujo.net> Message-ID: <87mwhbwhil.fsf@elektro.pacujo.net> Chris Angelico : > On Fri, Feb 28, 2014 at 10:30 PM, Marko Rauhamaa wrote: >> Chris Angelico : >> a.state = a.INIT > > In theory, yes. If that's all people will ever do, then you can safely > use == to check. Why are you using is? The main reason to use "is" is to indicate that the object is a sentinel object whose identity is what is meaningful, not the content. Using == would work but would give some poor soul the idea that the state variable could hold any imaginable string. The implementation should be able to change the state objects to any (distinct) objects at all (say, the new enums, or ints, or some more elaborate class instances) without any changes in the code. Marko From neilc at norwich.edu Fri Feb 28 08:47:02 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Fri, 28 Feb 2014 13:47:02 +0000 (UTC) Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> Message-ID: On 2014-02-28, Marko Rauhamaa wrote: > Chris Angelico : >> Python currently has dispatch tables and if/elif chains, and a >> strong cultural aversion to switch. You could change that by >> coming up with some *really* awesome proposal, but you'll be >> fighting against the tide a bit. > > It's easy have a "cultural aversion" when the language doesn't > provide the facility. > > Switch statements provide for excellent readability in parsers > and state machines, for example. They also allow the Python > compiler to optimize the statement internally unlike long > if-else chains. Once you remove all the features of switch that wouldn't fit in Python, e.g.; fall-through, jumps, breaks; whats left provides negligible benefit over if-elif-else or dict-dispatch. A pythonic switch statement doesn't provide enough features to bother with its implemention. Check out Go's switch statement for an example of what it might look like in Python. Except you'd get it without labeled break or the fallthrough statement. Would you still want to use it? -- Neil Cerutti From casevh at gmail.com Fri Feb 28 09:23:38 2014 From: casevh at gmail.com (casevh at gmail.com) Date: Fri, 28 Feb 2014 06:23:38 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <81aa3b17-fcaf-4aea-bef7-429403ac8d27@googlegroups.com> Message-ID: On Thursday, February 27, 2014 2:33:35 AM UTC-8, Mark H. Harris wrote: > No... was not aware of gmpy2... looks like a great project! I am wondering > why it would be sooo much faster? For multiplication and division of ~1000 decimal digit numbers, gmpy2 is ~10x faster. The numbers I gave were for ln() and sqrt(). > I was hoping that Stefan Krah's C accelerator was using FFT fast fourier > transforms for multiplication at least... > .. snip .. > I have not looked at Krah's code, so not sure what he did to speed things > up... (something more than just writing it in C I would suppose). IIRC, cdecimal uses a Number Theory Transform for multiplication of very large numbers. It has been a while since I looked so I could be wrong. casevh From marko at pacujo.net Fri Feb 28 09:26:23 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 16:26:23 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> Message-ID: <87d2i7wbxs.fsf@elektro.pacujo.net> Neil Cerutti : > Check out Go's switch statement for an example of what it might > look like in Python. Except you'd get it without labeled break or > the fallthrough statement. No need for the fallthrough (except that multiple cases should be supported). Labeled breaks wouldn't be needed because there are no fallthroughs. > Would you still want to use it? Probably. Guile (scheme) has: (case (state self) ((CONNECTING CONNECTED) ...) ((DISCONNECTING) ...) (else ...)) Python isn't "averse" to the switch statement because it would be not that useful. Rather, the problem is that Python doesn't have nonliteral constants (scheme has builtin symbols). It is difficult to come up with truly Pythonic syntax for the switch statement. Something like switch self.state from Connection.State: case CONNECTING or CONNECTED: ... case DISONNECTING: ... else: ... would be possible, but here, "Connection.State" is evaluated at compile time. Don't know if there are any precedents to that kind of thing in Python. Marko From neilc at norwich.edu Fri Feb 28 09:30:46 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Fri, 28 Feb 2014 14:30:46 +0000 (UTC) Subject: References, and avoiding use of ???variable??? (was: Can global variable be passed into Python function?) References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <85ha7knedo.fsf_-_@benfinney.id.au> Message-ID: On 2014-02-28, Ben Finney wrote: > "Mark H. Harris" writes: >> So, yeah, thinking about variables is just not going away. > > Right. I would like, ideally, for the Python documentation to > avoid mentioning that term entirely; and I would hope for that > to promote a better understanding of Python's data model. > > The wider programming community, though, will no doubt continue > to use that term to refer to various (incompatible) data > models, and I certainly don't expect the Python community to > pretend it doesn't exist. I like the characteristic of Python that assignment and argument passing work the same way. If only C were so simple! The tutorial makes things sound more high-falutin' than that [Tutorial 4.6 Defining Functions]: The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). [...] How about: The actual parameters (arguments) to a function call are passed via assignment to the variables in the local symbol table of the called function. Am I oversimplifying? -- Neil Cerutti From rosuav at gmail.com Fri Feb 28 09:37:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 01:37:33 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87d2i7wbxs.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> <87d2i7wbxs.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 1:26 AM, Marko Rauhamaa wrote: > Python isn't "averse" to the switch statement because it would be not > that useful. Rather, the problem is that Python doesn't have nonliteral > constants (scheme has builtin symbols). It is difficult to come up with > truly Pythonic syntax for the switch statement. > > Something like > > switch self.state from Connection.State: > case CONNECTING or CONNECTED: > ... > case DISONNECTING: > ... > else: > ... > > would be possible, but here, "Connection.State" is evaluated at compile > time. Don't know if there are any precedents to that kind of thing in > Python. Can you elaborate on this "nonliteral constants" point? How is it a problem if DISCONNECTING isn't technically a constant? It follows the Python convention of being in all upper-case, so the programmer understands not to rebind it. Is the problem that someone might (naively or maliciously) change the value of DISCONNECTING, or is the problem that Python doesn't fundamentally know that it won't change? ChrisA From joshua at landau.ws Fri Feb 28 09:41:20 2014 From: joshua at landau.ws (Joshua Landau) Date: Fri, 28 Feb 2014 14:41:20 +0000 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On 27 February 2014 16:14, Chris Angelico wrote: > On Fri, Feb 28, 2014 at 3:01 AM, Eric Jacoboni wrote: >> >>>>> a_tuple = ("spam", [10, 30], "eggs") >>>>> a_tuple[1] += [20] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment >> >> Ok... I accept this message as += is a reassignment of a_tuple[1] and a >> tuple is immutable... >> >> But, then, why a_tuple is still modified? > > This is a common confusion. > > The += operator does two things. First, it asks the target to please > do an in-place addition of the other operand. Then, it takes whatever > result the target gives back, and assigns it back into the target. So > with a list, it goes like this: > >>>> foo = [10, 30] >>>> foo.__iadd__([20]) > [10, 30, 20] >>>> foo = _ Would it be better to add a check here, such that if this gets raised to the top-level it includes a warning ("Addition was inplace; variable probably mutated despite assignment failure")? From wolfgang.maier at biologie.uni-freiburg.de Fri Feb 28 09:41:49 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Fri, 28 Feb 2014 14:41:49 +0000 (UTC) Subject: extend methods of decimal module Message-ID: Mark H. Harris gmail.com> writes: > > If you get a chance, take a look at the dmath.py code on: > > https://code.google.com/p/pythondecimallibrary/ > Hi Mark, here is an enhancement for your epx function. Your current version comes with the disadvantage of potentially storing extremely large values in n and d because of the multiplications in the while loop: q = D(x) n = q c = D(1) d = D(1) ex = 1 + q prev_ex = D(0) while (ex != prev_ex): prev_ex = ex c += 1 d *= c # can become a huge number n *= q # this as well ex += n/d in general, large numbers are handled well by the Decimal class, but there is a certain burden on these calculations and with VERY large numbers you can also get a decimal.Overflow: >>> exp(200000) Traceback (most recent call last): File "", line 1, in epx(190000) File "C:\Python34\dmath_rev.py", line 27, in epx n *= q decimal.Overflow: [] My re-write of the part above is: q = D(x) c = 1 new_element = q ex = 1 + new_element prev_ex = D(0) while (ex != prev_ex): prev_ex = ex c += 1 # every new element in the series is a known fraction of the # previous element, # so there is no need to store large numbers new_element *= q/c ex += new_element in my hands, this simple change increases performance (exact timing left to you) and boost the range of possible calculations: >>> epx2(1000000) Decimal('3.033215396802087545086402141E+434294') Cheers, Wolfgang From rosuav at gmail.com Fri Feb 28 09:43:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 01:43:55 +1100 Subject: Tuples and immutability In-Reply-To: References: Message-ID: On Sat, Mar 1, 2014 at 1:41 AM, Joshua Landau wrote: > Would it be better to add a check here, such that if this gets raised > to the top-level it includes a warning ("Addition was inplace; > variable probably mutated despite assignment failure")? That'd require figuring out whether or not the variable was actually mutated, and that's pretty hard to work out. So there's a FAQ entry, which Zachary already posted: http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works Also, we just answer this question every now and then :) Presumably more often on -tutor than here. ChrisA From xpysol at gmail.com Fri Feb 28 09:52:03 2014 From: xpysol at gmail.com (Wolfgang) Date: Fri, 28 Feb 2014 06:52:03 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: Message-ID: <8b1ae93d-6e92-4927-bbaf-2d8fd5e76114@googlegroups.com> Uhh, the curse of not copy-pasting everything: > >>> exp(200000) should, of course, read >>> epx(190000) > Traceback (most recent call last): > File "", line 1, in > epx(190000) > File "C:\Python34\dmath_rev.py", line 27, in epx > n *= q > decimal.Overflow: [] > From breamoreboy at yahoo.co.uk Fri Feb 28 10:06:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Feb 2014 15:06:43 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <87y50vwjq4.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> Message-ID: On 28/02/2014 11:38, Marko Rauhamaa wrote: > Switch statements provide for excellent readability in parsers and state > machines, for example. They also allow the Python compiler to optimize > the statement internally unlike long if-else chains. > There are umpteen recipes for switch statements so take your pick or if you don't like any of them write your own. Much easier than beating your head against multiple brick walls, which is what raising this one on python-ideas is likely to be. See http://legacy.python.org/dev/peps/pep-0275/ and http://legacy.python.org/dev/peps/pep-3103/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From torriem at gmail.com Fri Feb 28 09:49:25 2014 From: torriem at gmail.com (Michael Torrie) Date: Fri, 28 Feb 2014 07:49:25 -0700 Subject: Can global variable be passed into Python function? In-Reply-To: <857g8foc93.fsf@benfinney.id.au> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <857g8foc93.fsf@benfinney.id.au> Message-ID: <5310A1F5.70207@gmail.com> On 02/28/2014 01:46 AM, Ben Finney wrote: > Steven D'Aprano writes: > >> On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote: >>> class Connection: >>> IDLE = "IDLE" >> [...] >>> CONNECTED = "CONNECTED" >> [...] >>> def disconnect(self): >>> ... >>> if self.state is CONNECTED: >>> ... >> >> Why do you care that the state is *that specific* string, rather than >> any old string with the value "CONNECTED"? > > I can think of a reason: > > * When you publish the API for the ?Connection? class, > > * and another party writes code that sets ?state? to a string with the > value ?"CONNECTED"?, > > * and you implemented the check as ?self.state == "CONNECTED"?, > > * and their code works with your class and it goes into production, > > * you're then not able to change the expected value without breaking > that party's code. Sure. If he replaced the line if self.state is CONNECTED with if self.state == self.CONNECTED then he is free to change CONNECTED at any time. So yes, "is" is not necessary here. Equality checking works fine. From steve+comp.lang.python at pearwood.info Fri Feb 28 10:11:49 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 15:11:49 GMT Subject: extend methods of decimal module References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> Message-ID: <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Feb 2014 19:52:45 +1100, Chris Angelico wrote: > On Fri, Feb 28, 2014 at 6:34 PM, Steven D'Aprano > wrote: >> On Fri, 28 Feb 2014 16:00:10 +1100, Chris Angelico wrote: >> >>> If we had some other tag, like 'd', we could actually construct a >>> Decimal straight from the source code. Since source code is a string, >>> it'll be constructed from that string, and it'll never go via float. >> >> Now that Python has a fast C implementation of Decimal, I would be >> happy for Python 4000 to default to decimal floats, and require special >> syntax for binary floats. Say, 0.1b if you want a binary float, and 0.1 >> for a decimal. > > Maybe, but I believe the cdecimal module is still slower than typical > floating point. Yes, cdecimal is about 10 times slower than binary floats. But the point is, for most applications, that will be plenty fast enough. And for those where it isn't, there's always binary. > There'd also be considerations regarding NumPy and how > you'd go about working with an array of non-integer values, and so on. I would expect that numpy 4000 would still use binary floats internally, and simply so a one-off conversion of decimals to floats when you initalise the array. Converting decimals to floats is no less accurate than converting base-ten strings to floats, so there's no loss there. [...] >> But for now, backwards-compatibility requires that the default floating >> point type remains binary float. But we could maybe agitate for a >> 1.234d Decimal literal type. Care to write a PEP? >> >> :-) > > Heh. Strong consideration here: it would mean importing the decimal > module on startup. > >>>> t=time.time(); import decimal; time.time()-t > 4.5000159740448 >>>> t=time.time(); import decimal; time.time()-t > 0.0 > > A dummy import (when it's already loaded) is so fast that it's > immeasurable, but four and a half seconds to load up decimal? This is > 3.4.0b2 on Windows, btw. It was a lot quicker on my Linux box, probably > because the OS or disk cache had the file. So maybe it wouldn't be too > bad in practice; but it's still a cost to consider. I would expect that by the time Python 4000 has a concrete implementation, that figure will be a lot lower. Either due to software optimisations, or just the general increase in speed in computer hardware. >>> The question is how far Python wants to bless the Decimal type with >>> syntax - after all, if Decimal can get a literal notation, why can't >>> Fraction, and why can't all sorts of other types? And that's a huge >>> can of worms. >> >> I like Fractions, but I don't think they're important enough for the >> average users to require literal notation. > > Yeah, but where do you draw the line? Either decimal.Decimal becomes a > built-in type, That's where you draw the line. Binary floats for speed, decimals for compatibility with school arithmetic. (Well, mostly compatible.) > or there needs to be a system for constructing literals > of non-built-in types. And if Decimal becomes built-in, then why that > and not <>? 'Cos we have ten fingers and in count in decimal :-P > Also, if Decimal becomes a built-in type, does that affect the numeric > tower? I don't see why whether the type is built-in or not should affect its position in the numeric tower. (I would expect that by the time Python 4000 comes around, Decimal will be nicely integrated in the tower.) -- Steven From marko at pacujo.net Fri Feb 28 10:29:54 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 17:29:54 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> <87d2i7wbxs.fsf@elektro.pacujo.net> Message-ID: <877g8fgsr1.fsf@elektro.pacujo.net> Chris Angelico : > Can you elaborate on this "nonliteral constants" point? How is it a > problem if DISCONNECTING isn't technically a constant? It follows the > Python convention of being in all upper-case, so the programmer > understands not to rebind it. Is the problem that someone might > (naively or maliciously) change the value of DISCONNECTING, or is the > problem that Python doesn't fundamentally know that it won't change? This last point. It would make it impossible for Python to treat the switch statement as anything but an alternate form of chained if-else. A dict optimization wouldn't actually optimize anything because it would have to be constructed every time the statement is executed. switch self.state from Connection.State: case CONNECTING or CONNECTED: ... case DISONNECTING: ... else: ... would have to be transformed by Python into: _X1 = self.state _X2 = Connection.State if _X1 is _X2.CONNECTING or _X1 is _X2.CONNECTED: ... elif _X1 is _X2.DISCONNECTING: ... else: ... So optimization is gone. Then we have the syntactic burden. Python currently doesn't (seem to) have a syntactic precedent for such implicit dot notation. (Note that even Java had to complicate its syntax analogously with enums.) In "CONNECTING or CONNECTED", "or" wouldn't be an operator in an expression but a particle. Another syntactic oddity is the two indentation levels. BTW, here's a syntax that doesn't introduce any new keywords: with self.state from Connection.State: if CONNECTING or CONNECTED: ... elif DISONNECTING: ... else: ... Marko From rosuav at gmail.com Fri Feb 28 10:36:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 02:36:07 +1100 Subject: extend methods of decimal module In-Reply-To: <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Mar 1, 2014 at 2:11 AM, Steven D'Aprano wrote: >> or there needs to be a system for constructing literals >> of non-built-in types. And if Decimal becomes built-in, then why that >> and not <>? > > 'Cos we have ten fingers and in count in decimal :-P We talk in words and characters, so we have an inbuilt Unicode type. We count in decimal using Arabic numerals, so we have an inbuilt Decimal type. We also learn, in grade school, to manipulate vulgar fractions, so should Fraction be inbuilt? And we use transcendental numbers, too. And ordered mappings - most real-world interpretations of "dictionary" include that it's sorted alphabetically. Not all of them need to be inbuilt. >> Also, if Decimal becomes a built-in type, does that affect the numeric >> tower? > > I don't see why whether the type is built-in or not should affect its > position in the numeric tower. (I would expect that by the time Python > 4000 comes around, Decimal will be nicely integrated in the tower.) Well, it's more important if it's the default (and asking for an explicit float if you want it), but it would still be a bit odd for just one of the built-in numeric types to not have a place in an otherwise-tidy tower. But definitely, if it's the default, we have to ask: what about complex numbers? Are they now two Decimals? Can we get complex floats? And does all this mean there's a massive duplication going on? What happens if you sum() a Decimal, a float, a Decimal complex, and a float complex? What's the resulting type? All these questions would have to be answered. That said, though, I would support the addition of a Decimal literal, and start encouraging its use. Python startup performance is a cost, but maybe the cost of Decimal could be either reduced or deferred till first use, so that's not so obvious. Being able to tell people "Just type 0.1d and it'll be more accurate at the expense of being slower" would be a significant gain. But someone else can champion that PEP :) ChrisA From rosuav at gmail.com Fri Feb 28 10:46:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 02:46:39 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <877g8fgsr1.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> <87d2i7wbxs.fsf@elektro.pacujo.net> <877g8fgsr1.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 2:29 AM, Marko Rauhamaa wrote: > BTW, here's a syntax that doesn't introduce any new keywords: > > with self.state from Connection.State: > if CONNECTING or CONNECTED: > ... > elif DISONNECTING: > ... > else: > ... Okay, I understand your 'from' now. What it really does is introduce a new scope, a read-only one presumably (because you really do NOT want the Pandora's Box that ECMAScript's 'with' is) from which unqualified names will be looked up. I would say that that's a very reasonable idea, quite separately from a switch statement. Suppose you had something like this: with scope(Connection.State): if self.state == CONNECTING: print("I am not",DISCONNECTING) It'd require a change to the LOAD_GLOBAL opcode to have it look in multiple scopes. If you want to change something, be explicit about where the change goes, but for lookups, it would be possible to have them go to multiple places. I suspect, though, that this wouldn't fly; I already posited such a theory, and was told that CPython's internals made it much more convenient to not introduce infinitely nesting scopes - the two use-cases that I'd most look at are these: # This executes as a function doubled = [x*2 for x in lst] # This implicitly unbinds e in a finally clause try: foo() except Exception as e: pass Neither is quite perfect; the closure method is mostly clean, but has some extremely esoteric edge cases, and the unbinding means that a previous value for 'e' is lost. But both are kept rather than introducing this concept of true subscoping, because CPython's implementation makes the latter hard. Predicating your entire proposal on something that has been avoided twice and just recently turned down, though, is a good way to get the whole proposal rejected. ChrisA From donarb at nwlink.com Fri Feb 28 10:47:23 2014 From: donarb at nwlink.com (donarb) Date: Fri, 28 Feb 2014 07:47:23 -0800 (PST) Subject: Output JSON-schema from bottle application? In-Reply-To: References: Message-ID: <29018bc7-87b7-4ff6-b5d3-f3b57f95a5b0@googlegroups.com> On Thursday, February 27, 2014 7:49:07 PM UTC-8, Alec Taylor wrote: > Are there libraries for doing this? > > I would like to autogenerate JSON-schema for use inside an API explorer. > > However whenever there is a schema change; I would only like to change > the schema in one place (where possible). > > E.g.: For use here - https://github.com/salesking/json-schema-browser > > How do I do this? > > Thanks for all suggestions, > > Alec Taylor Found this on PyPi, can't say if it's suitable for your requirements. https://pypi.python.org/pypi/jsonschema From steve+comp.lang.python at pearwood.info Fri Feb 28 10:50:09 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 15:50:09 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Feb 2014 12:02:03 +0200, Marko Rauhamaa wrote: > PS On the topic of enums, when are we getting support for a switch > statement? http://legacy.python.org/dev/peps/pep-3103/ http://legacy.python.org/dev/peps/pep-0275/ -- Steven From harrismh777 at gmail.com Fri Feb 28 13:04:12 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 10:04:12 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, February 28, 2014 9:50:09 AM UTC-6, Steven D'Aprano wrote: > > PS On the topic of enums, when are we getting support for a switch > > statement? > http://legacy.python.org/dev/peps/pep-3103/ > http://legacy.python.org/dev/peps/pep-0275/ > I have reviewed these peps, and I heard Guido's 2007 keynote, as well I have heard him speak on YouTube several times about the inadvisability of a pythonized switch statement (similar to C). I think the real issue is about the syntax... because of python's unique indent strategy going back to ABC, a pythonized switch statement would play havoc with the many text parsers out there used for development (TestWrangler, and many others). Personally I would still like to see a pythonized switch statement at some point. I prefer the syntactical form of PEP 275, but unlike the notion of dropping optimization and converting to if elif else under the proverbial covers, I would prefer to see a conversion to the dict dispatch table under the covers. At any rate... and I don't think even Guido can really argue against this,... a switch statement is just more readable to human beings that a dict dispatch table, or a long if elif chain... and one of the main points of python (going all the way back to ABC) was to make very highly readable code. marcus From harrismh777 at gmail.com Fri Feb 28 13:17:21 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 10:17:21 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: Message-ID: <8fc1043a-2ea2-4c8e-8ac4-c6829614c8cf@googlegroups.com> On Friday, February 28, 2014 8:41:49 AM UTC-6, Wolfgang Maier wrote: > Hi Mark, > > here is an enhancement for your epx function. > > Wolfgang hi Wolfgang, thanks much! As a matter of point in fact, I ran into this little snag and didn't understand it, because I was thinking that outside of memory there should not be any overflow for decimal in python / which means, I suppose, that the C accelerated decimal does have some built-in limitations. So, yes, I got some overflows too... Also, thanks for your comment about my D(str()) function... from Oscar to you, and everyone else... well that has to go. Well, now I gotta get busy and clean this thing up... Thanks again. marcus From harrismh777 at gmail.com Fri Feb 28 13:23:38 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 10:23:38 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <63868b32-5206-435d-aa3d-f3040f65f72b@googlegroups.com> Message-ID: <40c397ad-079a-4086-b6f6-52abb1d5d9de@googlegroups.com> On Friday, February 28, 2014 2:54:12 AM UTC-6, Wolfgang Maier wrote: > Since by now, I guess, we all agree that using the string representation is > the wrong approach, you can simply use Decimal instead of D() throughout > your code. > Best, > Wolfgang hi Wolfgang, ...right... I'm going to clean it up. Thanks, 'preciate it. From harrismh777 at gmail.com Fri Feb 28 13:34:32 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 10:34:32 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <61ddea56-7417-4520-ac76-f1cf6400bd9a@googlegroups.com> On Friday, February 28, 2014 9:11:49 AM UTC-6, Steven D'Aprano wrote: > >> Now that Python has a fast C implementation of Decimal, I would be > >> happy for Python 4000 to default to decimal floats, and require special > >> syntax for binary floats. Say, 0.1b if you want a binary float, and 0.1 > >> for a decimal. > Steven Yes. ... and for clarification back to one of my previous comments, when I refer to 'float' I am speaking of the IEEE binary floating point representation built-in everywhere... including the processor! ... not the concept of tracking a floating point, say in decimal for instance. Isn't it amazing... the IEEE binary float or double is so entrenched (including the processor) that even though it has inherent problems... we are kinda stuck with it for a while. I have been thinking that we need extended instructions in the processor (similar to MMX) to handle accelerating decimal float floating point arithmetic, as in the decimal module. Back in the day when memory was expensive binary floats made sense... but today there is no reason to continue to stick with that limitation. And on the other hand, think of all the amazing things folks have done with floats and doubles... all these years. marcus From rosuav at gmail.com Fri Feb 28 13:37:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 05:37:37 +1100 Subject: extend methods of decimal module In-Reply-To: <61ddea56-7417-4520-ac76-f1cf6400bd9a@googlegroups.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> <61ddea56-7417-4520-ac76-f1cf6400bd9a@googlegroups.com> Message-ID: On Sat, Mar 1, 2014 at 5:34 AM, Mark H. Harris wrote: > Yes. ... and for clarification back to one of my previous comments, when I refer to 'float' I am speaking of the IEEE binary floating point representation built-in everywhere... including the processor! ... not the concept of tracking a floating point, say in decimal for instance. > Are you aware that IEEE 754 includes specs for decimal floats? :) http://en.wikipedia.org/wiki/IEEE_floating_point#Basic_formats ChrisA From marko at pacujo.net Fri Feb 28 13:53:15 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 20:53:15 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87iorzf4ro.fsf@elektro.pacujo.net> "Mark H. Harris" : > I think the real issue is about the syntax... because of python's > unique indent strategy going back to ABC, a pythonized switch > statement would play havoc with the many text parsers out there used > for development (TestWrangler, and many others). I also took a look at the proposals. I don't think it's the editor issue. The variant I proposed most recently: with self.state from Connection.State: if CONNECTING or CONNECTED: ... elif DISONNECTING: ... else: ... would be handled gracefully by all sane python editors, I believe. The main problem is that it can't be optimized effectively without bringing in an element of preprocessing. That preprocessing is done by the human developer with the dict dispatch table, but nothing in regular Python gives the compiler enough guaranteed information to build the dispatch table. There are ways to be smart, but it would be a lot of additional code for the compiler for a questionable performance gain. > a switch statement is just more readable to human beings that a dict > dispatch table, or a long if elif chain... and one of the main points > of python (going all the way back to ABC) was to make very highly > readable code. A dict dispatch table is just awful. At least have the decency of creating inner classes. ... which brings up the point for another post... Marko From rosuav at gmail.com Fri Feb 28 13:59:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 05:59:44 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87iorzf4ro.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 5:53 AM, Marko Rauhamaa wrote: > A dict dispatch table is just awful. Really? How is that? I've used them, often. Yes, there are times when I could express something more cleanly with a C-style switch statement, but other times the dispatch table is fundamentally cleaner. I shared an example a few posts ago in this thread; care to elaborate on how it's "just awful"? ChrisA From marko at pacujo.net Fri Feb 28 14:20:52 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 21:20:52 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> Message-ID: <877g8ff3hn.fsf@elektro.pacujo.net> Chris Angelico : > On Sat, Mar 1, 2014 at 5:53 AM, Marko Rauhamaa wrote: >> A dict dispatch table is just awful. > > Really? How is that? I've used them, often. Yes, there are times when > I could express something more cleanly with a C-style switch > statement, but other times the dispatch table is fundamentally > cleaner. I shared an example a few posts ago in this thread; care to > elaborate on how it's "just awful"? Your example: compare_key = { # Same target(s). ast.Assign: lambda node: ' '.join(dump(t) for t in node.targets), # Same target and same operator. ast.AugAssign: lambda node: dump(node.target) + dump(node.op) + "=", # A return statement is always compatible with another. ast.Return: lambda node: "(easy)", # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. ast.Expr: lambda node: "(maybe)", # These ones are never compatible, so return some # object that's never equal to anything. ast.Import: lambda node: float("nan"), ast.ImportFrom: lambda node: float("nan"), ast.Pass: lambda node: float("nan"), ast.Raise: lambda node: float("nan"), ast.If: lambda node: float("nan"), } vs (my proposal): with key from ast: if Assign: return ' '.join(dump(t) for t in node.targets) elif AugAssign: # Same target and same operator. return dump(node.target) + dump(node.op) + "=" elif Return: # A return statement is always compatible with another. return "(easy)" elif Expr: # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. return "(maybe)" else: # These ones are never compatible, so return some # object that's never equal to anything. return float("nan") Which do *you* find more readable? Marko From harrismh777 at gmail.com Fri Feb 28 14:26:48 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 11:26:48 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> <5310a735$0$29985$c3e8da3$5496439d@news.astraweb.com> <61ddea56-7417-4520-ac76-f1cf6400bd9a@googlegroups.com> Message-ID: On Friday, February 28, 2014 12:37:37 PM UTC-6, Chris Angelico wrote: > > Are you aware that IEEE 754 includes specs for decimal floats? :) > Yes. I am from back in the day... way back... so 754 1985 is what I have been referring to. IEEE 854 1987 and the generalized IEEE 754 2008 have the specs for decimal floating point included. Everyone is thinking in the same general direction... its kinda like the Y2K problem based on a stupid limit that because of entrenchment takes forever to resolve moving forward with technological advance. marcus From harrismh777 at gmail.com Fri Feb 28 14:39:11 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 11:39:11 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: <53103c03$0$11113$c3e8da3@news.astraweb.com> References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> Message-ID: On Friday, February 28, 2014 1:34:27 AM UTC-6, Steven D'Aprano wrote: > Now that Python has a fast C implementation of Decimal, I would be happy > for Python 4000 to default to decimal floats, and require special syntax > for binary floats. Say, 0.1b if you want a binary float, and 0.1 for a > decimal. > > Steven Just a side note on how fast... Stefan Krah's performance specs state 120x improvement on many multiplication computations (like PI for instance)... well, its not hype. On my P7350 dual core 2Ghz Intel box (2009 mac mini) running Gnu/Linux, I used the piagm(n) AGM routine from my dmath.py library to benchmark against my own C routines, BC, and a couple of other math packages. The results were phenomenal... my processor is a low-end gem as compared to modern SOTA processors out there, and even yet: 1 million digits of PI --- 13 minutes 10 million digits of PI --- 3 hours 55 minutes Those were new digit/time PRs for me, by-the-by... and the other methods I've used don't even come close... so, Stefan is doing some kind of transform in "decimal" over and above just compiling the extension in C that is really speeding things up quite a bit. (that was just a random side note, sorry) From harrismh777 at gmail.com Fri Feb 28 15:17:02 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 12:17:02 -0800 (PST) Subject: extend methods of decimal module In-Reply-To: References: <02cdd9c7-aef7-4cc7-a813-cd1c9627ceb4@googlegroups.com> <94b1962a-0004-4c5b-b484-972a166b88b5@googlegroups.com> <55525f2c-fd3a-4927-b642-2dbf5eae7e9b@googlegroups.com> <360e87d2-4daf-4222-8ebe-51f3e4d1fade@googlegroups.com> <9f7b535f-9e5d-45df-96f6-6cd8f6b4a524@googlegroups.com> <530fff58$0$11113$c3e8da3@news.astraweb.com> <53103c03$0$11113$c3e8da3@news.astraweb.com> Message-ID: <92393442-4624-4d50-9e0a-f7a36d3aca4c@googlegroups.com> On Friday, February 28, 2014 1:39:11 PM UTC-6, Mark H. Harris wrote: > On Friday, February 28, 2014 1:34:27 AM UTC-6, Steven D'Aprano wrote: > > > > > Now that Python has a fast C implementation of Decimal, I would be happy > > > for Python 4000 to default to decimal floats, and require special syntax > > > for binary floats. Say, 0.1b if you want a binary float, and 0.1 for a > > > decimal. > > > > > > Steven > > > > Just a side note on how fast... Stefan Krah's performance specs state 120x improvement on many multiplication computations (like PI for instance)... well, its not hype. > > > > On my P7350 dual core 2Ghz Intel box (2009 mac mini) running Gnu/Linux, I used the piagm(n) AGM routine from my dmath.py library to benchmark against my own C routines, BC, and a couple of other math packages. The results were phenomenal... my processor is a low-end gem as compared to modern SOTA processors out there, and even yet: > > > > 1 million digits of PI --- 13 minutes > > 10 million digits of PI --- 3 hours 55 minutes > Oh, rats(), I forgot the comparison.... Py3.2 [ 1 million digits : 21 hours 21 minutes ] --> Py3.3.4 [ 1 million digits : 13 minutes ] ... that is astounding. All I did was install 3.3.4, no change in the AGM routine. Cheers From harrismh777 at gmail.com Fri Feb 28 15:22:31 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 12:22:31 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <877g8ff3hn.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> Message-ID: On Friday, February 28, 2014 1:20:52 PM UTC-6, Marko Rauhamaa wrote: > > Which do *you* find more readable? > Yep, my point exactly. nice illustration. From marko at pacujo.net Fri Feb 28 16:03:25 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 28 Feb 2014 23:03:25 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> Message-ID: <87wqgfdk6a.fsf@elektro.pacujo.net> "Mark H. Harris" : > Yep, my point exactly. nice illustration. So now, for you and me: let's compare. if key is ast.Assign: return ' '.join(dump(t) for t in node.targets) elif key is ast.AugAssign: # Same target and same operator. return dump(node.target) + dump(node.op) + "=" elif key is ast.Return: # A return statement is always compatible with another. return "(easy)" elif key is ast.Expr: # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. return "(maybe)" else: # These ones are never compatible, so return some # object that's never equal to anything. return float("nan") vs (my proposal): with key from ast: if Assign: return ' '.join(dump(t) for t in node.targets) elif AugAssign: # Same target and same operator. return dump(node.target) + dump(node.op) + "=" elif Return: # A return statement is always compatible with another. return "(easy)" elif Expr: # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. return "(maybe)" else: # These ones are never compatible, so return some # object that's never equal to anything. return float("nan") Which do *you* find more readable? Marko From breamoreboy at yahoo.co.uk Fri Feb 28 16:23:36 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Feb 2014 21:23:36 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <87wqgfdk6a.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> Message-ID: On 28/02/2014 21:03, Marko Rauhamaa wrote: > "Mark H. Harris" : > >> Yep, my point exactly. nice illustration. > > So now, for you and me: let's compare. > > if key is ast.Assign: > return ' '.join(dump(t) for t in node.targets) > elif key is ast.AugAssign: > # Same target and same operator. > return dump(node.target) + dump(node.op) + "=" > elif key is ast.Return: > # A return statement is always compatible with another. > return "(easy)" > elif key is ast.Expr: > # Calling these never compatible is wrong. Calling them > # always compatible will give lots of false positives. > return "(maybe)" > else: > # These ones are never compatible, so return some > # object that's never equal to anything. > return float("nan") > > vs (my proposal): > > with key from ast: > if Assign: > return ' '.join(dump(t) for t in node.targets) > elif AugAssign: > # Same target and same operator. > return dump(node.target) + dump(node.op) + "=" > elif Return: > # A return statement is always compatible with another. > return "(easy)" > elif Expr: > # Calling these never compatible is wrong. Calling them > # always compatible will give lots of false positives. > return "(maybe)" > else: > # These ones are never compatible, so return some > # object that's never equal to anything. > return float("nan") > > Which do *you* find more readable? > > > Marko > http://c2.com/cgi/wiki?SwitchStatementsSmell -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From steve+comp.lang.python at pearwood.info Fri Feb 28 18:04:01 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 23:04:01 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> Message-ID: <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Feb 2014 20:53:15 +0200, Marko Rauhamaa wrote: > "Mark H. Harris" : > >> I think the real issue is about the syntax... because of python's >> unique indent strategy going back to ABC, a pythonized switch statement >> would play havoc with the many text parsers out there used for >> development (TestWrangler, and many others). > > I also took a look at the proposals. I don't think it's the editor > issue. The variant I proposed most recently: > > with self.state from Connection.State: > if CONNECTING or CONNECTED: > ... > elif DISONNECTING: > ... > else: > ... > > would be handled gracefully by all sane python editors, I believe. > > The main problem is that it can't be optimized effectively without > bringing in an element of preprocessing. You can't have it both ways: you cannot claim that switch or case is more readable than a chain of if...elif, and then propose a syntax which is effectively a chain of if...elif while still claiming it is an improvement. It's not. All you've done is introduce an element of implicit magic to the syntax. >> a switch statement is just more readable to human beings that a dict >> dispatch table, or a long if elif chain... and one of the main points >> of python (going all the way back to ABC) was to make very highly >> readable code. > > A dict dispatch table is just awful. At least have the decency of > creating inner classes. Why (how?) would you want to use *multiple* classes for a single switch? Dict dispatch tables are elegant, attractive and efficient if you are using pre-existing functions or functions you can create using lambda: dispatch = { BLUE: handle_blue, RED: lambda arg: process(arg, this, that), ... } dispatch[key](something) It gets unwieldy if the functions don't already exist and cannot be embedded as a single expression. In that case, there are two simple approaches for when your switch cases are strings: - move the functions into a class, as self-less methods, then use the class __dict__ as the dispatch table; - or move the functions into an external module, and use the module __dict__ as the dispatch table. Even when you're not switching on strings, with the aid of a simple helper function, it's trivial: dispatch = {} def case(*args): def decorator(func): for a in arg: dispatch[a] = func return func return decorator class Dispatch: @case(BLUE) def handle_blue(something): ... @case(RED): def handle_red(something): ... dispatch[BLUE](something) There are all sorts of simple and neat ways to handle switches in Python. That's why the pressure on the language to grow special syntax is quite low. It simply isn't important enough. -- Steven From marko at pacujo.net Fri Feb 28 18:06:38 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 01:06:38 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> Message-ID: <87sir2et1d.fsf@elektro.pacujo.net> Mark Lawrence : > http://c2.com/cgi/wiki?SwitchStatementsSmell Your brief summary, please, Mark? Anyway, the first 1000 lines or so that I managed to read from that page stated a valid principle, which however doesn't invalidate the existence of a switch statement. A colleague of mine taught me decades back that the whole point of OO was the avoidance of if and switch statements. So if your code has an if or switch statement, chances are you are doing something wrong. I agree. However, like all other maxims, that principle, too, has exceptions. Two recurring examples are parsers/decoders and state machines. Sure, you can implement states beautifully with objects/classes (and I do do that when performance is not an issue), but having experimented with different implementation techniques (in C, C++ and Java), I have concluded that switch statements are often unbeatable in performance and clarity. And I sometimes run into convoluted factory (anti)patterns whose sole purpose is to avoid straightforward switch statements in a decoder. Marko From ben+python at benfinney.id.au Fri Feb 28 18:17:10 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 10:17:10 +1100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: <85wqgen7yh.fsf@benfinney.id.au> Marko Rauhamaa writes: > Ben Finney : > > > First reason: This is better done by making it clear the value is an > > arbitrary object that won't be compared for equality. Just use > > ?object()? to creeate each value and be done with it. That's a hack, > > but it's better than pretending you'll use the string as a string of > > text and then breaking that expectation. [?] > > So, I think Marko's use case is not a justification for comparing > > string values with ?is?. > > [?] However, since any distinct objects will do, there is nothing > preventing you from using string objects. As has been pointed out to you, the whole point here is that string objects often *are not* distinct, despite conceptually having distinct cretion in the source. That's why an ?object()? invocation is recommended: because it *will* create distinct objects. Strings do not have that property. So strings are *not* suitable for this use case. -- \ ?It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place.? ?Henry L. | _o__) Mencken | Ben Finney From ben+python at benfinney.id.au Fri Feb 28 18:33:27 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 10:33:27 +1100 Subject: References, and avoiding use of ???variable??? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <85ha7knedo.fsf_-_@benfinney.id.au> Message-ID: <85sir2n77c.fsf@benfinney.id.au> Neil Cerutti writes: > On 2014-02-28, Ben Finney wrote: > > Right. I would like, ideally, for the Python documentation to > > avoid mentioning that term entirely; and I would hope for that > > to promote a better understanding of Python's data model. > > I like the characteristic of Python that assignment and argument > passing work the same way. Yes. They both work by binding a name to a value. > The tutorial makes things sound more high-falutin' than that > [Tutorial 4.6 Defining Functions]: > > The actual parameters (arguments) to a function call are > introduced in the local symbol table of the called function > when it is called; thus, arguments are passed using call by > value (where the value is always an object reference, not the > value of the object). [...] > > How about: > > The actual parameters (arguments) to a function call are passed > via assignment to the variables in the local symbol table of > the called function. > > Am I oversimplifying? As you can see by what you quoted from me above, I think the use of ?variable? here is unnecessarily confusing. That whole chapter of the tutorial talks about ?variable? and ?variable assignment?, when IMO it should avoid those terms and use the clearer terminology of ?reference?, ?name?, and ?binding a name to a value?. (Why don't I submit these documentation changes myself? That's a matter for a separate thread.) -- \ ?All my life I've had one dream: to achieve my many goals.? | `\ ?Homer, _The Simpsons_ | _o__) | Ben Finney From steve+comp.lang.python at pearwood.info Fri Feb 28 18:33:31 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Feb 2014 23:33:31 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> Message-ID: <53111ccb$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Feb 2014 21:20:52 +0200, Marko Rauhamaa wrote: > Your example: [snip] I'm not going to show the example as quoted by you, because my news client is wrapping it in ugly ways and I don't want to spend the time fixing it. I'll just say that, as given, it's a great big wall of text, a solid and ugly block, but can be easily fixed to be more readable and look more like a switch with a judicious amount of indentation: compare_key = { ast.Assign: # Same target(s). lambda node: ' '.join(dump(t) for t in node.targets), ast.AugAssign: # Same target and same operator. lambda node: dump(node.target) + dump(node.op) + "=", ast.Return: # A return statement is always compatible with another. lambda node: "(easy)", ast.Expr: # Calling these never compatible is wrong. Calling them # always compatible will give lots of false positives. lambda node: "(maybe)", } which compares favourably with your version: > with key from ast: > if Assign: > return ' '.join(dump(t) for t in node.targets) > elif AugAssign: > # Same target and same operator. > return dump(node.target) + dump(node.op) + "=" > elif Return: > # A return statement is always compatible with another. > return "(easy)" > elif Expr: > # Calling these never compatible is wrong. Calling them > # always compatible will give lots of false positives. > return "(maybe)" I've deliberately dropped out "else" clause, because the two code snippets as shown by you don't do the same thing. The dict dispatch table shown initially lists the remaining keys allowed: ast.Import, ast.ImportFrom, ast.Pass, ast.Raise, ast.If and sets them all individually to five different but equivalent functions, lambda node: float("nan"). This is both good and bad: good, because it enumerates precisely what keys are expected, and will fail if given an unexpected value; bad because it requires repeating yourself five times to give the five keys the same function: ast.Import: lambda node: float("nan"), ast.ImportFrom: lambda node: float("nan"), etc. (Actually five different functions which happen to do exactly the same thing.) On the other hand, your with...if...elif version simply uses a single "else" statement, which means it will accept *any other value at all*, not just the five keys accepted by Chris' version. So there is a semantic difference between the two. In practice, sometimes you want a strict dispatch table that raises an error when given something unexpected, other times nothing is unexpected and you want an "else" or "otherwise" clause that captures everything. There are all sorts of ways to handle this in practice, e.g. using defaultdict, or subclassing dict and giving it a __missing__ method, or simply deal with the default case outside of the table itself: # instead of this dispatch[key](node) # do this dispatch.get(key, lambda node: float('nan'))(node) > Which do *you* find more readable? With proper code layout, the dict-based dispatch table is at least as readable, and it avoids needing any magic compiler support. -- Steven From harrismh777 at gmail.com Fri Feb 28 18:36:06 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 15:36:06 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: <87wqgfdk6a.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> Message-ID: <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> On Friday, February 28, 2014 3:03:25 PM UTC-6, Marko Rauhamaa wrote: > > Marko ... and between me and you, here is a snip from dmath.py from the atan(x) function: if (n**2 < D(1)): a = __atan__(n) elif (n == D(1)): a = gpi/4 elif (n == D(-1)): a = -(gpi/4) elif (n < D(-1)): a = __atan__Lt_neg1__(n) else: a = __atan__Gt_1__(n) This if--elif--else is not only ugly, its just not readable either, and besides that, its not elegant, nor is it humanly helpful... its does work though, and its absolutely necessary. ugh. First, its not immediately clear what it does. Well, there isn't just one atan(x) routine, there are at least four of them, depending on whether you're a purist, and they must be selected. Second, because of the strict intent ideology of python in the first place, I can't indent this code to make it more readable without breaking python's syntax. Third, this is a VERY simple if elif block. More complex ones are much worse... for human reading that is... I know its a pain in the neck, but python does need a switch statement. Is it a stubborn question? I don't really think that almost every modern computer language has a switch block because of some C paradigm. I think its because most coders find them useful, at least readable, and therefore essential. On the other hand, I have coded many scripts and lots of commercial software that used no switch blocks at all... particularly my C++ and Java stuff. Sooo... From ben+python at benfinney.id.au Fri Feb 28 19:02:46 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 11:02:46 +1100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <87sir2et1d.fsf@elektro.pacujo.net> Message-ID: <85k3cen5uh.fsf@benfinney.id.au> Marko Rauhamaa writes: > Mark Lawrence : > > > http://c2.com/cgi/wiki?SwitchStatementsSmell > > Your brief summary, please, Mark? > > Anyway, the first 1000 lines or so that I managed to read from that page > stated a valid principle, which however doesn't invalidate the existence > of a switch statement. The first sentence on that page explains that it's describing a ?code smell?, with a link to the page which explains that term . Did you read that page? A code smell is an indication that something is wrong in the code. That indication is not 100% accurate; the point is that it's accurate enough to be worth further scrutiny to find what problem may be causing the smell. > However, like all other maxims, that principle, too, has exceptions. Of course. That's the point of describing something as a ?code smell?: it may have exceptions where the smell does not indicate an actual problem, but those are not the normal case where the smell is encountered. More often, it indicates a problem that should be fixed. -- \ ?Members of the general public commonly find copyright rules | `\ implausible, and simply disbelieve them.? ?Jessica Litman, | _o__) _Digital Copyright_ | Ben Finney From marko at pacujo.net Fri Feb 28 19:03:51 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 02:03:51 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87ob1qeqe0.fsf@elektro.pacujo.net> Steven D'Aprano : > You can't have it both ways: you cannot claim that switch or case is > more readable than a chain of if...elif, and then propose a syntax > which is effectively a chain of if...elif while still claiming it is > an improvement. It's not. All you've done is introduce an element of > implicit magic to the syntax. You may be right that Python has too many practical problems for a truly fitting switch syntax. > Why (how?) would you want to use *multiple* classes for a single > switch? Well, I was just given a whole link on the very topic: Here's a shorter one: Anyway, while implementing states as singleton inner class instances is elegant and highly readable, the technique suffers in one significant respect: it can be very slow. Often a state machine has numerous states but the typical execution path only visits a few of them. However, the pattern calls for declaring classes (or instances) for all states in the state machine constructor. Switch statements make it possible to avoid this creation overhead. > Dict dispatch tables are elegant, attractive and efficient if you are > using pre-existing functions or functions you can create using lambda: I beg to differ. The dict dispatch tables are very hard to read. The fully blown-out if-else chain beats it in elegance hands down. > There are all sorts of simple and neat ways to handle switches in > Python. That's why the pressure on the language to grow special syntax > is quite low. It simply isn't important enough. Of course the threshold for new syntax should be exceptionally high. Python as a language is already close to the sweet spot. Marko From marko at pacujo.net Fri Feb 28 19:11:53 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 02:11:53 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> Message-ID: <87k3ceeq0m.fsf@elektro.pacujo.net> Ben Finney : > As has been pointed out to you, the whole point here is that string > objects often *are not* distinct, despite conceptually having distinct > cretion in the source. You know full well that this initialization creates references to distinct objects: class ABC: IDLE = "IDLE" CONNECTING = "CONNECTING" CONNECTED = "CONNECTED" DISCONNECTING = "DISCONNECTING" DISCONNECTED = "DISCONNECTED" The 5 constants can (and should) be distinguished with the "is" operator. Using "==" in this case would be slightly misleading. You could define: class ABC: IDLE = None CONNECTING = 1 CONNECTED = list DISCONNECTING = MyDisconnecting(9) DISCONNECTED = float("nan") without changing the functionality of the state machine (as long as "is" is used to identify the state). Marko From harrismh777 at gmail.com Fri Feb 28 19:22:02 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 16:22:02 -0800 (PST) Subject: Tuples and immutability In-Reply-To: References: Message-ID: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> On Thursday, February 27, 2014 10:01:39 AM UTC-6, Eric Jacoboni wrote: > > ('spam', [10, 30, 20], 'eggs') > > I get a TypeError for an illegal operation, but this operation is still > > completed? hi Eric, others have answered your question specifically, but the issue (which is recurring) begs a couple of questions, which will also be recurring... ehem. This little snag (if it can be called that) is a side effect from two python inherent design considerations: 1) not to be a nudge, but dynamic typing is the first... 2) and the concept of immutability is the second. I'll address the second first by asking a question... should an immutable type (object) be able to hold (contain) mutable objects ... should tuples be allowed to hold lists? lists within a tuple should be converted to tuples. If you want a tuple to hold a list, make it a list in the first place. Tuples should not be changed... and as you point out... half changing a tuple is not a good condition if there is an exception... Which brings me to my second point... dynamic binding... (and everything associated with that) is at play here too.... please, don't get me wrong, this is not flame bait and I'm not advocating static binding, nor do I want static binding, nor do I want to open that can of worms again... just saying. I really think this is a bug; honestly. IMHO it should be an error to use += with an immutable type and that means not at all. In other words, the list should not even be considered, because we're talking about changing a tuple... which should not be changed (nor should its members be changed). Soooo.... the type does not support item assignment, yet the item got assigned. This is at least inconsistent... and to my small mind means... bug report. :) From steve+comp.lang.python at pearwood.info Fri Feb 28 19:22:51 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Mar 2014 00:22:51 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <8738j3xynr.fsf@elektro.pacujo.net> <87mwhbwhil.fsf@elektro.pacujo.net> Message-ID: <5311285b$0$29985$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Feb 2014 14:25:54 +0200, Marko Rauhamaa wrote: > Chris Angelico : > >> On Fri, Feb 28, 2014 at 10:30 PM, Marko Rauhamaa >> wrote: >>> Chris Angelico : >>> a.state = a.INIT >> >> In theory, yes. If that's all people will ever do, then you can safely >> use == to check. Why are you using is? > > The main reason to use "is" is to indicate that the object is a sentinel > object whose identity is what is meaningful, not the content. Using == > would work but would give some poor soul the idea that the state > variable could hold any imaginable string. Why should identity be important for testing the state of a state variable? There is a good reason for using "is" with actual sentinel values, because we wish to protect against the (rare) situation where some other object happens to compare equal to our sentinel. But why should states be treated as sentinels instead of ordinary values where identity is not important? The most important reason to *not* use "is" is that doing so *implicitly* exposes an implementation detail, namely that each state is a singleton. Identity shouldn't be that important. Why does it matter that there is only a single instance of the state INIT (say)? Why shouldn't an implementation feel free to create and discard as many instances as needed? Whether there is one INIT instance or a million is an implementation detail that shouldn't matter to the user, they should be able to just write "if state == INIT" and get the right answer. > The implementation should be able to change the state objects to any > (distinct) objects at all (say, the new enums, or ints, or some more > elaborate class instances) without any changes in the code. In practice, this is often not true. Often you have compatibility requirements with (say) external libraries or protocols, where the states are set by value. E.g. you may have to be compatible with a C library where the states are given as ints. But more importantly, you don't actually have that much freedom to change the states. Common sense[1] tells us that we're not really free to replace states with arbitrary objects, they should be values that match the name of the state. Given a state BLUE, we want inspecting it in a debugger, or printing it, to display BLUE, not sBxvGe74sk or 23 or and certainly not YELLOW. After all, the states are *symbols*, which means they don't really have any (internal) state or behaviour apart from their name. (In Python, we have to given them a value, we can't just refer to name BLUE without giving it a value, but the value isn't important. What we really care about is the name. Fundamentally, there's not terribly much difference between an API that says: "The colour variable can be BLUE or YELLOW" versus one that says: "The colour variable can be 'BLUE' or 'YELLOW'" In both cases, you can't change the public API. Adding or subtracting a couple of quotation marks is not a big deal (although perhaps it is a small deal). Although it may seem at first that by exposing the implementation ("states are given by strings") you're limiting your freedom to change the implementation, in practice you don't actually have that much freedom to do so, and very likely you're never[2] going to use that freedom anyway. States are symbols, and rarely need behaviour apart from equality, so why would you bother to change the implementation? (If this sounds like a mild argument against Enums, I guess it is. After all, Python worked quite well for 20+ years without Enums. Using strings as "poor man's enums" works well enough. That's why it took so long for Python to get "proper" enums, and even then, they aren't a core feature of the language.) [1] Common sense: so rare it is practically a super power. [2] Well, hardly ever. -- Steven From arielin82 at gmail.com Fri Feb 28 13:45:59 2014 From: arielin82 at gmail.com (=?ISO-8859-1?Q?Ariel_Arga=F1araz?=) Date: Fri, 28 Feb 2014 15:45:59 -0300 Subject: Persist python objects without a relational DB Message-ID: Hi, I would like to know which is the best framework to persist my python objects in disk. I heard about ZODB (http://www.zodb.org/en/latest/index.html) is this the best or there is another ? -- Ariel Arga?araz -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko at pacujo.net Fri Feb 28 19:32:18 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 02:32:18 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: <87d2i6ep2l.fsf@elektro.pacujo.net> "Mark H. Harris" : > if (n**2 < D(1)): > a = __atan__(n) > elif (n == D(1)): > a = gpi/4 > elif (n == D(-1)): > a = -(gpi/4) > elif (n < D(-1)): > a = __atan__Lt_neg1__(n) > else: > a = __atan__Gt_1__(n) Drop the outermost parentheses in the if statements. They add to the clutter. Anyway, how would you express the above in, say, Java? Marko From ned at nedbatchelder.com Fri Feb 28 19:40:06 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 28 Feb 2014 19:40:06 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: On 2/28/14 6:36 PM, Mark H. Harris wrote: > On Friday, February 28, 2014 3:03:25 PM UTC-6, Marko Rauhamaa wrote: >> >> Marko > > ... and between me and you, here is a snip from dmath.py from the atan(x) function: > > if (n**2 < D(1)): > a = __atan__(n) > elif (n == D(1)): > a = gpi/4 > elif (n == D(-1)): > a = -(gpi/4) > elif (n < D(-1)): > a = __atan__Lt_neg1__(n) > else: > a = __atan__Gt_1__(n) > > This if--elif--else is not only ugly, its just not readable either, and besides that, its not elegant, nor is it humanly helpful... its does work though, and its absolutely necessary. ugh. > > First, its not immediately clear what it does. Well, there isn't just one atan(x) routine, there are at least four of them, depending on whether you're a purist, and they must be selected. > > Second, because of the strict intent ideology of python in the first place, I can't indent this code to make it more readable without breaking python's syntax. > > Third, this is a VERY simple if elif block. More complex ones are much worse... for human reading that is... > > I know its a pain in the neck, but python does need a switch statement. Is it a stubborn question? I don't really think that almost every modern computer language has a switch block because of some C paradigm. I think its because most coders find them useful, at least readable, and therefore essential. I don't understand: you show an if/elif chain that cannot be expressed as a switch statement (because it uses < ), and then conclude that Python needs a switch statement? That doesn't make any sense. -- Ned Batchelder, http://nedbatchelder.com From steve+comp.lang.python at pearwood.info Fri Feb 28 19:44:33 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Mar 2014 00:44:33 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> Message-ID: <53112d71$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Mar 2014 02:03:51 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> You can't have it both ways: you cannot claim that switch or case is >> more readable than a chain of if...elif, and then propose a syntax >> which is effectively a chain of if...elif while still claiming it is an >> improvement. It's not. All you've done is introduce an element of >> implicit magic to the syntax. > > You may be right that Python has too many practical problems for a truly > fitting switch syntax. I didn't make that claim. My claim is that your suggested syntax is no real improvement over existing syntax. >> Why (how?) would you want to use *multiple* classes for a single >> switch? > > Well, I was just given a whole link on the very topic: > > No no no, you've deleted the context. I'm not talking about making a switch statement unnecessary by using polymorphism. I was responding to your claim that instead of using a dict, one should: [quote] At least have the decency of creating inner classes. [end quote] I don't understand this. That's why I asked why and how. I can only imagine you mean something like this: class Outer: class InnerOne: ... class InnerTwo: ... class InnerThree: ... but I don't see how you get from that to the functionality of a dispatch table, or what you're supposed to do with the nested classes. > Here's a shorter one: > > That's not a way of implementing switching. That's a way of *avoiding* switching. Despite the name, it has little to do with state machines. > Anyway, while implementing states as singleton inner class instances is > elegant and highly readable, O_o That's terribly, terribly inelegant. Why not use the class objects themselves, instead of instantiating them? Even then, you haven't escaped the use of a dict dispatch table, or a chain of if...elif. You've just defined the symbols you use. > the technique suffers in one significant > respect: it can be very slow. Particularly if you program Java in Python. > Often a state machine has numerous states > but the typical execution path only visits a few of them. However, the > pattern calls for declaring classes (or instances) for all states in the > state machine constructor. Switch statements make it possible to avoid > this creation overhead. How do you avoid creating the classes or instances? If they haven't been created, how can the compiler reference them? >> Dict dispatch tables are elegant, attractive and efficient if you are >> using pre-existing functions or functions you can create using lambda: > > I beg to differ. The dict dispatch tables are very hard to read. The > fully blown-out if-else chain beats it in elegance hands down. Only if you lay out the dict badly. Poorly written code is ugly and hard to read no matter what you do. -- Steven From ben+python at benfinney.id.au Fri Feb 28 19:50:37 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 11:50:37 +1100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87k3ceeq0m.fsf@elektro.pacujo.net> Message-ID: <85fvn2n3mq.fsf@benfinney.id.au> Marko Rauhamaa writes: > Ben Finney : > > > As has been pointed out to you, the whole point here is that string > > objects often *are not* distinct, despite conceptually having distinct > > cretion in the source. > > You know full well that this initialization creates references to > distinct objects: > > class ABC: > IDLE = "IDLE" > CONNECTING = "CONNECTING" > CONNECTED = "CONNECTED" > DISCONNECTING = "DISCONNECTING" > DISCONNECTED = "DISCONNECTED" > > The 5 constants can (and should) be distinguished with the "is" > operator. >From each other, of course they're distinct, because they are unequal. They are *not* necessarily distinct from other strings with equal value, defined elsewhere. That's what has been pointed out to you many times. So, either you care about these values being distinct from all others because you want to compare them with ?is? (and so strings are a poor choice); or you don't care about that, and you should instead compare these values with the equality operator ?==?. Either way, don't compare strings with ?is?. If you want objects you can compare reliably with ?is?, use some other type. -- \ ?Don't be afraid of missing opportunities. Behind every failure | `\ is an opportunity somebody wishes they had missed.? ?Jane | _o__) Wagner, via Lily Tomlin | Ben Finney From ben+python at benfinney.id.au Fri Feb 28 19:53:51 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 11:53:51 +1100 Subject: Persist python objects without a relational DB References: Message-ID: <85bnxqn3hc.fsf@benfinney.id.au> Ariel Arga?araz writes: > Hi, I would like to know which is the best framework to persist my > python objects in disk. The Python Wiki has a directory of tools for object persistence in Python . -- \ ?Our task must be to free ourselves from our prison by widening | `\ our circle of compassion to embrace all humanity and the whole | _o__) of nature in its beauty.? ?Albert Einstein | Ben Finney From steve+comp.lang.python at pearwood.info Fri Feb 28 19:58:34 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Mar 2014 00:58:34 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87k3ceeq0m.fsf@elektro.pacujo.net> Message-ID: <531130b9$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Mar 2014 02:11:53 +0200, Marko Rauhamaa wrote: > Ben Finney : > >> As has been pointed out to you, the whole point here is that string >> objects often *are not* distinct, despite conceptually having distinct >> cretion in the source. > > You know full well that this initialization creates references to > distinct objects: > > class ABC: > IDLE = "IDLE" > CONNECTING = "CONNECTING" > CONNECTED = "CONNECTED" > DISCONNECTING = "DISCONNECTING" > DISCONNECTED = "DISCONNECTED" > > The 5 constants can (and should) be distinguished with the "is" > operator. Using "==" in this case would be slightly misleading. I disagree. You are focusing on identity, but identity is (usually) not important. That's an implementation detail. What we have here is the curse of the singleton design anti-pattern: http://accu.org/index.php/journals/337 https://molecularmusings.wordpress.com/2011/11/11/singleton-is-an-anti-pattern/ Since the symbols IDLE, CONNECTING etc. don't have state apart from their name, whether there is one or a million and one instances is irrelevant. -- Steven From breamoreboy at yahoo.co.uk Fri Feb 28 20:07:33 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Mar 2014 01:07:33 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: On 01/03/2014 00:40, Ned Batchelder wrote: > On 2/28/14 6:36 PM, Mark H. Harris wrote: >> On Friday, February 28, 2014 3:03:25 PM UTC-6, Marko Rauhamaa wrote: >>> >>> Marko >> >> ... and between me and you, here is a snip from dmath.py from the >> atan(x) function: >> >> if (n**2 < D(1)): >> a = __atan__(n) >> elif (n == D(1)): >> a = gpi/4 >> elif (n == D(-1)): >> a = -(gpi/4) >> elif (n < D(-1)): >> a = __atan__Lt_neg1__(n) >> else: >> a = __atan__Gt_1__(n) >> >> This if--elif--else is not only ugly, its just not readable >> either, and besides that, its not elegant, nor is it humanly >> helpful... its does work though, and its absolutely necessary. ugh. >> >> First, its not immediately clear what it does. Well, there isn't >> just one atan(x) routine, there are at least four of them, depending >> on whether you're a purist, and they must be selected. >> >> Second, because of the strict intent ideology of python in the >> first place, I can't indent this code to make it more readable without >> breaking python's syntax. >> >> Third, this is a VERY simple if elif block. More complex ones are >> much worse... for human reading that is... >> >> I know its a pain in the neck, but python does need a switch >> statement. Is it a stubborn question? I don't really think that >> almost every modern computer language has a switch block because of >> some C paradigm. I think its because most coders find them useful, at >> least readable, and therefore essential. > > I don't understand: you show an if/elif chain that cannot be expressed > as a switch statement (because it uses < ), and then conclude that > Python needs a switch statement? That doesn't make any sense. > What a sneaky trick, trying to confuse people here with mere *FACTS* :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From marko at pacujo.net Fri Feb 28 20:06:38 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 03:06:38 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> <53112d71$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <874n3ienhd.fsf@elektro.pacujo.net> Steven D'Aprano : > I can only imagine you mean something like this: > > class Outer: > class InnerOne: > ... > > class InnerTwo: > ... > > class InnerThree: > ... > No, I mean this: class StateMachine: def __init__(self): sm = self class Idle: def connect(self): ... sm.set_state(Connecting) ... class Connecting: def poll(self): if sm.sock....: sm.set_state(Connected) class Connected: ... self.set_state(Idle) def set_state(self, state): self.state = state() def connect(self): self.state.connect() def poll(self): self.state.poll() ... >> Often a state machine has numerous states but the typical execution >> path only visits a few of them. However, the pattern calls for >> declaring classes (or instances) for all states in the state machine >> constructor. Switch statements make it possible to avoid this >> creation overhead. > > How do you avoid creating the classes or instances? If they haven't > been created, how can the compiler reference them? The comparison is between three techniques: 1. dict dispatch -- considered barely readable by me 2. the state pattern (see "class StateMachine" above) 3. sentinel state objects with switches What I said in the above paragraph is that state machines can be written using the state pattern (thus avoiding the need for switch statements). However, the pattern often consumes lots of time and space. Marko From harrismh777 at gmail.com Fri Feb 28 20:08:45 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 17:08:45 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> On Friday, February 28, 2014 6:40:06 PM UTC-6, Ned Batchelder wrote: > > I don't understand: you show an if/elif chain that cannot be expressed > as a switch statement (because it uses < ), and then conclude that > Python needs a switch statement? That doesn't make any sense. > Forgive me. I would rewrite the structure, switch x: case GT_1: __atan__Gt_1__(x) case LT_1: __atan__Lt_1__(x) case IS_1: a = gpi/4 case IS_n1: a = -gpi/4 default: __atan__(x) or somesuch... way better... yes, there are some issues, but all workable with some effort marcus From marko at pacujo.net Fri Feb 28 20:10:43 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 01 Mar 2014 03:10:43 +0200 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87k3ceeq0m.fsf@elektro.pacujo.net> Message-ID: <87zjlad8q4.fsf@elektro.pacujo.net> Ben Finney : >>From each other, of course they're distinct, because they are unequal. > > They are *not* necessarily distinct from other strings with equal > value, defined elsewhere. That's what has been pointed out to you many > times. That point is completely irrelevant. The state objects only need to be distinct from each other. How do I know? I originally wrote the example. > So, either you care about these values being distinct from all others > because you want to compare them with ?is? (and so strings are a poor > choice); Strings are as good objects for the purpose as any and have some nice advantages during troubleshooting and logging. Marko From breamoreboy at yahoo.co.uk Fri Feb 28 20:10:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Mar 2014 01:10:49 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <87ob1qeqe0.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> Message-ID: On 01/03/2014 00:03, Marko Rauhamaa wrote: > >> Dict dispatch tables are elegant, attractive and efficient if you are >> using pre-existing functions or functions you can create using lambda: > > I beg to differ. The dict dispatch tables are very hard to read. The > fully blown-out if-else chain beats it in elegance hands down. > I think you're talking nonsense. I've been happily using dict dispatch tables for years and, like Steven and presumably many others, find them dead easy to read. Perhaps you should invest in a better optician and/or glasses? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From breamoreboy at yahoo.co.uk Fri Feb 28 20:19:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Mar 2014 01:19:02 +0000 Subject: Can global variable be passed into Python function? In-Reply-To: <87zjlad8q4.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87k3ceeq0m.fsf@elektro.pacujo.net> <87zjlad8q4.fsf@elektro.pacujo.net> Message-ID: On 01/03/2014 01:10, Marko Rauhamaa wrote: > Ben Finney : > >> >From each other, of course they're distinct, because they are unequal. >> >> They are *not* necessarily distinct from other strings with equal >> value, defined elsewhere. That's what has been pointed out to you many >> times. > > That point is completely irrelevant. The state objects only need to be > distinct from each other. How do I know? I originally wrote the example. > >> So, either you care about these values being distinct from all others >> because you want to compare them with ?is? (and so strings are a poor >> choice); > > Strings are as good objects for the purpose as any and have some nice > advantages during troubleshooting and logging. > > > Marko > How many more times do you have to be shot down before you give up? Or do you intend coming back like the Phoenix, or worse still like our resident unicode expert, to haunt us? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eric.jacoboni at gmail.com Fri Feb 28 20:27:17 2014 From: eric.jacoboni at gmail.com (Eric Jacoboni) Date: Sat, 01 Mar 2014 02:27:17 +0100 Subject: Tuples and immutability In-Reply-To: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> References: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> Message-ID: Le 01/03/2014 01:22, Mark H. Harris a ?crit : > I'll address the second first by asking a question... should an immutable type (object) be able to hold (contain) mutable objects ... should tuples be allowed to hold lists? > > lists within a tuple should be converted to tuples. If you want a tuple to hold a list, make it a list in the first place. You're perfectly right and that why i've corrected my code to use a list of lists instead of tuple of list. I was hoping Python would prevent me for such a mistake (because such a situation can't be cleary intentional, isn't ?). Now, i will use tuple only with immutable items. IMHO it should be an error to use += with an immutable type and that means not at all. In other words, the list should not even be considered, because we're talking about changing a tuple... which should not be changed (nor should its members be changed). I agree with that too... My error was to first consider the list, then the tuple... I should have considered the tuple first... Anyway, the TypeError should rollback, not commit the mistake. From harrismh777 at gmail.com Fri Feb 28 20:29:13 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 17:29:13 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> Message-ID: <01310865-ae26-4249-9d15-bf6dd1b4a73a@googlegroups.com> On Friday, February 28, 2014 7:10:49 PM UTC-6, Mark Lawrence wrote: > I think you're talking nonsense. I've been happily using dict dispatch > tables for years and, like Steven and presumably many others, find them > dead easy to read. Perhaps you should invest in a better optician > and/or glasses? > That's the rub right there... yes, they are easy to read for someone who uses them for many years... but not to the average coder, or scientist who just happens to be using python (like she may have used BASIC in the past, or someone else who has no idea at this stage of their python career what a dict is, let alone what a dict dispatch table is (I like to think of virtual function table myself, which its not) ... that is really the point. Readability is important when the reader needs eye glasses... that is the whole point in a nutshell. From rosuav at gmail.com Fri Feb 28 20:39:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 12:39:05 +1100 Subject: Tuples and immutability In-Reply-To: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> References: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> Message-ID: On Sat, Mar 1, 2014 at 11:22 AM, Mark H. Harris wrote: > lists within a tuple should be converted to tuples. If you want a tuple to hold a list, make it a list in the first place. Tuples should not be changed... and as you point out... half changing a tuple is not a good condition if there is an exception... > A tuple is perfectly fine containing a list. If you want a tuple to be "recursively immutable", then you're talking about hashability, and *then* yes, you need to convert everything into tuples - but a tuple is not just an immutable list. The two are quite different in pupose. > I really think this is a bug; honestly. IMHO it should be an error to use += with an immutable type and that means not at all. In other words, the list should not even be considered, because we're talking about changing a tuple... which should not be changed (nor should its members be changed). > Definitely not! Incrementing an integer with += is a perfectly normal thing to do: x = 5 x += 1 It's just a matter of knowing the language and understanding what's going on. ChrisA From ben+python at benfinney.id.au Fri Feb 28 20:41:17 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 12:41:17 +1100 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87k3ceeq0m.fsf@elektro.pacujo.net> <87zjlad8q4.fsf@elektro.pacujo.net> Message-ID: <857g8en1aa.fsf@benfinney.id.au> Marko Rauhamaa writes: > Ben Finney : > > > They are *not* necessarily distinct from other strings with equal > > value, defined elsewhere. That's what has been pointed out to you > > many times. > > That point is completely irrelevant. The state objects only need to be > distinct from each other. In which case, don't mislead the reader by comparing with ?is?. Since you don't care about identity, only that the objects have different values, you should be comparing for equality with ?==?. > How do I know? I originally wrote the example. Yes. And as the author, you're being misleading by using the identity comparison, when you don't care about their identity by your own admission here. -- \ Eccles: ?I'll get [the job] too, you'll see. I'm wearing a | `\ Cambridge tie.? Greenslade: ?What were you doing there?? | _o__) Eccles: ?Buying a tie.? ?The Goon Show, _The Greenslade Story_ | Ben Finney From rosuav at gmail.com Fri Feb 28 20:50:21 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 12:50:21 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <877g8ff3hn.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 6:20 AM, Marko Rauhamaa wrote: > Your example: > > compare_key = { > # Same target(s). > ast.Assign: lambda node: ' '.join(dump(t) for t in node.targets), > # Same target and same operator. > ast.AugAssign: lambda node: dump(node.target) + dump(node.op) + "=", > # A return statement is always compatible with another. > ast.Return: lambda node: "(easy)", > # Calling these never compatible is wrong. Calling them > # always compatible will give lots of false positives. > ast.Expr: lambda node: "(maybe)", > # These ones are never compatible, so return some > # object that's never equal to anything. > ast.Import: lambda node: float("nan"), > ast.ImportFrom: lambda node: float("nan"), > ast.Pass: lambda node: float("nan"), > ast.Raise: lambda node: float("nan"), > ast.If: lambda node: float("nan"), > } > > vs (my proposal): > > with key from ast: > if Assign: > return ' '.join(dump(t) for t in node.targets) > elif AugAssign: > # Same target and same operator. > return dump(node.target) + dump(node.op) + "=" > elif Return: > # A return statement is always compatible with another. > return "(easy)" > elif Expr: > # Calling these never compatible is wrong. Calling them > # always compatible will give lots of false positives. > return "(maybe)" > else: > # These ones are never compatible, so return some > # object that's never equal to anything. > return float("nan") > > Which do *you* find more readable? Your proposal requires that I wrap the whole thing up in a function, or else pass the lookup key to my function every time and switch on it, instead of getting back a single function once. So you haven't truly matched the functionality, which means it's hard to compare readability - I'd have to also look at how readable the call site is, and that's definitely going to be penalized. Remember, I pointed out that the function gets called more than once - once on the special case and then once in a loop. Plus, how do you implement mutability? The else clause needs to do a one-off print to stderr, so either the dispatch table needs to be changed, or the else clause needs some other system of keeping track of its previously-seen list. Additionally, I have another script that actually monkey-patches the Expr case out, simply by changing the dict. It works just fine, because, again, the dict is mutable. To do that with a switch statement, I'd need to put an explicit 'if' into there. Show me that version and let's see how readable it is. There may be a case (pun intended) for adding a switch block to Python, but this isn't a strong supporting instance. ChrisA From steve+comp.lang.python at pearwood.info Fri Feb 28 20:59:56 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Mar 2014 01:59:56 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> <53112d71$0$29985$c3e8da3$5496439d@news.astraweb.com> <874n3ienhd.fsf@elektro.pacujo.net> Message-ID: <53113f1b$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Mar 2014 03:06:38 +0200, Marko Rauhamaa wrote: > Steven D'Aprano : > >> I can only imagine you mean something like this: >> >> class Outer: >> class InnerOne: >> ... >> >> class InnerTwo: >> ... >> >> class InnerThree: >> ... >> >> > No, I mean this: > > class StateMachine: > def __init__(self): > sm = self > > class Idle: > def connect(self): > ... > sm.set_state(Connecting) > ... [...] Ah, interesting. You're not just using the classes as symbols, you actually are giving them behaviour and using a State pattern. But I'm not sure that there is a good reason to put the class definitions inside the __init__ method. That means every time you create a new StateMachine instance, the classes have to be re-created. (That might be a feature if you intend for instance1.IDLE != instance2.IDLE, but I don't see any good reason for that.) It will be much more efficient if you pull all the Idle, etc. classes out and make them top-level global classes. Or at least stick them inside the StateMachine class, which means that they only get created once, and are shared between all StateMachine instances. But then the closure over sm won't work... I'll need to think some more about that. However, the example as given won't quite work. You never instantiate the Idle etc. classes, which means the methods won't work. You need to make them class methods or static methods, or perform some metaclass magic prevent them from being turned into instance methods when called. Since in this example you've actually got significant behaviour in the states, they aren't just symbols, and some sort of solution along these lines (whether you use multiple inner classes or not) is appropriate. -- Steven From rosuav at gmail.com Fri Feb 28 21:00:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 13:00:42 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <87sir2et1d.fsf@elektro.pacujo.net> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <87sir2et1d.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 10:06 AM, Marko Rauhamaa wrote: > A colleague of mine taught me decades back that the whole point of OO > was the avoidance of if and switch statements. So if your code has an if > or switch statement, chances are you are doing something wrong. > > I agree. *boggle* Are you seriously suggesting that every condition requires the declaration of an object type? UGH! No thank you. ChrisA From rosuav at gmail.com Fri Feb 28 21:01:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 13:01:45 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> Message-ID: On Sat, Mar 1, 2014 at 12:08 PM, Mark H. Harris wrote: > On Friday, February 28, 2014 6:40:06 PM UTC-6, Ned Batchelder wrote: > >> >> I don't understand: you show an if/elif chain that cannot be expressed >> as a switch statement (because it uses < ), and then conclude that >> Python needs a switch statement? That doesn't make any sense. >> > > Forgive me. I would rewrite the structure, > > switch x: > case GT_1: > __atan__Gt_1__(x) > case LT_1: > __atan__Lt_1__(x) > case IS_1: > a = gpi/4 > case IS_n1: > a = -gpi/4 > default: > __atan__(x) > > or somesuch... way better... yes, there are some issues, but all workable with some effort Does your switch construct have to handle the magic of GT_1 meaning "> 1", or do you first figure out where it falls with an if/elif tree? ChrisA From rosuav at gmail.com Fri Feb 28 21:03:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Mar 2014 13:03:53 +1100 Subject: Can global variable be passed into Python function? In-Reply-To: <53113f1b$0$29985$c3e8da3$5496439d@news.astraweb.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> <53112d71$0$29985$c3e8da3$5496439d@news.astraweb.com> <874n3ienhd.fsf@elektro.pacujo.net> <53113f1b$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Mar 1, 2014 at 12:59 PM, Steven D'Aprano wrote: > However, the example as given won't quite work. You never instantiate the > Idle etc. classes, which means the methods won't work. You need to make > them class methods or static methods, or perform some metaclass magic > prevent them from being turned into instance methods when called. Actually, he does - setting a state means instantiating that state. I still don't see where the benefit is, beyond that you reach the right margin quicker than anyone else does. ChrisA From ned at nedbatchelder.com Fri Feb 28 21:15:38 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Fri, 28 Feb 2014 21:15:38 -0500 Subject: Can global variable be passed into Python function? In-Reply-To: <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> Message-ID: On 2/28/14 8:08 PM, Mark H. Harris wrote: > On Friday, February 28, 2014 6:40:06 PM UTC-6, Ned Batchelder wrote: > >> >> I don't understand: you show an if/elif chain that cannot be expressed >> as a switch statement (because it uses < ), and then conclude that >> Python needs a switch statement? That doesn't make any sense. >> > > Forgive me. I would rewrite the structure, > > switch x: > case GT_1: > __atan__Gt_1__(x) > case LT_1: > __atan__Lt_1__(x) > case IS_1: > a = gpi/4 > case IS_n1: > a = -gpi/4 > default: > __atan__(x) > > or somesuch... way better... yes, there are some issues, but all workable with some effort > Mark, if you are going to advocate for a feature, find a good use case, this one is absurd. Where did the constants GT_1 etc, come from? -- Ned Batchelder, http://nedbatchelder.com From greg.ewing at canterbury.ac.nz Fri Feb 28 22:08:45 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 01 Mar 2014 16:08:45 +1300 Subject: References, and avoiding use of ???variable??? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <85ha7knedo.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > That whole chapter of the tutorial talks about ?variable? and ?variable > assignment?, when IMO it should avoid those terms and use the clearer > terminology of ?reference?, ?name?, and ?binding a name to a value?. What about all the other things that can be assigned to but aren't names? (List and dict elements, attributes, etc.) What do you suggest calling them? -- Greg From greg.ewing at canterbury.ac.nz Fri Feb 28 22:10:10 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 01 Mar 2014 16:10:10 +1300 Subject: Can global variable be passed into Python function? In-Reply-To: <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: Mark H. Harris wrote: > if (n**2 < D(1)): > a = __atan__(n) > elif (n == D(1)): > a = gpi/4 > elif (n == D(-1)): > a = -(gpi/4) > elif (n < D(-1)): > a = __atan__Lt_neg1__(n) > else: > a = __atan__Gt_1__(n) That's not a candidate for a switch statement, because the comparisons are not all equality comparisons. -- Greg From steve+comp.lang.python at pearwood.info Fri Feb 28 22:29:57 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 01 Mar 2014 03:29:57 GMT Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <531115e1$0$29985$c3e8da3$5496439d@news.astraweb.com> <87ob1qeqe0.fsf@elektro.pacujo.net> <53112d71$0$29985$c3e8da3$5496439d@news.astraweb.com> <874n3ienhd.fsf@elektro.pacujo.net> <53113f1b$0$29985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <53115435$0$29985$c3e8da3$5496439d@news.astraweb.com> On Sat, 01 Mar 2014 13:03:53 +1100, Chris Angelico wrote: > On Sat, Mar 1, 2014 at 12:59 PM, Steven D'Aprano > wrote: >> However, the example as given won't quite work. You never instantiate >> the Idle etc. classes, which means the methods won't work. You need to >> make them class methods or static methods, or perform some metaclass >> magic prevent them from being turned into instance methods when called. > > Actually, he does - setting a state means instantiating that state. Ah, so he does. -- Steven From ben+python at benfinney.id.au Fri Feb 28 23:22:45 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 01 Mar 2014 15:22:45 +1100 Subject: References, and avoiding use of ???variable??? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <85ha7knedo.fsf_-_@benfinney.id.au> Message-ID: <8538j2mtt6.fsf@benfinney.id.au> Gregory Ewing writes: > Ben Finney wrote: > > That whole chapter of the tutorial talks about ?variable? and ?variable > > assignment?, when IMO it should avoid those terms and use the clearer > > terminology of ?reference?, ?name?, and ?binding a name to a value?. > > What about all the other things that can be assigned > to but aren't names? (List and dict elements, attributes, > etc.) What do you suggest calling them? Assignment binds a reference to a value. A name is a special kind of reference. -- \ ?We are all agreed that your theory is crazy. The question that | `\ divides us is whether it is crazy enough to have a chance of | _o__) being correct.? ?Niels Bohr (to Wolfgang Pauli), 1958 | Ben Finney From harrismh777 at gmail.com Fri Feb 28 23:36:25 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 20:36:25 -0800 (PST) Subject: Can global variable be passed into Python function? In-Reply-To: References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> <4bd11eec-395a-4484-a991-9fabf12328e1@googlegroups.com> Message-ID: On Friday, February 28, 2014 8:15:38 PM UTC-6, Ned Batchelder wrote: > Mark, if you are going to advocate for a feature, find a good use case, > this one is absurd. Where did the constants GT_1 etc, come from? Not at all. Think of the C switch block... if you read about it in the K & R you'll think its useless... because it can only switch on a SINGLE character. So, to make it work what do you do??? You create some constants that are actually really and totally just a number... one character... that represents GT_1 or anything else. The switch block "switches" on a character in C. In python it could switch on absolutely anything we like... the point is not how it switches... but how it "looks" to human beings, and "maybe" how it performs. For me its more important that code be readable first and foremost... then optimized. Yes, I can use if elif else blocks and I can and do use dict dispatch tables.... but I "wish" there were a switch case default block in python so that some things could be coded to be clearer to a human reader. just sayin... not arguing though... just a comment. From harrismh777 at gmail.com Fri Feb 28 23:45:56 2014 From: harrismh777 at gmail.com (Mark H. Harris) Date: Fri, 28 Feb 2014 20:45:56 -0800 (PST) Subject: Tuples and immutability In-Reply-To: References: <059a3d10-453a-40fd-99f9-33ceb8ecabf7@googlegroups.com> Message-ID: <2ddad91d-e188-4fd0-be1c-ed30edbf280b@googlegroups.com> On Friday, February 28, 2014 7:27:17 PM UTC-6, Eric Jacoboni wrote: > I agree with that too... My error was to first consider the list, then > the tuple... I should have considered the tuple first... > Anyway, the TypeError should rollback, not commit the mistake. I believe so too, but I'm not one of the core devs. And they do not agree. Ever since day one with me and python I have questioned whether a tuple even makes sense. Well, certainly it does, because it has so much less overhead and yet it acts like a list (which for so many situations thats really what we want anyway... a list, that never changes). Tuples are great, for what they are designed to do. But now consider, why would I purposely want to place a mutable object within an immutable list? A valid question of high importance. Why indeed? I really believe IMHO that the error should have come when you made the list an item of a tuple. An immutable object should have NO REASON to contain a mutable object like list... I mean the whole point is to eliminate the overhead of a list ... why would the python interpreter allow you to place a mutable object within an immutable list in the first place. This is just philosophical, and yes, the core dev's are not going to agree with me on this either. I think the situation is interesting for sure... and it will surface again, you can count on that. Cheers From roy at panix.com Sat Feb 22 23:19:22 2014 From: roy at panix.com (Roy Smith) Date: Sat, 22 Feb 2014 23:19:22 -0500 Subject: Can tuples be replaced with lists all the time? References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: In article <64af70e3-6876-4fbf-8386-330d2f48735a at googlegroups.com>, Sam wrote: > My understanding of Python tuples is that they are like immutable lists. If > this is the cause, why can't we replace tuples with lists all the time (just > don't reassign the lists)? Correct me if I am wrong. There are many tasks for which either a list or a tuple would work fine. But, not all. Basically: If you need something which is hashable (i.e. to be used as a dictionary key), you need to use a tuple. If you need something which you can mutate (say, to accumulate items as you go through a loop), then you need to use a list. Beyond that, you get into religious territory. From roy at panix.com Sun Feb 23 09:20:37 2014 From: roy at panix.com (Roy Smith) Date: Sun, 23 Feb 2014 09:20:37 -0500 Subject: Mac vs. Linux for Python Development References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> Message-ID: In article <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c at googlegroups.com>, twiz wrote: > Hello, > > I'm sure this is a common question but I can't seem to find a previous thread > that addresses it. If one one exists, please point me to it. > > I've been developing with python recreationally for a while on Ubuntu but > will soon be transitioning to full-time python development. I have the > option of using a Mac or Ubuntu environment and I'd like to hear any thoughts > on the pros and cons of each. Specifically, how's the support for numpy and > scipy? How are the IDEs? Which is a better food: asparagus or cauliflower? I run Python (including scipy, numpy, iPython, matplotlib, statsmodels, scikit-learn, pandas, etc) on both OSX and Ubuntu. For server and back-end work, I find linux a better platform, partly because there tends to be a larger selection of pre-built packages available (although, I'm not even sure I can defend that statement). On the other hand, I despise every linux desktop I've ever worked with. I've settled into a mode of OSX on my desktops (I have a 8 GB MacBook Pro at home, and a Mini on my desk in the office), and Ubuntu for all my "real work". I'm not a huge fan of IDEs, so I can't give you much advice there. I pretty much live in emacs and terminal windows. I do find the integration of iPython and matplotlib to be compelling, so that's my current environment of choice for anything involving graphics. A common scenario for me is running the iPython kernel on some Ubuntu box in AWS, and a browser on my OSX desktop, with an ssh port tunnel nailed up to let them talk to each other. The bottom line is, if you've got it narrowed down to Ununtu or OSX, you can't go wrong with either choice. Use whichever you're more comfortable using. From invalid at invalid.invalid Sun Feb 23 12:07:19 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 23 Feb 2014 17:07:19 +0000 (UTC) Subject: Can tuples be replaced with lists all the time? References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: On 2014-02-23, Sam wrote: > My understanding of Python tuples is that they are like immutable > lists. If this is the cause, why can't we replace tuples with lists > all the time (just don't reassign the lists)? Correct me if I am > wrong. In addition to the things related to one being mutable and the other immutable, there is a certain tradition that often results in differnt usages for them. Though it's certainly not required, lists are more often used as variable length _homogeneous_ containers -- sort of like a variable length array or linked list in C. The "type" or "meaning" of element #N is the same as that of element #M. In constrast, tuples are often used as fixed-length heterogenous containers (more like a struct in C except the fields are named 0, 1, 2, 3, etc.). In a particular context, the Nth element of a tuple will always mean one thing (e.g. a person's last name) while the Mth element will always be something else (e.g. a person's age). -- Grant From roy at panix.com Sun Feb 23 12:48:52 2014 From: roy at panix.com (Roy Smith) Date: Sun, 23 Feb 2014 12:48:52 -0500 Subject: Can tuples be replaced with lists all the time? References: <64af70e3-6876-4fbf-8386-330d2f48735a@googlegroups.com> Message-ID: In article , Grant Edwards wrote: > In constrast, tuples are often used as fixed-length heterogenous > containers (more like a struct in C except the fields are named 0, 1, > 2, 3, etc.). In a particular context, the Nth element of a tuple will > always mean one thing (e.g. a person's last name) while the Mth > element will always be something else (e.g. a person's age). And, of course, namedtuples make that much more explicit. It also appears that tuples are more memory efficient. I just ran some quick tests on my OSX box. Creating a list of 10 million [1, 2, 3, 4, 5] lists gave me a 1445 MB process. The name number of (1, 2, 3, 4, 5) tuples was 748 MB. I'm sure this is implementation dependent, but it seems plausible to assume similar results will be had on other implementations. From roy at panix.com Sun Feb 23 20:28:49 2014 From: roy at panix.com (Roy Smith) Date: Sun, 23 Feb 2014 20:28:49 -0500 Subject: Functions help References: Message-ID: In article , Mark Lawrence wrote: > On 24/02/2014 00:55, alex23 wrote: > > On 23/02/2014 3:43 PM, Scott W Dunning wrote: > >> I had a question regarding functions. Is there a way to call a > >> function multiple times without recalling it over and over. Meaning > >> is there a way I can call a function and then add *5 or something like > >> that? > > > > The same way you repeat anything in Python: with a loop construct. > > > > for _ in range(5): > > func() > > For the benefit of newbies, besides the obvious indentation error above, > the underscore basically acts as a dummy variable. I'll let the > language lawyers give a very detailed, precise description :) As far as I know, it's purely convention. _ is a legal variable name in Python, and the convention is that unpacking something into _ means, "I don't care about that value". It's also used to ignore several values: _, _, foo, bar, _ = blah unpacks a 5-tuple, of which you only care about the 3rd and 4th values. From invalid at invalid.invalid Mon Feb 24 10:38:11 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 24 Feb 2014 15:38:11 +0000 (UTC) Subject: Functions help References: Message-ID: On 2014-02-24, Benjamin Kaplan wrote: > On Sun, Feb 23, 2014 at 5:39 PM, alex23 wrote: >> On 24/02/2014 11:09 AM, Mark Lawrence wrote: >>> >>> On 24/02/2014 00:55, alex23 wrote: >>>> >>>> >>>> for _ in range(5): >>>> func() >>> >>> >>> the obvious indentation error above >> >> >> Stupid cut&paste :( >> -- > > Your message came through fine for me (viewing as mailing list in > gmail). Mark's client must be dropping spaces. It was also fine here reading comp.lang.python using slrn. -- Grant Edwards grant.b.edwards Yow! I have the power to at HALT PRODUCTION on all gmail.com TEENAGE SEX COMEDIES!! From invalid at invalid.invalid Mon Feb 24 14:42:22 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 24 Feb 2014 19:42:22 +0000 (UTC) Subject: [OT] Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <87sird7wuw.fsf@handshake.de> <8454E8CB-E6E3-452F-8E54-9A77BFF34EC2@gmail.com> <1m3gg9lbf2ln5m2kbki954t17mqni3b20k@4ax.com> <53095145$0$29985$c3e8da3$5496439d@news.astraweb.com> <877g8mcg1m.fsf@elektro.pacujo.net> <87ob1yay9m.fsf@elektro.pacujo.net> <08aa32de-cd51-4888-bd60-2c2b53d86ecc@googlegroups.com> Message-ID: On 2014-02-24, Michael Torrie wrote: > On 02/24/2014 11:05 AM, j.e.haque at gmail.com wrote: >> typedef struct { >> int value; >> } Number; >> >> Number *o; >> o = malloc(sizeof(*o)); >> o->value=3; >> printf("o<%p>, o->value<%p>\n", o, &o->value); >> >> o<0x9fe5008>, o->value<0x9fe5008> >> >> Is the compiler borked? > > Why would you think that? The address of the start of your malloc'ed > structure is the same as the address of the first element. Surely > this is logical? Not only is it logical, the C standard explicitly requires it. Here's a second-hand citation since I don't happend to have an actual copy of the standard on hand: C1x ?6.7.2.1.13: A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within a structure object, but not at its beginning. -- Grant Edwards grant.b.edwards Yow! I'm gliding over a at NUCLEAR WASTE DUMP near gmail.com ATLANTA, Georgia!! From invalid at invalid.invalid Mon Feb 24 14:35:53 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 24 Feb 2014 19:35:53 +0000 (UTC) Subject: Mac vs. Linux for Python Development References: <2465a8c7-ce0e-4606-ad3b-9135c96e3e4c@googlegroups.com> <164260540.5194858.1393266319716.JavaMail.root@sequans.com> Message-ID: On 2014-02-24, Chris Angelico wrote: > So pick any distro that strikes your fancy! Try it out! If it doesn't > work out, pick a different one. Start with one that your friends use > (if you have any), that way you can get immediate help. That last bit of advice shouldn't be overlooked. If you're new to Linux, just about any mainstream distro for which you can easily get help is going to be a go smoother than one for which you're left with nothing but Google and web-based forums full of incoherent advice and wrong answers. Personally, I prefer Gentoo, but it's probably a bit too nuts-and-bolts for many people. -- Grant Edwards grant.b.edwards Yow! I'm ZIPPY the PINHEAD at and I'm totally committed gmail.com to the festive mode. From roy at panix.com Mon Feb 24 20:54:06 2014 From: roy at panix.com (Roy Smith) Date: Mon, 24 Feb 2014 20:54:06 -0500 Subject: Coding a simple state machine in python References: <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com> Message-ID: In article <65ac9612-fd48-472a-b077-c802be96ece3 at googlegroups.com>, Ronaldo wrote: > How do I write a state machine in python? I have identified the states and > the conditions. Is it possible to do simple a if-then-else sort of an > algorithm? Below is some pseudo code: > > if state == "ABC": > do_something() > change state to DEF > > if state == "DEF" > perform_the_next_function() There's lots of ways to code state machines in Python. The last time I did one, I made each state a function. Each function returned a (next_state, output) tuple. I don't know if that's the best way, but it worked and seemed logical to me. Here's a trivial example with just two states: class StateMachine: def __init__(self): self.state = self.start def process(self, input): for item in input: self.state, output = self.state(item) print output def start(self, item): if item > 5: return self.end, "done" else: return self.start, "still looking" def end(self, item): if item < 3: return self.start, "back to the beginning" else: return self.end, "still stuck at the end" sm = StateMachine() sm.process([1, 2, 6, 4, 2, 2]) When you run it, it should print: still looking still looking done still stuck at the end back to the beginning still looking From invalid at invalid.invalid Tue Feb 25 15:44:19 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 25 Feb 2014 20:44:19 +0000 (UTC) Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: On 2014-02-25, mauro wrote: > Dictionaries and sets share a few properties: > - Dictionaries keys are unique as well as sets items > - Dictionaries and sets are both unordered > - Dictionaries and sets are both accessed by key > - Dictionaries and sets are both mutables > > So I wonder why operations such us intersection, union, difference, > symmetric difference that are available for sets and are not available > for dictionaries without going via key dictviews. What would be the definition of the union, intersection, and difference of these two dicts? {1:'blue', 2:'red'} {1:'green', 3:'yellow'} -- Grant Edwards grant.b.edwards Yow! I smell like a wet at reducing clinic on Columbus gmail.com Day! From gordon at panix.com Tue Feb 25 15:44:42 2014 From: gordon at panix.com (John Gordon) Date: Tue, 25 Feb 2014 20:44:42 +0000 (UTC) Subject: intersection, union, difference, symmetric difference for dictionaries References: Message-ID: In mauro writes: > - Dictionaries and sets are both accessed by key As far as I have used sets, they are not accessed by key. >>> x = set([1, 2, 'buckle my shoe']) >>> x set([1, 2, 'buckle my shoe']) >>> 1 in x True >>> 5 in x False -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From roy at panix.com Wed Feb 26 09:37:20 2014 From: roy at panix.com (Roy Smith) Date: Wed, 26 Feb 2014 09:37:20 -0500 Subject: Need help in writing some code so i can re-use it in every module or class References: Message-ID: In article , Unix SA wrote: > Hello Experts, > > I have requirement, like i want to use below command in python script. > > --username --password arguments> > > now my requirement is i want to write some class so i can re-use " > --username --password " part via importing as module > or class .. and re-use that in other module or classes .. so i dont have > to write that in every module or classes .. > > Now why i wan to do this is ... currently we are using is going > to change in near future to , so i dont have go to every module > and change that command if i have written single module or class and re-use > it in other ? What you are talking about is a very common technique. You write some code which abstracts the intent of an operation, but hides the implementation details. Then, you can change the implementation without all the places it's called from having to be aware of the change. So, it sounds like you want to write a function which accepts the two variable parts of the command, namely the username and password. That function will then use call(), or one of its variants, from the subprocess module (http://docs.python.org/2/library/subprocess.html) to execute the actual command, inserting all the other boilerplate. If, at some point in the future, you change which command you're calling, nothing but your function needs to change. From invalid at invalid.invalid Fri Feb 28 11:09:09 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 28 Feb 2014 16:09:09 +0000 (UTC) Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> <87d2i7wbxs.fsf@elektro.pacujo.net> <877g8fgsr1.fsf@elektro.pacujo.net> Message-ID: On 2014-02-28, Marko Rauhamaa wrote: > Chris Angelico : > >> Can you elaborate on this "nonliteral constants" point? How is it a >> problem if DISCONNECTING isn't technically a constant? It follows the >> Python convention of being in all upper-case, so the programmer >> understands not to rebind it. Is the problem that someone might >> (naively or maliciously) change the value of DISCONNECTING, or is the >> problem that Python doesn't fundamentally know that it won't change? > > This last point. It would make it impossible for Python to treat the > switch statement as anything but an alternate form of chained if-else. There are a couple nice things about a switch () statement: 1) It guarantees that 'expr' is evaluated exactly once. If you want that with a chained if/else you have to create a temporary variable. 2) It guarantees that exactly one path is chosen (assuming we're not going to duplicate C's "fall through" mistake). The result is that it makes the author's intention instantly clear to the reader: we're going to evaluate some expression _exactly_once_ and then select _exactly_one_ of several paths based on that value. Sure, you can do the same thing with a chained if/elif/else, but it requires some effort for the reader to figure that out. Accidently type "if" instead of "elif" two thirds of the way down, and you get something that works right _most_ of the time, but not always. [Not that _I've_ ever done that and then read through the whole thing six times over a period of two days before noticing it.] :) If the availability of an alternate but computationally equivalent representation was a valid argument against a language feature, then we ought to toss out Python entirely: It's always possible to write the exact same algorithm, so why bother with Python? > A dict optimization wouldn't actually optimize anything because it > would have to be constructed every time the statement is executed. I don't think question should be "how does this help the compiler?" The question should be "how does this help the _user_ of the compiler? The user of the compiler spends more time reading code than anything else. Something that makes code easier to read is therefore worth considering. A switch statement is easier to read than a chained if/else. IMO, _that's_ the proper argument for a switch statement. Trying to justify a switch statement as a way to help generate more efficient code seems silly: This is not 1970 -- any decent compiler should be able to generate the same code for a switch statement and for an equivalent chained if/else. -- Grant Edwards grant.b.edwards Yow! I want to read my new at poem about pork brains and gmail.com outer space ... From invalid at invalid.invalid Fri Feb 28 09:31:06 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 28 Feb 2014 14:31:06 +0000 (UTC) Subject: posting code snippets References: <85ppm8nqx7.fsf@benfinney.id.au> Message-ID: On 2014-02-28, Chris Angelico wrote: > The problem does have to believe that the rubber duck/teddy > bear/figurine is an expert, though. I've had my siblings or parents > come to me with problems and, without saying a word or touching the > computer or anything, I've solved them. The problem itself respects > my skill, and retracts its objection and solves itself. The same thing works with expensive/complex test equipment instead of an expert. You drag out the lab scope, logic analyzer, spectrum analyzer, sweep generator, strip plotter, and the machine that goes "ping". You start to get everything set up to nail that problem securely to the dissecting board. Long before you actually get to that point, the problem becomes intimidated and reveals itself and a solution. -- Grant Edwards grant.b.edwards Yow! If our behavior is at strict, we do not need fun! gmail.com From roy at panix.com Fri Feb 28 09:43:30 2014 From: roy at panix.com (Roy Smith) Date: Fri, 28 Feb 2014 09:43:30 -0500 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <87y50vwjq4.fsf@elektro.pacujo.net> <87d2i7wbxs.fsf@elektro.pacujo.net> Message-ID: In article <87d2i7wbxs.fsf at elektro.pacujo.net>, Marko Rauhamaa wrote: > Neil Cerutti : > > > Check out Go's switch statement for an example of what it might > > look like in Python. Except you'd get it without labeled break or > > the fallthrough statement. Python already has a switch statement. It's just spelled funny... class Switch(Exception): pass class Case1(Switch): pass class Case2(Switch): pass class Case3(Switch): pass try: raise value except Case1: print "did case 1" except (Case2, Case3): print "did either case 2 or 3" else: print "did default" No fall-through, however. I'm sure with a little meta-class magic, you could write a Case() which eliminates the need for manually declaring the cases. From invalid at invalid.invalid Fri Feb 28 09:20:35 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 28 Feb 2014 14:20:35 +0000 (UTC) Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> Message-ID: On 2014-02-28, Marko Rauhamaa wrote: > Here's a use case for "is" with strings (or ints): > > class Connection: > IDLE = "IDLE" > CONNECTING = "CONNECTING" > CONNECTED = "CONNECTED" > DISCONNECTING = "DISCONNECTING" > DISCONNECTED = "DISCONNECTED" > > def __init__(self): > self.state = IDLE > > def connect(self, address): > ... > self.state = CONNECTING > ... > > def disconnect(self): > ... > if self.state is CONNECTED: > ... I don't really see the point. Why won't '==' work just as well? Are you hoping that 'is' is faster at runtime than '=='? -- Grant Edwards grant.b.edwards Yow! Th' MIND is the Pizza at Palace of th' SOUL gmail.com From invalid at invalid.invalid Fri Feb 28 17:00:20 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 28 Feb 2014 22:00:20 +0000 (UTC) Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> Message-ID: On 2014-02-28, Mark Lawrence wrote: > http://c2.com/cgi/wiki?SwitchStatementsSmell So lack of a switch state is an attempt to force Python programmers to write things in an "object oriented" way? -- Grant Edwards grant.b.edwards Yow! FUN is never having to at say you're SUSHI!! gmail.com From roy at panix.com Fri Feb 28 19:02:44 2014 From: roy at panix.com (Roy Smith) Date: Fri, 28 Feb 2014 19:02:44 -0500 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <0b414429-74ee-45dd-9465-c87e98c362f2@googlegroups.com> Message-ID: In article <0b414429-74ee-45dd-9465-c87e98c362f2 at googlegroups.com>, "Mark H. Harris" wrote: > On Friday, February 28, 2014 3:03:25 PM UTC-6, Marko Rauhamaa wrote: > > > > Marko > > ... and between me and you, here is a snip from dmath.py from the atan(x) > function: > > if (n**2 < D(1)): > a = __atan__(n) > elif (n == D(1)): > a = gpi/4 > elif (n == D(-1)): > a = -(gpi/4) > elif (n < D(-1)): > a = __atan__Lt_neg1__(n) > else: > a = __atan__Gt_1__(n) > > This if--elif--else is not only ugly, its just not readable either, and > besides that, its not elegant, nor is it humanly helpful... its does > work though, and its absolutely necessary. ugh. > > First, its not immediately clear what it does. Well, there isn't just one > atan(x) routine, there are at least four of them, depending on whether > you're a purist, and they must be selected. This kind of stuff is pretty common in numerical code. Depending on the sign/magnitude/quadrant/whatever of the argument, you'll want to use one of several algorithms to minimize roundoff error, etc. But, how would this be any nicer with switch? From roy at panix.com Fri Feb 28 19:48:26 2014 From: roy at panix.com (Roy Smith) Date: Fri, 28 Feb 2014 19:48:26 -0500 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <87sir2et1d.fsf@elektro.pacujo.net> Message-ID: In article , Ben Finney wrote: > Of course. That's the point of describing something as a ???code smell???: > it may have exceptions where the smell does not indicate an actual > problem, but those are not the normal case where the smell is > encountered. More often, it indicates a problem that should be fixed. An apt analogy is refrigerator smell. Sometimes it means the leftovers from 3 months ago have evolved into a sentient life form. Sometimes it just means you've got a piece of Roquefort. From roy at panix.com Fri Feb 28 22:15:10 2014 From: roy at panix.com (Roy Smith) Date: Fri, 28 Feb 2014 22:15:10 -0500 Subject: Can global variable be passed into Python function? References: <27ac2248-0ca3-4ba6-9d25-eaad324bc5e9@googlegroups.com> <5f4f5a5f-327a-4616-8235-17ee9e74c488@googlegroups.com> <530fef58$0$11113$c3e8da3@news.astraweb.com> <871tynznpd.fsf@elektro.pacujo.net> <53104798$0$11113$c3e8da3@news.astraweb.com> <87ha7jy2qs.fsf@elektro.pacujo.net> <5310b031$0$29985$c3e8da3$5496439d@news.astraweb.com> <87iorzf4ro.fsf@elektro.pacujo.net> <877g8ff3hn.fsf@elektro.pacujo.net> <87wqgfdk6a.fsf@elektro.pacujo.net> <87sir2et1d.fsf@elektro.pacujo.net> Message-ID: On Sat, Mar 1, 2014 at 10:06 AM, Marko Rauhamaa wrote: > A colleague of mine taught me decades back that the whole point of OO > was the avoidance of if and switch statements. So if your code has an if > or switch statement, chances are you are doing something wrong. This sounds like a classic case of a useful observation being taken out of context. On of the standard mantras about OOP is that you should not "use code to find code". By that, they mean, you should not do things like (pseudo-code): if type(obj) == Foo: frobnicate_with_foo(obj) else if type(obj_ == Bar: frobnicate_with_bar(obj) else: frobnicate_with_other(obj) But rather, you should let the class dispatch machinery handle figuring out which version of frobnicate() to call. That's a reasonable statement, but somehow that seems to have gotten twisted into, "If you're doing OOP, you should never have any 'if' statements".