Re: pytz question: GMT vs. UTC
Le jeudi 30 janvier 2014 04:27:54 UTC+1, Chris Angelico a écrit : > On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: > > >> How cruel... I suspect the smack at 0degC is much more painful > > >> than one > > >> at room temperature > > >> > > > It's the 21st century; you should be making use of Unicode: 0°C. > > > > I started to read that and thought you were going to advocate the use of > 0°K... > > == The temperature unit is the "Kelvin", not the "Degree Kelvin". One writes: 0 K, 275.15 K It can also be the "Degree Celsius", not the "Celsius". One writes: -273.15 °C, 0 °C >>> import unicodedata as ud >>> for c in '\u2109\u212a\u2103\u00b0': ... print(ud.name(c)) ... DEGREE FAHRENHEIT KELVIN SIGN DEGREE CELSIUS DEGREE SIGN >>> jmf -- https://mail.python.org/mailman/listinfo/python-list
Re: Python shell wont open IDLE or an exisiting .py files
On 1/29/2014 11:16 PM, Ben Finney wrote: Terry Reedy writes: On 1/29/2014 6:26 PM, shangonich...@sbcglobal.net wrote: > If I launch the Python GUI it opens a Python Shell fine. But as > soon as I try to open a file (including a "new" file), it closes > the Shell. This I do not. What is 'Python GUI'? What is 'Python Shell'? Those are (part of) the names of menu entries created by the Python installer for MS Windows. I am not sure exactly what programs they invoke. One entry is 'IDLE (Python GUI)'. I have never seen Idle referred to as 'Python GUI' as the later is non-specific and could refer to wxpython or pyqt or some other Python GUI. Idle open a window called Python x.y.z Shell (until recently just Shell). The other menu entry is 'Python (Command line)' and I am guessing that the paragraph above has nothing to do with this entry. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: buggy python interpretter or am I missing something here?
On 1/30/2014 12:13 AM, Gregory Ewing wrote: Steven D'Aprano wrote: On Mon, 27 Jan 2014 12:22:22 -0800, Rick Johnson wrote: Why do we even need an "input" function anyway if all it is going to do is read from stdin? That's not all it does. What else it does is print a prompt before reading and to strip off the trailing newline. For example, it handles backspacing, so that typing H E L O O BACKSPACE BACKSPACE L O gives "HELLO" rather than "HELOO\x7f\x7fO". No, it doesn't -- that's handled at a lower level. Any other method of reading from stdin, as long as it hasn't been redirected away from the console, has the same behaviour. I typed some backspaces in the input to each of the following experiments, and they didn't end up in the data: >>> import sys >>> x = sys.stdin.readline() HELLO >>> x 'HELLO\n' >>> import os >>> f = os.fdopen(0) >>> y = f.readline() adsxx >>> y 'adsxx\n' So input() really is a pure convenience function. (That doesn't mean it's not worth having, though!) It is equivalent to def input(prompt): sys.stdout.write(prompt) return sys.stdin.read()[:-1] There was once an eval around the return, but that was determined to be a bad idea. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On 30.01.2014 04:27, Chris Angelico wrote: > On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: >>> How cruel... I suspect the smack at 0degC is much more painful >>> than one >>> at room temperature >>> >> It's the 21st century; you should be making use of Unicode: 0°C. > > I started to read that and thought you were going to advocate the use of > 0°K... It's 0 K. The SI-unit 'Kelvin' has no degree (although Lord Kelvin was a professor). *g* -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On Thu, Jan 30, 2014 at 8:49 PM, Christian Heimes wrote: > On 30.01.2014 04:27, Chris Angelico wrote: >> On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: How cruel... I suspect the smack at 0degC is much more painful than one at room temperature >>> It's the 21st century; you should be making use of Unicode: 0°C. >> >> I started to read that and thought you were going to advocate the use of >> 0°K... > > It's 0 K. The SI-unit 'Kelvin' has no degree (although Lord Kelvin was a > professor). *g* That thing. I knew that, honest I did. My brain's just not working properly at the moment, something to do with consecutive hours awake. But later on I'll be 0K. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
Le jeudi 30 janvier 2014 10:49:11 UTC+1, Christian Heimes a écrit : > On 30.01.2014 04:27, Chris Angelico wrote: > > > On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: > > >>> How cruel... I suspect the smack at 0degC is much more painful > > >>> than one > > >>> at room temperature > > >>> > > >> It's the 21st century; you should be making use of Unicode: 0°C. > > > > > > I started to read that and thought you were going to advocate the use of > > 0°K... > > > > It's 0 K. The SI-unit 'Kelvin' has no degree (although Lord Kelvin was a > > professor). *g* Glad, that you read (received?) my previous post! -- https://mail.python.org/mailman/listinfo/python-list
Work on Call for Participation for EuroPython 2015 has started
[Please help spread the word by forwarding to other relevant mailing lists, user groups, etc.; thanks :-)] The EuroPython Society (EPS) has started work on preparing the Call for Participation (CFP) for organizing the EuroPython 2015 conference: http://www.europython-society.org/ For 2015, we are setting up a new structure for the conference organization, which is focused on local and distributed work groups that are closely integrated with the EuroPython Society. We hope to greatly reduce the work load for the local teams, attract community members that want to get involved and to streamline the whole process of transitioning from one location to the next, making the conference organization a lot easier for everyone. If you are interested in potentially signing up as local team or participating in the work groups, please subscribe to one of our communication channels: * Tumblr http://www.tumblr.com/follow/europythonsociety * RSS http://www.europython-society.org/rss * Twitter https://twitter.com/europythons * EuroPython Mailing List https://mail.python.org/mailman/listinfo/europython We are aiming for end of February as announcement date for the CFP 2015. Enjoy, -- Marc-Andre Lemburg Director EuroPython Society http://www.europython-society.org/ -- https://mail.python.org/mailman/listinfo/python-list
fseek In Compressed Files
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
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)? -- https://mail.python.org/mailman/listinfo/python-list
1 > 0 == True -> False
Hello, $ python Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1 > 0 == True False >>> (1 > 0) == True True >>> 1 > (0 == True) True >>> What am I missing here ? T. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Thibault Langlois schrieb: 1 > 0 == True False What am I missing here ? This, perhaps: http://www.primozic.net/nl/chaining-comparison-operators-in-python/ Greetings, Thomas -- Ce n'est pas parce qu'ils sont nombreux à avoir tort qu'ils ont raison! (Coluche) -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Thibault Langlois writes: > Hello, > > $ python > Python 2.7.4 (default, Sep 26 2013, 03:20:26) > [GCC 4.7.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 1 > 0 == True > False > >>> (1 > 0) == True > True > >>> 1 > (0 == True) > True > >>> > > What am I missing here ? One or both of the following: >>> 0 == True False >>> True and False False >>> 1 > 0 True Or the fact that (1 > 0 == True) means ((1 > 0) and (0 == True)), where each expression in such a chain is evaluated once, though in this case it really does not matter since 0 is a literal. Hm, I don't know if the evaluation short-circuits. I think not, but I've never needed to know, and I don't need to know now. -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On 2014-01-30 08:45, wxjmfa...@gmail.com wrote: Le jeudi 30 janvier 2014 04:27:54 UTC+1, Chris Angelico a écrit : On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: >> How cruel... I suspect the smack at 0degC is much more painful >> than one >> at room temperature >> > It's the 21st century; you should be making use of Unicode: 0°C. I started to read that and thought you were going to advocate the use of 0°K... == The temperature unit is the "Kelvin", not the "Degree Kelvin". One writes: 0 K, 275.15 K Not that long ago I saw a science fiction film in which one of the "scientists" said "degrees Kelvin". The rest of the "science" was somewhat dubious too... It can also be the "Degree Celsius", not the "Celsius". One writes: -273.15 °C, 0 °C import unicodedata as ud for c in '\u2109\u212a\u2103\u00b0': ... print(ud.name(c)) ... DEGREE FAHRENHEIT KELVIN SIGN DEGREE CELSIUS DEGREE SIGN -- https://mail.python.org/mailman/listinfo/python-list
Re:fseek In Compressed Files
Ayushi Dalmia Wrote in message: > 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. > Start with the zlib module. Note that it doesn't handle all possible compression types, like compress and pack. I don't imagine that seeking to a line in a compressed text file would be any easier than a non compressed one. Try using gzip.open in a text mode to get a handle, then loop through it line by line. If you save all the offsets in a list, you should subsequently be able to seek to a remembered offset. But realize it'll be horribly slow, compared to a non compressed one. Consider using readlines and referencing the lines from there. Or building a temp file if too big for ram. If this is not enough, tell us your Python version and your os, and show what you've tried and what went wrong. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re:Try-except-finally paradox
Jessica Ross Wrote in message: > I found something like this in a StackOverflow discussion. def paradox(): > ... try: > ... raise Exception("Exception raised during try") > ... except: > ... print "Except after try" > ... return True > ... finally: > ... print "Finally" > ... return False > ... return None > ... return_val = paradox() > Except after try > Finally return_val > False > > I understand most of this. > What I don't understand is why this returns False rather than True. Does the > finally short-circuit the return in the except block? > The finally has to happen before any return inside the try or the except. And once you're in the finally clause you'll finish it before resuming the except clause. Since it has a return, that will happen before the other returns. The one in the except block will never get reached. It's the only reasonable behavior., to my mind. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Jussi Piitulainen wrote: > Thibault Langlois writes: > >> Hello, >> >> $ python >> Python 2.7.4 (default, Sep 26 2013, 03:20:26) >> [GCC 4.7.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> 1 > 0 == True >> False >> >>> (1 > 0) == True >> True >> >>> 1 > (0 == True) >> True >> >>> >> >> What am I missing here ? > > One or both of the following: > >>>> 0 == True >False >>>> True and False >False >>>> 1 > 0 >True > > Or the fact that (1 > 0 == True) means ((1 > 0) and (0 == True)), > where each expression in such a chain is evaluated once, though in > this case it really does not matter since 0 is a literal. > > Hm, I don't know if the evaluation short-circuits. I think not, but > I've never needed to know, and I don't need to know now. It is easy to check though: >>> def zero(): ... print("zero") ... return 0 ... >>> def one(): ... print("one") ... return 1 ... >>> def true(): ... print("true") ... return True ... >>> one() > zero() == true() one zero true False >>> zero() > one() == true() zero one False So yes, evaluation does short-curcuit. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Peter Otten writes: > Jussi Piitulainen wrote: > > > Thibault Langlois writes: > > > >> Hello, > >> > >> $ python > >> Python 2.7.4 (default, Sep 26 2013, 03:20:26) > >> [GCC 4.7.3] on linux2 > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> 1 > 0 == True > >> False > >> >>> (1 > 0) == True > >> True > >> >>> 1 > (0 == True) > >> True > >> >>> > >> > >> What am I missing here ? > > > > One or both of the following: > > > >>>> 0 == True > >False > >>>> True and False > >False > >>>> 1 > 0 > >True > > > > Or the fact that (1 > 0 == True) means ((1 > 0) and (0 == True)), > > where each expression in such a chain is evaluated once, though in > > this case it really does not matter since 0 is a literal. > > > > Hm, I don't know if the evaluation short-circuits. I think not, but > > I've never needed to know, and I don't need to know now. > > It is easy to check though: > > >>> def zero(): > ... print("zero") > ... return 0 > ... > >>> def one(): > ... print("one") > ... return 1 > ... > >>> def true(): > ... print("true") > ... return True > ... > >>> one() > zero() == true() > one > zero > true > False > >>> zero() > one() == true() > zero > one > False > > So yes, evaluation does short-curcuit. Now I'm experiencing a mild form of information overload. Thanks anyway :) My guess was wrong. Now that I think of it, I've implemented a parser and evaluator once with this kind of chaining, and it may well have short-circuited. -- https://mail.python.org/mailman/listinfo/python-list
Add directory to sys.path based on variable
I want to add a path to sys.path based upon a variable Can I do that? Hardcodeing the path works fine, but I want to set it based upon a variable. I know I can set PYTHONPATH, but just wondering if I can add a directory on the fly to sys.path using a variable -- https://mail.python.org/mailman/listinfo/python-list
Re: Add directory to sys.path based on variable
On 30/01/2014 12:39, loial wrote: > I want to add a path to sys.path based upon a variable > > Can I do that? > > Hardcodeing the path works fine, but I want to set it based upon a > variable. > > I know I can set PYTHONPATH, but just wondering if I can add a > directory on the fly to sys.path using a variable Certainly: import sys newpath = "c:/users/tim/modules" sys.path.append(newpath) TJG -- https://mail.python.org/mailman/listinfo/python-list
Re:1 > 0 == True -> False
Thibault Langlois Wrote in message: > Hello, > > $ python > Python 2.7.4 (default, Sep 26 2013, 03:20:26) > [GCC 4.7.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. 1 > 0 == True > False (1 > 0) == True > True 1 > (0 == True) > True > > What am I missing here ? > > T. > You tell us. You supply only half the question, what it does, without saying what you expected or needed. I expect you're either confused about comparison chaining or about what happens when you compare objects of different types. Doing an ordered comparison between two types is undefined by default, and not guaranteed to even give the same result between builds. So the following may give different results on your 2.7.4 than on mine. 5 < "abc" Python 3 fixes that by throwing an exception. TypeError: unorderable types This should solve it, since the first and third expression would seem to be undefined. Unfortunately there's yet another wrinkle. For hysterical reasons, True and False are instances of class bool, which is derived from int. So for comparison purposes False==0 and True==1. But in my opinion, you should never take advantage of this, except when entering obfuscation contests. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Try-except-finally paradox
On Thu, Jan 30, 2014 at 11:05 PM, Dave Angel wrote: > The finally has to happen before any return inside the try or the > except. And once you're in the finally clause you'll finish it > before resuming the except clause. Since it has a return, that > will happen before the other returns. The one in the except block > will never get reached. > > It's the only reasonable behavior., to my mind. It's arguable that putting a return inside a finally is unreasonable behaviour, but that's up to the programmer. A finally clause can be used to do what might be done in C++ with a destructor: "no matter how this function/block exits, do this as you unwind the stack". In C++, I might open a file like this: void func() { ofstream output("output.txt"); // do a whole lot of stuff ... // at the close brace, output.~output() will be called, which will close the file } In Python, the equivalent would be: def func(): try: output = open("output.txt", "w") # do a whole lot of stuff ... finally: output.close() (Actually, the Python equivalent would be to use a 'with' clause for brevity, but 'with' uses try/finally under the covers, so it comes to the same thing.) The concept of the finally clause is: "Whether execution runs off the end, hits a return statement, or throws an exception, I need you do this before anything else happens". Having a return statement inside 'finally' as well as in 'try' is a bit of a corner case, since you're now saying "Before you finish this function and return something, I need you to return something else", which doesn't usually make sense. If you think Python's behaviour is confusing, first figure out what you would expect to happen in this situation :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Try-except-finally paradox
On 2014-01-30 13:02, Chris Angelico wrote: On Thu, Jan 30, 2014 at 11:05 PM, Dave Angel wrote: The finally has to happen before any return inside the try or the except. And once you're in the finally clause you'll finish it before resuming the except clause. Since it has a return, that will happen before the other returns. The one in the except block will never get reached. It's the only reasonable behavior., to my mind. It's arguable that putting a return inside a finally is unreasonable behaviour, but that's up to the programmer. A finally clause can be used to do what might be done in C++ with a destructor: "no matter how this function/block exits, do this as you unwind the stack". In C++, I might open a file like this: void func() { ofstream output("output.txt"); // do a whole lot of stuff ... // at the close brace, output.~output() will be called, which will close the file } In Python, the equivalent would be: def func(): try: output = open("output.txt", "w") # do a whole lot of stuff ... finally: output.close() (Actually, the Python equivalent would be to use a 'with' clause for brevity, but 'with' uses try/finally under the covers, so it comes to the same thing.) The concept of the finally clause is: "Whether execution runs off the end, hits a return statement, or throws an exception, I need you do this before anything else happens". Having a return statement inside 'finally' as well as in 'try' is a bit of a corner case, since you're now saying "Before you finish this function and return something, I need you to return something else", which doesn't usually make sense. If you think Python's behaviour is confusing, first figure out what you would expect to happen in this situation :) One of the reasons that the 'with' statement was added was to prevent the mistake that you've just done. ;-) What if the file can't be opened? -- https://mail.python.org/mailman/listinfo/python-list
Re: Try-except-finally paradox
On Fri, Jan 31, 2014 at 12:11 AM, MRAB wrote: > One of the reasons that the 'with' statement was added was to prevent > the mistake that you've just done. ;-) > > What if the file can't be opened? Yeah, whoops. The open shouldn't be inside try/finally. def func(): output = open("output.txt", "w") try: # do a whole lot of stuff ... finally: output.close() But my point still stands, I believe :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
end quote help for a newbie
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, thanks for any assistance, peter -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
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 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 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 6 727 t0b2c0i0e0 7 431 t0b2c0i1e0 8 532 t0b1c0i0e0:652 t0b1c0i0e0:727 t0b2c0i0e0 9 378 t0b1c0i0e0 10 666 t0b2c0i0e0 11 405 t0b1c0i0e0 12 702 t0b1c0i0e0 13 755 t0b1c0i0e0 14 781 t0b1c0i0e0 15 593 t0b1c0i0e0 16 725 t0b1c0i0e0 17 989 t0b2c0i1e0 18 221 t0b1c0i0e0:402 t0b1c0i0e0:842 t0b1c0i0e0 19 405 t0b1c0i0e0 20 200 t0b1c0i0e0:300 t0b1c0i0e0:398 t0b1c0i0e0:649 t0b1c0i0e0 21 66 t0b1c0i0e0 22 30 t0b1c0i0e0 23 126 t0b1c0i0e0:895 t0b1c0i0e0 24 355 t0b1c0i0e0:374 t0b1c0i0e0:378 t0b1c0i0e0:431 t0b3c0i0e0:482 t0b1c0i0e0:546 t0b3c0i0e0:578 t0b1c0i0e0 25 198 t0b1c0i0e0 -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
Not sure if this is exactly what you're asking, but perhaps you want triple quotes? >>> print "now is the time for all good men ..." now is the time for all good men ... >>> print '''now is the time for "all good men" ...''' now is the time for "all good men" ... It's not easy to visually distinguish two apostrophes from a double quote in all fonts, so I've explicitly written this using rich text and highlighted the Python session snippet in Courier. Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
On 2014-01-30 13:26, 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, What are you trying to put between the quotes? -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 12:49:19 PM UTC, Dave Angel wrote: > Thibault Langlois Wrote in message: > > > Hello, > > > > > > $ python > > > Python 2.7.4 (default, Sep 26 2013, 03:20:26) > > > [GCC 4.7.3] on linux2 > > > Type "help", "copyright", "credits" or "license" for more information. > > 1 > 0 == True > > > False > > (1 > 0) == True > > > True > > 1 > (0 == True) > > > True > > > > > > > > What am I missing here ? > > > > > > T. > > > > > > > You tell us. You supply only half the question, what it does, > > without saying what you expected or needed. > > > > I expect you're either confused about comparison chaining or about > > what happens when you compare objects of different types. > > > > > > Doing an ordered comparison between two types is undefined by > > default, and not guaranteed to even give the same result between > > builds. So the following may give different results on your > > 2.7.4 than on mine. > > 5 < "abc" > > > > Python 3 fixes that by throwing an exception. TypeError: > > unorderable types > > > > This should solve it, since the first and third expression would > > seem to be undefined. Unfortunately there's yet another wrinkle. > > > > > > For hysterical reasons, True and False are instances of class > > bool, which is derived from int. So for comparison purposes > > False==0 and True==1. But in my opinion, you should never take > > advantage of this, except when entering obfuscation > > contests. > > > > > > -- > > DaveA You are right. I should have given some context. I am looking at this from the perspective of the teacher that has to explain idiosyncrasies of the language to inexperienced students. There are two aspects in this example. 1. the equivalence of True/False with integers 1/0 which have pro and cons. 2. the chaining rules of operators. I agree that it may make sense in some cases like x > y > z but when operators are mixed it leads to counter intuitive cases as the one I pointed out. The recommendations to student are 1) do not assume True == 1 and do not use operator chaining. -- https://mail.python.org/mailman/listinfo/python-list
Convert NTP timestamp from NTP packet to System time and date format
Hello everyone; I want to write NTP client which sends and receives NTP packet to NTP server and should read the value from one of the four offsets and convert it to user readable local or GMT time format, I specifically want to know which offsets should I read in order to get correct timestamp from the packet. Any suggestion or help will be appreciated. -- *Sadia* -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
On Fri, Jan 31, 2014 at 12:34 AM, Ayushi Dalmia wrote: > where temp.txt is the posting list file which is first written in a > compressed format and then read later. Unless you specify otherwise, a compressed file is likely to have sub-byte boundaries. It might not be possible to seek to a specific line. What you could do, though, is explicitly compress each line, then write out separately-compressed blocks. You can then seek to any one that you want, read it, and decompress it. But at this point, you're probably going to do better with a database; PostgreSQL, for instance, will automatically compress any content that it believes it's worthwhile to compress (as long as it's in a VARCHAR field or similar and the table hasn't been configured to prevent that, yada yada). All you have to do is tell Postgres to store this, retrieve that, and it'll worry about the details of compression and decompression. As an added benefit, you can divide the text up and let it do the hard work of indexing, filtering, sorting, etc. I suspect you'll find that deploying a database is a much more efficient use of your development time than recreating all of that. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 12:40 AM, Thibault Langlois wrote: > The recommendations to student are 1) do not assume True == 1 and do not use > operator chaining. Not "do not use", but "do not misuse". Python's operator chaining is awesome for bounds checking: if 3 < x < 20: print("x is between 3 and 20, exclusive") You can even, since it short-circuits, do crazy stuff like: x = random.randrange(30) if int(input("Min: ")) < x < int(input("Max: ")): print("It's within those bounds.") It won't ask for a maximum if it's already failed to be within the minimum. (Okay, don't do this one. Not good code. Heh.) But don't use operator chaining when you don't mean it to behave that way. That's all! ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert NTP timestamp from NTP packet to System time and date format
On Fri, Jan 31, 2014 at 12:34 AM, Sadia Bashir <11msccssbas...@seecs.edu.pk> wrote: > Hello everyone; > > I want to write NTP client which sends and receives NTP packet to NTP server > and should read the value from one of the four offsets and convert it to > user readable local or GMT time format, I specifically want to know which > offsets should I read in order to get correct timestamp from the packet. > Any suggestion or help will be appreciated. > Any time you're looking at network protocols, the one obvious place to look is the RFCs. Just do a web search for 'rfc ntp' to find the relevant ones. In my case, the search results pulled up a couple of good-looking hits from ietf.org (the Internet Engineering Task Force - those guys are the authority on this sort of matter), plus the Wikipedia article for NTP, with a section "Relevant RFCs", which would make good reading. Enjoy! Networking's awesome fun. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Add directory to sys.path based on variable
Ok, that works fine with the apth hard coded, but I want to do something like the code below. i.e I am trying to dynamically add a path that is relative to the path of the current executing python script. In this case the import fails. import sys import os from os.path import * scriptpath=os.path.dirname(sys.argv[0]) otherscriptspath=printerpath.replace("scripts","otherscripts") sys.path.append(otherscriptspath) from AuditUpdate import * -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
In article <3dcdc95d-5e30-46d3-b558-afedf9723...@googlegroups.com>, Thibault Langlois wrote: > You are right. I should have given some context. > I am looking at this from the perspective of the teacher that has to explain > idiosyncrasies of the language to inexperienced students. > There are two aspects in this example. > 1. the equivalence of True/False with integers 1/0 which have pro and cons. > 2. the chaining rules of operators. I agree that it may make sense in some > cases like x > y > z but when operators are mixed it leads to counter > intuitive cases as the one I pointed out. > > The recommendations to student are 1) do not assume True == 1 and do not use > operator chaining. Better than that, do what I do. 1) Assume that you don't have the full operator precedence table memorized and just parenthesize everything. 2) In cases where the expression is so simple, you couldn't possibly be wrong, see rule #1. -- https://mail.python.org/mailman/listinfo/python-list
Re: Add directory to sys.path based on variable
On Fri, Jan 31, 2014 at 1:03 AM, loial wrote: > In this case the import fails. > > import sys > import os > from os.path import * Not sure why you need that, since you're explicitly naming "os.path.dirname". The base "import os" shoul cover that for you. > scriptpath=os.path.dirname(sys.argv[0]) > otherscriptspath=printerpath.replace("scripts","otherscripts") > sys.path.append(otherscriptspath) Try adding here: print(sys.argv[0]) print(otherscriptspath) See what they tell you. Is sys.argv[0] what you think it is? Is the resulting path what you expect? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Add directory to sys.path based on variable
On 30/01/2014 14:03, loial wrote: > Ok, that works fine with the apth hard coded, but I want to do something like > the code below. i.e I am trying to dynamically add a path that is relative to > the path of the current executing python script. > > In this case the import fails. > > import sys > import os > from os.path import * > > scriptpath=os.path.dirname(sys.argv[0]) > otherscriptspath=printerpath.replace("scripts","otherscripts") > sys.path.append(otherscriptspath) > > from AuditUpdate import * Well, adding a path to sys.path and then importing is generally considered a safe bet. So it's more likely that somewhere inside your path manipulation something's going wrong. You've presumably not cut-and-pasted that code from the console (since you've got an undefined "printerparth" on the 6th line). But why not scatter some print()s and os.listdir()s around, eg: import os, sys print(sys.path) print(sys.argv[0]) scriptpath=os.path.dirname(sys.argv[0]) print(scriptpath) otherscriptpath = scriptpath.replace("xxx", "yyy") print(otherscriptpath) print(os.listdir(otherscriptpath)) ... and so on. Somewhere in there, I imagine something won't be as you expect. Feel free to come back here if you need more help. TJG -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 1:08 AM, Roy Smith wrote: > Better than that, do what I do. > > 1) Assume that you don't have the full operator precedence table > memorized and just parenthesize everything. Or: 1a) Assume that you don't have the full operator precedence table memorized and just look it up, for whichever language you're working with today. :) Usually the precedence table will also remind me of operator chaining, and whether the integer division and modulo operators are backward (compare REXX and Python with their % and // operators), and anything else that needs concern. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Add directory to sys.path based on variable
Idiot that I am...I was not calling the script with the full path ! Thanks for your help -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thu, Jan 30, 2014 at 6:08 AM, Roy Smith wrote: > 1) Assume that you don't have the full operator precedence table > memorized and just parenthesize everything. > > 2) In cases where the expression is so simple, you couldn't possibly be > wrong, see rule #1. Also, assume you don't have the function definition syntax memorized, and just define functions. And assume you don't know Python, so just hire someone else to write your code instead. -- Devin -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
On Thu, 30 Jan 2014 13:26:16 +, 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). I don't understand the problem. Perhaps if you show us what you have tried, and the error you get? Please copy and paste both your code and the full error, from the first line starting with "Traceback" and ending with the error message. Regardless of using print or not, you terminate strings with a matching quotation mark. If you start the string with a double-quote, you terminate it with the same double-quote. If you use a single-quote, the same applies. These two are okay: "Double quote" "Single quote" But not this: "Mixed quotes' 'Mixed quotes" > The literal should be enclosed in double quotes “ “ What editor are you using? If you are typing your code in Microsoft Office, you're going to have a bad time. At the very least, you need to turn "Smart Quotes" off. Python will not accept curly quotes such as ‘’ or “” or any of the various other quotation marks, only plain old typewriter quotation marks ' and " (actually, these are foot and inch marks, but everyone treats them as if they were quotation marks). > 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, UK or USA keyboard won't make any difference. You need to use an ordinary text editor (or better still, a programmer's text editor) but not a word processor such as Word. If you must use Word, disable "Smart Quotes". That will avoid at least one source of problems. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 2:08:58 PM UTC, Roy Smith wrote: > In article <3dcdc95d-5e30-46d3-b558-afedf9723...@googlegroups.com>, > > Thibault Langlois wrote: > > > > > You are right. I should have given some context. > > > I am looking at this from the perspective of the teacher that has to > > explain > > > idiosyncrasies of the language to inexperienced students. > > > There are two aspects in this example. > > > 1. the equivalence of True/False with integers 1/0 which have pro and cons. > > > 2. the chaining rules of operators. I agree that it may make sense in some > > > cases like x > y > z but when operators are mixed it leads to counter > > > intuitive cases as the one I pointed out. > > > > > > The recommendations to student are 1) do not assume True == 1 and do not > > use > > > operator chaining. > > > > Better than that, do what I do. > > > > 1) Assume that you don't have the full operator precedence table > > memorized and just parenthesize everything. > > > > 2) In cases where the expression is so simple, you couldn't possibly be > > wrong, see rule #1. Agreed ! -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
In article , Chris Angelico wrote: > On Fri, Jan 31, 2014 at 1:08 AM, Roy Smith wrote: > > Better than that, do what I do. > > > > 1) Assume that you don't have the full operator precedence table > > memorized and just parenthesize everything. > > Or: > > 1a) Assume that you don't have the full operator precedence table > memorized and just look it up, for whichever language you're working > with today. :) It's faster to just stick in some extra parens. Not to mention that it makes the code more clear for everybody reading it later. Operator precedence is a tricky thing. In part, because it's somewhat arbitrary, and in part because it changes from language to language. Using "extra" parens to make my meaning clear (to both the compiler and other humans who read the code in the future) is a simple technique which works in all languages. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Roy Smith writes: > In article <3dcdc95d-5e30-46d3-b558-afedf9723...@googlegroups.com>, > Thibault Langlois wrote: > > > You are right. I should have given some context. I am looking at > > this from the perspective of the teacher that has to explain > > idiosyncrasies of the language to inexperienced students. > > > > There are two aspects in this example. > > 1. the equivalence of True/False with integers 1/0 which have pro > > and cons. > > 2. the chaining rules of operators. I agree that it may make sense > > in some cases like x > y > z but when operators are mixed it leads > > to counter intuitive cases as the one I pointed out. > > > > The recommendations to student are 1) do not assume True == 1 and > > do not use operator chaining. > > Better than that, do what I do. > > 1) Assume that you don't have the full operator precedence table > memorized and just parenthesize everything. > > 2) In cases where the expression is so simple, you couldn't possibly > be wrong, see rule #1. There's nothing to parenthesize in x <= y < z = w, unless you mean something rather weird that is not equivalent anyway (and may not be compatible with avoiding assumptions like True == 1). There's not much to remember: the comparison operators are a semantically coherent class (as far as I can see) and have the same precedence level somewhere between proper operators (let's call them that) and and and or and if else[1]. Ok, I'm not quite sure how the two branches of a conditional expression combine. Rather than find out, use parentheses, yes: (x + 1) if c else x == x + (1 if c else 0) == x + bool(c) I agree about using parentheses when in doubt, but there is some room here for more education and less doubt. Python gets these right. [1] Sorry... -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 1:49 AM, Roy Smith wrote: > In article , > Chris Angelico wrote: > >> On Fri, Jan 31, 2014 at 1:08 AM, Roy Smith wrote: >> > Better than that, do what I do. >> > >> > 1) Assume that you don't have the full operator precedence table >> > memorized and just parenthesize everything. >> >> Or: >> >> 1a) Assume that you don't have the full operator precedence table >> memorized and just look it up, for whichever language you're working >> with today. :) > > It's faster to just stick in some extra parens. Not to mention that it > makes the code more clear for everybody reading it later. That won't protect you from getting modulo and truncating-division mixed up. :) > Operator precedence is a tricky thing. In part, because it's somewhat > arbitrary, and in part because it changes from language to language. > Using "extra" parens to make my meaning clear (to both the compiler and > other humans who read the code in the future) is a simple technique > which works in all languages. It's not arbitrary, but there are differences from language to language. Yes, parens can help, but I would strongly advocate NOT using them where it's utterly unambiguous: x = (2*3)+4 # Pointless! Whether your language works with * before + (the sane way, doing what we expect from algebra) or purely left to right (the insane way, but some languages do do that), the parens are superfluous. Don't use 'em! But if you work with both PHP and any other language that has a ?: operator, parenthesizing any nesting of them will avoid a PHP stupidity. Not that that's really any sort of argument here, though. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thu, 30 Jan 2014 09:08:58 -0500, Roy Smith wrote: > 1) Assume that you don't have the full operator precedence table > memorized and just parenthesize everything. Oh really? Do you actually write stuff like this? b = ((2*a) + 1) if (b >= (-1)): ... I would hope not. > 2) In cases where the expression is so simple, you couldn't possibly be > wrong, see rule #1. Or, you can avoid superstitious responses *wink* (1) Learn the operator precedences to the best of your ability. It's not hard, most of it works just like the precedences you're used to from maths class (remember that?) or in the most intuitively useful way. E.g. `1 + x == 2` does the useful thing of calculating 1 + x before testing for equality, rather than the stupid thing of calculating x == 2 first then adding it to 1. (2) When in doubt, use parentheses. (3) When the expression is complex, a few extra parentheses can help make it easier to understand. "Seven, plus or minus two" is (roughly) the number of distinct items the human short- term memory can hold. Grouping terms together can help reduce the distinct number of items the reader needs to keep in short-term memory. E.g. `x+1 > 0 and y >= 5` is potentially as many as 9 distinct items to keep in short-term memory. But bracketing some terms as in `(x+1 > 0) and (y >= 5)` can reduce that down to as few as two items. (4) But too many parens obscure the meaning of the expression too. Aim for a good balance, neither too few nor too many. Your judgement of the right number of parens is a skill, which will come with experience. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert NTP timestamp from NTP packet to System time and date format
On Thu, 30 Jan 2014 18:34:04 +0500 Sadia Bashir wrote: > Hello everyone; > > I want to write NTP client which sends and receives NTP packet to NTP > server and should read the value from one of the four offsets and convert > it to user readable local or GMT time format, I specifically want to know > which offsets should I read in order to get correct timestamp from the > packet. > Any suggestion or help will be appreciated. Maybe this lib is of interest to you: https://pypi.python.org/pypi/ntplib/ It does all the NTP stuff for you. If you want to implement that stuff by yourself just take a look at the code of ntplib, it should explain what you want. Regards, Johannes -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On Thu, Jan 30, 2014 at 10:23 AM, Grant Edwards wrote: > On 2014-01-30, Christian Heimes wrote: >> On 30.01.2014 04:27, Chris Angelico wrote: >>> On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: > How cruel... I suspect the smack at 0degC is much more painful > than one > at room temperature > It's the 21st century; you should be making use of Unicode: 0??C. >>> >>> I started to read that and thought you were going to advocate the use of >>> 0??K... >> >> It's 0 K. The SI-unit 'Kelvin' has no degree (although Lord Kelvin was a >> professor). > > And he did have a degree. I heard he was a very cold individual. -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On 2014-01-30, Christian Heimes wrote: > On 30.01.2014 04:27, Chris Angelico wrote: >> On Thu, Jan 30, 2014 at 1:40 PM, MRAB wrote: How cruel... I suspect the smack at 0degC is much more painful than one at room temperature >>> It's the 21st century; you should be making use of Unicode: 0??C. >> >> I started to read that and thought you were going to advocate the use of >> 0??K... > > It's 0 K. The SI-unit 'Kelvin' has no degree (although Lord Kelvin was a > professor). And he did have a degree. -- Grant Edwards grant.b.edwardsYow! Wait ... is this a FUN at THING or the END of LIFE in gmail.comPetticoat Junction?? -- https://mail.python.org/mailman/listinfo/python-list
Re: pytz question: GMT vs. UTC
On 2014-01-30, wxjmfa...@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. -- Grant Edwards grant.b.edwardsYow! BELA LUGOSI is my at co-pilot ... gmail.com -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
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 > -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 8:39:03 PM UTC+5:30, Steven D'Aprano wrote: > On Thu, 30 Jan 2014 09:08:58 -0500, Roy Smith wrote: > > 1) Assume that you don't have the full operator precedence table > > memorized and just parenthesize everything. > Oh really? Do you actually write stuff like this? > b = ((2*a) + 1) > if (b >= (-1)): > ... > I would hope not. > > 2) In cases where the expression is so simple, you couldn't possibly be > > wrong, see rule #1. > Or, you can avoid superstitious responses *wink* > (1) Learn the operator precedences to the best of your ability. It's > not hard, most of it works just like the precedences you're used > to from maths class (remember that?) or in the most intuitively > useful way. > E.g. `1 + x == 2` does the useful thing of calculating 1 + x > before testing for equality, rather than the stupid thing of > calculating x == 2 first then adding it to 1. > (2) When in doubt, use parentheses. > (3) When the expression is complex, a few extra parentheses can > help make it easier to understand. "Seven, plus or minus two" > is (roughly) the number of distinct items the human short- > term memory can hold. Grouping terms together can help reduce > the distinct number of items the reader needs to keep in > short-term memory. > E.g. `x+1 > 0 and y >= 5` is potentially as many as 9 distinct > items to keep in short-term memory. But bracketing some terms > as in `(x+1 > 0) and (y >= 5)` can reduce that down to as few > as two items. > (4) But too many parens obscure the meaning of the expression too. Aim > for a good balance, neither too few nor too many. Your judgement > of the right number of parens is a skill, which will come with > experience. (5) use APL -- all ordinary operators group right to left and at the same precedence level -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
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. -- https://mail.python.org/mailman/listinfo/python-list
[ANN] Last news from Python FOSDEM 2014
Python @ FOSDEM 2014 Hi all, Last news about the Python devroom at FOSDEM 2014 [1] Schedule There is a last change in the schedule, "PyPy: a fast Python Virtual Machine" will replace "Web Scraping 101 in Python". Yasoob can't be present in Belgium :/ +--+--+--+ | TimeSlot | Talk | Speaker | +==+==+==+ | 09:00| Logic Programming in Python | Pierre Carbonnelle | +--+--+--+ | 09:30| Introduction to py.test fixtures | Floris Bruynooghe| +--+--+--+ | 10:00| openpyxl | Eric Gazoni | +--+--+--+ | 10:30| Introducing the Eve REST API Framework | Nicola Iarocci | +--+--+--+ | 11:00| Stack switching for fun and profit | Saúl Ibarra Corretgé | +--+--+--+ | 11:30| SQLAlchemy Drill | Erik Janssens| +--+--+--+ | 12:00| Some recipes with Alembic | Claude Huchet| +--+--+--+ | 12:30| Post-mortem Debugging and Web Development | Alessandro Molina| +--+--+--+ | 14:00| The next generation Python Software Foundation (PSF) | Marc-Andre Lemburg | +--+--+--+ | 14:30| How PyPy makes your code run fast | Romain Guillebert| +--+--+--+ | 15:00| Using All These Cores: Transactional Memory under the hood | Armin Rigo | +--+--+--+ | 15:30| A deep dive into PEP3156, the new asyncio module | Saúl Ibarra Corretgé | +--+--+--+ | 16:00| Concurrent pr ogramming with Python and my little experiment | Benoit Chesneau | +--+--+--+ | 16:30| Integrating Python and C using CFFI | Floris Bruynooghe| +--+--+--+ | 17:00| PyPy : a fast Python Virtual Machine | Romain Guillebert| +--+--+--+ | 17:30| Generators, or how to step to the infinite and beyond | Andrea Crotti| +--+--+--+ Sponsors We are glad to announce you that we have a lot of awesome sponsors for the event. Gold Affinitic Built on expertise achieved over more than 10 years in the development and implementation of web solutions Affinitic is your ideal partner through every stage of your project: from its conception and analysis to its final implementation, not forgetting vital training support.The strength competence, quality and safety of our developments are based on our skill in the domain of open source software and our active presence in communities of developers. http://www.affinitic.be Python Software Foundation The Python Software Foundation (PSF) is a 501(c)(3) non-profit corporation that holds the intellectual property rights behind the Python programming language. We manage the open source licensing for Python version 2.1 and later and own and protect the trademarks associated with Python.We also run the North Ameri can PyCon conference annually, support other Python conferences around the world, and fund Python related development with our grants program and by funding special projects. htt
[ANN] Last news from Python FOSDEM 2014
Python @ FOSDEM 2014 Hi all, Last news about the Python devroom at FOSDEM 2014 [1] Schedule There is a last change in the schedule, "PyPy: a fast Python Virtual Machine" will replace "Web Scraping 101 in Python". Yasoob can't be present in Belgium :/ +--+--+--+ | TimeSlot | Talk | Speaker | +==+==+==+ | 09:00| Logic Programming in Python | Pierre Carbonnelle | +--+--+--+ | 09:30| Introduction to py.test fixtures | Floris Bruynooghe| +--+--+--+ | 10:00| openpyxl | Eric Gazoni | +--+--+--+ | 10:30| Introducing the Eve REST API Framework | Nicola Iarocci | +--+--+--+ | 11:00| Stack switching for fun and profit | Saúl Ibarra Corretgé | +--+--+--+ | 11:30| SQLAlchemy Drill | Erik Janssens| +--+--+--+ | 12:00| Some recipes with Alembic | Claude Huchet| +--+--+--+ | 12:30| Post-mortem Debugging and Web Development | Alessandro Molina| +--+--+--+ | 14:00| The next generation Python Software Foundation (PSF) | Marc-Andre Lemburg | +--+--+--+ | 14:30| How PyPy makes your code run fast | Romain Guillebert| +--+--+--+ | 15:00| Using All These Cores: Transactional Memory under the hood | Armin Rigo | +--+--+--+ | 15:30| A deep dive into PEP3156, the new asyncio module | Saúl Ibarra Corretgé | +--+--+--+ | 16:00| Concurrent pr ogramming with Python and my little experiment | Benoit Chesneau | +--+--+--+ | 16:30| Integrating Python and C using CFFI | Floris Bruynooghe| +--+--+--+ | 17:00| PyPy : a fast Python Virtual Machine | Romain Guillebert| +--+--+--+ | 17:30| Generators, or how to step to the infinite and beyond | Andrea Crotti| +--+--+--+ Sponsors We are glad to announce you that we have a lot of awesome sponsors for the event. Gold Affinitic Built on expertise achieved over more than 10 years in the development and implementation of web solutions Affinitic is your ideal partner through every stage of your project: from its conception and analysis to its final implementation, not forgetting vital training support.The strength competence, quality and safety of our developments are based on our skill in the domain of open source software and our active presence in communities of developers. http://www.affinitic.be Python Software Foundation The Python Software Foundation (PSF) is a 501(c)(3) non-profit corporation that holds the intellectual property rights behind the Python programming language. We manage the open source licensing for Python version 2.1 and later and own and protect the trademarks associated with Python.We also run the North Ameri can PyCon conference annually, support other Python conferences around the world, and fund Python related development with our grants program and by funding special projects. htt
Re: fseek In Compressed Files
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? -- https://mail.python.org/mailman/listinfo/python-list
Another surprise from the datetime module
I was astounded just now to discover that datetime.timedelta doesn't have a replace() method (at least not in Python 2.7). Is there some fundamental reason why it shouldn't, or is this just an oversight? My immediate use case was wanting to print a timedelta without the fractions of seconds. The most straight-forward is: print td.replace(microseconds=0) but that doesn't work. Yes, I know I can use strftime, but (as I've mentioned before :-)), that requires dragging up the reference page to figure out what grotty little format string I need. The brute-force print timedelta(seconds=int(td.total_seconds())) is easier than that, but plain old replace() would be even easier. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On 30/01/2014 14:46, Thibault Langlois wrote: On Thursday, January 30, 2014 2:08:58 PM UTC, Roy Smith wrote: In article <3dcdc95d-5e30-46d3-b558-afedf9723...@googlegroups.com>, Thibault Langlois wrote: You are right. I should have given some context. I am looking at this from the perspective of the teacher that has to explain idiosyncrasies of the language to inexperienced students. There are two aspects in this example. 1. the equivalence of True/False with integers 1/0 which have pro and cons. 2. the chaining rules of operators. I agree that it may make sense in some cases like x > y > z but when operators are mixed it leads to counter intuitive cases as the one I pointed out. The recommendations to student are 1) do not assume True == 1 and do not use operator chaining. Better than that, do what I do. 1) Assume that you don't have the full operator precedence table memorized and just parenthesize everything. 2) In cases where the expression is so simple, you couldn't possibly be wrong, see rule #1. Agreed ! Pleased to see that as always plenty of helpful responses here. 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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Another surprise from the datetime module
On 30/01/2014 17:32, Roy Smith wrote: I was astounded just now to discover that datetime.timedelta doesn't have a replace() method (at least not in Python 2.7). Is there some fundamental reason why it shouldn't, or is this just an oversight? My immediate use case was wanting to print a timedelta without the fractions of seconds. The most straight-forward is: print td.replace(microseconds=0) but that doesn't work. Yes, I know I can use strftime, but (as I've mentioned before :-)), that requires dragging up the reference page to figure out what grotty little format string I need. The brute-force print timedelta(seconds=int(td.total_seconds())) is easier than that, but plain old replace() would be even easier. datetime.timedelta doesn't have a strftime method either. AttributeError: 'datetime.timedelta' object has no attribute 'strftime' -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Try-except-finally paradox
On 30/01/2014 06:33, Andrew Berg wrote: On 2014.01.29 23:56, Jessica Ross wrote: I found something like this in a StackOverflow discussion. def paradox(): ... try: ... raise Exception("Exception raised during try") ... except: ... print "Except after try" ... return True ... finally: ... print "Finally" ... return False ... return None ... return_val = paradox() Except after try Finally return_val False I understand most of this. What I don't understand is why this returns False rather than True. Does the finally short-circuit the return in the except block? My guess would be that the interpreter doesn't let the finally block get skipped under any circumstances, so the return value gets set to True, but then it forces the finally block to be run before returning, which changes the return value to False. Mine too. We can check that the interpreter gets as far as evaluating the return value in the except block: >>> def paradox2(): try: raise Exception("Raise") except: print("Except") return [print("Return"), True][1] finally: print("Finally") return False return None >>> ret = paradox2() Except Return Finally >>> ret False -- https://mail.python.org/mailman/listinfo/python-list
Re: Another surprise from the datetime module
On 2014-01-30, Roy Smith wrote: > I was astounded just now to discover that datetime.timedelta > doesn't have a replace() method (at least not in Python 2.7). > Is there some fundamental reason why it shouldn't, or is this > just an oversight? > > My immediate use case was wanting to print a timedelta without > the fractions of seconds. The most straight-forward is: > > print td.replace(microseconds=0) That would be nice. In the meantime, this works for your use case: td -= td % timedelta(seconds=1) -- Neil Cerutti -- https://mail.python.org/mailman/listinfo/python-list
Re: fseek In Compressed Files
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 9:56:19 AM UTC-5, Jussi Piitulainen wrote: > There's nothing to parenthesize in x <= y < z = w Hmm >>> x <= y < z = w File "", line 1 SyntaxError: can't assign to comparison I don't think any number of parentheses will help that :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Try-except-finally paradox
On 01/30/2014 10:12 AM, Rotwang wrote: On 30/01/2014 06:33, Andrew Berg wrote: On 2014.01.29 23:56, Jessica Ross wrote: I found something like this in a StackOverflow discussion. --> def paradox(): ... try: ... raise Exception("Exception raised during try") ... except: ... print "Except after try" ... return True ... finally: ... print "Finally" ... return False ... return None ... --> return_val = paradox() Except after try Finally --> return_val False I understand most of this. What I don't understand is why this returns False rather than True. Does the finally short-circuit the return in the except block? My guess would be that the interpreter doesn't let the finally block get skipped under any circumstances, so the return value gets set to True, but then it forces the finally block to be run before returning, which changes the return value to False. Mine too. We can check that the interpreter gets as far as evaluating the return value in the except block: --> def paradox2(): try: raise Exception("Raise") except: print("Except") return [print("Return"), True][1] finally: print("Finally") return False return None --> ret = paradox2() Except Return Finally --> ret False And just to be thorough, if the finally block doesn't have a return: --> def paradox3(): try: raise Exception("Raise") except: print("Except") return [print("Return"), True][1] finally: print("Finally") return None --> print(paradox3()) Except Return Finally True -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 10:09:03 AM UTC-5, Steven D'Aprano wrote: > On Thu, 30 Jan 2014 09:08:58 -0500, Roy Smith wrote: > > > 1) Assume that you don't have the full operator precedence table > > memorized and just parenthesize everything. > > Oh really? Do you actually write stuff like this? > > b = ((2*a) + 1) Well, OK, I exaggerated a bit. Multiplication binds stronger than addition in any language I've ever used, so I assume I know that one. But not much beyond that. > if (b >= (-1)): No, I wouldn't use either set of parens their either. But, if I have any doubt at all, I rather than look it up, I just put parens. And my threshold for doubt is pretty low. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 10:09:03 AM UTC-5, Steven D'Aprano wrote: > E.g. `x+1 > 0 and y >= 5` is potentially as many as 9 distinct > items to keep in short-term memory. But bracketing some terms > as in `(x+1 > 0) and (y >= 5)` can reduce that down to as few > as two items. Yes, that's probably how I would write that, although, this is even simpler: (x > -1) and (y >= 5) -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 5:56 AM, Roy Smith wrote: > On Thursday, January 30, 2014 10:09:03 AM UTC-5, Steven D'Aprano wrote: > >> E.g. `x+1 > 0 and y >= 5` is potentially as many as 9 distinct >> items to keep in short-term memory. But bracketing some terms >> as in `(x+1 > 0) and (y >= 5)` can reduce that down to as few >> as two items. > > Yes, that's probably how I would write that, although, this is even simpler: > > (x > -1) and (y >= 5) Be careful; that's not the same thing. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: end quote help for a newbie
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 >-- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On 30/01/2014 12:49, Dave Angel wrote: [...] For hysterical reasons, True and False are instances of class bool, which is derived from int. So for comparison purposes False==0 and True==1. But in my opinion, you should never take advantage of this, except when entering obfuscation contests. Really? I take advantage of it quite a lot. For example, I do things like this: 'You have scored %i point%s' % (score, 's'*(score != 1)) -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On 01/30/2014 11:03 AM, Chris Angelico wrote: On Fri, Jan 31, 2014 at 5:56 AM, Roy Smith wrote: Yes, that's probably how I would write that, although, this is even simpler: (x > -1) and (y >= 5) Be careful; that's not the same thing. How so? -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Fri, Jan 31, 2014 at 6:22 AM, Ethan Furman wrote: > On 01/30/2014 11:03 AM, Chris Angelico wrote: > >> On Fri, Jan 31, 2014 at 5:56 AM, Roy Smith wrote: >>> >>> >>> Yes, that's probably how I would write that, although, this is even >>> simpler: >>> >>> (x > -1) and (y >= 5) >> >> >> Be careful; that's not the same thing. > > > How so? > Well, if x is an integer, then they're the same. If it's floating point, I think they're the same, but don't quote me on that. But for arbitrary types, there's no way of knowing what x+1 will result in. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Rotwang Wrote in message: > On 30/01/2014 12:49, Dave Angel wrote: >> [...] >> >> For hysterical reasons, True and False are instances of class >> bool, which is derived from int. So for comparison purposes >> False==0 and True==1. But in my opinion, you should never take >> advantage of this, except when entering obfuscation >> contests. > > Really? I take advantage of it quite a lot. For example, I do things > like this: > > 'You have scored %i point%s' % (score, 's'*(score != 1)) > I also did that kind of thing when computer resources were more precious the program readability. Like in 73 when my satellite navigation system had to fit in 2k code and 1.5k data. Here I'd probably do something like 'You have scored {} {}' .format (score, 'point' if score==1 else 'points') -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 7:08 AM, Dave Angel wrote: >> 'You have scored %i point%s' % (score, 's'*(score != 1)) >> > > Here I'd probably do something like > > 'You have scored {} {}' .format (score, 'point' if score==1 else > 'points') Bah, what's the fun in that? 'You have scored %i point%.*s' % (score, score!=1, 's') BTW, the layout of the original bugs me slightly: >> 'You have scored %i point%s' % (score, 's'*(score != 1)) I don't like having spaces around != and none around *. I'd either squash the != up or space out the *: 'You have scored %i point%s' % (score, 's'*(score!=1)) 'You have scored %i point%s' % (score, 's' * (score != 1)) Operators should always have at least as much space around them as more tightly-binding operators, IMO. In this instance, it'd be reasonable to squash the != and space the *, or to squash both, or to space both, but not the "backward" spacing of the original :) But that's just my opinion. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
Roy Smith writes: > On Thursday, January 30, 2014 9:56:19 AM UTC-5, Jussi Piitulainen wrote: > > > There's nothing to parenthesize in x <= y < z = w > > Hmm > > >>> x <= y < z = w > File "", line 1 > SyntaxError: can't assign to comparison > > I don't think any number of parentheses will help that :-) Er, sorry about that. Here: >>> x <= y < z == w Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined Much better :) -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 7:14 AM, Jussi Piitulainen wrote: >> I don't think any number of parentheses will help that :-) > > Er, sorry about that. Here: > x <= y < z == w > Traceback (most recent call last): > File "", line 1, in > NameError: name 'x' is not defined > > Much better :) See, you still all think the solution is with parentheses and stuff. It's not. The solution is with apostrophes - look! >>> 'x' <= 'y < z == w' True Now it works! ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thu, Jan 30, 2014 at 1:08 PM, Dave Angel wrote: > Rotwang Wrote in message: >> Really? I take advantage of it quite a lot. For example, I do things >> like this: >> >> 'You have scored %i point%s' % (score, 's'*(score != 1)) >> > > I also did that kind of thing when computer resources > were more > precious the program readability. Like in 73 when my satellite > navigation system had to fit in 2k code and 1.5k > data. > > Here I'd probably do something like > > 'You have scored {} {}' .format (score, 'point' if score==1 else > 'points') Of course if you're at all concerned about i18n then the proper way to do it would be: ngettext("You have scored %d point", "You have scored %d points", score) % score -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 7:28 AM, Ian Kelly wrote: > Of course if you're at all concerned about i18n then the proper way to > do it would be: > > ngettext("You have scored %d point", "You have scored %d points", score) % > score Ugh, so much duplication! We can totally do better than that. ngettext(*(lambda x,s: (x,x+'s',s))("You have scored %d point",score)) Much better! Incidentally, in creating the above abomination, I found that I can't do this: >>> print(*(lambda x: (x,x+'s'))("You have scored %d point"),score) SyntaxError: only named arguments may follow *expression But I can do this: >>> print(score,*(lambda x: (x,x+'s'))("You have scored %d point")) 1 You have scored %d point You have scored %d points Why is tuple unpacking limited to the last argument? Is it just for the parallel with the function definition, where anything following it is keyword-only? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Jan 30, 2014 1:40 PM, "Chris Angelico" wrote: > > On Fri, Jan 31, 2014 at 7:28 AM, Ian Kelly wrote: > > Of course if you're at all concerned about i18n then the proper way to > > do it would be: > > > > ngettext("You have scored %d point", "You have scored %d points", score) % score > > Ugh, so much duplication! We can totally do better than that. > > ngettext(*(lambda x,s: (x,x+'s',s))("You have scored %d point",score)) > > Much better! > > > Incidentally, in creating the above abomination, I found that I can't do this: > > >>> print(*(lambda x: (x,x+'s'))("You have scored %d point"),score) > SyntaxError: only named arguments may follow *expression > > But I can do this: > > >>> print(score,*(lambda x: (x,x+'s'))("You have scored %d point")) > 1 You have scored %d point You have scored %d points > > Why is tuple unpacking limited to the last argument? Is it just for > the parallel with the function definition, where anything following it > is keyword-only? Lack of a convincing use case, and the position of the following arguments would then be dependent upon the length of the tuple, which in many cases could result in subtle bugs. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 8:17 AM, Ian Kelly wrote: >> Why is tuple unpacking limited to the last argument? Is it just for >> the parallel with the function definition, where anything following it >> is keyword-only? > > Lack of a convincing use case, and the position of the following arguments > would then be dependent upon the length of the tuple, which in many cases > could result in subtle bugs. Okay. Just seemed an odd restriction; I can unpack an iterable into a function's args (great!), I can have other args before that tuple (handy!), but I can't have any after. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Statement evals as False in my IDE and True elsewhere
This is puzzling. (Using Python 2.5, WinXP, Boa Constructor 0.6.1 definitely running the code through Python 2.5) If I run these lines in my program, through my IDE (Boa Constructor), fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] fake_result = not all(i == '[omitted]' for i in fake_data) print 'This is fake result: ', fake_result I get this result: >>> This is fake result: False BUT, if I run those *exact same lines* (copied and pasted) in the Python 2.5 shell within Boa Constructor, or with IDLE with Python 2.5, I get: >>> This is fake result: True ...which is what it seems like it should evaluate to, right? What the heck is going on? How is this even possible? There is nothing that I know of in my code to cause this change, but perhaps there is. Otherwise I am at a total loss. Thanks, Che M -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Thursday, January 30, 2014 10:09:03 AM UTC-5, Steven D'Aprano wrote: > `(x+1 > 0) and (y >= 5)` Me: > this is even simpler: > (x > -1) and (y >= 5) On Thursday, January 30, 2014 2:03:42 PM UTC-5, Chris Angelico wrote: > Be careful; that's not the same thing. In what way? I'm assuming x is some numeric type. And further assuming it's not some humungous floating point value, so we run into precision issues. -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
CM wrote: > This is puzzling. (Using Python 2.5, WinXP, Boa Constructor 0.6.1 > definitely running the code through Python 2.5) > > If I run these lines in my program, through my IDE (Boa Constructor), > > fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] > fake_result = not all(i == '[omitted]' for i in fake_data) > print 'This is fake result: ', fake_result > > I get this result: > > This is fake result: False > > BUT, if I run those *exact same lines* (copied and pasted) in the Python > 2.5 shell within Boa Constructor, or with IDLE with Python 2.5, I get: > > This is fake result: True > > ...which is what it seems like it should evaluate to, right? What the > heck is going on? How is this even possible? There is nothing that I > know of in my code to cause this change, but perhaps there is. Otherwise > I am at a total loss. Hint: >>> def demo(): ... fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] ... fake_result = not all(i == '[omitted]' for i in fake_data) ... print 'This is fake result: ', fake_result ... >>> demo() This is fake result: True >>> from numpy import all >>> demo() This is fake result: False -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 9:09 AM, Roy Smith wrote: > On Thursday, January 30, 2014 10:09:03 AM UTC-5, Steven D'Aprano wrote: >> `(x+1 > 0) and (y >= 5)` > > Me: >> this is even simpler: >> (x > -1) and (y >= 5) > > On Thursday, January 30, 2014 2:03:42 PM UTC-5, Chris Angelico wrote: >> Be careful; that's not the same thing. > > In what way? I'm assuming x is some numeric type. And further assuming it's > not some humungous floating point value, so we run into precision issues. Now you're changing the problem domain :) Like I said, if it's an integer, you definitely will get the same result from each of the above; but that doesn't mean the expressions are equivalent. They just might happen to produce the same result for values within some particular domain. (I wouldn't even be 100% confident that it's valid for any numeric type, though I can't think of any float values that it would break on, and complex and int are unorderable anyway.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
On Fri, Jan 31, 2014 at 9:04 AM, CM wrote: > fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] > fake_result = not all(i == '[omitted]' for i in fake_data) > print 'This is fake result: ', fake_result Trying to get my head around this. You want to see if all the values in fake_data are '[omitted]' or not? That is to say, if there's anything that isn't '[omitted]'? Not sure that that's a normal thing to be asking, but that's what your code appears to do. What happens if you try this? fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] fake_result = set(fake_data)>{'[omitted]'} In theory, that should do the exact same thing as your code (returning True if there's anything in fake_data that is not '[omitted]'). The other thing to try is peppering your code with print statements. Divide the work up into pieces - show the entire loop and what happens - print out everything you can imagine. See where the difference begins between inside and outside the IDE. Once you find that, you'll have a clue as to what's wrong. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Why this throws an UnboundLocalError ?
Dear all, I have a very simple module glic3@e4200:# cat globalstate.py GLOBAL = 0 def update(): GLOBAL += 1 however it doesn't work!! glic3@e4200:# python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import globalstate >>> globalstate.update() Traceback (most recent call last): File "", line 1, in File "globalstate.py", line 4, in update GLOBAL += 1 UnboundLocalError: local variable 'GLOBAL' referenced before assignment And I don't know why :( Anyone ? Thanks!! -- Marc -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
On Thursday, January 30, 2014 5:14:57 PM UTC-5, Peter Otten wrote: > Hint: > > >>> def demo(): > ... fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] > ... fake_result = not all(i == '[omitted]' for i in fake_data) > ... print 'This is fake result: ', fake_result > > >>> demo() > This is fake result: True > > >>> from numpy import all > >>> demo() > This is fake result: False That's brilliant, thanks! Now I'm just a bit unsure of what to do about it. First, I don't actually have the line "from numpy import all" in that module's code, although I have imports of numpy; I think it is getting brought in through Matplotlib's pylab module, which I do import in that module. In any case, what's the most Pythonic way to deal with this? My first thought was to create the old all function and rename it so there would be no conflict: (both of what follows taken from answers here: http://stackoverflow.com/questions/18774388/re-import-aliased-shadowed-python-built-in-methods) builtin_all = __builtins__.all but I got the error: AttributeError: 'dict' object has no attribute 'all' So I wound up doing this: from __builtin__ import * which fixed the problem...but seems less than optimal, because what if I wanted to have numpy's all still in play? Again, thanks for restoring my faith in causality, Che M -- https://mail.python.org/mailman/listinfo/python-list
Re: Why this throws an UnboundLocalError ?
On Fri, Jan 31, 2014 at 9:46 AM, Marc Aymerich wrote: > GLOBAL = 0 > > def update(): > GLOBAL += 1 If you assign to a name, Python makes it local, unless you explicitly tell it that you want it to be global: def update(): global GLOBAL GLOBAL += 1 But be aware that the ALL_CAPS name conventionally means a constant. Since you're changing its value, it's not constant (wow! :) ), so using a name of GLOBAL is a bad idea. (Also, obviously, you want to name it appropriately to what you're doing, but I assume you called it this as part of cutting down your example. For which, by the way, thank you. You posted a complete example, and the full traceback, and the Python version and platform. That's everything that we need to help you - it's such a luxury!!) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Why this throws an UnboundLocalError ?
On 30/01/2014 22:46, Marc Aymerich wrote: Dear all, I have a very simple module glic3@e4200:# cat globalstate.py GLOBAL = 0 def update(): GLOBAL += 1 however it doesn't work!! glic3@e4200:# python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. import globalstate globalstate.update() Traceback (most recent call last): File "", line 1, in File "globalstate.py", line 4, in update GLOBAL += 1 UnboundLocalError: local variable 'GLOBAL' referenced before assignment And I don't know why :( Anyone ? Thanks!! You must tell the update function that GLOBAL is global. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Why this throws an UnboundLocalError ?
On 1/30/14 5:46 PM, Marc Aymerich wrote: Dear all, I have a very simple module glic3@e4200:# cat globalstate.py GLOBAL = 0 def update(): GLOBAL += 1 however it doesn't work!! glic3@e4200:# python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. import globalstate globalstate.update() Traceback (most recent call last): File "", line 1, in File "globalstate.py", line 4, in update GLOBAL += 1 UnboundLocalError: local variable 'GLOBAL' referenced before assignment And I don't know why :( Anyone ? Thanks!! Assignment statements in functions implicitly make local names. If you want to assign a new value to a global name in a function, you have to use a global statement: def update(): global GLOBAL GLOBAL += 1 -- Ned Batchelder, http://nedbatchelder.com -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
On Fri, Jan 31, 2014 at 9:48 AM, CM wrote: > builtin_all = __builtins__.all > > but I got the error: > > AttributeError: 'dict' object has no attribute 'all' Try using square brackets notation instead. Apparently your __builtins__ is a dictionary, not a module, though I don't know why (probably something to do with numpy, which I've never actually used). But try this: builtin_all = __builtins__["all"] It might work. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
> Try using square brackets notation instead. Apparently your > __builtins__ is a dictionary, not a module, though I don't know why > (probably something to do with numpy, which I've never actually used). > > But try this: > builtin_all = __builtins__["all"] > > It might work. Yes, it does. Thanks! Che M -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
On Thursday, January 30, 2014 5:25:31 PM UTC-5, Chris Angelico wrote: > On Fri, Jan 31, 2014 at 9:04 AM, CM wrote: > > > fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] > > > fake_result = not all(i == '[omitted]' for i in fake_data) > > > print 'This is fake result: ', fake_result > > > > Trying to get my head around this. You want to see if all the values > in fake_data are '[omitted]' or not? That is to say, if there's > anything that isn't '[omitted]'? Not sure that that's a normal thing > to be asking, but that's what your code appears to do. That's what I want, yes. It probably sure isn't a normal thing to be asking, and I wouldn't be surprised if I am approaching it the wrong way. Essentially, if ALL the items in that list are '[omitted]', I must not process the list, but if even one of them is something other than '[omitted]', I need to process it. If there is a more Pythonic / better way to approach that, I'd like to know it. > In theory, that should do the exact same thing as your code (returning > True if there's anything in fake_data that is not '[omitted]'). Yes, as you saw and as Peter showed, that the builtin all was shadowed by numpy's all. I wouldn't have thought of that, but it makes sense now. These sorts of shadowing problems are so rare for me that I never think about that possibility. -- https://mail.python.org/mailman/listinfo/python-list
HOW EVOLUTIONISTS MISUSE SCIENCE
http://www.talkorigins.org/ > Vs > http://www.trueorigin.org/ > WHICH ONE'S TRUE? > This one!: http://www.trueorigin.org/ -- Thrinaxodon, The Ultimate Defender of USENET -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
CM wrote: > On Thursday, January 30, 2014 5:14:57 PM UTC-5, Peter Otten wrote: > >> Hint: >> >> >>> def demo(): >> ... fake_data = ['n/a', 'n/a', 'n/a', 'n/a', '[omitted]', '12'] >> ... fake_result = not all(i == '[omitted]' for i in fake_data) >> ... print 'This is fake result: ', fake_result >> >> >>> demo() >> This is fake result: True >> >> >>> from numpy import all >> >>> demo() >> This is fake result: False > > That's brilliant, thanks! Now I'm just a bit unsure of what to do about > it. First, I don't actually have the line "from numpy import all" in that > module's code, although I have imports of numpy; I think it is getting > brought in through Matplotlib's pylab module, which I do import in that > module. > > In any case, what's the most Pythonic way to deal with this? My first > thought was to create the old all function and rename it so there would be > no conflict: > > (both of what follows taken from answers here: > http://stackoverflow.com/questions/18774388/re-import-aliased-shadowed- python-built-in-methods) > > builtin_all = __builtins__.all > > but I got the error: > > AttributeError: 'dict' object has no attribute 'all' > > So I wound up doing this: > > from __builtin__ import * > > which fixed the problem...but seems less than optimal, because what if I > wanted to have numpy's all still in play? import numpy # you can now use numpy's all as numpy.all(...) del all # remove numpy's all from your module's global namespace and # thus make the builtin visible again -- https://mail.python.org/mailman/listinfo/python-list
Re: Statement evals as False in my IDE and True elsewhere
On Fri, Jan 31, 2014 at 10:00 AM, CM wrote: > Essentially, if ALL the items in that list are '[omitted]', I must not > process the list, but if even one of them is something other than > '[omitted]', I need to process it. Okay. The set example that I gave will work, then - as long as all items are hashable (if they're strings, they are). Up to you which one's more readable. In any case, that could do with a supporting comment. My first suspicion was that it ought to be written as: fake_result = '[omitted]' not in fake_data and that it was calculating the wrong thing. But it is doing what you think it is. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On 30 January 2014 20:38, Chris Angelico wrote: > > Why is tuple unpacking limited to the last argument? Is it just for > the parallel with the function definition, where anything following it > is keyword-only? You're not the first person to ask that: http://www.python.org/dev/peps/pep-0448/ If you're able and willing to implement it, I believe the support is there. The primary reason I know of for its non-inclusion was that it was first proposed (with code) during a feature freeze. -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On Fri, Jan 31, 2014 at 10:36 AM, Joshua Landau wrote: > On 30 January 2014 20:38, Chris Angelico wrote: >> >> Why is tuple unpacking limited to the last argument? Is it just for >> the parallel with the function definition, where anything following it >> is keyword-only? > > You're not the first person to ask that: > http://www.python.org/dev/peps/pep-0448/ > > If you're able and willing to implement it, I believe the support is > there. The primary reason I know of for its non-inclusion was that it > was first proposed (with code) during a feature freeze. Ah, okay. Glad it's not a fundamentally hard concept. I don't know that I want to dig into actually implementing that, just now, but I've added myself as nosy on bug 2292 (which is where the patch is being discussed, and is referenced in the PEP). I don't have a major use-case for it in Python, though I've used the equivalent Pike feature all over the place (it's done as @args where args is an array, and it's equivalent to listing the args - pretty much the same as *args in Python) - it's handy, even though it's almost never really crucial. It's perhaps telling that the only time I can recall running into this with Python is in making some deliberately bad code :D ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: 1 > 0 == True -> False
On 30/01/2014 23:36, Joshua Landau wrote: On 30 January 2014 20:38, Chris Angelico wrote: Why is tuple unpacking limited to the last argument? Is it just for the parallel with the function definition, where anything following it is keyword-only? You're not the first person to ask that: http://www.python.org/dev/peps/pep-0448/ On a vaguely-related note, does anyone know why iterable unpacking in calls was removed in Python 3? I mean things like def f(x, (y, z)): return (x, y), z I don't have a use case in mind, I was just wondering. -- https://mail.python.org/mailman/listinfo/python-list
Removal of iterable unpacking in function calls (was: 1 > 0 == True -> False)
Rotwang writes: > On a vaguely-related note, does anyone know why iterable unpacking in > calls was removed in Python 3? This is explained in the PEP which described its removal http://www.python.org/dev/peps/pep-3113/>, especially http://www.python.org/dev/peps/pep-3113/#why-they-should-go>. -- \ “My, your, his, hers, ours, theirs, its. I'm, you're, he's, | `\ she's, we're, they're, it's.” —anonymous, alt.sysadmin.recovery | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list