Re: [Tutor] Question on "import foobar" vs "from foobar import *"
If I might offer one small comment... It seems to me that this argument also goes to a code readability issue; ergo, if you choose "from foobar..." as opposed to "import foobar", then from that point on you only need employ foobar's methods in your code, and they are not alway easily recognizable. i.e, by importing foobar, you will always prefix a method with its' parent module name, which [I think] makes the code more understandable. >From the virtual desk of Lowell Tackett --- On Sat, 1/9/10, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] Question on "import foobar" vs "from foobar import *" To: tutor@python.org Date: Saturday, January 9, 2010, 10:21 AM "Rob Cherry" wrote > Extending on this advice somewhat - is it *ever* correct to "import foobar". Yes, it is *usually* correct to "import foobar" and rarely correct to "from foobar". The exception being if you only need one or two names from foobar, but usually you need a lot more, in which case use import foobar. To save typing you can give foobar a shorter name: import foobar as fb For some reason that convenience feature doesn't get mentioned all that often but I use it a lot. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about function inside of function
On Sat, Jan 9, 2010 at 07:28, Alan Gauld wrote: > > "Richard D. Moores" wrote >> >> to be put in a function. For convenience sake, I've put this new >> function inside the one that calls it. >> >> Question 1: Is this bad practice? It works fine that way, but.. > > No, but there are some issues to consider. > Denis has addressed some but one other is... > > Reuse: by hiding the function inside the outer one it means it can only ever > be used inside that function. That's OK. It's very specific to the enclosing function. > It may be better to have it as a module level > function - even if you use the _prefix to limit its use outside the module. > >> Question 2: If the answer to Q1 is no, is there a standard place to >> put a function inside of another function? Is it standard to have it >> the first line of the function? I've put mine at the point where it >> would be called, mainly as a reminder to myself. > > Top of the function is best because as Denis says it only gets defined once > per function call. If you are really paranoid and the function only gets > used in exceptional cases then you could define it at the point of use but > in that case you probably don't need a function at all! I moved it to the top. But since writing it I debugged and edited the script so that the small function is used in only one case. So you're right, I don't need it as a function at all. Thanks, Alan. Right on as usual. Dick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Expanding a Python script to include a zcat and awk pre-process
galaxywatc...@gmail.com wrote: After many more hours of reading and testing, I am still struggling to finish this simple script, which bear in mind, I already got my desired results by preprocessing with an awk one-liner. I am opening a zipped file properly, so I did make some progress, but simply assigning num1 and num2 to the first 2 columns of the file remains elusive. Num3 here gets assigned, not to the 3rd column, but the rest of the entire file. I feel like I am missing a simple strip() or some other incantation that prevents the entire file from getting blobbed into num3. Any help is appreciated in advance. #!/usr/bin/env python import string import re import zipfile highflag = flagcount = sum = sumtotal = 0 f = file("test.zip") z = zipfile.ZipFile(f) for f in z.namelist(): ranges = z.read(f) This reads the whole file into ranges. In your earlier incantation, you looped over the file, one line at a time. So to do the equivalent, you want to do a split here, and one more nesting of loops. lines = z.read(f).split("\n")#build a list of text lines for ranges in lines:#here, ranges is a single line and of course, indent the remainder. ranges = ranges.strip() num1, num2, num3 = re.split('\W+', ranges, 2) ## This line is the root of the problem. sum = int(num2) - int(num1) if sum > 1000: flag1 = " " flagcount += 1 else: flag1 = "" if sum > highflag: highflag = sum print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total ranges over 10 million: ", flagcount print "Largest range: ", highflag == $ zcat test.zip 134873600, 134873855, "32787 Protex Technologies, Inc." 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, "12838 HFF Infrastructure & Operations" 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc Roussillon" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Expanding a Python script to include a zcat and awk pre-process
I finally got it working! I would do a victory lap around my apartment building if I wasn't recovering from a broken ankle. Excuse my excitement, but this simple script marks a new level of Python proficiency for me. Thanks to Kent, Bob, Denis, and others who pointed me in the right direction. It does quite a few things: decompresses a zipped file or files if there is an archive of them, processes a rather ugly csv file (ugly because it uses a comma as a delimiter, yet there are commas in double quote separated fields), and it does a simple subtraction of the two columns with a little summary to give me the data I need. #!/usr/bin/env python import string import re import zipfile highflag = flagcount = sum = sumtotal = 0 z = zipfile.ZipFile('textfile.zip') for subfile in z.namelist(): print "Working on filename: " + subfile + "\n" data = z.read(subfile) pat = re.compile(r"""(\d+), (\d+), (\".+\"|\w+)""") for line in data.splitlines(): result = pat.match(line) ranges = result.groups() num1 = ranges[0] num2 = ranges[1] sum = int(num2) - int(num1) if sum > 1000: flag1 = " " flagcount += 1 else: flag1 = "" if sum > highflag: highflag = sum print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total ranges over 10 million: ", flagcount print "Largest range: ", highflag A few observations from a Python newbie: The zipfile and gzip modules should really be merged together. gzcat on unix reads both compression formats. It took me way too long to figure out the namelist() method. But I did learn a lot more about how zip actually works as a result. Is there really no way to extract the contents of a single zipped file without using a 'for in namelist' construct? Trying to get split() to extract just two columns from my data was a dead end. The re module is the way to go. I feel like I am in relatively new territory with Python's regex engine. Denis did save me some valuable time with his regex, but my file had values in the 3rd column that started with alphas as opposed to numerics only, and flipping that (\".+\"|\d+)""") to a (\".+\"|\w +)""") had me gnashing teeth and pulling hair the whole way through the regex tutorial. When I finally figured it out, I smack my forehead and say "of course!". The compile() method of Python's regex engine is new for me. Makes sense. Just something I have to get used to. I do have the feeling that Perl's regex is better. But that is another story. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Hooray! I finished the 'Learning Python for absolute beginners'
Ok, it's not a big deal, but once I learned enough I went off on a few tangents to create programs of my own design. Since I had to return the book to the public library, I finally got back to finishing the last chapter. Since the book is not current, I took the time to decipher the differences and eventually figured out the final project creating an asteroids game using the latest livewires. I would eventually like to use pygame, but for now I'm content that it works. I know there have been some questions in the past about errors, so this is simply being submitted as a placemarker for those working through the same book. I'm really glad I decided to learn Python! I also figured out how to configure Eclipse IDE to recognize modules. Apparently in the preferences for each 'project' is a separate PYTHONPATH.. which is not to be confused with sys.path. Adding the appropriate folders to the preferences allows the user to browse through a module i.e. after writing: 'from livewires import games' typing: 'games.' yields a drop down menu of all methods etc very convenient when trying to follow older tutorials of older packages. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hooray! I finished the 'Learning Python for absolute beginners'
Nice one... I should still get to starting lol... 2010/1/10 Tim Goddard > Ok, it's not a big deal, but once I learned enough I went off on a few > tangents to create programs of my own design. Since I had to return > the book to the public library, I finally got back to finishing the > last chapter. Since the book is not current, I took the time to > decipher the differences and eventually figured out the final project > creating an asteroids game using the latest livewires. I would > eventually like to use pygame, but for now I'm content that it works. > > I know there have been some questions in the past about errors, so > this is simply being submitted as a placemarker for those working > through the same book. > > I'm really glad I decided to learn Python! > > I also figured out how to configure Eclipse IDE to recognize modules. > Apparently in the preferences for each 'project' is a separate > PYTHONPATH.. which is not to be confused with sys.path. Adding the > appropriate folders to the preferences allows the user to browse > through a module i.e. > > after writing: > 'from livewires import games' > > typing: > 'games.' yields a drop down menu of all methods etc very > convenient when trying to follow older tutorials of older packages. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hooray! I finished the 'Learning Python for absolutebeginners'
"Tim Goddard" wrote I also figured out how to configure Eclipse IDE to recognize modules. Apparently in the preferences for each 'project' is a separate PYTHONPATH.. which is not to be confused with sys.path. Adding the appropriate folders to the preferences allows the user to browse through a module i.e. I assume you have already installed the PyDev plugin? I'm currently reading a book on Eclipse (Eclipse Distilled) which has turned up many settings and tricks that I was unaware of. It is a powerful tool but like all such it takes a lot of learing to get the most from it. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on "import foobar" vs "from foobar import *"
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. 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. ;) On Sat, Jan 9, 2010 at 8:35 AM, Lowell Tackett wrote: > If I might offer one small comment... > > It seems to me that this argument also goes to a code readability issue; > ergo, if you choose "from foobar..." as opposed to "import foobar", then > from that point on you only need employ foobar's methods in your code, and > they are not alway easily recognizable. i.e, by importing foobar, you will > always prefix a method with its' parent module name, which [I think] makes > the code more understandable. > > From the virtual desk of Lowell Tackett > > > --- On *Sat, 1/9/10, Alan Gauld * wrote: > > > From: Alan Gauld > Subject: Re: [Tutor] Question on "import foobar" vs "from foobar import *" > To: tutor@python.org > Date: Saturday, January 9, 2010, 10:21 AM > > > > "Rob Cherry" http://mc/compose?to=pythontu...@lxrb.com>> > wrote > > > Extending on this advice somewhat - is it *ever* correct to "import > foobar". > > Yes, it is *usually* correct to "import foobar" and rarely correct to "from > foobar". > The exception being if you only need one or two names from foobar, but > usually you need a lot more, in which case use import foobar. > > To save typing you can give foobar a shorter name: > > import foobar as fb > > For some reason that convenience feature doesn't get mentioned > all that often but I use it a lot. > > HTH, > > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on "import foobar" vs "from foobar import *"
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. Not a copy (which means duplicating the attribute) but a new reference to the original attribute. Example >>> import sys >>> from sys import modules >>> sys.modules is modules True >>> m = dict(sys.modules) # create a copy >>> m is modules False -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
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] Question on "import foobar" vs "from foobar import *"
Lie Ryan dixit: > only use "from module import *" if the > module was designed for such use In most cases, this translates to: the imported module defines __names__, which holds the list of names (of the objects) to be exported. Check it. Below, a,b,c,f,g,X,Y are defined, but only c,g,Y are exported. This means "from mod import *" will only import these names. Without __names__ defined, it would import all. ### module mod.py ### __names__ = ['c','g','Y'] a = ... b = ... c = ... def f(): ... def g(): ... class X(object): ... class Y(object): ... Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] formatting*
"Lowell Tackett" wrote In the meantime, posing this query took me somewhere I hadn't imagined... I got turned on to the 'Gmane' mailsite, which pretty much solved all my issues, plus presented a much nicer 'reading room'. I actually use it as a news feed into Outlook Express. I only occasionally use the gmane web site. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] question about function inside of function
I'm working on a function that seems to cry out for some of its code to be put in a function. For convenience sake, I've put this new function inside the one that calls it. Question 1: Is this bad practice? It works fine that way, but.. Question 2: If the answer to Q1 is no, is there a standard place to put a function inside of another function? Is it standard to have it the first line of the function? I've put mine at the point where it would be called, mainly as a reminder to myself. An outline of the big function is: if: else: for loop for loop if elif the function call the function else Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
hi, iam a beginner. sample_file = file("/home/ee08m082/Desktop/python/123.txt","w") sample_file.write("About Pythons\n") in the above two line code,123.txt is being created but "About Pythons" is not being written in the file. my OS is redhat linux and python version is 2.3.4 thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
sudhir prasad wrote: hi, iam a beginner. sample_file = file("/home/ee08m082/Desktop/python/123.txt","w") sample_file.write("About Pythons\n") in the above two line code,123.txt is being created but "About Pythons" is not being written in the file. my OS is redhat linux and python version is 2.3.4 thanks You forgot to close the file. sample_file.close() DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Expanding a Python script to include a zcat and awk pre-process
After many more hours of reading and testing, I am still struggling to finish this simple script, which bear in mind, I already got my desired results by preprocessing with an awk one-liner. I am opening a zipped file properly, so I did make some progress, but simply assigning num1 and num2 to the first 2 columns of the file remains elusive. Num3 here gets assigned, not to the 3rd column, but the rest of the entire file. I feel like I am missing a simple strip() or some other incantation that prevents the entire file from getting blobbed into num3. Any help is appreciated in advance. #!/usr/bin/env python import string import re import zipfile highflag = flagcount = sum = sumtotal = 0 f = file("test.zip") z = zipfile.ZipFile(f) for f in z.namelist(): ranges = z.read(f) ranges = ranges.strip() num1, num2, num3 = re.split('\W+', ranges, 2) ## This line is the root of the problem. sum = int(num2) - int(num1) if sum > 1000: flag1 = " " flagcount += 1 else: flag1 = "" if sum > highflag: highflag = sum print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total ranges over 10 million: ", flagcount print "Largest range: ", highflag == $ zcat test.zip 134873600, 134873855, "32787 Protex Technologies, Inc." 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, "12838 HFF Infrastructure & Operations" 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc Roussillon" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about function inside of function
Richard D. Moores dixit: > I'm working on a function that seems to cry out for some of its code > to be put in a function. For convenience sake, I've put this new > function inside the one that calls it. > > Question 1: Is this bad practice? It works fine that way, but.. > > Question 2: If the answer to Q1 is no, is there a standard place to > put a function inside of another function? Is it standard to have it > the first line of the function? I've put mine at the point where it > would be called, mainly as a reminder to myself. > > An outline of the big function is: > > if: > else: > for loop > for loop > if > elif > the function > call the function > else > > Thanks, Do you realize the inner func will be redefined before each call? Meaning in your case n calls x n outer loops x n inner loops. def f() ... is actually a kind of masked assignment f = function()... To avoid polluting the global namespace (if it's what you mean), you can assiattach the inner func as an attribute of the outer: "g.f = f". Unfortunately, it's not possible (I guess), to define it directly using "def g.f()". Also, if a func logically is an attribute of another, then probably you're close to defined an object, possibly with other attributes. Think at the design of the application. I may be wrong, but I guess the only common case where you should (and must) define a func inside another is the one of a func factory, ie a func that defines (and returns) a new func: def makeAdder(val): def adder(x): return x + adder.val adder.val = val return adder add3 = makeAdder(3) print add3(2) # --> 5 Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about function inside of function
On Sat, Jan 9, 2010 at 05:03, spir wrote: > Do you realize the inner func will be redefined before each call? Oh, I forgot about that. Thanks! Dick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on "import foobar" vs "from foobar import *"
"Rob Cherry" wrote Extending on this advice somewhat - is it *ever* correct to "import foobar". Yes, it is *usually* correct to "import foobar" and rarely correct to "from foobar". The exception being if you only need one or two names from foobar, but usually you need a lot more, in which case use import foobar. To save typing you can give foobar a shorter name: import foobar as fb For some reason that convenience feature doesn't get mentioned all that often but I use it a lot. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about function inside of function
"Richard D. Moores" wrote to be put in a function. For convenience sake, I've put this new function inside the one that calls it. Question 1: Is this bad practice? It works fine that way, but.. No, but there are some issues to consider. Denis has addressed some but one other is... Reuse: by hiding the function inside the outer one it means it can only ever be used inside that function. It may be better to have it as a module level function - even if you use the _prefix to limit its use outside the module. Question 2: If the answer to Q1 is no, is there a standard place to put a function inside of another function? Is it standard to have it the first line of the function? I've put mine at the point where it would be called, mainly as a reminder to myself. Top of the function is best because as Denis says it only gets defined once per function call. If you are really paranoid and the function only gets used in exceptional cases then you could define it at the point of use but in that case you probably don't need a function at all! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] cookielib and form authentication woes
dear tutors, I'm trying to use a GPS tracking service called InstaMapper. The service changes how frequently it updates the tracking device's position based on whether the UI is being accessed on the InstaMapper webpage. I'd like to have the increased update frequency happen all the time so I thought I'd write a python script to login to my account and access the page periodically: import urllib2, urllib, cookielib cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) params = urllib.urlencode(dict(username_hb='user', password_hb='resu')) opener.open('http://www.instamapper.com/fe?action=login', params) if not 'id' in [cookie.name for cookie in cj]: raise ValueError, "Login failed" # now try secured page resp = opener.open('http://www.instamapper.com/fe?page=track&device_key=abc ') print resp.read() resp.close() The ValueError is raised each time. If I remove this and read the response, the page thinks I have disabled cookies and blocks access. Why isn't cj grabbing the InstaMapper cookie? Are there better ways to make the tracking service think I'm viewing my account constantly? -Matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor