Re: [Tutor] SEE THE QUESTION AT THE BOTTOM
On 03-Feb-12 21:38, Debashish Saha wrote: BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. The part that's confusing you is that it is not outside the for loop. It is PART of the for loop syntax. The loop construct used is: for in : else: This means you run , executing once for each iteration, and a statement in that body may elect to break out of the loop prematurely. If nothing breaks out of the loop (i.e., you exit the loop because the was exhausted), then and only then execute . It's a handy mechanism to handle the case where the for loop failed to find whatever it was searching for. Most other languages I've used don't have this, and you end up doing messier manual logic steps to accomplish the same thing. Tip: Please don't type a message IN ALL CAPITAL LETTERS; it gives the impression you are shouting at your audience. HTH, HAND -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] SEE THE QUESTION AT THE BOTTOM
INPUT: *for n in range(2, 1000):* *for x in range(2, n):* *if n % x == 0:* *print n, 'equals', x, '*', n/x* *break* *else:* *# loop fell through without finding a factor* *print n, 'is a prime number'* OUTPUT: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 :QUESTION: BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Importing libraries
Why don't I have to import str or list to access their attributes like I do with the math or random or any other library? -- Michael J. Lewis mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getattribute__
Alan Gauld wrote: On 04/02/12 00:30, Stayvoid wrote: Could you provide some examples (easy and hard ones) and comments on the topic? I'm trying to understand how this thing works. Commenting on the topic... It's not one most beginners(*) should be worrying about you rarely need to use it. But its slightly easier than the related __setattribute__. That is spelled "__setattr__". -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getattribute__
Stayvoid wrote: Hi! Could you provide some examples (easy and hard ones) and comments on the topic? I'm trying to understand how this thing works. When you do an attribute lookup on an object, say obj.attr, Python uses something like a search path to find the attribute: it tries various things, and looks in various places, until it has a success or finally gives up. Here's a simplified version: 1) First try to create a computed attribute using the special method __getattribute__ (new style classes only). 2) If not successful, look in the instance itself. 3) If not found, look in the class. 4) If still not found, look in any superclasses (if any). 5) If still not found, try to create a computed attribute using the special __getattr__ method. 6) If not successful, raise AttributeError. "New style classes" are those that inherit from object, or a Python built-in type like str, int, list, etc. class Spam: # "classic class", __getattribute__ is ignored pass class Ham(object): # "new style" class, __getattribute__ is special pass "Classic classes" come from the earliest versions of Python. "New style classes" started in Python 2.2, which is not so new any more, but the name has stuck. Starting from Python 3, all classes are "new style" and the distinction can be ignored. Notice that there are two special methods: __getattribute__ is always called, and if it returns a value, that value is used. __getattr__ is only called if everything else fails. Here's an example of how you might use them: class Test(object): a = "this is attached to the class" def __init__(self): self.b = "this is attached to the instance" def __getattr__(self, name): print("calling __getattr__") if name == 'c': return "this is computed by __getattr__" else: # Nothing left to do. You have to raise an exception yourself. raise AttributeError('no such attribute') def __getattribute__(self, name): print("calling __getattribute__") if name == 'd': return "this is computed by __getattribute__" else: # Always let the superclass try. return super(Test, self).__getattribute__(name) To test it, copy and paste the class definition into IDLE or the interactive interpreter, and then experiment. E.g.: py> instance = Test() py> instance.d calling __getattribute__ 'this is computed by __getattribute__' What's the difference between class attribute a and instance attribute b? Class attributes are shared across all instances, while instances each get their own personal version of instance attributes. In the example above, where self.b gets assigned the same value every time, the difference is insignificant, but normally you might do something like this: class PrintJob(object): size = "A4" # Set the global default def __init__(self, data, size=None): if size is not None: self.size = size # override the default self.data = data Now each PrintJob gets its own size, but only when needed; otherwise the default A4 gets used instead. Last but not least... __getattribute__ and __getattr__ are used for looking up attributes. You can also write attributes, and delete them, and Python provides magic methods to handle them too: __setattr__ -- used to write the attribute, it is ALWAYS called if present __delattr__ -- used to delete the attribute, it is ALWAYS called if present Be warned that using __setattr__ is tricky to get right, and __delattr__ is hardly ever needed (at least in my experience). Actually all of these magic attr methods are hardly ever needed, but __delattr__ is even less common than the rest. Abuse of magic attr methods can lead to hard to understand code and mysterious, hard-to-solve bugs. Consider them for advanced use only. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __getattribute__
On 04/02/12 00:30, Stayvoid wrote: Could you provide some examples (easy and hard ones) and comments on the topic? I'm trying to understand how this thing works. Commenting on the topic... It's not one most beginners(*) should be worrying about you rarely need to use it. But its slightly easier than the related __setattribute__. (*)And this is a list for beginners... Now does that help, or would you like to be more specific? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] __getattribute__
Hi! Could you provide some examples (easy and hard ones) and comments on the topic? I'm trying to understand how this thing works. Cheers. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On 03/02/2012 20:32, Debashish Saha wrote: what is the basic difference between numpy and pylab? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor http://catb.org/esr/faqs/smart-questions.html -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Comparing numpy and pylab
Debashish Saha wrote: Welcome! > what is the basic difference between numpy and pylab? You can find out yourself. Start Python's interactive interpreter and type help("pylab"): >>> help("pylab") ... This is a procedural interface to the matplotlib object-oriented plotting library. ... >>> help("numpy") ... NumPy = Provides 1. An array object of arbitrary homogeneous items 2. Fast mathematical operations over arrays 3. Linear Algebra, Fourier Transforms, Random Number Generation ... Get into the habit to look for an answer yourself before you ask here. Then tell us what you have already tried. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
what is the basic difference between numpy and pylab? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8"
On 02/03/2012 10:46 AM, Simeon Tesfaye wrote: Hello everyone, Two thoughts, but realize I don't know anything about pyshp. I am having a bit of trouble here with my code, which uses a shapefile library, named pyshp, to import, edit, and save GIS files within Python. So, I open up my shapefile (data is polylines, meaning, not points or polygons) "shapefile=shapefile.Reader("file.shp") shps=shapefile.shapes() shprec = shapefile.records() " Then I carry out some edits, and I save my file. 1) Do you close the file? When I want to open it again, within the same script, in order to access some of the data I just modified, I get this message : "Traceback (most recent call last): File "", line 1, in troncop=troncon.shapes() File "C:\Python25\Lib\shapefile.py", line 310, in shapes while shp.tell()< self.shpLength: File "C:\Python25\Lib\shapefile.py", line 222, in __shape print(f.read(8)) 2) Did you add that line? I'm guessing you inserted that right before a read() , so you could see what the data looks like. But this statement reads the 8 bytes and prints them, then throws them away. So the original read() that follows will get the next 8 bytes of the file, which might not look right. File "C:\Python25\lib\struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 8" I reckon this part tries to import header information for shape data, which would be stored in C (?), and fails to "unpack" it in PYTHON. I've tried putting an "IF" to check whether f.read(8) was actually a string (type) and of length equal to 8. I still get the same error message. I've also tried skipping the "unpack" part altogther, not with much success. I'm really not too familiar with Python, si if anyone could help me out with this, I'd be really grateful. You should supply a link to the pyshp so that people who are willing to install it, will be sure to get the same one you did. Likewise any other environmental data about your system. I can tell you're running Python 2.5 on some Windows system, but it'd be nice if you just said so. Other thoughts: If there's any binary data in that file, you might need to open it with a "b" mode. Without it Windows will convert crlf into linefeeds, which you don't want to do if it's binary data. We don't see your open here, so who knows? -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8"
On Fri, Feb 3, 2012 at 10:46 AM, Simeon Tesfaye < simeon.tesf...@eaudeparis.fr> wrote: > Hello everyone, > > I am having a bit of trouble here with my code, which uses a shapefile > library, named pyshp, to import, edit, and save GIS files within Python. > So, I open up my shapefile (data is polylines, meaning, not points or > polygons) > "shapefile=shapefile.Reader("file.shp") > shps=shapefile.shapes() > shprec = shapefile.records() > " > Then I carry out some edits, and I save my file. > When I want to open it again, within the same script, in order to access > some of the data I just modified, I get this message : > > "Traceback (most recent call last): > File "", line 1, in > troncop=troncon.shapes() > File "C:\Python25\Lib\shapefile.py", line 310, in shapes > while shp.tell() < self.shpLength: > File "C:\Python25\Lib\shapefile.py", line 222, in __shape > print(f.read(8)) > File "C:\Python25\lib\struct.py", line 87, in unpack > return o.unpack(s) > error: unpack requires a string argument of length 8" > > > I reckon this part tries to import header information for shape data, > which would be stored in C (?), and fails to "unpack" it in PYTHON. > > I've tried putting an "IF" to check whether f.read(8) was actually a > string (type) and of length equal to 8. I still get the same error message. > I've also tried skipping the "unpack" part altogther, not with much > success. > > I'm really not too familiar with Python, si if anyone could help me out > with this, I'd be really grateful. > > Thanks in advance, > > S.T. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > All that this error means is that you have an array longer than the number of values that you are assigning to it. I.E: array = [1, 2, 3] a, b = array This causes an error since there are too many values in the array. To fix this, just change the second line to: a, b = array[:2] in my example. -- My Blog - Defenestration Coding http://defenestrationcoding.wordpress.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue with a shapefile (ArcGIS) library (pyshp) "unpack requires a string argument of length 8"
Hello everyone, I am having a bit of trouble here with my code, which uses a shapefile library, named pyshp, to import, edit, and save GIS files within Python. So, I open up my shapefile (data is polylines, meaning, not points or polygons) "shapefile=shapefile.Reader("file.shp") shps=shapefile.shapes() shprec = shapefile.records() " Then I carry out some edits, and I save my file. When I want to open it again, within the same script, in order to access some of the data I just modified, I get this message : "Traceback (most recent call last): File "", line 1, in troncop=troncon.shapes() File "C:\Python25\Lib\shapefile.py", line 310, in shapes while shp.tell() < self.shpLength: File "C:\Python25\Lib\shapefile.py", line 222, in __shape print(f.read(8)) File "C:\Python25\lib\struct.py", line 87, in unpack return o.unpack(s) error: unpack requires a string argument of length 8" I reckon this part tries to import header information for shape data, which would be stored in C (?), and fails to "unpack" it in PYTHON. I've tried putting an "IF" to check whether f.read(8) was actually a string (type) and of length equal to 8. I still get the same error message. I've also tried skipping the "unpack" part altogther, not with much success. I'm really not too familiar with Python, si if anyone could help me out with this, I'd be really grateful. Thanks in advance, S.T. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] any cons to using a module of functions?
On 03/02/12 05:05, Che M wrote: is very bad form and I should refactor, and so I am beginning to put these functions in their own module so that I can import the module and its functions when I need it; they will all be in one place and only only place. While that's tempting it is better if you use multiple modules such that the functions in them are related in some way. A single mixed bag of functions will eventually become messy to maintain. Even if some modules only contain a single function its a lot clearer than having a "bag of bits" My question is about resources. Let's say I have the module, myUtils.py, and I import it into every other module that will need one or more of the functions within it. Is this in any way costly in terms of memory? Not really, Python creates one instance of the module and all the importing modules refer to that instance. The only way it's wasteful is if you have 20 functions and only need two then you have 18 function objects that you don't need. (see the point above about multiple modules!) But even then the memory usage is unlikely to be a major issue since 18 function objects will generally consume minimal memory on a modern PC. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] any cons to using a module of functions?
Che M wrote: > > I have a bunch of functions that do various utility-type tasks in an > application (such as prettifying date strings, etc.), and they are used in > many modules. Much of the time, I have just been lazily copying and > pasting the functions into whichever modules need them. I realize that is > very bad form and I should refactor, and so I am beginning to put these > functions in their own module so that I can import the module and its > functions when I need it; they will all be in one place and only only > place. > > My question is about resources. Let's say I have the module, myUtils.py, > and I import it into every other module that will need one or more of the > functions within it. Is this in any way costly in terms of memory? > (since each time I import myUtils.py I import *all* the functions, instead > of in the cut&paste approach, where I just run the functions I need). I hope by "importing all functions" you mean import myutils or from myutils import foo, bar The oh-so-convenient from myutils import * will sooner or later result in nasty name clashes. > I'm fairly sure this is not at all an issue, but I just want to understand > why it's not. After entering the interactive interpreter (Python 2.7) I see >>> import sys >>> len(sys.modules) 39 >>> len(sys.builtin_module_names) 20 So there are already forty or sixty modules, depending on how you count; the memory and runtime impact of adding one more is likely negligable. There is an effect on your processes. If you hammer up a quick and dirty script using your kitchen-sink myutils.py, then forget the script, and in a year or so need it again it's likely that myutils have evolved and your script will not work out of the box. At that point it will start to pay off having unit tests in place that ensure a stable api and to put everything into version control. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor