Re: [Tutor] Sharing Code Snippets
Tried it out.It's really cool.From next time on, shall try to make use of this. Thanks. :) On 11 April 2013 06:58, Amit Saha amitsaha...@gmail.com wrote: Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. I hope that's a useful suggestion. [1] https://gist.github.com/ Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- -- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running python from windows command prompt
Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print Average:, avg def average(num_list): return sum(num_list)/len(num_list) if __name__ == __main__: main(sys.argv[1:]) When running in command line I am getting these errors: In case 1. data = sys.argv[1] In case 2, data = float(sys.argv[1]) In case 3, data = int (sys.argv[1]) Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.u...@tcs.com Website: http://www.tcs.com Experience certainty. IT Services Business Solutions Outsourcing From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Date: 04/10/2013 10:58 PM Subject: Re: [Tutor] Running python from windows command prompt Sent by: Tutor tutor-bounces+arijit.ukil=tcs@python.org On 10/04/13 13:32, Arijit Ukil wrote: I like to run a python program my_python.py from windows command prompt. This program ( a function called testing) takes input as block data (say data = [1,2,3,4] and outputs processed single data. Hopefully the code below is not your entire program. If it is it won't work. You define 2 functions but never call them. Also you don't print anything so there is no visible output. Finally this a code does not read the values from sys.argv. (See my tutorial topic 'Talking to the user') As for the error message, others have replied but basically you need to either change to the folder that your file exists in or specify the full path at the command prompt. import math def avrg(data): return sum(data)/len(data) def testing (data): val = avrg(data) out = pow(val,2) return out HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor =-=-= Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you image/gif___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running python from windows command prompt
On Thu, Apr 11, 2013 at 11:38 AM, Arijit Ukil arijit.u...@tcs.com wrote: Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print Average:, avg def average(num_list): return sum(num_list)/len(num_list) if __name__ == __main__: main(sys.argv[1:]) Two major problems: One: The __main__ methods processes (correctly) the args and drops argv[0] But your main() function is calling sys.argv again Two: sum() and len() expect a list -- more accurately an iterable. when you say data = argv[1] data is a scalar. If you know of list comprehensions, it can be easier or else, think of a function to convert a list of strings (argv[1:] to a list of floats; more general than int) def arg2list(arg): args = [] for a in arg: args.append(float(a)) return args Now replace the data = line with data = arg2list(argv) # NOT sys.argv HTH Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running python from windows command prompt
On 11/04/13 07:08, Arijit Ukil wrote: Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print Average:, avg def average(num_list): return sum(num_list)/len(num_list) if __name__ == __main__: main(sys.argv[1:]) When running in command line I am getting these errors: In case 1. data = sys.argv[1] In case 2, data = float(sys.argv[1]) In case 3, data = int (sys.argv[1]) Try printing data to see what you are doing wrong in each case. You need data to be a list of numbers. None of your three cases produces that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Looks like a judgment bug.
I found this under Windows Python3 l=http://f/; l[-1] is not '/' False and this under Linux Python3 l = http://ff.f/; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
Op 11-04-13 12:41, w qj schreef: I found this under Windows Python3 l=http://f/; l[-1] is not '/' False and this under Linux Python3 l = http://ff.f/; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? This looks like a is not versus != thing. Someone (I think Steven Apprano) posted a couple of days ago on this mailing list to only use is and is not when comparing to None. It works fine with regular operators. $ python3 Python 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] on linux2 Type help, copyright, credits or license for more information. l = http://ff.f/; l[-1] '/' l[-1] is not '/' True l[-1] != '/' False Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Appending an extra column in a data file
Subject: Re: [Tutor] Appending an extra column in a data file On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin oscar.j.benja...@gmail.com wrote: fin = open('old.dat') fout = open('new.dat', 'w') with fin, fout: for line in fin: This has the same problems as contextlib.nested: An error raised while opening 'new.dat' could prevent 'old.dat' from being closed properly. Thanks for pointing out the potential bug there. It's not a big problem in this case with the file open for reading. But, yeah, I'm hanging my head in shame here... ;) Cool. This solves a problem it had with contextlib.nested some time ago. (sorry for kinda hijacking this thread, but..) Would it be safe (both __exit__ calls are guaranteed to be made) to use code like this (if it worked, that is!)? import sys import contextlib def someCloseFunc(): print Yaaay properly closed! @contextlib.contextmanager def funcOne(arg): e = None try: yield arg except: e = sys.exc_info()[1] print e finally: someCloseFunc() if e: yield e yield None funcTwo = funcOne with contextlib.nested(funcOne(one-ish), funcTwo(two-ish)) as (one, two): print one, two * traceback one-ish two-ish Yaaay properly closed! generator didn't stop Yaaay properly closed! Traceback (most recent call last): File F:/mgr.py, line 23, in module print one, two File C:\Program Files\Python27\lib\contextlib.py, line 24, in __exit__ self.gen.next() File C:\Program Files\Python27\lib\contextlib.py, line 121, in nested if exit(*exc): File C:\Program Files\Python27\lib\contextlib.py, line 36, in __exit__ raise RuntimeError(generator didn't stop after throw()) RuntimeError: generator didn't stop after throw() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sharing Code Snippets
Subject: [Tutor] Sharing Code Snippets Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. I hope that's a useful suggestion. [1] https://gist.github.com/ Hi, Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites. That way the information is lost forever if github decides to remove the code. Often these sites have expiration dates for their contents. Albert-Jan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Appending an extra column in a data file
On 11 April 2013 12:24, Albert-Jan Roskam fo...@yahoo.com wrote: Subject: Re: [Tutor] Appending an extra column in a data file On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin oscar.j.benja...@gmail.com wrote: fin = open('old.dat') fout = open('new.dat', 'w') with fin, fout: for line in fin: This has the same problems as contextlib.nested: An error raised while opening 'new.dat' could prevent 'old.dat' from being closed properly. Thanks for pointing out the potential bug there. It's not a big problem in this case with the file open for reading. But, yeah, I'm hanging my head in shame here... ;) Cool. This solves a problem it had with contextlib.nested some time ago. (sorry for kinda hijacking this thread, but..) Would it be safe (both __exit__ calls are guaranteed to be made) to use code like this (if it worked, that is!)? Partly because it doesn't work I really can't figure out what you're trying to do. import sys import contextlib def someCloseFunc(): print Yaaay properly closed! @contextlib.contextmanager def funcOne(arg): e = None try: yield arg except: e = sys.exc_info()[1] print e finally: someCloseFunc() if e: I guess you already know that the lines two lines below will break the contextmanager decorator: yield e yield None What effect are you actually wanting from the two lines below (I'm assuming that you didn't want the error message shown)? Is it significant that funcTwo is funcOne, or is that just to keep the demonstration simple? funcTwo = funcOne with contextlib.nested(funcOne(one-ish), funcTwo(two-ish)) as (one, two): print one, two * traceback one-ish two-ish Yaaay properly closed! generator didn't stop Yaaay properly closed! Traceback (most recent call last): File F:/mgr.py, line 23, in module print one, two File C:\Program Files\Python27\lib\contextlib.py, line 24, in __exit__ self.gen.next() File C:\Program Files\Python27\lib\contextlib.py, line 121, in nested if exit(*exc): File C:\Program Files\Python27\lib\contextlib.py, line 36, in __exit__ raise RuntimeError(generator didn't stop after throw()) RuntimeError: generator didn't stop after throw() Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Thu, 11 Apr 2013, Timo wrote: Op 11-04-13 12:41, w qj schreef: I found this under Windows Python3 l=http://f/; l[-1] is not '/' False and this under Linux Python3 l = http://ff.f/; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? This looks like a is not versus != thing. Someone (I think Steven Apprano) posted a couple of days ago on this mailing list to only use is and is not when comparing to None. You're absolutely correct. `is` compares the identity (basically id('/') == id('/') ) *sometimes* CPython will use a trick that caches smaller strings, so this might work one time: x = '/' y = '/' x is y True But then the next time you do the same thing it could return False. Or on a different OS. There's nothing (that I'm aware of) that will guarantee either result in this case. In the example case we were comparing that `l[-1]` referred to the same spot in memory as the literal string `/`. And as the example showed, sometimes it will be, other times it won't. The takeaway is to use `is` when you want to compare identity, and `==` when you want equaltiy. For example, That car is *my* car. The car I'm referring to is one specific car. But if I were to say... My car is a Chevette. That would be more like saying `car.model == 'Chevette'` - many different cars may actually be a Chevette. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Appending an extra column in a data file
snip Cool. This solves a problem it had with contextlib.nested some time ago. (sorry for kinda hijacking this thread, but..) Would it be safe (both __exit__ calls are guaranteed to be made) to use code like this (if it worked, that is!)? Partly because it doesn't work I really can't figure out what you're trying to do. You are right, I should have stated the goal: make contextlib.nested work in a way that it does not have the shortcoming that caused it become deprecated, namely, __exit__ is not guaranteed to be called if the outer with raises an exception. import sys import contextlib def someCloseFunc(): print Yaaay properly closed! @contextlib.contextmanager def funcOne(arg): e = None try: yield arg except: e = sys.exc_info()[1] print e finally: someCloseFunc() if e: I guess you already know that the lines two lines below will break the contextmanager decorator: yield e yield None Nope, I didn't realize that. Thank you. What effect are you actually wanting from the two lines below (I'm assuming that you didn't want the error message shown)? Is it significant that funcTwo is funcOne, or is that just to keep the demonstration simple? This is merely to keep the demonstration simple. And yes, I didn't want the error message. funcTwo = funcOne with contextlib.nested(funcOne(one-ish), funcTwo(two-ish)) as (one, two): print one, two * traceback one-ish two-ish Yaaay properly closed! generator didn't stop Yaaay properly closed! Two times Yaaay properly closed! means that __exit__ is called twice, right? Anyway, the code below at least runs without errors. Too bad the outcommented version with tuple unpacking raises an AttributeError. import sys import contextlib def someCloseFunc(): print Yaaay properly closed! @contextlib.contextmanager def funcOne(arg): try: yield arg except: yield sys.exc_info()[1] finally: someCloseFunc() funcTwo = funcOne with contextlib.nested(funcOne(one-ish), funcTwo(two-ish)) as (one, two): print one, two ##funcs = (funcOne, funcTwo) ##with contextlib.nested(*funcs) as (one, two): ## print one(one-ish), two(two-ish) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Appending an extra column in a data file
On 11 April 2013 13:25, Albert-Jan Roskam fo...@yahoo.com wrote: snip Cool. This solves a problem it had with contextlib.nested some time ago. (sorry for kinda hijacking this thread, but..) Would it be safe (both __exit__ calls are guaranteed to be made) to use code like this (if it worked, that is!)? Partly because it doesn't work I really can't figure out what you're trying to do. You are right, I should have stated the goal: make contextlib.nested work in a way that it does not have the shortcoming that caused it become deprecated, namely, __exit__ is not guaranteed to be called if the outer with raises an exception. The problem with contextlib.nested is that it cannot catch errors raised while its arguments are generated because nested hasn't even been called yet. For example in the code with nested(open('foo'), open('bar')) as foo, bar: do_stuff() the expressions used as arguments to the nested function are evaluated before nested is called. This is always true of function calls: def f1(): ... print('Calling f1') ... def f2(): ... print('Calling f2') ... def g(arg1, arg2): ... print('Calling g') ... g(f1(), f2()) Calling f1 Calling f2 Calling g def f_broken(): ... raise ValueError ... g(f1(), f_broken()) Calling f1 Traceback (most recent call last): File stdin, line 1, in module File stdin, line 2, in f_broken ValueError So if open raises an error nested is never called and the nested context manager does not exist in order to call the __exit__ methods of its arguments. Two times Yaaay properly closed! means that __exit__ is called twice, right? Yes it does. Anyway, the code below at least runs without errors. Too bad the outcommented version with tuple unpacking raises an AttributeError. import sys import contextlib def someCloseFunc(): print Yaaay properly closed! @contextlib.contextmanager def funcOne(arg): try: yield arg except: yield sys.exc_info()[1] Why do you want the two lines below? Attempting to yield twice gives an error like the one you showed before: from contextlib import contextmanager @contextmanager ... def f(): ... try: ... yield ... except: ... yield ... with f(): ... raise ValueError ... Traceback (most recent call last): File stdin, line 2, in module File q:\tools\Python27\lib\contextlib.py, line 36, in __exit__ raise RuntimeError(generator didn't stop after throw()) RuntimeError: generator didn't stop after throw() The contextmanager decorator should be used with a generator function that hits exactly one yield in its execution. That yield statement corresponds to the code block in the with statement. There is nothing for any other yield to correspond to. finally: someCloseFunc() funcTwo = funcOne with contextlib.nested(funcOne(one-ish), funcTwo(two-ish)) as (one, two): print one, two Since there isn't really any way that funcOne or funcTwo would raise an error when called there isn't any problem with using nested *in this case*. The error would have to be raised before the yield statement. If that's not really possible for any of the context managers that you want to use then nested is fine and you can use it without worry. ##funcs = (funcOne, funcTwo) ##with contextlib.nested(*funcs) as (one, two): ## print one(one-ish), two(two-ish) That's because you're passing functions into nested rather than calling the functions and passing the result into nested. Try this: context_managers = (funcOne('one'), funcTwo('two')) with contextlib.nested(*context_managers) as cms: # blah blah Note that if you're happy using nested there's no problem with creating the context managers on the line above. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running python from windows command prompt
On 11/04/13 07:08, Arijit Ukil wrote: Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print Average:, avg def average(num_list): return sum(num_list)/len(num_list) Note that in Python 2.2-2.7 if sum returns an integer the division may not be what you expect. 3/2 1 3/2.0 1.5 You may want to convert either the numerator or denominator to a float. It does not matter which as long as one of them is a float. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Guidance if possible
Hello again wonderful python tutor mailing list. I've got I guess more of a broad question than is usually asked on this list and perhaps some of you might find it annoying, that's fine, if it's inappropriate feel free to say so. I want to start work on a new python project that would visit a specific companies contest site daily and everyday fill out the active contest forms, as they allow you to enter once a day. I've got an outline in my head but am a little green to know any of the good web scraping/manipulation frameworks or if one is better than the other for something like this. I have no intention of doing anything professional/shady/annoying with this code and want to write it purely for my own amusement as well as to learn and obviously to perhaps win something cool. Any information anyone feels like providing would be awesome, I'm running Lubuntu 12.10, 2gb ram, old crappy notebook. My basic outline goes something like this.. Everyday the program visits the site and scrapes the links for all the contests. The program visits each contest page and verifies there is an entry form, indicating that the contest is active If the contest is active at that moment, it adds the title of the page to a text file, if the contest is inactive it adds the title of the page to a text file. If the contest is active, it fills out the form with my details and sends it off If the contest is inactive the title of the page is added to the permanently blacklisted text file and never messed with again. This might be a bit convoluted as well and any pointers are appreciated. Scott ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guidance if possible
On 11/04/13 23:33, Scurvy Scott wrote: the other for something like this. I have no intention of doing anything professional/shady/annoying with this code and want to write it purely for my own amusement as well as to learn and obviously to perhaps win something cool. Which is fine but you should still check the terms and conditions of the web sites because many such sites explicitly prohibit the use of web scrapers. Using one could disqualify you from winning, and disguising the fact you are using one is non trivial. Everyday the program visits the site and scrapes the links for all the contests. The program visits each contest page and verifies there is an entry form, indicating that the contest is active If the contest is active at that moment, it adds the title of the page to a text file, if the contest is inactive it adds the title of the page to a text file. If the contest is active, it fills out the form with my details and sends it off If the contest is inactive the title of the page is added to the permanently blacklisted text file and never messed with again. This might be a bit convoluted as well and any pointers are appreciated. Seems reasonable to me. Try looking at the http, urllib and cookie stuff in the stdlib. And then look at tools like Beautiful Soup and Element Tree for the content scraping bits. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sharing Code Snippets
On Thu, Apr 11, 2013 at 9:33 PM, Albert-Jan Roskam fo...@yahoo.com wrote: Subject: [Tutor] Sharing Code Snippets Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. I hope that's a useful suggestion. [1] https://gist.github.com/ Hi, Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites. That way the information is lost forever if github decides to remove the code. Often these sites have expiration dates for their contents. GitHub's Gists doesn't have an expiration date, since its primary purpose is not a paste bin. But yes, I understand that if GitHub decides to remove this service some day, the code is lost. -Amit. Albert-Jan -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On 11/04/13 20:41, w qj wrote: I found this under Windows Python3 l=http://f/; l[-1] is not '/' False and this under Linux Python3 l = http://ff.f/; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? No, it is a bug in your understanding. The is and is not operators are for testing object identity, not equality. Python makes very few promises about object identity, and in this case both examples are fine. When you write this code: l[-1] is not '/' # where l[-1] == '/' how does Python evaluate this expression? First, it looks up l[-1], which creates a new object equal to the single-character string '/'. Then, Python evaluates the literal '/'. Now it has a choice: it might *reuse* the object that was just created a microsecond ago, or it might create a *new* object with the same value. Both behaviours are allowed, the language does not specify one or the other. In the first case, you get one object referenced twice, and is not returns False. In the second case, you get two distinct objects referenced once each, and is not returns True. Both behaviours are correct, since Python doesn't promise when it will or won't create a new object in cases like this. Whether Python creates two distinct objects or not will depend on the version of Python you use, the implementation, the operating system, possibly even the day of the week. (Well, probably not the last one, but it *could*.) No promises are made, and you cannot rely on one behaviour or the other. You almost never need to use object identity, and should nearly always use == and != instead. Almost the only exception is when testing for the None singleton object. # if one of the values is None, always use is or is not: if x is None # for everything else, always use == or != x == '/' There are some other exceptions, but they are rare. For interest, I ran this expression under various different versions of Python: print ('http://f/'[-1] is '/') And these are the results I got: Jython 2.5: False IronPython 2.6: False CPython: 1.5: True 2.4: True 2.5: True 2.6: True 2.7: True 3.1: False 3.2: False 3.3: True Unless you have the exact same versions, built with the exact same compiler, on the exact same operating systems, you may get different results. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sharing Code Snippets
On 11/04/13 11:28, Amit Saha wrote: Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. Please don't. Small code snippets should be posted directly in the body of the email, not on some external website. They should be posted in PLAIN TEXT (do not use so-called rich-text, HTML formatted emails, since they destroy critical indentation and make it difficult for those using plain-text email clients to read your code). Like this: import random def coin_toss(): if random.random() 0.5: return head else: return tail It's much less work for everyone to read code snippets in the email: compare: SENDER: copy and paste code directly into email READER: read email write response versus: SENDER: open browser log in to external site copy and paste code into external site make sure code has been saved copy and paste url into email READER: read email open browser copy and paste url fix url if it has been mangled by line-wrapping read code copy and paste back to email for the response to say nothing about how it may effect those who use a screen reader. (They generally work well with email, not so well with many websites.) People may have access to their email, and be able to read and answer your question, but they may not have access to the web. Perhaps they are behind a firewall that blocks the website. For whatever reason, just because somebody is reading your email doesn't mean that they can or will follow to a website to read the important bit (the actual code). You should make it *easy* for people to answer, not harder. Code sharing sites are great for posting entire programs, but you, the reader, shouldn't be posting entire programs and expecting us to work out where the problem lies. Identify where the problem lies, and eliminate all unnecessary code. Please read this for more details: http://sscce.org/ -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Thu, Apr 11, 2013 at 8:41 PM, w qj after19...@gmail.com wrote: I found this under Windows Python3 l=http://f/; l[-1] is not '/' False and this under Linux Python3 l = http://ff.f/; l[-1] '/' l[-1] is not '/' True It's Looks like a python bug? No, this is not. The 'is' and 'is not' tests in Python are for checking the identities of Python objects - a string, a single character, a single number, everything is an object. So for example: a=1 b=1 a is b True id(a) == id(b) True When you perform the check, 'a is b', you are actually checking id(a) == id(b). In this case, since I am really referring to the same object, 1 with two different bindings - the identifier is the same. In your case, the check 'failed' on Windows and 'passed' on Linux, is because in one case, the identifiers were the same, and in another case it wasn't. So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. You may want to read up on Python's data model to learn more about this. Also, more on string interning here. [1] [1] http://stackoverflow.com/questions/15541404/python-string-interning HTH, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On 12/04/13 12:53, Amit Saha wrote: So for example: a=1 b=1 a is b True id(a) == id(b) True This is not a very good example, because that behaviour itself is implementation-dependent and not guaranteed. For example, in IronPython 2.6 I get completely different behaviour: a = 1 b = 1 a is b False print id(a), id(b) 43 44 Even in CPython, the implementation you are probably using, the behaviour will depend on all sorts of factors, such as the type of the object, and even the value: py a = 10001 py b = 10001 py a is b False py a = 1.0 py b = 1.0 py a is b False So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. No, not really. The best you can say is this: If Python has a choice between creating a new object, and re-using an existing object, and the object is mutable, Python will never re-use the object since that might introduce bugs. If the object is immutable, Python *may* re-use it, or it may not. When does Python have a choice between re-using existing objects? That's a complicated question, and there's no straightforward answer. The best I can do is give some examples: # References to a name will ALWAYS use the same object: x is x # always True # References to another identifier MIGHT re-use the same object: x.attr is x.attr # sometimes True, sometimes False x[index] is x[index] # the same # References to a literal MIGHT re-use the same object, if it is immutable: 'x' is 'x' # might be True ['x'] is ['x'] # always False # The same literal on the same line of code MIGHT be re-used: x = 123.5; y = 123.5; x is y # might be True # ...even if they aren't re-used when on separate lines. x = 123.5 y = 123.5 x is y # probably will be False # If two or more identifiers are assigned to a value at the same time, # Python GUARANTEES to use the same object: x = y = anything_you_like() x is y # always True # Assignment in general never makes a new object: x = something() y = x x is y # always True[1] Object identity is almost never important. About the only time it is important is when comparing things to None. But in practice, you can expect (but not rely on!) CPython to re-use the following: * Small integers. Which values count as small depend on the version, but -1 to 100 is common. * Strings that look like identifiers, e.g. x, item, but not hello world or ?. But don't rely on this, as it is not guaranteed and could go away at any time. [1] Technically, if you change the current namespace to a custom dict type, you could do anything you like. But that's cheating, and it's harder than it sounds to change the current namespace. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano st...@pearwood.info wrote: On 12/04/13 12:53, Amit Saha wrote: So for example: a=1 b=1 a is b True id(a) == id(b) True This is not a very good example, because that behaviour itself is implementation-dependent and not guaranteed. For example, in IronPython 2.6 I get completely different behaviour: a = 1 b = 1 a is b False print id(a), id(b) 43 44 Even in CPython, the implementation you are probably using, the behaviour will depend on all sorts of factors, such as the type of the object, and even the value: py a = 10001 py b = 10001 py a is b False py a = 1.0 py b = 1.0 py a is b False So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. No, not really. The best you can say is this: If Python has a choice between creating a new object, and re-using an existing object, and the object is mutable, Python will never re-use the object since that might introduce bugs. If the object is immutable, Python *may* re-use it, or it may not. Indeed. My point was to give the original poster at least *some* idea of what the issue really is. If he/she takes that hint and experiments, reads the Python data model, and finds something weird with that statement - he/she will discover the finer/exactly correct details. So, thanks for clarifying this. When does Python have a choice between re-using existing objects? That's a complicated question, and there's no straightforward answer. The best I can do is give some examples: # References to a name will ALWAYS use the same object: x is x # always True # References to another identifier MIGHT re-use the same object: x.attr is x.attr # sometimes True, sometimes False x[index] is x[index] # the same # References to a literal MIGHT re-use the same object, if it is immutable: 'x' is 'x' # might be True ['x'] is ['x'] # always False # The same literal on the same line of code MIGHT be re-used: x = 123.5; y = 123.5; x is y # might be True # ...even if they aren't re-used when on separate lines. x = 123.5 y = 123.5 x is y # probably will be False # If two or more identifiers are assigned to a value at the same time, # Python GUARANTEES to use the same object: x = y = anything_you_like() x is y # always True # Assignment in general never makes a new object: x = something() y = x x is y # always True[1] Object identity is almost never important. About the only time it is important is when comparing things to None. But in practice, you can expect (but not rely on!) CPython to re-use the following: * Small integers. Which values count as small depend on the version, but -1 to 100 is common. * Strings that look like identifiers, e.g. x, item, but not hello world or ?. The link to the SO question discusses string interning to some detail. But don't rely on this, as it is not guaranteed and could go away at any time. Yes, the 'is' check shouldn't really be relied on checks such as those for None objects. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Fri, Apr 12, 2013 at 1:42 PM, Amit Saha amitsaha...@gmail.com wrote: On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano st...@pearwood.info wrote: On 12/04/13 12:53, Amit Saha wrote: So for example: a=1 b=1 a is b True id(a) == id(b) True This is not a very good example, because that behaviour itself is implementation-dependent and not guaranteed. For example, in IronPython 2.6 I get completely different behaviour: a = 1 b = 1 a is b False print id(a), id(b) 43 44 Even in CPython, the implementation you are probably using, the behaviour will depend on all sorts of factors, such as the type of the object, and even the value: py a = 10001 py b = 10001 py a is b False py a = 1.0 py b = 1.0 py a is b False So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. No, not really. The best you can say is this: If Python has a choice between creating a new object, and re-using an existing object, and the object is mutable, Python will never re-use the object since that might introduce bugs. If the object is immutable, Python *may* re-use it, or it may not. Indeed. My point was to give the original poster at least *some* idea of what the issue really is. If he/she takes that hint and experiments, reads the Python data model, and finds something weird with that statement - he/she will discover the finer/exactly correct details. So, thanks for clarifying this. When does Python have a choice between re-using existing objects? That's a complicated question, and there's no straightforward answer. The best I can do is give some examples: # References to a name will ALWAYS use the same object: x is x # always True # References to another identifier MIGHT re-use the same object: x.attr is x.attr # sometimes True, sometimes False x[index] is x[index] # the same # References to a literal MIGHT re-use the same object, if it is immutable: 'x' is 'x' # might be True ['x'] is ['x'] # always False # The same literal on the same line of code MIGHT be re-used: x = 123.5; y = 123.5; x is y # might be True # ...even if they aren't re-used when on separate lines. x = 123.5 y = 123.5 x is y # probably will be False # If two or more identifiers are assigned to a value at the same time, # Python GUARANTEES to use the same object: x = y = anything_you_like() x is y # always True # Assignment in general never makes a new object: x = something() y = x x is y # always True[1] Object identity is almost never important. About the only time it is important is when comparing things to None. But in practice, you can expect (but not rely on!) CPython to re-use the following: * Small integers. Which values count as small depend on the version, but -1 to 100 is common. * Strings that look like identifiers, e.g. x, item, but not hello world or ?. The link to the SO question discusses string interning to some detail. But don't rely on this, as it is not guaranteed and could go away at any time. Yes, the 'is' check shouldn't really be relied on checks such as those for None objects. Correction: Yes, the 'is' check shouldn't really be relied on checks other than checks for None objects (for example). -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor