Re: [Tutor] Question on "import foobar" vs "from foobar import *"
On 1/10/2010 11:23 AM, Eric Pavey wrote: I should add (that as I understand it), when you do a 'from foo import blah', or 'from foo import *', this is doing a /copy/ (effectively) of that module's attributes into the current namespace. Doing "import foo" or "import foo as goo" is keeping a /reference /to the imported module rather than a copy. No, that's a roundabout way to look at it. Python's variable holds references to objects[1] and never the object themselves; name assignment statement in python never makes a copy of the object, but always makes a new reference to the same object. "Assignment statements" in python includes the '=', 'from import', and regular 'import' [2]. [1] this is call-by-object http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm [2] there are other more obscure statements that is an 'assignment statement' as well, such as "with ... as ...", "agumented assignment operators", dictionary/list assignment, etc. The list is non-exhaustive. If you use the 'from import' system, changes made to attrs of the imported module /won't/ be seen by any other module that imported it. If you do just an 'import' on a module (or 'import ... as ...'), then changes made to attrs on the imported module /will /be seen by othe modules that import it as well. I hope that is somewhat clear. ;) Read both links to effbot's article, they should make it clear why the current behavior is the way it is. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] samples on sort method of sequence object.
On 01/14/10 06:56, Hugo Arts wrote: > On Wed, Jan 13, 2010 at 8:21 PM, Stefan Behnel wrote: >> Hugo Arts, 13.01.2010 15:25: >>> >>> Here is my solution for the general case: >>> >>> from itertools import groupby >>> def alphanum_key(string): >>>t = [] >>>for isdigit, group in groupby(string, str.isdigit): >>>group = ''.join(group) >>>t.append(int(group) if isdigit else group) >>>return t >> >> Note that this won't work in Py3, where integers and strings are not >> ordered, i.e. not comparable w.r.t the < and > operators. >> > > True. You can accommodate by writing a ComparableInt class extending > int, and implement __lt__ and __gt__. > It's not exactly succinct, but it works. Not necessary, you can just pass the cmp= parameter to sort that checks the chunk's type. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching in a file
On 01/14/10 10:29, Hugo Arts wrote: > On Thu, Jan 14, 2010 at 12:05 AM, Alan Gauld > wrote: >> > >> > I prefer the next() approach. > Rightfully so. IMO, The while loop with readline is basically the C > version of that, for the poor people who don't have iterators. I would often prefer while loop with next() though. Writing a state machine with for-loop can become quite messy because of the implicit next() on each iteration. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation about __init__()
On 01/17/10 16:42, Robert wrote: > I have read quite a bit in the past 2 months, ( I have also looked at codes) > At this point, I think I understand well what __init__() is and does - > But, I have yet to see this *specifically* spelled out about the the > __init__ method for a Class; > > It is OPTIONAL, correct ? > > if I have NO start values/variables to set, no Base Class __init__ to > call --- the __init__ method is NOT required, correct ? No, __init__ is always required for new-style classes; however due to object inheritance (all new-style classes inherits from `object`), all new-style classes inherits the do-nothing __init__ from `object`. Essentially, it means __init__ can be omitted if it does the same as the super class' __init__. More generally, a method (e.g. MyClass.__init__) that does not override the superclass' method (e.g. MySuperClass.__init__) will use the superclass' definition of the method (i.e. when MyClass inherits from MySuperClass, and __init__ is not overrided in MyClass, MyClass.__init__ == MySuperClass.__init__). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The magic parentheses
On 01/24/10 17:14, David Hutto wrote: > Hi, > > This is my first post to the list, so tell me if I'm posting incorrectly. > > I'm creating a script, http://python.codepad.org/mHyqbJ2z that gives the area > of two circles, based on their radius, and displays the difference between > the two results. > > My problem is when the results are printed, I get this: > > Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] > on win32 > IDLE 2.6.4 No Subprocess > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') > ... > The parentheses, as well as the apostrophes and commas. I'm sure it's the way > I'm having the results printed after it's through, but not sure how to > correct it. > > I tried writing the 'Variable 1' and '2', as well as the 'is greater > than' within the y, and z local variables in the def return_difference_of12, > and got the same result as when I > listed the portions of the printed result's sentence in the non-local > variables I have now(I'm new to Python, so I'm not sure if this would be the > correct term). > > Any help would be appreciated. Thanks in advance. > OT: for short snippets like this, you should just paste it in the post rather than using codepad """ y = v1,var1,v3,v2,var2,period print y """ is not the same as """ print v1,var1,v3,v2,var2,period """ the first code creates a tuple, assign it to y, then prints the tuple; the latter prints the bunch of items separated with space. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The magic parentheses
On 01/24/10 19:17, David Hutto wrote: > Thanks > for the solutions and the quick responses. I just removed the variable > and used print, I thought they would be considered the same whether as > a variable, or as a direct line, guess not. > what is equivalent: print (a, b, c) and x = a, b, c print x both construct a tuple and prints a,b,c as tuple ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The magic parentheses
Do you know python's object model? A lot of these things will make much more sense once you do: http://effbot.org/zone/python-objects.htm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] multiply and sum two lists with list comprehension?
On 01/28/10 17:22, Muhammad Ali wrote: > Hi, > > I am multipliying two lists so that each of list As elements get multiplied > to the corresponding list Bs. Then I am summing the product. > > For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after > multiplication and then sum it to get 12. I can do it using map like this: > > sum(map(lambda i,j:i*j, A, B)) > > But map is being dropped out in python 3? or has it already been dropped? > And I have heard Guido say that list comprehension do a better job than map > so how would we do this with list comps? No, `map` will not be dropped in the foreseeable future. `lambda`, `map`, `filter`, and `reduce` will stay; but `reduce` will be moved into functools module (from previously a built-in function). http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading large bz2 Files
On 02/19/10 23:42, Norman Rieß wrote: > Hello, > > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > print line.strip() > > But after 4311 lines, it stoppes without a errormessage. The bz2 file is > much bigger though. > How can i read the whole file line by line? Is the bz2 file an archive[1]? [1] archive: contains more than one file ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading large bz2 Files
On 02/20/10 07:42, Lie Ryan wrote: > On 02/19/10 23:42, Norman Rieß wrote: >> Hello, >> >> i am trying to read a large bz2 file with this code: >> >> source_file = bz2.BZ2File(file, "r") >> for line in source_file: >> print line.strip() >> >> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >> much bigger though. >> How can i read the whole file line by line? > > Is the bz2 file an archive[1]? > > [1] archive: contains more than one file Or more clearly, is the bz2 contains multiple file compressed using -c flag? The -c flag will do a simple concatenation of multiple compressed streams to stdout; it is only decompressible with bzip2 0.9.0 or later[1]. You cannot use bz2.BZ2File to open this, instead use the stream decompressor bz2.BZ2Decompressor. A better approach, is to use a real archiving format (e.g. tar). [1] http://www.bzip.org/1.0.3/html/description.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading large bz2 Files
On 02/20/10 07:49, Norman Rieß wrote: > Am 19.02.2010 21:42, schrieb Lie Ryan: >> On 02/19/10 23:42, Norman Rieß wrote: >> >>> Hello, >>> >>> i am trying to read a large bz2 file with this code: >>> >>> source_file = bz2.BZ2File(file, "r") >>> for line in source_file: >>> print line.strip() >>> >>> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >>> much bigger though. >>> How can i read the whole file line by line? >>> >> Is the bz2 file an archive[1]? >> >> [1] archive: contains more than one file >> > > No it is a single file. But how could i check for sure? Its extracts to > a single file... use "bzip2 -dc" or "bunzip2" instead of "bzcat" since bzcat concatenates its output file to a single file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] webmail client for pop3 in python
On 02/24/10 13:53, Kirk Bailey wrote: > Anyone knoow of a good python Webmail client in python for my windows > notebook? what do you mean by "python webmail client"? Could you elaborate? If you want to send email programmatically, use the smtplib module if the server supports SMTP. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange list behaviour in classes
On 02/24/10 10:27, C M Caine wrote: > Thanks all (again). I've read the classes tutorial in its entirety > now, the problem I had didn't seem to have been mentioned at any point > explicitly. I'm still a fairly inexperienced programmer, however, so > maybe I missed something in there or maybe this is a standard > procedure in other OO programming languages. Not exactly, staticcally-typed languages typically uses keywords (like "static") to declare an variable as a class variable; but since in python, you don't need to do variable declaration the chosen design is to define class variable in the class itself and instance variable inside __init__() [actually this is not a precise description of what's actually happening, but it'll suffice for newbies] class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' if you want to access class attribute from inside a method, you prefix the attribute's name with the class' name, and if you want to access instance attribute from inside a method, prefix with self: class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' def method(self): print MyClass.classvariable print self.instancevariable But due to attribute name resolution rule, you can also access a class variable from self: class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' def method(self): print self.classvariable as long as the class variable isn't shadowed by an instance variable class MyClass(object): var = 'classvar' def method(self): print self.var#'classvar' self.var = 'instvar' print self.var#'instvar' del self.var print self.var#'classvar' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wHY
Why? That's a good philosophical question... hmm... why? Hmm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to use pydoc
On 02/27/10 00:31, Ricardo Aráoz wrote: > Checked the manuals on pydoc and wanted to try it. Must certainly be > doing something wrong but I can't figure what. Here's my session : The pydoc command works from your system shell (e.g. bash), not python shell; if you want to get help inside python's shell, use the help() built-in function. $ pydoc itertools # showing itertools's doc on your default pager (usually `less`) # $ python Python 2.6.4 (r264:75706, Jan 12 2010, 05:24:27) [GCC 4.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help('itertools') # showing itertools's doc on your default pager (usually `less`) # >>> # you need to pass the module's name as a string to help() >>> # either that, or import the module first: >>> import itertools >>> help(itertools) # showing itertools's doc on your default pager (usually `less`) # >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.
On 03/01/10 01:12, Alan Gauld wrote: > >> def getLines(file): >> """Get the content of a file in a lines list form.""" >> f = open(file, 'r') >> lines = f.readlines() >> f.close() >> return lines > > I'm not sure these functions add enough value to ghave them. I';d > probably just use > > try: open(outfile,'w').writelines(lines) > except IOError: #handle error > > try: lines = open(filename).readlines() > except IOError: #handle error > > The close will be done automatically since you don't hold a reference to > the file Remember why we have the new with-block? It's precisely because files will be automagically closed only if we're running on CPython; Python the language and thus alternative implementations doesn't guarantee automatic closing. I'd agree with the function having minimal utility value though: with open(file) as f: lines = f.readlines() # f.close() will be called by the context manager and if you're just copying to another file: from contextlib import nested with nested(open(infile), open(outfile, 'w')) as (fin, fout): fout.write(fin.read()) or even better, as Alan suggested, using shutil.copyfile(). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.
On 03/01/10 02:49, Karim Liateni wrote: > Lie Ryan wrote: >> On 03/01/10 01:12, Alan Gauld wrote: >> >>>> def getLines(file): >>>> """Get the content of a file in a lines list form.""" >>>> f = open(file, 'r') >>>> lines = f.readlines() >>>> f.close() >>>> return lines >>>> >>> I'm not sure these functions add enough value to ghave them. I';d >>> probably just use >>> >>> try: open(outfile,'w').writelines(lines) >>> except IOError: #handle error >>> >>> try: lines = open(filename).readlines() >>> except IOError: #handle error >>> >>> The close will be done automatically since you don't hold a reference to >>> the file >>> >> >> Remember why we have the new with-block? It's precisely because files >> will be automagically closed only if we're running on CPython; Python >> the language and thus alternative implementations doesn't guarantee >> automatic closing. I'd agree with the function having minimal utility >> value though: >> >> with open(file) as f: >> lines = f.readlines() >> # f.close() will be called by the context manager >> >> and if you're just copying to another file: >> >> from contextlib import nested >> with nested(open(infile), open(outfile, 'w')) as (fin, fout): >> fout.write(fin.read()) >> >> or even better, as Alan suggested, using shutil.copyfile(). >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > Thank you Lie but I have a restriction on the python version I must use > v2.2. > This feature is available only on later version 2.5 I believe. Then you should at the least use the try-finally block, I think that one has been there since 2.2? If you didn't use try-finally, there is no guarantee that f.close() would be called if an exception happened in the middle of reading/writing (e.g. KeyboardInterrupt, or perhaps user plugging off the thumbdrive, or bit more realistic having a full harddisk or exceeded some disk quota) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Over-riding radians as default for trig calculations
On 03/01/10 06:39, AG wrote: > After importing the math module and running > > math.cos( x ) > > the result is in radians. > > Is there a way of setting this so that it results in degrees? I don't > want to over-ride this permanently for my Python settings, so am happy > to specifically do it per equation or per program. I'd recommend you to get used to using radian measurement; though it may initially looks unfamiliar, working in radian (with computer or by-hand) is much more natural once you get used to it. Many formulaes become simpler when using radian while some are only valid in radian. The only reasonable point where you should convert from and between radians is when requesting input from non-mathematician users. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why is the max size so low in this mail list?
On 03/02/2010 04:13 AM, Wayne Watson wrote: > See Subject. 40K here, but other Python lists allow for larger (total) > sizes. I don't know, I've never realized it; that's an indication that the 40K limit is reasonable, at least to me. What did you get for posting >40K mails? Is your mail bounced? And if it does, is the bounce message helpful, like "please use pastebin or put a link"? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] object representation
On 03/05/2010 12:45 PM, Steven D'Aprano wrote: > E.g. a trie needs six pointers just to represent the single > key "python": > > '' -> 'p' -> 'y' -> 't' -> 'h' -> 'o' -> 'n' > > while a hash table uses just one: > > -> 'python' You can argue that had trie beed used as the datatype, there will actually be no need to store the key's string representation; the index of the object in the trie implies the textual representation. Such that, you will still need 6 pointers, but you won't need to store a string object. It will just be: '' -> ptrP -> ptrY -> ptrT -> ptrH -> ptrO -> ptrN and if for some reason the name is needed (perhaps for debugging?); then there could be an algorithm to reverse-map the ptrXs to char. I can imagine that to be implementable if variable names in python be limited to alphanumerics only and probably a select few of symbols. Unicode names makes things difficult though... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with iterations and breaking loops.
On 03/18/2010 02:02 AM, Karjer Jdfjdf wrote: > I'm having problems with iterations and loops.. So I'm curious about the > best Python-way to do iterations of lists (in if, while etc statements) > and breaking of loops. "Best" is a relative term to the current context of the problem. What is best for one case, might be worse for another. > I have a list of tuples with 2 values. I want to perform calculations on > all of these for each value in a range of values (e.g. 100 to 110). > > > list_of_tuples = [(90629, 4644), (90706, 4617), (90729, 4709)] > > #start value > n = 100 > #maximum value > nmax = 110 > > #First I create a list for the values > range_list = [] > while n < int(nmax+1): > range_list.append(n) > n = n + 1 "for i in xrange(n, nmax):" is a common idiom in python to do something a predetermined amount of time. Actually, all that code can be replaced with just "range_list = range(n, nmax)". Also, I think it is good if you can get used to counting with a half-open interval; though initially is a bit awkward, half-open counting is much less error prone. > print range_list > > > for i in range_list: > for t in list_of_tuples: > val1 = t[0] > val2 = t[1] > print "do stuff with\t" + str(val1) + '\t' + str(val2) + \ > '\tfor rangevalue\t' + str(i) > > But I think that the rangelist is not needed and it can be done better > (and faster for large quantities of data). I think it's better to have > somethng like the code below. But I'm having problems with breaking the > second loop and returning to the first loop. If I put in another > while-statement befor the for-statement it stops after 1 run and it has > to continue until the end of the range. I usually avoid preallocating large list to store results by using list-comprehension and generators. The interpreter would still have to allocate the list, but at least they're out of my immediate sight. Anyway, you should probably elaborate more about the problem you're having. What you've described up till now is "how I think the problem should be solved"; it is much more useful to describe "what the problem really is" so we can probably suggest a totally different approach to solve the problem. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutorial executable from python script.
On 03/21/2010 06:00 AM, Karim Liateni wrote: > > Hello Alan, > > In fact, I want to be sure the users can run it on every machine in our > network. > Especially, I want to be able to run it on Solaris 5.8 with python 1.5 > (Unix machine). > I wanted to know if I could make some custom executable like in C when > you want > to build a executable with a static library to be sure if the system > does not have > the correct shares libraries. If you know that the machine contains `python` (whatever the version is) you can use sys.version to check the system python's version. It can be as simple as: import sys if int(sys.version[0]) > 1 or (int(sys.version[0]) == 1 and int(sys.version[2] >= 5)): # or you can start a subprocess instead, # abusing import makes "if __name__ == '__main__':" magic not work import MyMainProgram else: # parentheses guards for python 3 print ('script is only compatible with python version 1.5 and above') Otherwise, if you cannot even rely on python being available, you may need to use shell script. > Perhaps the better is to build a python version embedded in my > application installation. > Do you have any examples or tutorial on how integrate python inside a > pplication to be > sure that we have all in one and not depand on any local machine > installation environment. > I need as to embed gtk python library for graphical use. That is indeed possible, however is there any reason why the server don't upgrade its python version? CPython makes it easy to do parallel installation of two different python version. If you can persuade the machine administrator to install python2.6 as an altinstall; you can simply change the hashbang line of your script to "#!/usr/bin/env python2.6" and all is well. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutorial executable from python script.
On 03/21/2010 08:51 PM, Karim Liateni wrote: > > Hello Lie, > > Thanks for your advices. > > To have correct updates from ITs is really a true pain. The network > is worldwide in our company. I found issues having decent version. > On my local workstation I have Python v1.5, on compute farm LSF > machines sometimes 2.2 , 2.3, 2.6. That's why I don't want to rely > on machine installation and provide a unique version with my > application installation. I know we did the same for TCL to be sure > to have 8.4 version. I just wanted to know if there is some tutos about > this topic. As Alan have said, if you target your script for python 1.5, it is quite likely that your script will still run in python 2.6. Can you describe what's your deployment strategy? Do you have an automated deployment or do you do it manually? How important is it for all computer in the network to have identical version of your script? Do all your servers have the GNU toolchain? How do the servers varies? Do they all have the same/similar hardware? Do they have a certain common subset of software? Can you give an estimate of the number of servers in the network? In general, it is impossible to have a super-package that can be deployed uniformly if your servers varies too widely. For example if most of your server uses x86 but several uses PowerPC, you will have to include different binaries for them. Or if there is a Windows-based server. The complexity of having such generic super-packager is similar to what the automake toolchain faces (in short, extremely complex). If you can guarantee that all your server contains 'python' however old it is; you can write the version checking script from the previous post. If you take some care, the version checking script should run in all python version from the very ancient to the latest. If you can guarantee that all your servers run certain version of a type of Unix, you may be able to pre-compile python in one of the machine and use this pre-compiled version on all machine. If you have to follow the local machine directory conventions (e.g. some servers want your script in /bin while the other in /usr/bin) you may need to write a script that modify the hashbang line appropriately. If you can guarantee that your servers have GNU toolchain, you can write a shell script to check the system python's version and download and compile python from source if the system's python version doesn't match. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Prime numbers
On 03/28/2010 09:57 PM, yd wrote: > It's not homework i just want to be able to convert my algorithm into > good code, and the only way to do that is by actually writing it. I'm > just writing it to learn how it's done. In most cases, when: 1) the code is effective (i.e. it always gives correct answer) 2) the code is efficient (i.e. it terminates in a reasonable amount of time, and uses a reasonable amount of memory) 3) you can articulate why you write your code in a particular way, can describe why the algorithm works, and can answer when challenged 4) you and other people can read your code six months later with relatively little difficulty 5) your code is as concise as possible, without affecting #4 (e.g. leveraged most of the side work to another library, used common idioms in the appropriate situations, etc) in most case, you probably have written a good code. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need some help on "How to Think Like a Computer Scientist: Learning with Python" exercise
On 03/31/2010 04:00 AM, Yahoo Mail wrote: > Hello All, > > I am competely new in Python programming. When i reading Chapter 4 in > "How to Think Like a Computer Scientist: Learning with Python" , > I am stuck in the exercise 4. > > Here is the question: > > Enter the following expressions into the Python shell: > 1. True or False > 2. True and False > 3. not(False) and True > 4. True or 7 > 5. False or 7 > 6. True and 0 > 7. False or 8 > 8. "happy" and "sad" > 9. "happy" or "sad" > 10. "" and "sad" > 11. "happy" and "" > Analyze these results. What observations can you make about values of > different types and logical operators? Can you write these observations > in the form of simple /rules/ about and and or expressions? > > I have no problem with 1-4, but compelely wrong with the rest. Like > question 5, i throught the answer is True, but when i type it in IDLE, > I got 7 instead, question 8 "happy' and 'sad', my answer is True, but > the answer is 'happy'. Can you please tell me why i am wrong. I really > appreciate any assistance you can give. This is python's flavor of short-circuiting. Read the doc at: >>> help("BOOLEAN") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Remote access from Windows PC to a Linux box
On 03/31/2010 03:29 AM, Mike Baker wrote: > Hi, > > I'm trying to connect to a Linux box from my Windows machine and execute > a series of commands - (ls, pwd, cat 'somefile', etc...). I'm using > Putty to do the ssh and have set up with Putty's Pagent agent to allow > me to enter a passphrase once per session to handle security keys > between the two boxes (so, no passwords needed for my remote scripts). > > I have code that will give me a remote prompt on the Linux machine where > I can manually enter commands. This works great, but I want a script to > always execute the same series of commands without having to do so > manually.. I also have code that will execute a single command like > cat a file and write the ouput to a new file. However, when I try to use > the communicate object in subprocess, my window hangs. > Seeing your case, probably a simple shell script on the server side would be an easier option. Whenever you ssh to the server, you just execute this startup script. You may also be able to configure putty to execute this script automatically, though since I never used putty I don't know if putty can do that. Or alternatively, you can create a .bashrc (or whatever the remote box's terminal default startup script is). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple bank account oriented object
On 03/31/2010 01:26 PM, Marco Rompré wrote: > > Please help me i think im on the right track but i need some guidance in > the dark. lol And what's your question? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple search and replace...
On 04/01/10 06:51, ALAN GAULD wrote: > But if it's fixed patterns you can either do a replace() > in a loop over your patterns: > > for pat in ['PID','OBR',.] > h7string = h7string.replace('\n'+pat, h7string) > > Or even build a regex that does it all in one. > (But the regex could get complex quickly!) Or even write a "regex precompiler" that converts a list of items to search into regex string (read: '|'.join(keywords)). That may be necessary depending on the complexity of your queries and your clash-handling scenario (what would you like to happen if your replacement string contains another string in the keywords?). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] constructor
On 04/05/10 04:11, Shurui Liu (Aaron Liu) wrote: > But the result I got from computer is like this: > A new critter has been born! > A new critter has been born! > > Hi. I'm an instance of class Critter. > > Hi. I'm an instance of class Critter. Because you tell it to do it in that order: crit1 = Critter() # A new critter has been born crit2 = Critter() # A new critter has been born crit1.talk() # Hi. I'm an instance of class Critter. crit2.talk() # Hi. I'm an instance of class Critter. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Menu data from file
On 04/05/10 08:54, Alan Gauld wrote: > Thats right you will need to parse the data to convert it into the > format you want. > This is one reason you might find it easier to use XML for storing the data > and use a tool like ElementCTree to parse it. s/ElementCTree/ElementTree/? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Menu data from file
On 04/05/10 17:39, Neven Goršić wrote: > Thank you for mentioning the possible options. > I already use option where I import .py module, > but I run into troubles when making executable with py2exe. Maybe you should elaborate what problems you're experiencing with py2exe? Probably we can solve that instead of developing workarounds. Many popular UI toolkit provides an XML-based menu file. Here is one for PyGTK: http://www.pygtk.org/pygtk2tutorial/sec-UIManager.html You should better use your GUI toolkit's version instead of writing your own. > I suppose that XML approach is the most general method. > Can you recommend a good introduction text (not for experts :-)) > and give more details about the tool ElementCTree. > > Maybe it will be educational and interesting for other beginners too. ElementTree is quite simple, though I don't think there are many good tutorials about it (at least I can't find one). In the simplest use case, you just use xml.etree.ElementTree.parse("menu.xml") and you can iterate the tree like so: import xml.etree.cElementTree as Et menuxml = """ """ # root = Et.parse("menu.xml") root = Et.fromstring(menuxml) def parse(menutk, element): for menu in mbar: if menu.tag == 'menu': # have submenus, recurse submenutk = add_menu(menutk) parse(submenutk, menu) elif emnu.tag == 'menuitem': add_menuitem(menutk, menuitem) or something like that. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Menu data from file
On 04/06/10 08:05, Neven Goršić wrote: > OK, I will describe my "case". > > I use menu date stored in list "shape" in file CMFlowData.py in the same > directory as my main program x.py. In the beginning of the program I > have command: > > import CMFlowData > > and everything works fine till I make executable with py2exe. There are > no error during "compilation" and exe are created in ...\dist directory. > I copy all my external files to that directory, together with > CMFlowData.py file, but when I run x.exe I get x.exe.log file with message: > > Traceback (most recent call last): > File "x.py", line 8, in > ImportError: No module named CMFlowData > Traceback (most recent call last): > File "x.py", line 8, in > ImportError: No module named CMFlowData > > All other files that I read from disk are created with relative paths > and work fine, except when I import > my own module. > > Is there some procedure to "announce" my module to the Python or System? I've never used py2exe myself, but from what I can gather py2exe should be able to collect the imported modules automatically. Did you follow everything in the py2exe tutorial: http://www.py2exe.org/index.cgi/Tutorial ? Are there any deviations of the things you did from the tutorial? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re Problems with creating XML-documents
On 04/15/10 16:03, Karjer Jdfjdf wrote: > When I try to parse the outputfile it creates different errors such as: >* ExpatError: not well-formed (invalid token): That error message is telling you that you're not parsing an XML file, merely an XML-like file. > Basically it ususally has something to do with not-well-formed XML. > Unfortunately the Java-program also alters the content on essential > points such as inserting spaces in tags (e.g. id="value" to id = " value " ), > which makes it even harder. The Java is really a b&%$#!, but I have > no alternatives because it is custommade (but very poorly imho). The bug is in the program generating the XML, it is much easier to fix it in Java side than trying to parse broken XML. > Sorry, I've nog been clear, but it's very difficult and frustrating for > me to troubleshoot this properly because the Java-program is quite huge and > *takes a long time to load before doing it's actions and when running > also requires a lot of time. The minimum is about 10 minutes per run. 10 minutes per-run is instant compared to writing a parser for invalid XML. And you can cut that 10 minutes short by using a smaller database for testing purpose. >>>/ text = str('\n' + \ > /' ' + str(instance.datetime) + ' \n' + \ > ' ' + instance.order + ' \n' + \ > '\n') > >>You can simplify this quite a lot. You almost certaionly don;t need >>the outer str() and you probably don;t need > the \ characters either. > > I use a very simplified text-variable here. In reality I also include > other fields which contain numeric values as well. I use the > \ to > keep each XML-tag on a seperate line to keep the overview. He means you can simplify it by using string interpolation: text = ''' %s %s ''' % (instance.id, instance.datetime, instance.order) >>Also it might be easier to use a triple quoted string and format >>characters to insert the dasta values. > >>>/ When I try to parse it, it keeps giving errors. > / >>Why do you need to parse it if you are creating it? >>Or is this after you read it back later? I don't understand the >>sequence of processing here. > >>>/ So I tried to use an external library jaxml, > / >>Did you try to use the standard library tools that come with Python, >>like elementTree or even sax? > > I've been trying to do this with minidom, but I'm not sure if this > is the right solution because I'm pretty unaware of XML-writing/parsing > > At the moment I'm > tempted to do a line-by-line parse and trigger on > an identifier-string that identifies the end and start of a record. > But that way I'll never learn XML. Why bother writing an XML-like parser when you can fix the generating program? And my recommendation, if you want to learn XML, learning to write xHTML Strict first (with a plain text editor! not some RealityWeaver or BackPage) is IMHO probably the easiest route (especially if you already know some HTML). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop comparison
On 04/16/10 16:50, Ark wrote: > Hi everyone. > A friend of mine suggested me to do the next experiment in python and Java. > > It's a simple program to sum all the numbers from 0 to 10. > > result = i = 0 > while i < 10: > result += i > i += 1 > print result > Are you sure you're not causing Java to overflow here? In Java, Arithmetic Overflow do not cause an Exception, your int will simply wrap to the negative side. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the binary math "wall"
On 04/21/10 02:58, Lowell Tackett wrote: > I'm running headlong into the dilemma of binary math representation, with > game-ending consequences, e.g.: > Never use float for representing numbers, use float to represent a "magnitude", do not rely on the exact representation of the number itself. If you need to control the representation of your number, either keep the number as integers or string or use fixed-point arithmetic (Decimal), depending on your use case. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary search question
On 04/24/10 23:39, Robert Berman wrote: >> -Original Message- >> From: tutor-bounces+bermanrl=cfl.rr@python.org [mailto:tutor- >> bounces+bermanrl=cfl.rr@python.org] On Behalf Of Alan Gauld >> Sent: Friday, April 23, 2010 7:41 PM >> To: tutor@python.org >> Subject: Re: [Tutor] Binary search question >> >> "Emile van Sebille" wrote >> >>>BIG SNIP >> >> And even at 1000 entries, the list creation slowed right >> down - about 10 seconds, but the searches even for "-5" were >> still around a second. >> >> So 'in' looks pretty effective to me! > > Now that is most impressive. > But that is with the assumption that comparison is very cheap. If you're searching inside an object with more complex comparison, say, 0.01 second per comparison, then with a list of 10 000 000 items, with 'in' you will need on *average* 5 000 000 comparisons which is 50 000 seconds compared to *worst-case* 24 comparisons with bisect which is 0.24 seconds. Now, I say that's 208333 times difference, most impressive indeed. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For loop breaking string methods
On 04/27/10 12:19, Dave Angel wrote: > Note also that if you insert or delete from the list while you're > looping, you can get undefined results. That's one reason it's common > to build a new loop, and just assign it back when done. Example would > be the list comprehension you showed earlier. I have to add to Dave's statement, if you "modify the list's content" while looping there is no undefined behavior; you get undefined behavior if you "modify the list's structure". Operations that modify a list's structure includes insertion, delete, append, etc; those operations which can modify the len() of list. Modifying the content, however, is perfectly safe. However, even when just modifying list's content, I personally still prefer list/generator comprehension. They're fast and simple. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I display my float as a string???
On 04/28/10 12:35, Marco Rompré wrote: > Here is my code, I need to display my float value as a string. > > item.set_prix str(float(prix)) print prix ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using Regex to produce text
On 04/29/10 01:32, m...@doctors.net.uk wrote: > While some patterns are infinite, other's aren't (e.g. The example I gave). How should the regex engine know about that? > Using a subset of Regex syntax to produce a set of strings has the > advantage of using a well understood and documented form, and if you > could hook into the existing API, at minimal coding effort. > In addition, it allows a nice symmetry between search and production of > resource names. String generation is generally simpler than string parsing. If the pattern of the string you're generating is so complex that you need a regex-powered name generator, it will probably be impossible to parse that. Use string interpolation/formatting instead: '%s_%0s.txt' % (name, num) > I suspect it's not that easy, as I don't think we can get to the internals of > the regex FSM. However, I thought it would be worth asking. The problem is how you would define the "universe" set of characters. If you had a '.', would you want alphanumeric only, all printable characters, all ASCII (0-127) characters, all byte (0-255) character, all Unicode characters? It's too ambiguous and if you say to follow what regex is doing, then regex just happen to not be choosing the most convenient default for pattern generators. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] blackjack game
On 04/30/10 06:23, Shurui Liu (Aaron Liu) wrote: > # Blackjack > # From 1 to 7 players compete against a dealer > > > Here is the code of this game. I want to change some part of them. > 1. Since I don't know what part of code is "responsible" for the > number of cards, so I don't know how to add a "card number check" > attribute, I mean, to check the number of card is more enough for next > time play no matter how many players there are, if cards are not more > enough, print out a notice and stop the program; The BJ_Game is responsible in querying the Deck if it has enough cards for the round. BJ_Game will calculate the number of players and asks if ask BJ_Deck if it can support that much player. Be careful when calculating number of cards since in blackjack using one deck it is possible to split one's hand into four (btw, why is BJ_Player inheriting BJ_Deck? that would make splitting impossible; a player has a hand but it is not a hand :-) > 2. I am not sure if I can let the winner get all of the cards and > print out what cards the winner has when the game finished. that depends on the house rule, I think, some games requires all player can see everyone else's card while other games keeps everyone's hand closed. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python list, right! but concretely?
On 05/02/10 15:49, spir ☣ wrote: > Hello, > > Is there anywhere some introduction material to the implementation of python > lists > (or to fully dynamic and flexible sequences, in general)? > More precisely, I'd like to know what kind of base data-structure is used > (linked list, dynamic array, something else -- and in case of array, how is > resizing computed). Also, how is "generics" (element are of free type, and > even heterogeneous) managed? Python's 'list' is an array of pointers to `PyObject` ('object' in Python) and the resizing algorithm keeps the list size such that "allocated / 2 <= actual <= allocated". When list need to resize, it overallocates the list slightly over 1.125 times than the requested size "(newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize". If you're interested in more precise details (since I do omit some, especially those that seems to be micro-optimization-related), you need to read the source at http://code.python.org/hg/trunk/file/e9d930f8b8ff/Objects/listobject.c > Denis > > PS: The reason is I'm trying to understand better the underlying layers of > magic facilities we use everyday. Starting from about no computer science > knowledge. I have a working implementation of linked lists in primitive > langguages ;-) (namely C & Pascal), but rather complicated to my taste; > and I'm probably overlooking commonly known and used tricks that could > make the algorithm simpler or more efficient. Real life implementation is always hairy, especially as the programmer cut corners to drench some speed benefit and include many error checkings. Today is the first time I actually looked at list's implementation, now I know why people hated C, for every line of real code, there's three or four lines of error checking code, e.g. to ensure malloc successfully allocated enough memory or that index access is in range. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie & Unittest ...
On 05/06/10 10:37, Damon Timm wrote: > Hi - am trying to write some unit tests for my little python project - > I had been hard coding them when necessary here or there but I figured > it was time to try and learn how to do it properly. > > This test works, however, it only runs as *one* test (which either > fails or passes) and I want it to run as 12 different tests (three for > each file type) and be able to see which key is failing for which file > type. I know I could write them all out individually but that seems > unnecessary. One way to do what you wanted is to harness python's dynamicity and generate the methods by their names: class TestFiles(unittest.TestCase): for methname, case in somedict: def test(self): ... __dict__[methname] = test ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about Python being object oriented
On 05/09/10 02:19, Tino Dai wrote: > Hi Everybody, > > My friend and I were having a disagreement about Python. Has Python > always been an OO language or was it at one point a procedural language like > C? Thanks! AFAIK Python has always been a mixed paradigm language. You can write fully OO code if you want, as well as procedural-style or imperative-style code (especially handy for quickie-scripts[1]). But as Bob Gailer pointed out, most OOP languages are build on top of procedural base, which is itself is build on top of imperative base. [1] compare to Java, a simple "hello world" must contain a class declaration, then a 'public stupi^B^B^Batic main', etc. Even C must have "public main". ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unable to run Programs on WINXP using Python3
On 05/12/10 13:31, Sivapathasuntha Aruliah wrote: > Hi > I thank you for your prompt response. I am using WINXP. Possibly programs > written for Python 3 may not work in Python2 as informed by you due to > syntax unmatch. Very unlikely. If python is told to execute a faulty script (or even arbitrary, non-python file), python would fail would fail with "SyntaxError" exception. > However when I try programs written for Python3 in Python3 > it first comes out with a pop up message "C:\python31\python.exe is not a > valid Win32 application". Your error message tells that either Python itself has crashed or Windows refuse to execute python.exe since it detected that python.exe is not a program. > When I click OK prompt on pop up message then on > dos box it states "Access is denied." I tried various types such as > python, python.exe and without these two also but same pop up message > comes out. Please advice. How did you install python? Did the installer or the machine crashed half-way through installation? Try reinstalling Python, make sure you download the correct installer. Can you start the interactive interpreter? Try starting just C:\Python26\python.exe (without script argument) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Find Elements in List That Equal A Specific Value
On 05/13/10 03:58, Su Chu wrote: > Hi there, > > I am new to Python. I am attempting to either define a "which" statement or > to find a method that already exists to do this sort of operation. > > My problem is as follows: > I have three lists, one with unique values (list 1), one a sequence of > values that are not necessarily unique (list2), and a shorter list with the > unique values of list 2 (list 3). List 1 and List 2 are of equal lengths. > > > An example: > list1 = [ 1, 2, 3, 4, 5, 6 ] > list2 = [ 2, 2, 2, 5, 6, 6 ] > list3 = [2, 5, 6] > > What I would like to do is find and sum the elements of list 1 given its > corresponding element in list 2 is equal to some element in list 3. > > For example, > the sum of the values in list1 given list2[i]==2 > would be 1 + 2 + 3 = 6. > the sum of the values in list1 given list2[i]==5 > would be 4 > the sum of the values in list1 given list2[i]==6 > would be 5 + 6 = 11 > > and so on. Obtaining these values, I'd like to store them in a vector. > > This seems pretty simple if a 'which' statement exists e.g. (which values in > list 1 == list3[k], and looping through k), but I can't find one. To write > one seems to require a loop. your proposed 'which' statement, had they existed, is a kind of loop, so I'm wondering why you want to avoid loops. >>> [sum(a for a, b in zip(list1, list2) if b == n) for n in list3] [6, 4, 11] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.5.4 - error in rounding
On 05/21/10 20:17, Neven Goršić wrote: > Hi! > > I run into Python error in rounding and not know how to predict when it will > occur in order to prevent wrong result. That's because it's floating point number. > What can I do to assure accurate result? Use decimal module to do precise control over your rounding. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.5.4 - error in rounding
On 05/22/10 01:30, Neven Goršić wrote: > Thanks! > It's pity that Python has such unreliable functions so you never know in > advanced when you will hit new one ... Well, it's not Python but the machine. Floating point number is not Real numbers; there are certain limitations imposed by physical limitations. You can read: What Every Computer Scientist Should Know About Floating-Point Arithmetic: http://docs.sun.com/source/806-3568/ncg_goldberg.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.5.4 - error in rounding
On 05/22/10 22:32, Steven D'Aprano wrote: > On Sat, 22 May 2010 07:16:20 am wesley chun wrote: >> correct, it is a floating point issue regardless of language.. it's >> not just Python. you cannot accurately represent repeating fractions >> with binary digits (bits). more info specific to Python here: >> http://docs.python.org/tutorial/floatingpoint.html >> >> also, keep in mind that '%f' is not a rounding operation... it just >> converts floats to strings. if you want to round, you need to use >> both string formatting as well as the round() built-in function. >> >> finally, +1 on using decimal.Decimal as necessary comfortwise. > > Why do people keep recommending Decimal? Decimals suffer from the exact > same issues as floats, plus they are slower. I was recommending Decimal because, to me, the OP seems to want to control how the rounding done, instead of actually wanting precision. Decimal is perfectly fine solution if you only want to control the rounding; using fraction to control rounding is possible, but can be a little awkward. Of course, Decimal only gives "predictable rounding", it doesn't really solve infinite .999.. problems. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SENTINEL, & more
On 05/29/10 18:29, spir ☣ wrote: > Hello, > > > from the thread: "class methods: using class vars as args?" > > On Sat, 29 May 2010 11:01:10 +1000 Steven D'Aprano > wrote: > >> On Fri, 28 May 2010 07:42:30 am Alex Hall wrote: >>> Thanks for all the explanations, everyone. This does make sense, >>> and I am now using the if(arg==None): arg=self.arg idea. It only >>> adds a couple lines, and is, if anything, more explicit than what >>> I was doing before. >> >> You should use "if arg is None" rather than an equality test. >> >> In this case, you are using None as a sentinel value. That is, you >> want your test to pass only if you actually receive None as an >> argument, not merely something that is equal to None. >> >> Using "arg is None" as the test clearly indicates your intention: >> >> The value None, and no other value, is the sentinel triggering >> special behaviour >> >> while the equality test is potentially subject to false positives, >> e.g. if somebody calls your code but passes it something like >> this: >> >> class EqualsEverything: def __eq__(self, other): return True >> >> instead of None. > > I'll try to clarify the purpose and use of sentinels with an example. > Please, advanced programmers correct me. A point is that, in > languages like python, sentinels are under-used, because everybody > tends to une None instead, or as all-purpose sentinel. Sentinels are underused not because everyone uses None, but because in many cases sentinels can be dangerous if not explicitly checked. In many cases, python prefers Exceptions (e.g. for-loop iteration) to sentinels. > Imagine you're designing a kind of database of books; with a user > interface to enter new data. What happens when an author is unknown? > A proper way, I guess, to cope with this case, is to define a > sentinel object, eg: UNKNOWN_AUTHOR = Object() There are many ways to > define a sentinel; one could have defined "=0" or "=False" or > whatever. But this choice is simple, clear, and secure because a > custom object in python will only compare equal to itself -- by > default. Sentinels are commonly written upercase because they are > constant, predefined, elements. In this case, I would prefer an unknown author to be an empty string (i.e. "") because using object() does not persist between serialization to the database (not to mention having to special-case it everywhere, with empty string, you only need to special case whenever you need to). > Hope I'm clear. In the very case of UNKNOWN_AUTHOR, it would hardly > have any consequence to use "==", instead of "is", as relational > operator for comparison. Because, as said above, by default, custom > objects only compare equal to themselves in python. But * This > default behaviour can be overriden, as shown by Steven above. * Using > "is" clarifies your intent to the reader, including yourself. * Not > all languages make a difference between "==" and "is". (Actually, > very few do it.) Good habits... > > > > === additional stuff -- more personal reflexion -- critics welcome > === > > Sentinels belong to a wider category of programming elements, or > objects, I call "marks". (Conventional term for this notion welcome.) > Marks are elements that play a role in a programmer's model, but have > no value. What is the value of NOVICE_MODE for a game? of the SPADE > card suit? of the character 'ø'? These are notions, meaning semantic > values, that must exist in an application but have no "natural" value > -- since they are not values semantically, unlike a position or a > color. What *is* "value"? Is there any difference between "semantic value" and "natural value"? IMHO, there is no difference, "numerical value" is only a subset of all "value". > In C, on could use a preprocessor flag for this: #define > NOVICE_MODE ... #ifdef NOVICE_MODE ... #endif NOVICE_MODE is here > like a value-less symbol in the program: precisely what we mean. But > not all languages have such features. (Indeed, there is a value > behind the scene, but it is not accessible to the programmer; so, the > semantics is correct.) > > Thus, we need to _arbitrarily_ assign marks values. Commonly, natural > numbers are used for that: they are called "nominals" (--> > http://en.wikipedia.org/wiki/Nominal_number) precisely because they > act like symbol names for things that have no value. The case of > characters is typical: that 'ø' is represented by 248 is just > arbitrary; we just need something, and software can only deal with > values; Digital computers can only deal with "natural numbers" (i.e. {0, 1, 2, 3, ...}), that's why we need to encode all values as natural numbers. integers maps nicely to natural number (0:0, 1:1, -1:2, 2:3, -2:4, 3:5, -3:6, 4:7, -4:8, ...). Everything has a value, but the question of whether such value is representable in a computer is equivalent to asking whether the value is representable as integers, or in other words, whether the "cardinality" of the set of all su
Re: [Tutor] class methods as static methods?
On 05/30/10 05:49, Alex Hall wrote: > Hi all, > In Battleship, I have a weapons.py file, currently with just one > missile type (a Harpoon anti-ship missile). This Harpoon class defines > a getImpactCoords method, which returns all coordinates on the map > that it will hit. I would like to not instantiate a Harpoon object, > just call the Harpoon's getImpactCoords method and pass it the > required arguments. Is this possible? Thanks. Sorry if I got the terms > backwards in the subject; I can never remember which is static and > which is non-static. > Yes you can make it a static method or class method: class Harpoon(object): @staticmethod def inst(a, b, c): print a, b, c @classmethod def cmeth(cls, a, b, c): print cls print a, b, c Harpoon.inst(1, 2, 3) Harpoon.cmeth(1, 2, 3) the question is, why would you want to? getImpactCoords() doesn't seem to be a function that makes sense without a missile instance (I may be mistaken). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOP clarification needed
On 06/03/10 01:37, Jim Byrnes wrote: > >>> some older procedural languages I always end up becoming confused by >>> the large number of built in methods. >> >> C is one of the simplest procedural languages around >> and yet it comes with a huge library of functions (several >> hundred in some cases). The size of the library should be easier >> to manage using OOP than with older function/procedure based >> libraries, because the functions are not just logically grouped >> in the documentation but in the code too. > > I don't know C, I was thinking more along the lines of Basic or Rexx.I > could sit down and read through a list of keywords and built in > functions and it would be compact enough that I would have a good idea > of what was available. I can't seem to do that with the OO languages, > but of course I am older now also. When I learned Visual Basic, I definitely remembered the thousands of pages of documentation for thousands of functions. Python is probably isn't much different in the size of the number of functions included in the stdlib, but IMHO help() and pydoc aids much better in navigating the docs compared to context sensitive help. Python's keywords are just: help> keywords Here is a list of the Python keywords. Enter any keyword to get more help. and elifif print as elseimport raise assert except in return break execis try class finally lambda while continuefor not with def fromor yield del global pass I don't think there are many non-esoteric languages with significantly less keywords than python. and the builtin functions: abs all any apply basestring bin bool buffer bytearray bytes callable chr classmethod cmp coerce compile complex delattr dict dir divmod enumerate eval execfile exit file filter float format frozenset getattr globals hasattr hash help hex id input int intern isinstance issubclass iter len list locals long map max min next object oct open ord pow print property quit range raw_input reduce reload repr reversed round set setattr slice sorted staticmethod str sum super tuple type unichr unicode vars xrange zip and unlike some languages, the list of python's built-ins actually gets smaller with py3k (84 items in 2.6.4 and 71 items in 3.1.2, excluding Exceptions) I never actually sit down and read through all the built-in function's documentation; I just skim through this list, make a mental note of what they appears to be doing from their name, and only read their documentation as the need to use them arises. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] backreferences - \0
On 06/06/10 19:36, Payal wrote: > On Sun, Jun 06, 2010 at 06:26:18PM +1000, Steven D'Aprano wrote: >> Two things. Firstly, the Python regex engine numbers backreferences from >> 1, not 0, so you need \1 and not \0. > > Thank for the mail, but i am still not getting it. e.g. > > In first sub I expected, > one two - one two > > I understand that \1 is first (group), \2 the second and etc. > But what is the entire regex? >>> re.sub('(one) (two)', r'\g<0> - \1 \2',s) the \g is equivalent to \number but is intended to ambiguate cases like "\g<2>0" vs. "\20". It happens that \g<0> refers to the entire group. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] while loops causing python.exe to crash on windows
On 06/07/10 11:08, Alex Hall wrote: > On 6/6/10, bob gailer wrote: >> On 6/6/2010 8:44 PM, Alex Hall wrote: >>> -- >>> Have a great day, >>> Alex (msg sent from GMail website) >>> mehg...@gmail.com;http://www.facebook.com/mehgcap >>> >>> >> What is your question? >> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> > Why would that code cause Windows to consider the process "not > responding", and how can I fix this so I can have a sort of "listener" > in place, awaiting a change in the "grid.turnOver" variable inside > Player.takeTurn() so that the main while loop can switch to the other > player once the one player's turn is over? I thought while loops would > do it, but Windows sees them as making python.exe unresponsive. Would you buy me a crystal ball to foresee what you're talking about? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Doubts galore.
On 06/11/10 01:14, prasad rao wrote: > Hi > > def cript(doc=None,data =None): >if doc==None and data==None:doc=sys.agv1 >elif doc: > data=open(doc,'r').read() > data_c= binascii.hexlify(data) >else:data_c= binascii.hexlify(data) >if doc: > q=tempfile.TemporaryFile() > q.write(data_c) > os.rename(q,doc) > return >return data_c > > > cript(doc='./language.txt') > Traceback (most recent call last): > File "", line 1, in > File "", line 10, in cript > TypeError: coercing to Unicode: need string or buffer, file found > > 1)Why I got the above error message with the above function?How to correct > it? The error message points out here: # line 10 os.rename(q,doc) ^^^ scanning a few lines earlier, we saw: q=tempfile.TemporaryFile() os.rename() doesn't rename a file object; os.rename() takes two string arguments. > 2)Is it reasonable to have 2 if blocks in a function as above? This is where boolean algebra can help. An elif-block will only be run when all the if-elif blocks before it evaluates to false. IOW, your code is equivalent to this: if doc==None and data==None: doc=sys.agv1 if not (doc==None and data==None) and doc: data=open(doc,'r').read() data_c= binascii.hexlify(data) except that "doc==None and data==None" is only evaluated once. So, using boolean algebra (assuming a reasonable definition of == and !=): not (doc==None and data==None) and doc (doc!=None or data!=None) and doc now depending on the intent of "doc" and "doc != None"; it may be possible to simplify that to only: data != None. Note that this is all assuming a reasonable definition of ==, !=, not, etc and assuming no side effects and assuming that the checks are equally lightweight. > 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save > my > file as I expect it to do) AFAIK, tempfile creates a file in harddisk, but I've never used tempfile, so don't quote me on that. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Linux webcam libraries?
On 06/13/10 04:22, Wayne Werner wrote: > Hi, > > I want to do something like this: > http://www.kulturblog.com/2007/11/marshie-attacks-halloween-interactive-driveway-activity/ > > I want to be able to grab a webcam image via python. So I'm curious if > anyone has had any experience/luck in this particular area and/or knows of > any libraries I should take a look at. I know my webcam definitely works > under linux because I can use the cheese program and see the image... > I think the upcoming pygame2 will have a camera module, though I've never personally used it. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string encoding
On 06/18/10 06:41, Rick Pasotto wrote: > I'm using BeautifulSoup to process a webpage. One of the fields has a > unicode character in it. (It's the 'registered trademark' symbol.) When > I try to write this string to another file I get this error: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: > ordinal not in range(128) > > In the interpreter the offending string portion shows as: 'Realtors\xc2\xae'. > > How can I deal with this single string? The rest of the document works > fine. You need to tell BeautifulSoup the encoding of the HTML document. You can encode this information in either the: - (preferred) Encoding is specified externally from HTTP Header ContentType declaration, e.g.: Content-Type: text/html; charset=utf-8 - HTML ContentType declaration: e.g. - XML declaration -- for XHTML document used for parsing using XML parser (hint: BeautifulSoup isn't XML/XHTML parser), e.g.: However, BeautifulSoup will also uses some heuristics to *guess* the encoding of a tag soup that doesn't have a proper encoding. So, the most likely reason is this, from Beautiful Soup's FAQ: http://www.crummy.com/software/BeautifulSoup/documentation.html#Why can't Beautiful Soup print out the non-ASCII characters I gave it? """ Why can't Beautiful Soup print out the non-ASCII characters I gave it? If you're getting errors that say: "'ascii' codec can't encode character 'x' in position y: ordinal not in range(128)", the problem is probably with your Python installation rather than with Beautiful Soup. Try printing out the non-ASCII characters without running them through Beautiful Soup and you should have the same problem. For instance, try running code like this: latin1word = 'Sacr\xe9 bleu!' unicodeword = unicode(latin1word, 'latin-1') print unicodeword If this works but Beautiful Soup doesn't, there's probably a bug in Beautiful Soup. However, if this doesn't work, the problem's with your Python setup. Python is playing it safe and not sending non-ASCII characters to your terminal. There are two ways to override this behavior. 1. The easy way is to remap standard output to a converter that's not afraid to send ISO-Latin-1 or UTF-8 characters to the terminal. import codecs import sys streamWriter = codecs.lookup('utf-8')[-1] sys.stdout = streamWriter(sys.stdout) codecs.lookup returns a number of bound methods and other objects related to a codec. The last one is a StreamWriter object capable of wrapping an output stream. 2. The hard way is to create a sitecustomize.py file in your Python installation which sets the default encoding to ISO-Latin-1 or to UTF-8. Then all your Python programs will use that encoding for standard output, without you having to do something for each program. In my installation, I have a /usr/lib/python/sitecustomize.py which looks like this: import sys sys.setdefaultencoding("utf-8") For more information about Python's Unicode support, look at Unicode for Programmers or End to End Unicode Web Applications in Python. Recipes 1.20 and 1.21 in the Python cookbook are also very helpful. Remember, even if your terminal display is restricted to ASCII, you can still use Beautiful Soup to parse, process, and write documents in UTF-8 and other encodings. You just can't print certain strings with print. """ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string encoding
On 06/18/10 14:21, Rick Pasotto wrote: >> Remember, even if your terminal display is restricted to ASCII, you can >> still use Beautiful Soup to parse, process, and write documents in UTF-8 >> and other encodings. You just can't print certain strings with print. > > I can print the string fine. It's f.write(string_with_unicode) that fails > with: > > UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: > ordinal not in range(128) > > Shouldn't I be able to f.write() *any* 8bit byte(s)? > > repr() gives: u"Realtors\\xc2\\xae" > > BTW, I'm running python 2.5.5 on debian linux. > The FAQ explains half of it, except that in your case, substitute what it says about "terminal" with "file object". Python plays it safe and does not implicitly encode a unicode string when writing into a file. If you have a unicode string and you want to .write() that unicode string to a file, you need to .encode() the string first, so: string_with_unicode = u"Realtors\xc2\xae" f.write(string_with_unicode.encode('utf-8')) otherwise, you can use the codecs module to wrap the file object: f = codecs.open('filename.txt', 'w', encoding="utf-8") f.write(string_with_unicode) # now you can send unicode string to f ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives?
On 06/24/10 02:10, pyt...@bdurham.com wrote: > Can someone confirm that Python 2.6 ftplib does *NOT* support > Unicode file names? Or must Unicode file names be specially > encoded in order to be used with the ftplib module? > I don't know the specifics about ftplib, however I believe in most file systems, file names are plain byte-strings, i.e. most file systems do not handle encoding, they only deal with plain bytes. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: need computer advice from wise Tutors
On 06/29/10 19:48, Richard D. Moores wrote: > On Tue, Jun 29, 2010 at 01:06, Alan Gauld wrote: >> "Richard D. Moores" wrote >> You log into Gmail and your browser downloads the Gmail page; >>> >>> Yes, of course. But I'm always logged into Gmail. >> >> But it is still continually downloading. The same applies to a >> desktop client, if you leave it running it can continually poll the >> server, just like gmail. > > Well, as I said, I found having Eudora do that was quite annoying (I'm > afraid I've forgotten the particulars). Gmail is not. In any event, > There are many, many reasons to choose to use Gmail over Eudora or OE > and their ilk. What makes you think what Eudora did and what rich web clients (e.g. gmail's web interface) did is any different? Gmail's rich AJAX-ful web client is almost the same as a full-fledged desktop client, except that it runs on Javascript in a browser instead of running as native code in the OS. BOTH do polls in intervals (or in case of IMAP with idle extension, wait for a push event), BOTH do download headers only or header+body only when requested, BOTH do client-side caching. Except that a rich webmail client, due to limitation by browser security, is inherently unable to do permanent caching; is much less configurable for its downloading preference; and is totally unconfigurable on polling interval. The advantages of desktop client is configurability and its caching mechanism is not constrained by browser security. The advantage of a rich webmail client is tighter coupling to the backend system and universal accessibility. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On 07/01/10 02:20, Aaron Chambers wrote: > I'm new to Python, and wanted to start messing around with it, but the > computer I'm using is running Windows 7, so is there a version of Python > that's compatible with 7? Yes. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "x and y" means "if x is false, then x, else y"??
On 07/05/10 22:23, Adam Bark wrote: > > I should add that this is how something like: > > if x != y: > do_something() > > works, if expects a True or False (this isn't always true but works for > comparison operators expressions such as this). > "if" expects an expression that can be converted to True or False by calling its __bool__()/__nonzero__(); in case of missing __bool__/__nonzero__, then the object is considered True. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Idea for a 'Weekly Python Tips' mailing list
On Fri, 6 Aug 2010 17:19:46 +0100, Ian Ozsvald wrote: Recently I've started to follow a couple of email lists that send me regular tip emails, I've found them to be rather nice - an easy to read tip that comes every week that I can digest when I'm ready and I can reference afterwards. In the main python list there is Python Weekly URL that summarizes the week's most interesting posts in c.l.py ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Word to Sound
On Sat, 07 Aug 2010 11:43:25 -0400, Chris King wrote: How do you convert a string into a sound object. Do you mean as in text-to-speech or playing byte string that contain sound data in a certain encoding to the speaker? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with sys.path.append
aug dawg gmail.com> writes: > > Earlier today, I tried to add a folder to my PYTHONPATH. When > I tried sys.path.app('location/of/folder'), the command successfully > executed it, but then when I did sys.path to check to see if it was > now in my PYTHONPATH, it was not there. Does anyone know what might > be causing this? > Appending to sys.path will only change the module search directory for the current *python* session. If you want to add a directory to the current *terminal* session, then export PYTHONPATH environment variable into your shell. If you want to *permanently* add a directory to the module search directory, add a .pth file to a directory that is already inside a search path (typically in /site-packages). Alternatively, modify the site.py file. See here for details: http://docs.python.org/install/#inst-search-path ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing list index start
On 09/11/10 07:36, Rance Hall wrote: > I'm using the following function style I found on the net to create > menus for a command line python script: > > It works well, but the first item is the list is item 0. This is > normal in most computing situations, but because this index is part of > the output It would be nice if the first item in the list is item 1. In most cases in Python, you would almost never need to reference the list's index directly since python makes it easy to use iterators; however in your particular case, which is a valid exception, enumerate() takes an optional second argument `start` which defines the number that enumerate start to count with, i.e. you can do: for i, option in enumerate(mainmenuoptions, 1): print('%s. %s' % (i, option)) > php provided a way to change this, but I can find no documentation > that says python can do this as well. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing list index start
On 09/11/10 23:25, Rance Hall wrote: > On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan wrote: >> On 09/11/10 07:36, Rance Hall wrote: > > > >> In most cases in Python, you would almost never need to reference the >> list's index directly since python makes it easy to use iterators; >> however in your particular case, which is a valid exception, enumerate() >> takes an optional second argument `start` which defines the number that >> enumerate start to count with, i.e. you can do: >> >> for i, option in enumerate(mainmenuoptions, 1): >>print('%s. %s' % (i, option)) >> >>> php provided a way to change this, but I can find no documentation >>> that says python can do this as well. >> > > > Thanks everyone for responding, Because this menu structure is > repeated many times in my code, the ideal solution would have been to > "set index start = 1" in the beginning of the script. That would produce a catastrophic effect. What would happen to standard library modules or external modules now that they have to work in a different base? > something like sysctl variables in Linux perhaps but in this case only > valid for this program. > > Its clear from the responses that this solution is not available in > python, I wish it were, it would make my life much easier for this > project. Personally I think it's a bad idea. Being able to globally rebase list index would triple the code's WTF count. > I like the approach that Lie suggested, as it seems more "natural > python" to me as opposed to a workaround. > > However this is also only half a solution since it applies to the > printed menus only and not to the response afterward. > > It seems that Luke is right looks like we have to do math with the indexes. > > Lie also referred to my particular case as a valid exception, are > there enough other such valid exceptions that requesting a feature > enhancement would gain some traction? When I mean, a valid exception, it's referring to "knowing the index number" of a list, not to the ability of changing the list's base. > If this is but one of a few special cases, I doubt it would be worth > the time or trouble to formally make the request. As an alternative solution, you can derive from UserList and overload the __getitem__ and __setitem__ operator: from UserList import UserList class RebasedList(UserList): def __init__(self, base=1, *args, **kwargs): UserList.__init__(self, *args, **kwargs) self.base = base def __getitem__(self, index): if self.base <= index < self.base + len(self): return UserList.__getitem__(self, index - self.base) else: raise IndexError( "RebasedList index out of range [%s-%s), " "given index %s" % (self.base, self.base+len(self), index)) def __setitem__(self, index, item): if self.base <= index < self.base + len(self): return UserList.__setitem__(self, index - self.base, item) else: raise IndexError( "RebasedList assignment index out of range [%s-%s), " "given index %s" % (self.base, self.base+len(self), index)) # for complete emulation, you will also need to override: # __iter__, __delitem__, __getslice__, __setslice__, # __delslice__, __add__, __mul__, index, insert, pop, # remove, and possibly others You can use it like this: rl = RebasedList(10, [3, 1, 2, 4, 2, 1] rl[10] # rl[0] rl[11] = 29 # rl[1] = 29 print rl # [3, 29, 2, 4, 2, 1] Then there is the case that negative index no longer work cleanly with a custom list base. > Maybe I should ask if there is a better way to do what I want to do > here. Is there? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] recursive problem
On 09/12/10 04:01, Walter Prins wrote: > I guess the question to ask/consider is: How can be establish whether a > particular object supports a particular interface/set of behaviours that > we require? E.g. how do we most pythonically check whether some object > "walks like a list" and "quacks like a list" without tying such code to > explicit type checking? In Python? By treating it like a list; and shooting the duck in their webby feet when it doesn't act like a list. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] recursive problem
On 09/12/10 03:18, Steven D'Aprano wrote: > Or you could do this: > > if do_this_will_succeed() and do_that_will_succeed() \ > and do_something_else_will_succeed(): > do_this() > do_that() > do_something_else() > else: > do_error() > > But that hasn't done anything to prevent race conditions. So the real > reason people use LBYL is that they're too lazy to write hideously > ugly, but reliable, code, and they're just hoping that they will never > expose the race condition. (Often this is a pretty safe hope, but not > always.) Or, probably the best alternative is to mix LBYL and EAFP, e.g.: attempt = 0 while attempt < 10: # first acquire the lock using EAFP try: lock = acquire_lock() except FailToAcquireLock: attempt += 1 time.sleep(1) else: # Now apply LBYL, since there is no point in doing # operations that may be expensive if they will definitely # fail by the quick check if account_active(fromAcc) and account_active(toAcc) and can_withdraw(fromAcc, amount): # this operations only writes to a scratch space withdraw(fromAcc, amount) deposit(toAcc, amount) # back to EAFP, since there is no way of assuring # this with LBYL try: # mark the scratch space as permanent change commit() except CommitFailure: raise SeriousError("this can't be happening") else: finally: # LBYL: # there is no point in releasing unacquired lock; # should probably be done inside release_lock() so that # calling release_lock() an unacquired lock safely does nothing if not lock: release_lock(lock) else: raise Failure("failed to acquire lock") else: do_error("no privilege") release_lock(lock) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tree problem
On 09/12/10 21:15, Roelof Wobben wrote: > > > Hello, > > I have this problem. > > Write a program named litter.py that creates an empty file named trash.txt in > each subdirectory of a directory tree given the root of the tree as an > argument (or the current directory as a default). By default, Python has a recursion limit of 1000 deep; that is, your function is calling itself 1000 times without returning. In this case, the only reason why you hit the recursion limit is if you have a directory which is 1000 deep (quite unlikely, Windows has a directory depth limit much lower than that). Or your function somehow never returns, in a typical recursive function, it's usually because you have problem in the precondition. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "Overloading" methods
On 09/17/10 00:22, Vince Spicer wrote: > > > Well I can't comment on right or wrong I would think creating a simple > class with a __call__ method is a little more pythonic. I think even more pythonic is to use closure: def create_setpattern(type_): def f(self, pattern, parameter): return pattern_generator(self, type_, pattern, parameter) return f setpattern_iis = create_setpattern('iis') for short function body, you can use lambda: def create_setpattern(t): return lambda s, pat, par: pattern_generator(s, t, pat, par) probably the best solution is to use functools.partial: from functools import partial setpattern_iis = partial(pattern_generator, type='iis') however, this does NOT work due to (TypeError: pattern_generator() got multiple values for keyword argument 'type'); do you think it will be reasonable for partial to support this use case? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] plotting pixels
> It appears that the Tk canvas widget does not support simply > plotting a pixel. However, I can plot a line only one pixel long. > I wonder why they do not simply provide the pixel plot primitive? I > have seen very many graphics packages that do this and I have always > wondered why. The primitive obviously exists in the underlying > code, because that is what everything else is built upon. Does Tk > actually have a something like a create_pixel method in the canvas > widget that I have missed? You don't want that. Tkinter's Canvas is a Smart Canvas, each lines and shapes corresponds to a Tcl/Tk object. If you want to plot a 800*600 image pixel-per-pixel in Tkinter's Canvas, then Tkinter would have to create 48 Tcl Objects. If you want to draw pixels and lines directly, Tkinter Canvas isn't suitable for that. Try using a different Canvas, one that uses a Stateless Canvas. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What are "singletons" good for?
On 09/19/10 02:50, Knacktus wrote: > Hey all, > > the usual explanation for the usage of a Singleton goes like this: > > "Use a singleton if you want to make sure, that only one instance of a > class exists." > > But now I ask myself: Why should I call the constructor of a class more > than once if I only want one instance? > After all, I decide in my code when to create an instance or when to > pass an existing instance around. The guarantee. If you're writing a module that may be used by two or more modules, that may be used by a script. A logger module is a good example; if your script imports two modules, and both modules import the same logger module and instantiate their own version of loggers, then it is difficult to coordinate the logging of those two modules. If instead the logger class is a Singleton, then the user of logger modules doesn't need to care about any other modules using the same logger module, since they will create an instance when needed or get the existing logger when someone else already made one. A configuration module is another good example. It is a common idiom in python to import a .py script for configuration purpose. The benefit of this is that the config file basically becomes a truly global variable (python does not have a true global variable). > What's the point? Is it the spared typing when instanciating a lot of > View classes (I wouldn't need to pass the session to the constructor). > Or are there some more advantages (instead of passing the same instance > aorund)? Also, what would you guys consider as disadvantages? Disadvantage? compared to what? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] plotting pixels
On 09/19/10 09:39, ALAN GAULD wrote: >> It appears that the Tk canvas widget does not support simply plotting > a pixel. > > Correct, and I agree it seems odd, but in practice drawing either lines or > ovals of one-pixel do the equivalent job - albeit a little more slowly. More slowly and takes huge amount of memory. A single Tk canvas object takes at least 14 words (= 114 bytes in 64-bit OS = 56 bytes in 32-bit OS) + the amount of data is needed to store the `kind of object`. That's much larger than the ideal 3 bytes per pixel (or 4 bytes with alpha). Tkinter's Canvas intentionally doesn't provide create_pixel() because unlike most other Canvas implementations, Tkinter's Canvas holds a stateful canvas objects instead of a simple drawing surface. Providing a create_pixel() will be too tempting for abuse, which would make the canvas unbearably slow and memory consuming. In short, Canvas is not designed for pixel drawing. > Digging a little deeper it seems the idiomatic way to do this in Python > is to use PIL the Python Imaging Library to create a GIF or bitmap > image and then insert that into Tkinters cancvas as an image object. > > The Pil ImageDraw class has a point() ethod If you need to plot pixels, do use pygame, PIL, or at least the PhotoImage trick. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] super.__init__() arguments
On 09/27/10 09:45, Jojo Mwebaze wrote: > Hey Tutor, > > Seems a small issue but this has been playing for a while now, what am i > doing wrong here? > super() without argument only works for Python 3. In Python 2.x, you have to pass to super your class name and your class instance, i.e.: Class Circle(Point): def __init__(self, radius=0, x=0, y=0): super(Point, self).__init__(x, y) self.radius = radius ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension, efficiency?
On 09/28/10 13:57, Bill Allen wrote: > I can now see that quite a bit of the code I write dealing with lists > can be done with list > comprehensions. My question is this, is the list comprehension styled > code generally > more efficient at runtime? If so, why? Yes, because the looping in list comprehension is done in C instead of a python construct. However, they are the type of efficiency that you shouldn't bother yourself with unless you're microoptimizing. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Scripting-Puzzle Pirates
On 10/24/10 15:33, Nathan Finney wrote: > Hey, > > So I got bored of having to do a repeated task on this game, YPP Puzzle > Pirates and I was wondering if it was possible to script it. Even if you can (hint: no, you can't), most games consider writing scripts to do tasks as botting, i.e. cheating. > My task > would be to start at a dock, click on the port arrow, choose a ship (a > different one each time and in order preferably), go to its hold, select > materials to be moved and move them to a set ship (the same one each > time), then return to the starting position. Now, that would be stealing or just rude, even if you do it manually. > If this is possible would I first need a set of the games coding (which > uses javascript) to be obtained so it could be read and a script used > upon it. Java is not the same as Javascript. Puzzle Pirate is a Java game. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What's the best way to model an unfair coin?
On 10/25/10 02:46, Jose Amoreira wrote: > On Sunday, October 24, 2010 01:18:52 pm Alan Gauld wrote: > >> In pseudo code: >> >> def coinToss(prob = 0.5): >> rand = random() >> if rand >= prob: return True >> else: return False >> >> print "Heads" if coinToss(6/11) else "Tails" >> > > The only problem with this snippet is integer division: 6/11=0, at least in > Python 2.6, so that the final line will always print "Heads". > > But wait! This is pseudo code! Ah, OK. Then 6/11=0.545454..., and Alan was > right (as usual). Except for the missing import (which is traditionally omitted in mailing list discussions when the context makes it clear), Alan's snippet is correct in Python 3, which defaults to real division. Though, I'd probably writes it differently: def coinToss(prob = 0.5): rand = random() return rand >= prob or even: def coinToss(prob = 0.5): return random() >= prob ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?
On 10/23/10 01:19, David Hutto wrote: > If I understand what i just said correctly, it just means it tells the > string what type to convert from when placing it into the final > result. basically, when doing this %-interpolation, python does this: ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp) do the first interpolation: "NEW LOW: %%.%sf at %%s" % i it's to be noted that %% is replaced by a single %, and %s is replaced by the right argument of %, so if i == 5 it now becomes: "NEW LOW: %.5sf at %s" % (lowz, timestamp) and now do the second interpolation, lowz is formatted with %.5f which means a floating value (f) with 5 decimal place, and timestamp is inserted in place of %s; so if you have lowz = 81.345678901234 and timestamp = "last year": "NEW LOW: 81.34567 at last year" However, as Steven noted, the complex, 2-phase interpolation can be simplified using the '*' decimal place specifier: ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp) # is equivalent with: "NEW LOW: %.*f at %s" % (i, lowz, timestamp) and Steven also remarked that now the interpolation is so simple, there is very little benefit in separating it into a different function. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators (the "at" sign)?
On 10/26/10 13:46, Alex Hall wrote: > Hi all, > Now that I am able to run the source code of an open source > application I hope to one day help develop, I am trying to understand > how it works. One thing I keep seeing is an at sign followed by a > word, usually (maybe always) immediately preceeding a function > definition. For example, and I know this exact code will not make much > sense, but it gives the idea: > class Bing(Messages, Updating, Dismissable): > > @set_index > def get_url(self, index=None): > return self.storage[index]['Url'] > > What is the "@set_index" for? Specifically, what is the at sign doing? > Google was only able to provide me with a very vague idea of what is > going on, though it seems to crop up a lot in classmethod and > staticmethod calls (not sure about those either). I read PEP 318, but > it was not much help since I am coming at this having no idea what I > am looking at. The PEP did explain why I have never run into this > before, though - it is apparently specific to Python. I see this sort > of thing all over this source code so it seems like a good idea to get > exactly what it is for. TIA! The decorator syntax is really just a shorthand, from this: @decorator def func(arg): pass is equivalent to: def func(arg): pass func = decorator(func) basically, a decorator is a function that takes an function as a parameter/callable and (usually) returns another function/callable as return value. A slightly advanced usage of decorator: def trace(func): """ trace will print the func's name, the number of times func have been called, the arguments it's called with, and the return value of func whenever func is called. """ # define an inner function def _decorator(arg): print ("The %sth call of %s with arg: %s" % (_decorator._numcall, func.__name__, arg)) _decorator._numcall += 1 ret = func(arg) print "finished", func.__name__, "returns:", ret return ret # this is used to store the number of times # the decorated function is called _decorator._numcall = 0 # disable the decorator when debugging is enabled if __debug__: # or: return _decorator if __debug__ else func return _decorator else: return func @trace def twice(arg): return 2 * arg # the @trace makes it as if you do this: # twice = trace(twice) $ # let's start the program $ python decor.py The 0th call of twice() with arg: 30 finished twice() returns: 60 The 1th call of twice() with arg: 3 finished twice() returns: 6 The 2th call of twice() with arg: 4 finished twice() returns: 8 74 $ $ # now call it with debugging disabled: $ python -O decor.py 74 another nifty use of decorator is for event handling for a hypothetical GUI toolkit (I've yet to actually see a toolkit that uses this syntax yet): @button.on_click def shoot(button): ... @window.on_keypress('p') def pause(key): ... other built-in functions designed for decorator syntax is @property, @classmethod, and @instancemethod. Decorator can become extremely powerful when combined with the descriptor protocol (.__get__, .__set__). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.listdir for symbolic links?
On 10/28/10 06:57, Sean Carolan wrote: > Is there an easy way to find the target of a symbolic link on a Linux > system with python? I'm looking for something like the output of the > bash command: "ls -l" you're looking for >>> os.path.realpath('/bin/uncompress') '/bin/gunzip' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Picking up citations
On Mon, 09 Feb 2009 14:42:47 -0800, Marc Tompkins wrote: > Aha! My list of "magic words"! > (Sorry for the top post - anybody know how to change quoting defaults in > Android Gmail?) > --- www.fsrtechnologies.com > > On Feb 9, 2009 2:16 PM, "Dinesh B Vadhia" > wrote: > > Kent /Emmanuel > > I found a list of words before the first word that can be removed which > I think is the only way to successfully parse the citations. Here they > are: > > | E.g. | Accord | See |See + Also | Cf. | Compare | Contra | But + See | > But + Cf. | See Generally | Citing | In | > I think the only reliable way to parse all the citations correctly, in the absence of "magic word" is to have a list of names. It involves a bit of manual work, but should be good enough if there are a small number of cases that is cited a lot of times. >>> names = '|'.join(['Carter', 'Jury Commision of Greene County', 'Lathe Turner', 'Fouche']) >>> rep = '|'.join(['.*?']) >>> dd = {'names': names, 'publ': rep} >>> re.search(r'((%(names)s) v. (%(names)s)(, [0-9]+ (%(publ)s) [0-9]+)* \([0-9]+\))' % dd, text).group() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
On Tue, 10 Feb 2009 09:43:18 -0500, python wrote: > Kent, > >> Except they are not equivalent when you want to print more than one >> thing. ... >> Python 2.6: >> In [1]: print(3, 4) >> (3, 4) > > I'm running Python 2.6.1 (32-bit) on Windows XP. > > I don't get the tuple-like output that you get. > > Here's what I get: > print( 3, 4 ) > 3 4 Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
On Wed, Feb 11, 2009 at 2:26 AM, wrote: > > > Are you sure it isn't python 3.x you're playing with? The reason why > simple print function "works" in python 2.x is because of a syntactical > coincidence, it is still a 100% statement. > > Yes, I'm sure :) I restarted IDLE and pasted my session output below: You didn't tell that you imported __future__'s print_function! I thought I was having a hallucination or something... seeing that behavior in python2.6 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] url parsing
On Sun, 15 Feb 2009 14:22:09 +0100, Andre Engels wrote: > What is 'new' in your solution? Apart from that, the following looks > simpler: > url = "http://this/is/my/url/to/parse"; parts = url.split('/') sol = '/'.join(parts[:-1]) sol > 'http://this/is/my/url/to' do you want something even more simpler? >>> url ="http://this/is/my/url/to/parse"; >>> url.rsplit('/', 1)[0] 'http://this/is/my/url/to' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate
On Sun, 2009-02-15 at 21:29 +0100, tutor-requ...@python.org wrote: > Do you know about sequence unpacking? In an assignment statement, when > the right side is a sequence, the left side can be a list of variables > of the same length as the sequence. Then each sequence element is > assigned to one variable. For example The left side can only be a tuple of "names". The tuple unpacking is a little bit of violation of python's object model, since while python's tuple usually contain objects, in tuple unpacking the tuple contains a list of names to be assigned. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate
On Mon, 2009-02-16 at 09:38 -0500, bob gailer wrote: > Lie Ryan wrote: > > On Sun, 2009-02-15 at 21:29 +0100, tutor-requ...@python.org wrote: > > > > > >> Do you know about sequence unpacking? In an assignment statement, when > >> the right side is a sequence, the left side can be a list of variables > >> of the same length as the sequence. Then each sequence element is > >> assigned to one variable. For example > >> > > > > > > The left side can only be a tuple of "names". The tuple unpacking is a > > little bit of violation of python's object model, since while python's > > tuple usually contain objects, in tuple unpacking the tuple contains a > > list of names to be assigned. > > > > > It's time to take a look at the Language Reference. > 6.3 Assignment statements. > assignment_stmt ::= (target_list "=")+ expression_list > a target list is not a tuple, even though it can look like one. > So I don't see it as any violation. Every time I heard about tuple unpacking, everyone always describes the target_list as tuple. I've never looked at the Language Reference on this particular case before, so I admit I didn't know that the Language Reference does make a distinction between the two. So, I'll retract calling it as violation, tuple and target_list is a completely different beast. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu
On Mon, 16 Feb 2009 22:34:23 -0700, Eric Dorsey wrote: > Greetings Tutor: > I've managed to install Python 2.6 on my Ubuntu VM from source, however, > it looks as though I missed something important along the way. My 2.6 > interpreter does not have readline support (example: I cant hit up arrow > to repeat the last command) Is there a way to add this functionality > now? WORKSFORME I have Ubuntu and python2.6 and the up arrow history works fine. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Proxies/Interceptors for file-like objects
On Thu, 19 Feb 2009 20:12:57 +1100, Oxymoron wrote: > Thanks for the answers everyone. > > Denis, I wish to wrap an already open file handle basically, so simply > extending and overriding doesn't help - my proxy won't be instantiated > like a file, just used like one and if not intercepting I need to > delegate down to the proxied "real" handle. If I'm missing something, > please let me know. Here's the actual scenario: > If you replace sys.stdin with your own file object, you don't need to define all of the file object interface, just the one that generates an error if not defined (i.e. the ones that you use). Alternatively, you may also consider using subprocess. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] KeyError: 'DEFAULT'
On Thu, 19 Feb 2009 11:45:52 -0800, Marc Tompkins wrote: > Don't use reserved words as variable names! str, set is built-in function not reserved words. Reserved words are like if, for, from, as (see the whole list type keywords in help() ) Nevertheless, it is a bad idea to use built-in function names. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calling user defined function
On Sun, 22 Feb 2009 22:21:22 +0100, roberto wrote: > hello > i have a question which i didn't solved yet: i can define a function > using the text editor provided by IDLE 3.0; then i'd like to call this > function from the python prompt > > but when i try to do it, python warns me that function doesn't exist of > course if i define the function directly using the >>> prompt, after > that everything is fine > > may you tell me where i have to save the file that defines the function > is order to use it later ? > is it a problem of path ? > > my version of python is 3.0, OS windows xp > > thank you very much in advance or you can also run your module with -i (interactive) argument, which means to put you into the interactive mode after the module ends. # mycode.py def foo(): print 'bar' print 'output of program (if any)' # then run this in your shell: $ python -i mycode.py output of program (if any) >>> foo() bar ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing perimeters in dictionary values?
On Tue, 24 Feb 2009 18:26:29 -0500, Kent Johnson wrote: > On Tue, Feb 24, 2009 at 5:13 PM, nathan virgil > wrote: >> I'm not familiar with lambdas yet, and I don't think this book will >> introduce me to them; they aren't listed in the index, anyway. Nobody remembers partial? from functools import partial newfunc = partial(myfunc, 1, 2, 3) newfunc() {'eatgrass': partial(eat, 'grass'), 'eatcarrot': partial(eat, 'carrot')} ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String to list conversion
> name like "foo" to be changed Nitpick: "foo" is a string, not a name... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu
On Thu, 19 Feb 2009 09:27:34 +0300, Ø²ÙØ§Ø¯ Ø¨Ù Ø¹Ø¨Ø¯Ø§ÙØ¹Ø²Ùز Ø§ÙØ¨Ø§ØªÙÙ wrote: > On Wed, 18 Feb 2009 20:19:56 -0700 > Eric Dorsey wrote: >> I did an aptitute install of ibreadline5-dev and then did ./configure >> and make again, and still don't have any functionality to be able to >> hit up-arrow and get a command repeated while inside the interpreter. >> Any ideas? >> >> > I don't know what's wrong, Python should pickup "libreadline" and use it > automatically if it was installed. > > Try passing "--with-readline" to the "configure" script. > > If that doesn't help, then I'm sorry, I'm out of ideas. > Try installing other readline modules that looks suspicious. In my Ubuntu machine (these are all readline-related modules in my machine, not only the ones that is needed for python), I have these packages installed: v lib32readline-dev- v libghc6-readline-dev - v libghc6-readline-doc - v libghc6-readline-prof- v libreadline-dbg - v libreadline-dev - i libreadline5 - GNU readline and history libraries, run-ti i A libreadline5-dev - GNU readline and history libraries, develo i readline-common - GNU readline and history libraries, common try matching that and ./configure then make. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu
On Wed, 2009-02-25 at 22:23 -0700, Eric Dorsey wrote: > Thanks for all your continued insights on this. I'm going to > investigate the .configure log, as well as look around at other > readline packages.. But, noob question, did you just go into something > like synaptic to find out what readline type packages are installed? > (Sorry if this is annoying anyone on the list, but its all in the name > of getting the Python inerpreter to be happy !) Or did you do some > kind of command line aptitude "list out readine stuff"? Yeah, you can go to synaptic and and do a search. Alternatively, you type "aptitude search readline" on the terminal (no need for sudo/root access for search). If you found what you want to install, you can use "sudo apt-get install " or "sudo aptitude install ". Synaptic is fine too, but not the "Add/Remove Application", the "Add/Remove Application" allows you to install applications not single packages. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to instantiate a class
On Thu, 26 Feb 2009 12:38:27 +0530, Abhishek Kumar wrote: > hello list, > You need to read through the tutorial first: http://docs.python.org/ tutorial/ If there are still things you don't understand, please ask again. As for your question, here is a sample useless python code: class MyClass(object): def __init__(self, arg): self.a = arg def foo(self, b): return self.a + b myinstance = MyClass(5) print myinstance.foo(6) # output 11 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to instantiate a class
On Thu, 26 Feb 2009 12:38:27 +0530, Abhishek Kumar wrote: > hello list, > You need to read through the tutorial first: http://docs.python.org/ tutorial/ If there are still things you don't understand, please ask again. As for your question, here is a sample useless python code: class MyClass(object): def __init__(self, arg): self.a = arg def foo(self, b): return self.a + b myinstance = MyClass(5) print myinstance.foo(6) # output 11 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] format a file
Try thinking what happens when you do this: line = 'this is a rellly long line\n' first = line[:20] second = line[20:] print first print second . . . . . . . . . . Have you got it? The first would contain "this is a re" and the second "llly long line\n" When you try to write to the file: de.write(first) de.write(second) why isn't there a new line between the first and second? Also, I think you should realize that with how you do it now, you may put line breaks in between words. Better to split on space line.split(' ') then ' '.join(first) + '\n' it together again. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] re Format a file
On Fri, 27 Feb 2009 09:59:40 +0530, prasad rao wrote: > def myform(s): > import os > so=open(s) > d=os.path.dirname(s)+os.sep+'temp.txt' > de=open(d,'w') > for line in so: > while len(line)>60: > item=line[60:] > try: > a,b=tem.split(' ',1) what is tem here? It must be a global, since I can't see any other reference to tem in the function definition. If tem is global, then the value of b (a.k.a. line) will never change (except for the first iteration) > de.write(line[:60]+a+'\n') > line=b > except ValueError: > pass > de.write(line+'\n') > so.close() > de.close() > os.remove(s) > os.rename(d,s) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What does the L at the end of a number means?
Nuno Hespanhol wrote: > Hi. > I have started learning phyton today! > I was playing around with some large numbers (fibonacci series) > and noticed that in some large calculations results have an "L" at the > end of a number. > Does this L stands for Large? Is there any way to disable this feature, > so that all numbers are shown? > > Thanks for your time. "L" means it is "long integer". In the python interpreter, when you do something like this: >>> a it will actually call the __repr__ of a and print it. >>> print a.__repr__() while >>> print a will call __str__ of a and print it >>> print a.__str__() Python 2.x's long integer __repr__ adds an extra L to denote long integer, however the __str__ does not. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 61, Issue 3
Daniele wrote: >> From: W W >> Subject: Re: [Tutor] modular program > >>> Where can I find some "best practices" for writing modular programs? >>> I thought about a txt file containing function calls that my program will >>> parse and execute in order, or is it better just to execute every .py file >>> in a certain "module" folder (I don't like this as modules could need to be >>> executed in different moments)? > >> You can pretty much take a look at any of the modules in your python >> library directory. In the case of my linux box, that's >> /usr/lib/python2.5/ > > I'm sorry, I've realized I didn't explain my needs at all. > I was a little influenced by drupal's definition of modules, which is > completely different from python's. > With module here I meant plug-in or extension: a piece of code written > by someone else that can be easily (and automaticallly) integrated > into my program. > My program must provide the posibility to be extended without editing > its code, just like mozilla's add-ons. It heavily depends on the design of the main program. The simplest way to have a plug-in system is probably having user writes python modules which your program will import and call a certain agreed function. for example mainprogram.py: um_name = raw_input('Enter usermodule's filename: ') um = __import__(um_name) um.run() usermodule.py: def run(): # do initializations required to install the module ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor