Re: [Tutor] Import Modules
On Wed, Apr 15, 2009 at 6:57 PM, Alan Gauld wrote: > When you import you import names, in the first case webapp. > Where the name is a package (ie a folder) that gives you access > to the modules (or sub packages) contained in that folder but > not to the contents of those items directly, hence the need for > webapp.util. In general, importing a package does not give access to members of a sub-package. You have to explicitly import the subpackage. For example, In [1]: import xml In [2]: xml.dom.Node --- AttributeErrorTraceback (most recent call last) /Users/kent/ in () AttributeError: 'module' object has no attribute 'dom' In [3]: import xml.dom In [4]: xml.dom.Node Out[4]: There are some exceptions, notably os.path: In [5]: import os In [6]: os.path Out[6]: but that is a special case and requires special coding in the os module. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
Ronald - I really encourage you to try to embrace some of the basic Python idioms as part of your Java->Python journey: 1. Iterators for item in list_of_items: # do something with item Is all that is needed to visit each item in a Python list. Your verbose MoveFirst, MoveNext, if more <> None, etc. is completely subsumed into the built-in machinery Python has for iterators. (4-space source indent is also the norm.) 2. Static typing Change that snippet to: def visit_each_item(collection): for item in collection: # do something with item, like printing its name And this code works for lists, tuples, and sets of items, or dicts with items as keys (assuming an item is hashable). (The old method would accept non-lists, too, but naming a parameter 'list_of_items' sounds like only lists are intended.) And the items in the list/tuple/set/whatever don't even have to be all the same type, as long as they all support the concept of "doing something". Such as: def print_each_items_name(collection): for item in collection: print item.name The Java approach is to define an interface called Nameable (or INameable?), with methods GetName and SetName. You want to talk about self-maintaining code? I wrote code like this before sets were even added to the language definition, and when this new data type came along, my code library handled it without changing a single line! Good thing that I didn't try to hack in some hare-brained run-time type safety like: if isinstance(collection,(list,tuple,dict)): for item in collection: ... blah blah... Or I would have to chase down all such code and add 'set' to the list. 3. Interfaces Interfaces are there to allow compilers to verify that a static data type will comply with an interface's requirements at runtime. Python skips this and just does the runtime check - if the object does not have the necessary attribute (and methods are just callable attributes), then an AttributeError gets thrown. If you have a design that calls for inheritance from a pure virtual abstract base class, then in Python, that base class is completely unnecessary. Sometimes in my code I will still include such a base class, for purposes of documentation or to help me remember later what the heck was I thinking? But such a thing is for my benefit, not Python's. 4. Getters and Setters This is such a fundamental dogma for Java developers that it may be difficult for you to let go. But do so, please! Assume that rootTag in your XMLExporter is a public variable, which you later must change to a method call (maybe to ensure that the given tag is actually a kosher XML tag string, and not something like "123...@^^!!!") - this is where the Python property allows you to map set and get access to an attribute through a pair of methods, while external code continues to access the property by its public name, "rootTag". No additional refactoring or recoding or recompiling necessary. Meanwhile, you can trim significant fat of "just in case I need to make this a method someday" code from your classes, and just use the attributes directly. 5. New concepts in Python Python has some exciting features related to its built-in support for collections that makes creating and working with them a dream. Read up on list comprehensions, generator expressions, iterators, and generators. You won't need them right away, but the sooner you get them, the sooner you'll be able to dump verbose (and slow!) code like: return_list = [] for blah in somecollection: return_list.append(something_about(blah)) and write: return_list = [something_about(blah) for blah in somecollection] Not only is this more compact and concise, it also runs faster. Also, learn about zip and itertools - these will make your programs just fly. Please try to hold off on the Newbie's Hubris. The code that you posted doesn't really present anything novel, or particularly awesome. Instead, think about this: class ApplicationClass(object): # objects of this class have no attributes - yet! pass def makeExportable(obj, exporter): obj.exporter = exporter a = ApplicationClass() makeExportable(a, SQLExporter) Now I have added exportability to an instance, without changing the class at all. This might even be a class from a 3rd party lib, whose source code I don't even have! Welcome to Python, but check your Java baggage at the door! -- Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
"Emile van Sebille" wrote Redundant, yes; syntax error, no. IIRC, semi-colons are optional line terminators. statement terminators I think. ie you can have several statements on a line by separating with semicolons: x=5; print x+2 7 Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
"Weidner, Ronald" wrote # This code is posted for the purpose of conversation. If it is of some # value to someone that would be great. But what I hope is that the code # sparks conversations about what I did in this code and why I did it. Since # the list seems thick with OOP questions at the moment, I thought this might # be relevant. Digest and enjoy. Some fairly quick comments based on an initial scan: class Item ( object ): Its good to put some documentation strings describing the purpose of the class, same for the methods. def __init__( self ): self._FullName = '' self._Recovery = 0 self._Exporter = SimpleItemExporter (); Why not make these default values of parameters? That then gives the clients the chance to initialise the values at instantiation time. class SimpleItemExporter ( object ): def __init__( self ): pass This does nothing, you do not need an __init__ if its not used. class XMLExporter ( object ): def __init__ ( self, tag='XML' ): self.SetRootTag( tag ) Nothing wrong with doing direct assignment inside a method. class SQLExporter ( object ): def __init__ ( self, tableName): self._TableName = tableName Which you do here! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Import Modules
"Giorgio Bonfiglio" wrote from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app The first line imports the webapp subpackage (that is not actually a module, it's a subdirectory with some .py files into). So why do i need to import the specific function in the second line? Does'nt it get imported in the first? The webapp name will get imported but to reach the function you would need to use webapp.util.run_wsgi_app Somebody decided that was too close to hard work so they imported that specific function. When you import you import names, in the first case webapp. Where the name is a package (ie a folder) that gives you access to the modules (or sub packages) contained in that folder but not to the contents of those items directly, hence the need for webapp.util. You could just use the long name each time but the direct import makes for shorter coding, especially if you use the function a lot. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
1. Python is not Java (see Philip Eby's blog entry http://dirtsimple.org/2004/12/python-is-not-java.html). Let go of your concepts that only Items can go into an ItemCollection - Python already has some perfectly good collection builtins. Instead of writing a custom ItemCollection, why not write a generic Exporter that takes any Python sequence (such as a list, set, tuple, etc., anything that supports iter)? 2. SQLExporter does not use recommended form for substituting values into an SQL statement. It is preferred that one use the 2-argument form of execute, in which the first argument contains '?' or '%s' placeholders, and the second argument is a tuple of values. That is, instead of: first, last = "Bobby", "Tables" cursor.execute("INSERT into STUDENT (firstname, lastname) values ('"+first+"','"+last+"')") Do: first, last = "Bobby", "Tables" cursor.execute("INSERT into STUDENT (firstname, lastname) values (?,?)", (first,last)) No need for wrapping in quotes, already handles values with embedded quotes, and no SQL injection jeopardy (http://xkcd.com/327/). This slightly complicates your SQL exporter, it would have to return a tuple containing the INSERT statement and the tuple of substitution values, instead of just a string to be passed to execute. 3. The Pythonic way to create a comma-separated string of values from a list of strings is: ','.join(value_list). If you have a list of tuples and want two comma-separated strings, do: keystring, valstring = (','.join(s) for s in zip(*key_value_tuple_list)) 4. While I am not a slave to PEP8, your mixed case method names with leading capitals look too much like class names and/or .Net method names. In general, I find your approach too intrusive into the objects you would like to export or load. I would prefer to see a Loader and/or Exporter class that takes my own application object, configured with table name and field names, and then creates the proper XML or SQL representation. -- Paul In the future, I'll try not to have a Java accent when speaking Python. ( No guarantee though :) ) That said, thanks for the syntax tips and Python preferred snips. One of your points represents a great opportunity to make mine. Suppose this code is several years old. Now we have a new requirement that states we need to work with the data as you described above. How much of the existing code would you have to change to make that change happen? The answer is exactly one line. And here is the line... exporter = SQLExporter("itemTable") And you would change the line to something like... exporter = SQLTupleExporter("itemTable") or perhaps... exporter = ExportItemToDatabase('127.0.0.1', 'user', 'pass', 'schema') Of course, you would need to define a class to go along with your change but all of that will be NEW code. Not a change to existing code. So, all of your existing code should still be valid and tested. The only thing you'll need to do validate and test your new code. There are no tentacles. Replacing exporter with a different kind of exporter does not invalidate anything you've done in your code before. Awesome. Maybe you need to do both? Maybe you need to export the old way, and export the new way. How difficult would that be with 2 export objects? In this case, you wouldn't need to change any lines of code, but rather you would add 2 more lines to the main logic and implement the needed class. It's really just a strategy for creating maintainable code. Maybe It's a good strategy, maybe it isn't. I guess it would depend on the project. I find the technique interesting and useful. -- Ronald Weidner ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] colours in IDLE
"mbikinyi brat" wrote When you type a code in IDLE-Python, they appear in different colours. For instance: factorial in blue and return and else and result in red. Any significance to these colours? Yes, they indicate different syntactic features. You can change them and see what they are for by looking at the configuration screens, the Highlighting tab. There is a drop down list that will show you what can be coloured. This is a useful tool since it can show an unterminated string (ie where you forgot the closing quote), or where you accidentally use a keyword as a variable name etc -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
>> i think it's a common style guideline in multiple >> languages i'm familiar with (other than Python) to Capitalize class >> names but keep variables, functions, and methods all lowered. > > In most cases I know, class names are capitalized, while func and method > names are camel-cased: > ThisKlass this is indeed called "CamelCased". > thisFunc this is called "mixedCase". an all-lowered alternative is "lower_case_with_underscores," as in 'this_func'. PEP8 seems to lean towards the latter over the former, altho i use both and also do not stay strict to it. here's the link if you're curious: http://www.python.org/dev/peps/pep-0008/ cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
Le Wed, 15 Apr 2009 12:20:20 -0700, wesley chun s'exprima ainsi: > i think it's a common style guideline in multiple > languages i'm familiar with (other than Python) to Capitalize class > names but keep variables, functions, and methods all lowered. In most cases I know, class names are capitalized, while func and method names are camel-cased: ThisKlass thisFunc Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
I must confess I do not really understand your intent (a) with the code itself (b) with the fact of publishing it Maybe I have read it too fast. What I saw is an implementation of strict object interface, in the sense strictly separating the inner and outer parts of an object. Sure, this is an aspect of OO. But AFAIK this is not very pythonic, not very common at least (and I personly do not feel attracted by this coding style -- rather I consider it a useless overload). For code security reasons? You may be interested in the concepts of the so-called "Object-capability model": http://en.wikipedia.org/wiki/Object_capability_model. -- It's ok not to be attracted to the code or the concept. It's not for everyone (or perhaps it's not for anyone). Thanks for the link. That was an interesting read. Let me confess my intentions. I enjoy programming and I also enjoy talking about programming, and sharing ideas. That's it. The problem that coding in this style tries to solve is change and evolution. During the evolution of software many things can change. Including the things we sometimes take for granted when we start a project. Like the input and output of the program. This example shows how cobbling a few objects together can produce some very different results with very little logic change. There are better more generic ways to solve these problems. Probably even more pythonic ways to solve them. I hope to discuss them in this thread. -- Ronald Weidner ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
> 1. Python is not Java although i agree with all 4 points that paul makes, this 1st one stands out the most. when i saw the code the first time, the immediate thought that came to my mind was, "This looks like Java code written with Python syntax." i thing the same functionality can be accomplished using half or a third of the total # of lines of code originally presented. > 2. SQLExporter does not use recommended form for substituting values into an SQL statement. yes, in addition to the "preferred" feeling, it will also help mitigate SQL injection attacks. this code looks like Java + JS. creating strings with few operations helps with performance too, as in... > 3. The Pythonic way to create a comma-separated string of values from a list of strings is: ','.join(value_list). >: > 4. While I am not a slave to PEP8, your mixed case method names with leading capitals look too much like class names and/or .Net method names. also agreed. i think it's a common style guideline in multiple languages i'm familiar with (other than Python) to Capitalize class names but keep variables, functions, and methods all lowered. well, the OP was right... it has indeed led to some discussion on the list! cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
1. Python is not Java (see Philip Eby's blog entry http://dirtsimple.org/2004/12/python-is-not-java.html). Let go of your concepts that only Items can go into an ItemCollection - Python already has some perfectly good collection builtins. Instead of writing a custom ItemCollection, why not write a generic Exporter that takes any Python sequence (such as a list, set, tuple, etc., anything that supports iter)? 2. SQLExporter does not use recommended form for substituting values into an SQL statement. It is preferred that one use the 2-argument form of execute, in which the first argument contains '?' or '%s' placeholders, and the second argument is a tuple of values. That is, instead of: first, last = "Bobby", "Tables" cursor.execute("INSERT into STUDENT (firstname, lastname) values ('"+first+"','"+last+"')") Do: first, last = "Bobby", "Tables" cursor.execute("INSERT into STUDENT (firstname, lastname) values (?,?)", (first,last)) No need for wrapping in quotes, already handles values with embedded quotes, and no SQL injection jeopardy (http://xkcd.com/327/). This slightly complicates your SQL exporter, it would have to return a tuple containing the INSERT statement and the tuple of substitution values, instead of just a string to be passed to execute. 3. The Pythonic way to create a comma-separated string of values from a list of strings is: ','.join(value_list). If you have a list of tuples and want two comma-separated strings, do: keystring, valstring = (','.join(s) for s in zip(*key_value_tuple_list)) 4. While I am not a slave to PEP8, your mixed case method names with leading capitals look too much like class names and/or .Net method names. In general, I find your approach too intrusive into the objects you would like to export or load. I would prefer to see a Loader and/or Exporter class that takes my own application object, configured with table name and field names, and then creates the proper XML or SQL representation. -- Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about
Le Wed, 15 Apr 2009 08:29:30 -0700, "Weidner, Ronald" s'exprima ainsi: > # This code is posted for the purpose of conversation. If it is of some > # value to someone that would be great. But what I hope is that the code > # sparks conversations about what I did in this code and why I did it. > Since # the list seems thick with OOP questions at the moment, I thought > this might # be relevant. Digest and enjoy. I must confess I do not really understand your intent (a) with the code itself (b) with the fact of publishing it Maybe I have read it too fast. What I saw is an implementation of strict object interface, in the sense strictly separating the inner and outer parts of an object. Sure, this is an aspect of OO. But AFAIK this is not very pythonic, not very common at least (and I personly do not feel attracted by this coding style -- rather I consider it a useless overload). For code security reasons? You may be interested in the concepts of the so-called "Object-capability model": http://en.wikipedia.org/wiki/Object_capability_model. Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
W W wrote: On Wed, Apr 15, 2009 at 12:27 PM, Carnell, James E mailto:jecarn...@saintfrancis.com>> wrote: Since # the list seems thick with OOP questions at the moment, I thought this might # be relevant. Digest and enjoy. class Item ( object ): def __init__( self ): self._FullName = '' self._Recovery = 0 self._Exporter = SimpleItemExporter (); # Don't understand First off, the semicolon is probably a syntax error. Redundant, yes; syntax error, no. IIRC, semi-colons are optional line terminators. ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. class Test: ... a=1; ... b=2; ... =Test() t.a 1 Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
On Wed, Apr 15, 2009 at 12:27 PM, Carnell, James E < jecarn...@saintfrancis.com> wrote: > Since # the list seems thick with OOP questions at the moment, I thought > this might # be relevant. Digest and enjoy. > > class Item ( object ): > >def __init__( self ): >self._FullName = '' >self._Recovery = 0 >self._Exporter = SimpleItemExporter (); # Don't > understand > > Bummer, I was hoping to consider myself at the tip of intermediate > python programming ... > > This is the first time I have ever seen a variable set to what appears > to be a function address(?). Since I am at work I can't copy paste this > thing yet. Is SimpleItemExporter from the parent class, object? I am > assuming Item extends or inherits (or whatever the right "word" is) from > object. First off, the semicolon is probably a syntax error. SimpleItemExporter is probably a class, but I don't think object is the parent. If you were trying to access something from object I'm fairly certain you'd use the dot operator, so it would be object.SimpleItemExporter() But if it's a class it would be a new instance of that class. Otherwise it doesn't make a lot of sense to have the parenthesis (unless SimpleItemExporter returns something useful... which it isn't named like it should). Consider the following: In [1]: def foo(): ...: print "Hello" ...: ...: In [2]: x = foo() Hello In [3]: x In [4]: x('a') --- TypeError Traceback (most recent call last) /home/wayne/ in () TypeError: 'NoneType' object is not callable In [5]: class foo: ...: def __init__(self, spam): ...: print spam ...: ...: In [7]: x = foo('eggs') eggs In [8]: x Out[8]: <__main__.foo instance at 0x9f0304c> In [9]: x() --- AttributeErrorTraceback (most recent call last) /home/wayne/ in () AttributeError: foo instance has no __call__ method In [10]: x.__init__('eggs') eggs --and--- In [11]: class spam: : def __init__(self, eggs): : lay(eggs) : def lay(x): : print x : : In [13]: class foo(spam): : def __init__(self, bar): : lay(bar) : : In [14]: x = foo('Ni') --- NameError Traceback (most recent call last) /home/wayne/ in () /home/wayne/ in __init__(self, bar) NameError: global name 'lay' is not defined - The above snippets seem to show what I stated before - SimpleItemExporter is a class on it's own - not a method/function in the object class. If that were the case then my class foo should have direct access to the lay function, AFAIK. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
"""But what I hope is that the code # sparks conversations about what I did in this code and why I did it.""" If anyone answers me thank you. really. Nevertheless, I am personally not pursuing to understand this code. Ronald Weidner left on vacation and won't be back until the 19th (I don't know French though). Maybe we should wait until then... == Bonjour, Je suis absente jusqu'au 19/04/09 inclus. Cordialement. Geneviève === ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
class Item ( object ): def __init__( self ): self._FullName = '' self._Recovery = 0 self._Exporter = SimpleItemExporter (); # Don't understand Bummer, I was hoping to consider myself at the tip of intermediate python programming ... This is the first time I have ever seen a variable set to what appears to be a function address(?). Since I am at work I can't copy paste this thing yet. Is SimpleItemExporter from the parent class, object? I am assuming Item extends or inherits (or whatever the right "word" is) from object. In the above code example, SimpleItemExporter is a class and Self._Exporter is an instance of that class. Yes, SimpleItemExporter does in fact inherit from object. Python lacks the 'new' keyword which may have made that line of code more clear but, in plain English this is what the line means... Create a new SimpleItemExporter and let me access it through the variable self._Exporter. By the way, I'm avoiding the notion of function address by implementing the concept of interfaces in these examples. Please Let us know if your questions about that line of code are answered. Once clear, we can move on to even more cool things in this code. There is a little more to the story relating to the whole self bit, but since I'm at work now too, I'll let someone else get into that for now. -- Ronald Weidner ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Here's something to talk about (Weidner, Ronald)
Since # the list seems thick with OOP questions at the moment, I thought this might # be relevant. Digest and enjoy. class Item ( object ): def __init__( self ): self._FullName = '' self._Recovery = 0 self._Exporter = SimpleItemExporter (); # Don't understand Bummer, I was hoping to consider myself at the tip of intermediate python programming ... This is the first time I have ever seen a variable set to what appears to be a function address(?). Since I am at work I can't copy paste this thing yet. Is SimpleItemExporter from the parent class, object? I am assuming Item extends or inherits (or whatever the right "word" is) from object. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regular expression problem
After he said that...I realized where I was being dumb... On Wed, Apr 15, 2009 at 10:29 AM, bob gailer wrote: > Spencer Parker wrote: > >> I have a python script that takes a text file as an argument. It then >> loops >> through the text file pulling out specific lines of text that I want. I >> have a regular expression that evaluates the text to see if it matches a >> >> specific phrase. Right now I have it writing to another text file that >> output. The problem I am having is that it finds the phrase prints it, >> but >> then it continuously prints the statement. There is only 1 entries in the >> >> file for the result it finds, but it prints it multiple times...several >> hundred before it moves onto the next one. But it appends the first one >> to >> the next entry...and does this till it finds everything. >> >> http://dpaste.com/33982/ >> >> >> Any Help? >> >> > > dedent the 2nd for loop. > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regular expression problem
Spencer Parker wrote: I have a python script that takes a text file as an argument. It then loops through the text file pulling out specific lines of text that I want. I have a regular expression that evaluates the text to see if it matches a specific phrase. Right now I have it writing to another text file that output. The problem I am having is that it finds the phrase prints it, but then it continuously prints the statement. There is only 1 entries in the file for the result it finds, but it prints it multiple times...several hundred before it moves onto the next one. But it appends the first one to the next entry...and does this till it finds everything. http://dpaste.com/33982/ Any Help? dedent the 2nd for loop. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] regular expression problem
I have a python script that takes a text file as an argument. It then loops through the text file pulling out specific lines of text that I want. I have a regular expression that evaluates the text to see if it matches a specific phrase. Right now I have it writing to another text file that output. The problem I am having is that it finds the phrase prints it, but then it continuously prints the statement. There is only 1 entries in the file for the result it finds, but it prints it multiple times...several hundred before it moves onto the next one. But it appends the first one to the next entry...and does this till it finds everything. http://dpaste.com/33982/ Any Help? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Here's something to talk about
# This code is posted for the purpose of conversation. If it is of some # value to someone that would be great. But what I hope is that the code # sparks conversations about what I did in this code and why I did it. Since # the list seems thick with OOP questions at the moment, I thought this might # be relevant. Digest and enjoy. class Item ( object ): def __init__( self ): self._FullName = '' self._Recovery = 0 self._Exporter = SimpleItemExporter (); def SetFullName( self, name ): self._FullName = name def SetRecovery( self, value ): self._Recovery = value def SetExporter( self, exporter ): self._Exporter = exporter def Export( self ): properties = { 'FullName':self._FullName, 'Recovery':self._Recovery } self._Exporter.Export( properties ) class ItemCollection( object ): def __init__( self ): self._ItemList = [] self._CollectionIndex = -1 self._Loader = None def Add ( self, item ): self._ItemList.append(item) def MoveFirst ( self ): self._CollectionIndex = -1 def MoveNext ( self ): self._CollectionIndex += 1 if self._CollectionIndex < ( len ( self._ItemList ) ): return self._ItemList[ self._CollectionIndex ] return None def MoveTo ( self, index ): pass def GetLength ( self ): pass def SetCollectionLoader ( self, loader ): self._Loader = loader def Load ( self ): if self._Loader <> None: self._Loader.LoadCollection(self) class SimpleItemExporter ( object ): def __init__( self ): pass def Export ( self, dictionary ): print "The recovery status of " +str(dictionary['FullName'])+ " is: " + str(dictionary['Recovery']) class XMLExporter ( object ): def __init__ ( self, tag='XML' ): self.SetRootTag( tag ) def SetRootTag ( self, tag ): self._RootTag = tag; def Export ( self, dictionary ): xml = "" keys = dictionary.keys() for key in keys: xml = xml + "\n\t<" + key + ">" + str(dictionary[key]) + "" print "<" + self._RootTag + ">" + xml + "\n" class SQLExporter ( object ): def __init__ ( self, tableName): self._TableName = tableName def Export ( self, dictionary ): value = "" field = "" first = 1 keys = dictionary.keys() for key in keys: if first <> 1: field = field + ", " value = value + ", " field = field + " " + key value = value + "'" + str(dictionary[key]) + "'" first = 0 print "INSERT into " + self._TableName + " (" + field + ") values (" + value + ")" class ItemCollectionLoader ( object ): def LoadCollection(self, collection): for i in range ( 1, 5 ): item = Item() item.SetFullName( 'Ron The Dude' ) item.SetRecovery( i ) collection.Add( item ) more = 1 collection = ItemCollection() # here we create a loader obbject loader = ItemCollectionLoader() # this loader object could do other things instead of the contrived example # shown here. Such as the loader object could read from a file, or a network # resource, stdin, whatever. As long as it's LoadCollection interface doesn't # change the object could be many things. I've decided to illustrate this concept # later in the code with the exporter object. collection.SetCollectionLoader(loader) collection.Load() collection.MoveFirst while more <> None: item = collection.MoveNext () if item <> None: # What's important here to note is that the exporter may have different # constructors but, the Export method takes the same arguments in each # export class. In other words, it's interface is the same. So, we # can easily switch one exporter object for another. With a little more # code you could even export these items in more than one format (if needed). #exporter = SimpleItemExporter() #
[Tutor] Import Modules
Hi, hope this mailing list is still active. I'm learning phyton. I can write simple programs, and i've studied all examples provided by the Google App Engine Documentation. As i understood, i can import a module using something like: import modulename Or, import a specific function, using: from modulename import functionname Ok, now let's look at the first example provided by google: http://code.google.com/intl/it-IT/appengine/docs/python/gettingstarted/usingwebapp.html I can see those lines: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app The first line imports the webapp subpackage (that is not actually a module, it's a subdirectory with some .py files into). So why do i need to import the specific function in the second line? Does'nt it get imported in the first? Thankyou for your help. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python books
On Wed, Apr 15, 2009 at 4:45 AM, Wayne Watson wrote: > It's unlikely you are going to find a pdf on Python that's suitable for > beginners. Do you mean pdf or a digital book? There are Python books in > digital form on the web. I'm not quite sure how it works, but I know of at > least one public library has them. I think it works that if you have a > library card, then you can get web access to read the book on-line. I think > this operates at a college level too. > Snake Wrangling for Kids is a perfectly good pdf for beginners (both to programming and python). I'd say the same about Think like a computer scientist - http://www.greenteapress.com/thinkpython/thinkpython.html But maybe that's just me :P -Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for starter projects
On Wed, Apr 15, 2009 at 3:50 AM, Evert Edel wrote: > Hi all, > > Now since I've got the learning python book I first did a quick read trough > it and now I'm going more slowly trough it and doing all the explained > things (in the interactive prompt). I do understand the basics behind OOP > and I'm wanting to start some smaller projects using the book as a reference > to get my hands on python. It seems to me that it's better to learn it with > smaller projects (and evolving with those). That's probably a fairly good idea... I would guess that most of us learned the same way, or at least in similar ways. > > But I really don't know what smaller projects would be good to start on as > beginner. I've got some ideas but those are more advanced (making a mpd > client, some website ideas). > > I hope you can give me some starting projects to learn python :). > Well, what do you enjoy? That's really probably the best way to program - when you program things you enjoy you tend to be more likely to stick with it. Do you like games? Maybe you could program a tic-tac-toe game. Or a guessing game. Do you like math? Perhaps you could write programs that will do certain math functions for you (Like the Fibonacci series, computing area, maybe even doing some calculus). Do you like drawing pictures? If you use Tkinter or the turtle module you could write some programs to do that. Maybe you could try writing your name, first in block, then in script (actually the script would end out rather complicated, but certainly fun[if that's what you enjoy]!) And of course, if you get stuck anywhere and need some help, we're always willing to help point you in the right direction. Good luck! HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sorting file paths made up of of strings and numbers
On Tue, Apr 14, 2009 at 10:36 PM, Bill Campbell wrote: > On Tue, Apr 14, 2009, Emad Nawfal ( ) wrote: > > > > Hi tutors, > > How can I sort the following list in a way that takes care of the > > right order of numbers? The sorted function compares strings here as > > far as I can see, but I want to have filepath2 follow filepath1. Your > > help is appreciated. > > There is at least one example of a method of dealing with this in > the O'Reilly ``Python cookbook''. > > > >>> myList > > ['filepath54', 'filepath25', 'filepath49', 'filepath0', 'filepath89', > > 'filepath52', 'filepath37', 'filepath32', 'filepath2', 'filepath15', > > 'filepath88', 'filepath70', 'filepath33', 'filepath58', 'filepath28', > > 'filepath61', 'filepath23', 'filepath64', 'filepath72', 'filepath11', > > 'filepath63', 'filepath76', 'filepath87', 'filepath45', 'filepath41', > > 'filepath68', 'filepath81', 'filepath75', 'filepath62', 'filepath46', > > 'filepath36', 'filepath39', 'filepath5', 'filepath34', 'filepath8', > > 'filepath67', 'filepath14', 'filepath82', 'filepath29', 'filepath47', > > 'filepath79', 'filepath13', 'filepath16', 'filepath71', 'filepath27', > > 'filepath100', 'filepath20', 'filepath92', 'filepath57', 'filepath73', > > 'filepath40', 'filepath44', 'filepath83', 'filepath50', 'filepath66', > > 'filepath94', 'filepath86', 'filepath22', 'filepath17', 'filepath84', > > 'filepath38', 'filepath12', 'filepath53', 'filepath6', 'filepath48', > > 'filepath60', 'filepath51', 'filepath90', 'filepath4', 'filepath78', > > 'filepath69', 'filepath35', 'filepath97', 'filepath93', 'filepath24', > > 'filepath26', 'filepath1', 'filepath3', 'filepath96', 'filepath77', > > 'filepath98', 'filepath18', 'filepath43', 'filepath19', 'filepath56', > > 'filepath65', 'filepath95', 'filepath55', 'filepath7', 'filepath99', > > 'filepath91', 'filepath85', 'filepath9', 'filepath59', 'filepath10', > > 'filepath30', 'filepath31', 'filepath80', 'filepath42', 'filepath74', > > 'filepath21'] > > >>> sorted(myList) > > ['filepath0', 'filepath1', 'filepath10', 'filepath100', 'filepath11', > > 'filepath12', 'filepath13', 'filepath14', 'filepath15', 'filepath16', > > 'filepath17', 'filepath18', 'filepath19', 'filepath2', 'filepath20', > > 'filepath21', 'filepath22', 'filepath23', 'filepath24', 'filepath25', > > 'filepath26', 'filepath27', 'filepath28', 'filepath29', 'filepath3', > > 'filepath30', 'filepath31', 'filepath32', 'filepath33', 'filepath34', > > 'filepath35', 'filepath36', 'filepath37', 'filepath38', 'filepath39', > > 'filepath4', 'filepath40', 'filepath41', 'filepath42', 'filepath43', > > 'filepath44', 'filepath45', 'filepath46', 'filepath47', 'filepath48', > > 'filepath49', 'filepath5', 'filepath50', 'filepath51', 'filepath52', > > 'filepath53', 'filepath54', 'filepath55', 'filepath56', 'filepath57', > > 'filepath58', 'filepath59', 'filepath6', 'filepath60', 'filepath61', > > 'filepath62', 'filepath63', 'filepath64', 'filepath65', 'filepath66', > > 'filepath67', 'filepath68', 'filepath69', 'filepath7', 'filepath70', > > 'filepath71', 'filepath72', 'filepath73', 'filepath74', 'filepath75', > > 'filepath76', 'filepath77', 'filepath78', 'filepath79', 'filepath8', > > 'filepath80', 'filepath81', 'filepath82', 'filepath83', 'filepath84', > > 'filepath85', 'filepath86', 'filepath87', 'filepath88', 'filepath89', > > 'filepath9', 'filepath90', 'filepath91', 'filepath92', 'filepath93', > > 'filepath94', 'filepath95', 'filepath96', 'filepath97', 'filepath98', > > 'filepath99'] > > >>> ``` > > -- > > áÇ ÃÚÑÝ ãÙáæãÇ ÊæÇØà ÇáäÇÓ Úáí åÖãå æáÇ ÒåÏæÇ Ýí ÅäÕÇÝå > > ßÇáÍÞíÞÉ.ãÍãÏ ÇáÛÒÇáí > > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > > Indiana University, Bloomington > > > > >___ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > -- > Bill > -- > INTERNET: b...@celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > Voice: (206) 236-1676 Mercer Island, WA 98040-0820 > Fax:(206) 232-9186 Skype: jwccsllc (206) 855-5792 > > An almost hysterical antagonism toward the gold standard is one issue which > unites statists of all persuasions. They seem to sense that gold and > economic freedom are inseparable. -- Alan Greenspan > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Thank you Kent and Bill. This is much easier than itemgetter. -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -
Re: [Tutor] OOP
On Wed, Apr 15, 2009 at 3:43 AM, mbikinyi brat wrote: > Dear ALL, > I am a python beginner and has never programmed and has been struggling to > understand how to create objects or classes in python. Can anyone help with > any concrete example. I have read most recommended textbooks but still have > difficulties figuring what it is all about. Any tutorial should contain simple examples of how to create classes. If you are struggling with *why* to create classes you might like this essay, which gives several reasons why you might want to start using classes in a design, with examples from the standard library: http://personalpages.tds.net/~kent37/stories/00014.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] colours in IDLE(How does the interpreter knows the meaning of factorial)
Hi, <> On Wed, Apr 15, 2009 at 7:41 PM, mbikinyi brat wrote: > Dear Oxymoron, > In my previous example I had to import math for it to work . But in this > code with the factorial, I have not imported anything yet when I call it > with factorial(5), I get the result. How is this possible? In this example, you're not using anything from an external module like math, your code is self-contained, so you did not have to import anything. Earlier you called math.pi - math is a module that's part of standard Python, but still needs to be imported, it is external to your file. > Regards, > Henry > > --- On Wed, 4/15/09, Oxymoron wrote: > > From: Oxymoron > Subject: Re: [Tutor] colours in IDLE > To: tutor@python.org > Date: Wednesday, April 15, 2009, 5:36 AM > > Hi, > > On Wed, Apr 15, 2009 at 7:29 PM, mbikinyi brat > wrote: >> Dear ALL, >> When you type a code in IDLE-Python, they appear in different colours. >> For instance: >> def factorial(n): >> if n==0: >> return 1 >> else: >> recurse=factorial(n-1) >> result=n*recurse >> return result >> factorial in blue and return and else and result in red. >> Any significance to these colours? >> > > That's called "syntax-highlighting", it basically allows you to read > the code clearer. Different Python language constructs are given > appropriate colours. I don't use IDLE myself, but in your example, > 'factorial' - is a function name - an identifier in general, that's > assigned one colour, whereas 'def', 'else', 'return' are Python > keywords - you cannot use these as identifiers - they're assigned yet > another colour. Keywords, braces, operators, identifiers - these > constitute the 'syntax' of Python. Hence using colours highlights the > syntax so it's easier to read -- syntax-highlighting ;-). > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- There is more to life than increasing its speed. -- Mahatma Gandhi ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python books
It's unlikely you are going to find a pdf on Python that's suitable for beginners. Do you mean pdf or a digital book? There are Python books in digital form on the web. I'm not quite sure how it works, but I know of at least one public library has them. I think it works that if you have a library card, then you can get web access to read the book on-line. I think this operates at a college level too. Consider Python for Absolute Beginners. If you are pressed for money, go to a college bookstore and see if you can find it used, probably $18 USD used (I know by experience! I do not own it or have done much more than browse a few pages of it.). I know of one university here that uses it. It is not likely that it would be used for a computer science (CS) classes, but I suspect there are students there in non-CS classes who might need to use Python. For example, engineers, math-majors, elementary statistics classes, and even upper-level astronomy classes. One can often get a good sense of a book by going to Amazon. They have a Look-Inside feature that allows you to browse parts of many books. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet All the neutrons, and protons in the human body occupy a cube whose side is 5.52*10**-6 meters (tiny!). That adds up to a 150 pound person. It's not a surprise that we are mostly space. (Calculation by WTW) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] colours in IDLE
Hi, On Wed, Apr 15, 2009 at 7:29 PM, mbikinyi brat wrote: > Dear ALL, > When you type a code in IDLE-Python, they appear in different colours. > For instance: > def factorial(n): > if n==0: > return 1 > else: > recurse=factorial(n-1) > result=n*recurse > return result > factorial in blue and return and else and result in red. > Any significance to these colours? > That's called "syntax-highlighting", it basically allows you to read the code clearer. Different Python language constructs are given appropriate colours. I don't use IDLE myself, but in your example, 'factorial' - is a function name - an identifier in general, that's assigned one colour, whereas 'def', 'else', 'return' are Python keywords - you cannot use these as identifiers - they're assigned yet another colour. Keywords, braces, operators, identifiers - these constitute the 'syntax' of Python. Hence using colours highlights the syntax so it's easier to read -- syntax-highlighting ;-). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] colours in IDLE
Dear ALL, When you type a code in IDLE-Python, they appear in different colours. For instance: def factorial(n): if n==0: return 1 else: recurse=factorial(n-1) result=n*recurse return result factorial in blue and return and else and result in red. Any significance to these colours? Regards, Henry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calculate area of a circle
Hi, On Wed, Apr 15, 2009 at 6:52 PM, mbikinyi brat wrote: > Hi All, > This is a code I have written to calculate the area of a circle. > def area(radius): > temp=math.pi*radius**2 > return temp > > I now call it by entering area(12) at the prompt in IDLE. This is the error > message I get. Can someone help please? > Traceback (most recent call last): > File "", line 1, in > area(10) > File "", line 2, in area > temp=math.pi*radius**2 > NameError: global name 'math' is not defined You need to import the 'math' module to use its member pi. Prior to using the module (e.g. before typing in the area function), type: import math Lookup modules for more info (e.g. http://docs.python.org/tutorial/modules.html). -- K ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] calculate area of a circle
you need import math On Wed, Apr 15, 2009 at 2:22 PM, mbikinyi brat wrote: > Hi All, > This is a code I have written to calculate the area of a circle. > *def area(radius): > temp=math.pi*radius**2 > return temp* > ** > *I* now call it by entering *area(12)* at the prompt in IDLE. This is the > error message I get. Can someone help please? > *Traceback (most recent call last): > File "", line 1, in > area(10) > File "", line 2, in area > temp=math.pi*radius**2 > NameError: global name 'math' is not defined* > ** > Regards, > Henry > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cheers, Vishwajeet http://www.singhvishwajeet.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Looking for starter projects
Hi all, This is my first post to this tutor list, so I hope you'll all get this message :). I've bought last year a book on python programming (Learning python from O'Reilly) to get started with python. I'm wanting to learn python for two purposes: learning some webdevving (with django?) and being able to write some smaller programs. Now since I've got the learning python book I first did a quick read trough it and now I'm going more slowly trough it and doing all the explained things (in the interactive prompt). I do understand the basics behind OOP and I'm wanting to start some smaller projects using the book as a reference to get my hands on python. It seems to me that it's better to learn it with smaller projects (and evolving with those). But I really don't know what smaller projects would be good to start on as beginner. I've got some ideas but those are more advanced (making a mpd client, some website ideas). I hope you can give me some starting projects to learn python :). Thanks in advance, Evert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] calculate area of a circle
Hi All, This is a code I have written to calculate the area of a circle. def area(radius): temp=math.pi*radius**2 return temp I now call it by entering area(12) at the prompt in IDLE. This is the error message I get. Can someone help please? Traceback (most recent call last): File "", line 1, in area(10) File "", line 2, in area temp=math.pi*radius**2 NameError: global name 'math' is not defined Regards, Henry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOP
"mbikinyi brat" wrote I am a python beginner and has never programmed Welcome to the tutor list. and has been struggling to understand how to create objects or classes in python. Can anyone help with any concrete example. Most tutorials have examples of classes and objects. Certainly mine does. There is an example in the Raw Data topic (with a sidebar at the end explaining it line by line) There is also a more detailed explanatyioon in the OOP topic in the Advanced section Here is one example: # define a class class Message: def __init__(self, msg=""): self.text = msg def show(self): print self.text # create some objects m1 = Message("Hello world") m2 = Message("Goodbye!") m3 = Message() # send the objects a message m1.show() m3.show() m2.show() I have read most recommended textbooks but still have difficulties figuring what it is all about. If you can show us an example and tell us what you don't understand we might be able to give more specific answers. Also please tell us which version of Python you are using and which Operating System. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] OOP
Dear ALL, I am a python beginner and has never programmed and has been struggling to understand how to create objects or classes in python. Can anyone help with any concrete example. I have read most recommended textbooks but still have difficulties figuring what it is all about. Thanks, Henry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor