Re: [Tutor] Using superclass __init__ method
There are several areas this seems to touch upon, most of them well covered by Guido himself in http://www.python.org/2.2/descrintro.html firstly to call a super class' methods you get the subclass to refer to the *superclass* then the method (note not to the superclass instance) from newstyle tutorial (comment mine): class B: def m(self): print "B here" class C(B): def m(self): print "C here" B.m(self) #refer to the class definition not the instance of C via self. Secondly to run __init__ as you have described is normal behaviour because the __call__ function that every new instance must go through makes sure that __init__ is called, and as there is not one defined in subclass it uses the one in superclass. This should have the same effect, but is more controllable: class Base: def __init__(self): print "hello" class Child(Base): def __init__(self): Base.__init__(self) produces:: >>> c = Child() hello This might also help make things clearer class Base: def __init__(self): print "hello" class Child(Base): def __init__(self): Base.__init__(self) def foo(self): print "foo" c = Child() b = Base() x = Child() x.foo() Child.foo(x) #1 Child.foo(b) #2 The class defintion of Child is an object (since 2.2) and can be called with parameters. at #1 we see foo printed out because we have called the Child object method foo with an object of type Child (this is essentially self) Of course we can try passing in another object (#2) but it will barf. This issue is frankly just muddy. Not because of bad design or poor documentation but because it is a awkward subject. Read the link above - most of us mortals have had to read it several times. Things also get a little more complex with __new__ but its all in there However I have not found a really good explanation of the whole instance creation thing - perhaps this list could make one? -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] time challange
You are fairly close >>> t1 = today() >>> t1 >>> t2 = today() + RelativeDateTime(hours=20) >>> t2 >>> t3 = t2 - t1 >>> t3.hours 20.0 >>> slice = t3/20 >>> slice t3 is a "Delta" - that is an abstract representation of time - it is not the 20 hours since midnight, just 20 hours at any time in the universe. slice is just 1/20th of that same abstract time. But because of the munificence of Marc we can add that abstract hour to a real fixed time (ignoring Einstein of course) >>> t1 + slice And so that is a "real" datetime 1/20th of the way forward from t1 so a simple loop will get you your 20 evenly spaced time periods, which is what i think you were asking for. cheers On 9/22/05, nephish <[EMAIL PROTECTED]> wrote: > Hey there, > > i use mx.DateTime.RelativeDateTimeDiff to get the difference between > date_x and date_y. > what i need to do divide this amount of time into 20 different times > that spaced out between the date_x and the date_y. > > so if the difference between date_x and date_y is 20 hours, i need 20 > DateTimes that are one hour apart from each other. If the difference is > 40 minutes, i need the 20 DateTimes to be spaced out 2 minutes from each > other.. > > what would be a way to pull this off? i have looked at the docs for > mxDateTime > http://www.egenix.com/files/python/mxDateTime.html > and there seems to be a divide operation, but i dont quite know what it > is talking about > with the deltas. > > anyone have a good start point? > > thanks > shawn > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python DB
I would look quite seriously at SQLObject It is a bit rough round the edges but given a class defintion, it then creates the underlying SQL tables and handles the CRUD (create update delete) for you. I do not like this approach and prefer the other but equally nice ability it has to look at a database and create appropriate classes, which you can then use. It is a class of Object Relational mapper, of which there are a few Java production level ones but I do not know of any "real world" uses of SQL Object. Perhaps others do. Backups and access from other applications imply you want a fairly serious admin load afterwarss - in which case I would think very carefully before using anything other than a "real" RDBMS (Oracle, MySQL, Postgres MSAccess even). Backups and synchronous access are what they are designed to do. However are you quite sure a normal db table will not suffice - I tend to find that the underlying data structure is never as fluid as one suspects. Patient - disease - treatment sounds a fairly striaghtforward domain. Perhaps if you shared a few things that make you worried it will change dramatically someone might be able to suggest workable structures. On 9/22/05, Matt Williams <[EMAIL PROTECTED]> wrote: > Dear List, > > Thanks for all the advice! Obviously, I'm still a bit torn, but some of > the ideas looked good. > > In terms of spec, the DB can be fairly simple (single access, etc.). > Lower dependency on other libraries is good. Also, it needs to be cross- > platform. > > The problem (I have) with SQL-type DB is that I cannot be sure ahead of > time of the exact data structure. The DB will be about patients, who > have diseases, and also have treatments.Clearly, I can't specify now > the exact structure of the table. The advantage of SQL is that you can > (in general) do things like constrain types for fields, and give > enumerated options, which makes the data more consistent. > > The thing I liked about KirbyBase was that it used text files. This is a > real advantage, as it means that I can access the data from other > application easily, and also makes it easier to back-up (can just copy a > few files). The same would seem to be true of the XML-based options. The > advantage of ZODB was that the "object" structure seemed to map well to > the concept of patients, with diseases, with treatments, etc. (and > Shelve would work at least as a trial implementation) > > The final thing is that I needs to have a simple GUI frontend. The nice > thing about ZODB is that I could just map the eventhandlers to functions > on objects.. > > If people have more comments in the light of the bigger spec. above, I'd > still love to hear them... > > Matt > > _______ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simplifying with string-formatting operator
I would suggest you use the built in datetime modules or egenix mx.DateTime. for example >>> import datetime >>> year = "05"; month="09";day="23" >>> dateobj = datetime.date(int(year)+2000, int(month), int(day)) >>> dateobj.strftime("%A %B %y") 'Friday September 05' >>> obviously you need to look at how the incoming 2 digit strings are checked and so on. By the way the strftime("%A %B %y") tells python to print out the date as %A which is locale weekday etc etc. with the %A or %B being replaced in a similar way to %s in normal string formatting. strftime is well documented in the time module docs. cheers On 9/23/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello > > Does anyone have any idea on how i could simplify the following program by > using strings? > > # dateconvert2.py > #Converts day month and year numbers into two date formats > > import string > > def main(): ># get the day month and year >day, month, year = input("Please enter the day, month and year numbers: > ") > >date1 = str(month)+"/"+str(day)+"/"+str(year) > >months = ["January", "February", "March", "April", > "May", "June", "July", "August", > "September", "October", "November", "December"] > monthStr = months[month-1] >date2 = monthStr+" " + str(day) + ", " + str(year) > >print "The date is", date1, "or", date2 > > main() > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with pi and the math module.
it might be a little clearer if you look at sys.modules In the sys module is a useful dictionary called "modules" This dictionary maps all the names of modules we import, to the objects that are those modules. for example (I am only importing pprint to make it easier to read) >>> import sys, pprint >>> pprint.pprint( sys.modules ) {'UserDict': , '__builtin__': , '__main__': , 'copy_reg': , ... 'sys': , 'types': , 'warnings': , 'zipimport': } So how does an import change this "namespace"? Well, lets try one. I am going to choose the math module, becasue it has an easy to spot constant in there called pi. >>> import math >>> pprint.pprint( sys.modules ) ... 'math': , ... aha - that was not there earlier. >>> import sys, pprint >>> import math >>> sys.modules['__main__'].__dict__['pi'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'pi' >>> sys.modules['__main__'].__dict__['math'] >>> math.pi 3.1415926535897931 So in the namespace of __main__ (where we run the interpreter) there exists a module named 'math', and this module holds in its namespace a constant called pi. Now lets restart our python interepreter and try again >>> import sys, pprint >>> from math import * >>> import sys, pprint >>> pprint.pprint( sys.modules ) ... 'math': ... There it is again. ? Now if i have a look at the __main__ namespace (its __dict__) >>> sys.modules['__main__'].__dict__['math'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'math' >>> sys.modules['__main__'].__dict__['pi'] 3.1415926535897931 math is not in the namespace, but pi is directly there. Thats the difference between import math which imports a module into the current namespace and from math import * which imports all the contents of math into the namespace one last thing >>> import random as offthewall >>> pprint.pprint( sys.modules ) ... 'pprint': , 'random': , ... >>> random.randint(1,10) Traceback (most recent call last): File "", line 1, in ? NameError: name 'random' is not defined Whoops - but it is clearly shown in the sys.modules. That is correct - because we have imported the module (file) called random. However when I am in the __main__ namespace and do random.randint(1,10), Python tries to find "random" in the __main__namespace. >>> sys.modules['__main__'].__dict__['offthewall'] >>> sys.modules['__main__'].__dict__['random'] Traceback (most recent call last): File "", line 1, in ? KeyError: 'random' We have imported the module random but with a name of offthewall so >>> offthewall.randint(1,10) 1 >>> offthewall.randint(1,10) 8 works fine. On 9/24/05, Pujo Aji <[EMAIL PROTECTED]> wrote: > hi, > > if you use : import math > you can type: diameter * math.pi > > if you use from math import * > you can type: diameter * pi > > Cheers, > pujo > > > On 9/24/05, Nathan Pinno <[EMAIL PROTECTED]> wrote: > > > > > > Hi all, > > > > I need help with pi and the math module. I had import math at the top of a > program, but when it came to diameter*pi, it said that pi was not defined. > > > > How do I use it correctly? > > > > Thanks, > > Nathan Pinno > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HTTP GET Request
> Basicall, what I need is a stand alone CGI. Instead of the program passing > the data off to a CGI, I want it to parse and handle the request directly. instead of which program ? Http requests are served by a web server (ie Apache), which depending on the type of request passes the request to wherever. As such any HTTP request *must* be handled first by a web server, and cgi scripts traditionally lived in cgi-bin directory on the server so a URL would look like http://www.example.com/cgi-bin/myscript.py I think you have 3 options 1. use the cgi module in python to create scripts like the one above. They will not be fast but it gives you a lowlevel access to the request However cgi was out of date about 8 years ago - it has some seriouslimitations mostly on speed/capacity. 2. use a system like mod_python. This is better than cgi for lots of reasons, mostly to do with speed. Here you also have access to the request objects, but there is a bit of a learning curve. 3. Zope - higher level than even mod_python and still more of a learning curve (there is a multitude of python based cgi repalcements, Django, webware and others spring to mind. But there is no clear "winner" amoungst the community) I would recommend that you look at taking a weekend to install apache, and play with both the cgi module and mod_python. mod_python is pretty good and fairly well documented, as well as being pretty low level. I think there is a lot to do here - perhaps if you tell us exactly what you need we can point you at a solution. Some web hosters provide mod_python or zope hosting and that might be a way to get up and running faster. On 9/27/05, Jerl Simpson <[EMAIL PROTECTED]> wrote: > Hello, > > I have been looking through some of the HTTP projects and haven't quite > found what I'm looking for. > Basicall, what I need is a stand alone CGI. Instead of the program passing > the data off to a CGI, I want it to parse and handle the request directly. > > The part I'm having trouble with is actually getting the request and parsing > it. > > Let's say I have a URI that looks like: > ?var1=val1&var2=val2&...varn=valn > > I'd like to find a way to get these into some datastructure so I can use > them to generate my output. > > It seems like a simple thing, but as I'm new to python, I don't know where > to start. > > Thank you for any help you can give. > > > Jerl > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] find data in html file
> But to get the data like price,bidders,shipment etc without the official > eBayAPI is hard. > Maybe anyone has a solution made ? Ebay specifically change around their HTML codes, tags and formatting (in quite a clever way) to stop people doing exactly what you are trying to do. I think it changes every month. Like people say, use the API - You need to become an "ebay developer" (signup) and can use your own code or the python-ebay thing for free in "the sandbox", but must pay $100 or so to have your code verified as "not likey to scrunch our servers" before they give you a key for the real world. Its a bit of a pain, so i just hacked turbo-ebay a while back and made do. Worked quite well really. -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beautiful soup
How did you change it to look at the file on your PC? You appear to have told urllib2 to use "FRE_word_list.htm", it cannot find that online so tried to look for it on your local disk at '\\C:\\Python24\\FRE_word_list.htm I would suggest that you either put your local html on a web server and send in that local URL or replace html = urllib2.urlopen(url).read() with html = open(r'c:\myfolder\myfile.html').read() and see where that takes you. cheers On 10/4/05, David Holland <[EMAIL PROTECTED]> wrote: > I tried to use this script which I found on the web :- > import urllib2, pprint > from BeautifulSoup import BeautifulSoup > > > def cellToWord(cell): > """Given a table cell, return the word in that > cell.""" > # Some words are in bold. > if cell('b'): > return cell.first('b').string.strip() # > Return the bold piece. > else: > return cell.string.split('.')[1].strip() # > Remove the number. > > > def parse(url): > """Parse the given URL and return a dictionary > mapping US words to > foreign words.""" > > > # Read the URL and pass it to BeautifulSoup. > html = urllib2.urlopen(url).read() > soup = BeautifulSoup() > soup.feed(html) > > > # Read the main table, extracting the words from > the table cells. > USToForeign = {} > mainTable = soup.first('table') > rows = mainTable('tr') > for row in rows[1:]:# Exclude the first > (headings) row. > cells = row('td') > if len(cells) == 3: # Some rows have a > single colspan="3" cell. > US = cellToWord(cells[0]) > foreign = cellToWord(cells[1]) > USToForeign[US] = foreign > > > return USToForeign > > > if __name__ == '__main__': > url = > 'http://msdn.microsoft.com/library/en-us/dnwue/html/FRE_word_list.htm' > > USToForeign = parse(url) > pairs = USToForeign.items() > pairs.sort(lambda a, b: cmp(a[0].lower(), > b[0].lower())) # Web page order > pprint.pprint(pairs) > > and it works well. However I change it to get it to > look at a file on my PC, then I get this message :- > Traceback (most recent call last): > File "C:\Python24\beaexp2", line 43, in -toplevel- >USToForeign = parse(url) > File "C:\Python24\beaexp2", line 20, in parse >html = urllib2.urlopen(url).read() > File "C:\Python24\lib\urllib2.py", line 130, in > urlopen >return _opener.open(url, data) > File "C:\Python24\lib\urllib2.py", line 358, in open >response = self._open(req, data) > File "C:\Python24\lib\urllib2.py", line 376, in > _open >'_open', req) > File "C:\Python24\lib\urllib2.py", line 337, in > _call_chain >result = func(*args) > File "C:\Python24\lib\urllib2.py", line 1119, in > file_open >return self.open_local_file(req) > File "C:\Python24\lib\urllib2.py", line 1135, in > open_local_file >stats = os.stat(localfile) > OSError: [Errno 2] No such file or directory: > '\\C:\\Python24\\FRE_word_list.htm > Any idea how to solve it ? The file is on my PC. > > I am using Python 2.4 on Win XP. > > Thanks in advance. > > David > > > > ___ > How much free photo storage do you get? Store your holiday > snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help to understand terms for desinging a program
This is a pretty big question, and it would be easier to answer if you can give us more details about what you want to do. It seems you want to inspect outgoing mails (possibly rewrite their addresses?) before the mails are sent out. If you are looking to send out emails to a list then I suggest looking at mailman - a python mailing list manager. If you want to use python to examine mail messages and do not care what mailserver (MTA) you use you could try exim instead of qmail and then try exim-python. http://botanicus.net/dw/exim-python/exim-4.32py1.html On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote: > Hi, > I need to make a program which will accomplish following. I dont > need the code. I want to make it myself. But I need guidance from you > people because I am not a good programmer. I need help in > understanding following terms. > > " qmail-queue reads a mail message from descriptor 0. It > then reads envelope information from descriptor 1. It > places the message into the outgoing queue for future > delivery by qmail-send. > > The envelope information is an envelope sender address > followed by a list of envelope recipient addresses. The > sender address is preceded by the letter F and terminated > by a 0 byte. Each recipient address is preceded by the > letter T and terminated by a 0 byte. The list of recipi- > ent addresses is terminated by an extra 0 byte. If qmail- > queue sees end-of-file before the extra 0 byte, it aborts > without placing the message into the queue." > > I want to inspect messages before passing them to actuall qmail-queue > program. > Thanks in advance for your help. > -- > Regards, > Hameed U. Khan > Registered Linux User #: 354374 > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help to understand terms for desinging a program
I would suggest that you look firstly at qmails own built in ruleset. something like that must be achieveable without writing a special plugin. qmail control files are usually in /var/qmail/control. Nothing obvious in the man pages i am afraid. Good luck On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote: > On 10/5/05, paul brian <[EMAIL PROTECTED]> wrote: > > This is a pretty big question, and it would be easier to answer if you > > can give us more details about what you want to do. > > > > It seems you want to inspect outgoing mails (possibly rewrite their > > addresses?) before the mails are sent out. > > > > If you are looking to send out emails to a list then I suggest looking > > at mailman - a python mailing list manager. > > > > If you want to use python to examine mail messages and do not care > > what mailserver (MTA) you use you could try exim instead of qmail and > > then try exim-python. > > http://botanicus.net/dw/exim-python/exim-4.32py1.html > > > > > > > > > > > > On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote: > > > Hi, > > > I need to make a program which will accomplish following. I dont > > > need the code. I want to make it myself. But I need guidance from you > > > people because I am not a good programmer. I need help in > > > understanding following terms. > > > > > > " qmail-queue reads a mail message from descriptor 0. It > > > then reads envelope information from descriptor 1. It > > > places the message into the outgoing queue for future > > > delivery by qmail-send. > > > > > > The envelope information is an envelope sender address > > > followed by a list of envelope recipient addresses. The > > > sender address is preceded by the letter F and terminated > > > by a 0 byte. Each recipient address is preceded by the > > > letter T and terminated by a 0 byte. The list of recipi- > > > ent addresses is terminated by an extra 0 byte. If qmail- > > > queue sees end-of-file before the extra 0 byte, it aborts > > > without placing the message into the queue." > > > > > > I want to inspect messages before passing them to actuall qmail-queue > > > program. > > > Thanks in advance for your help. > > > -- > > > Regards, > > > Hameed U. Khan > > > Registered Linux User #: 354374 > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > -- > > Paul Brian > > m. 07875 074 534 > > t. 0208 352 1741 > > > > Thanks paul for you quick reply but I have to stick with qmail. I want > to check envelopes when user attempts to send message. Because our > company want to restrict some users to send message to selected > domains only. I've been given this task. Anyway thanks again for your > time. > -- > Regards, > Hameed U. Khan > Registered Linux User #: 354374 > - > *Computer without Linux is just like the world without computer.* > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing Variables
Sort ofnot really When a module is imported the following things happen import ONE a module object (dict essentially) named ONE is created. This is the module ONE.py's namespace. The module object is added to sys.modules the code in the object is executed inside the ONE dict (namespace) now if ONE has at the top import os ONE is able to use the line os.path.join (mydir, "foo.txt") If however we do not have the line import os we will get an error as the namespace of one does not have a reference to the module object of os as an example import your one.py and run pprint.pprint(sys.modules['one'].__dict__) You will see what a virgin namesapce looks like - there is a lot in there but it boils down to __builtins__, __doc__, __file__, __name__ and whatever you define (_-dict__) care notes --- You can easily get into circular references with imports, simply because code at the module level (ie not in a function or class) will be executed at the first import - and if it calls code that is in the next module which waits on code in the first etc etc. So as you said, put everything into classes or functions or be very careful with your imports. (I am not sure I answered the question but it is late now...:-) yrs On 10/5/05, Matt Williams <[EMAIL PROTECTED]> wrote: > Dear List, > > I'm trying to clarify something about accessing variables. > > If I have ONE.py file with some variable a, and ONE imports TWO, which > has a variable b, can TWO access variable a (I don't think so, but I > just thought I'd check). > > I guess the way round this is just to make some classes & objects, and > then they can easily pass parameters to each other, but I just thought > I'd check. > > Matt > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] and-or precedence
has a higher priority than (as shown on the page you referenced -its "ascending priority"). Perhaps that could be clearer. I find that brackets always make life easier in these cases (a rare statement in the Python world :-), and on a personal note I would always always comment heavily boolean operations that are not immediately obvious. it saves brain ache later on. >>> ((1 or 2) and 3) 3 However 1 or 2 and 3 is <1> if is evaluated first. cheers On 10/10/05, Krishna <[EMAIL PROTECTED]> wrote: > >>> 1 or 2 and 3 > 1 > > Why does the above expression return 1? As per my understanding of > boolean operations, this is what should have happaned: > > 1 or 2 => 1 and then > 1 and 3 => 3 > > The library reference also suggests that 'or' has higher priority than 'and'. > http://docs.python.org/lib/boolean.html > > Thanks > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Walk a dictionary recursively
Firstly are you using this to store or alter data regarding Microsoft Active Directory?. If so I suggest you look at some of their ADSI / WMI interfaces for COM (if you use win32com from Mark Hammond or activeState life becomes a lot easier. Well the Windows programming part of it does) As for the particulars of your question, you might find life simpler if you created a "parentID" (and/or childID) for each unique entry in the tree. As you are going to be growing the data list in size one other area to look at is generators - this will enable you to walk arbitrarily large trees but with a far lower memory footprint and hence a lot faster. A generator class returns an object that will walk through an iteration set (like a for loop) but at the end of every step will "disappear" from the stack and when it is called again it starts exactly where it left off. So I would suggest you create generaotr based classes to store your data, using an explicit parent/child relationship rather than relying on the implicit relationships of which dictionary is stored inside which dictionary. It is still a far chunk of work. I suggest you start on the parent child thing first. Think about having a single point of entry that creates a new object and then "hangs" it on the tree. I hope that helps and do please come back to the list with how you are gettng on. On 10/11/05, Negroup - <[EMAIL PROTECTED]> wrote: > Hi tutors, in my application I found convenient to store all the data > in a data structure based on a dictionary containing a lot of keys, > and each of them host other dictionary with lists and dictionaries > nested inside and so on... > > First of all I'd like to know if it is normal to use so complex data > structures in which store data, or if it possible in some way to > organize them using smaller "organizational units". > > This is instead the problem I should solve as soon as possible: I > should apply a function, exactly the string's method decode('utf-8'), > to each key and value of the above descripted dictionary. Consider > that the keys are integers or strings, and if a key is a list, I need > to decode each contained element. Is there a way to walk recursively > the dictionary, or should I write my own walk function? > > Thanks in advance, > negroup > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: if-else statements
My apologies - I keep failing to reply-all. -- Forwarded message -- From: paul brian <[EMAIL PROTECTED]> Date: Oct 14, 2005 10:04 AM Subject: Re: [Tutor] if-else statements To: Andre Engels <[EMAIL PROTECTED]> I would also suggest you look at either datetime module or the mx.DateTime modules (from egenix). They are both very good and contain plenty of error checking for just such things, aas well as nicely overriding operators like + (so you can add 2 weeks to a date easily). >>> import datetime We can try an invlaid date and trap the error (using try: Except: statements) >>> datetime.date(2005,02,30) Traceback (most recent call last): File "", line 1, in ? ValueError: day is out of range for month A valid date >>> d = datetime.date(2005,02,27) And shown in a easy to read format >>> d.strftime("%A %B %d %Y") 'Sunday February 27 2005' cheers On 10/14/05, Andre Engels <[EMAIL PROTECTED]> wrote: > 2005/10/14, [EMAIL PROTECTED] <[EMAIL PROTECTED]>: > > Hello > > > > I'm having some trouble with my if, else statements. For some reason, the > > months that have 31 days work fine, but the months that have 28/30 do not > > work. Am I doing something wrong? it is supposed to take a date as an > > input like 9/31/1991 and then say that the date is not valid because > > september only has 30 days. > > First hint: > Where is 'month' used in your program? The answer is: nowhere. It > should be used. Why? > > Second hint: > Currently, the program checks each date first for validity with > respect to January, then throws the outcome away to do the same with > February, etcetera upto December. Thus, the final outcome says whether > the date is correct in December, not whether it is correct in the > given month. > > (actual code below) > > > import string > > > > def main(): > > # get the day month and year > > month, day, year = input("Please enter the mm, dd, : ") > > date1 = "%d/%d/%d" % (month,day,year) > > > > months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] > > > > if day <= months[1]: > > d = "valid" > > else: > > n = "not valid" > > > > if day <= months[2]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[3]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[4]: > > d = "valid" > > else: > > n = "not valid" > > > > if day <= months[5]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[6]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[7]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[8]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[9]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[10]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[11]: > > d = "valid" > > else: > > d = "not valid" > > > > if day <= months[12]: > > d = "valid" > > else: > > d = "not valid" > > > > print "The date you entered", date1, "is", d +"." > > > > main() > > Correct and shortened code: > > Instead of the whole line "if day <= months[1]"... series of > if-then-else statements, use only one statement, namely: > > if day <= months[month]: >d = "valid" > else: >d = "not valid" > > -- > Andre Engels, [EMAIL PROTECTED] > ICQ: 6260644 -- Skype: a_engels > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] passing variable to python script
There are several approaches ranging from the simple but limited to rather advanced. raw_input is the simplest but it is to be deprecated, and more importantly it limits you to entering commands after the script is running. automation becomes harder $ myscript Those args are put into a list called sys.argv where sys.argv[0] is the name of the script you ran and any subsequent ones are sys.argv[1] {2] etc etc However my favourite is optparse module, which allows you to set up what options you like (for example $ myscript -q --outfile=/home/foo.txt) and will carefully check their validity, provide defaults, convert to floats etc where needed, and there is a cool easygui addon. On guido's Artima weblog there is a good article on using special main cases - it is pretty "deep" so do not worry if you cannot put it all to use - at least you know where you can get to. The above $ myscript is the best way to call a script, because you can run it from the command line automatically, manually, and if you use the convention of wrapping the script in a main() function, then putting this at the bottom of the file if __name__ == '__main__': main() (ie you have a function addTwoNumbers(a,b), and main takes args[1] and args[2] and passes them to addTwoNumbers) Then main() will only be run when the script is called from the command line, meaning the same code can be import'ed and addTwoNumbers can be called from any other python program. HTH On 10/14/05, Alan Gauld <[EMAIL PROTECTED]> wrote: > > i want to pass an argument (a number) to a python > > script when running it: > >> python script.py > > > > i want to be able to use within script.py > > as a parameter. > > > > how do i set this up? > > This is covered in the 'talking to the user' topic in my tutorial. > > The short answer is use sys.argv > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to create GUI for Python progs
It seems to depend on what you want easygui --- Very simple, very easy to set up, but is NOT event driven (ie the program uses it much like it would use raw_input but with drop boxes. All other guis are event driven - that is the gui has the main loop, and when it detects (a button click) it fires off a request to the rest of the program to do something. The main frameworks (ie they provide widgets like buttons so you do not have to write your own button code) pyQT --- Extrememly well suported and mature, Has a good drag and drop developer. Is free for Linux / open source use. Commercially is a bit more confused. tkinter The default python Gui but it might be changing - see frederick Lundh's IDE for what can be done in it. WxPython - Simialr to pyQt, widgets bigger than tkinter Wrappers around the above frameworks for ease PythonCard --- As recommended above. There are a plethora of gui interfaces (http://wiki.python.org/moin/GuiProgramming) Almost as many as web frameworks ! I suggest starting with easygui if you just want pop up dialogs, otherwise take a day or two to get to grips with QT. with a drag and drop editor it is surprisingly good. There is a tutorial by a B Rempt somewhere on line. On 10/13/05, Olexiy Kharchyshyn <[EMAIL PROTECTED]> wrote: > > I'm really confused on the issue how to create windows, forms, etc. in > Python & can't find any manual for that. > Could you possibly advise me smth useful? > -- > Best regards, > > Olexiy Kharchyshyn > > [EMAIL PROTECTED] > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) (fwd)
I would suggest that you use "add Remove Programs" in the control panel and remove the python and win32 installations that you have installed Then visit www.activestate.com and download the package for activePython (http://activestate.com/Products/Download/Download.plex?id=ActivePython) You may need to download the latest MSI (MS installer) files from microsoft as Win95 does not understand them Activestate has a nice installer and you would be up and running then. cheers On 10/17/05, Danny Yoo <[EMAIL PROTECTED]> wrote: > [Keeping tutor in CC] > > -- Forwarded message -- > Date: Mon, 17 Oct 2005 22:03:22 +1300 > From: Dave Shea <[EMAIL PROTECTED]> > To: Danny Yoo <[EMAIL PROTECTED]> > Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > Hi Danny, > > Thanks for your note. I tried your original suggestion of using the > C:\Python24 as the home directory but to no avail. So now I am a bit stuck > on your and Alan's next suggestion which is to use PythonWin. > > I downloaded: > http://optusnet.dl.sourceforge.net/sourceforge/pywin32/pywin32-204.win32-py2 > .4.exe > > and it installed fine. > > However, it is listed as "Python for Windows extensions" so I assume that > installing this whilst still having Pythin24 installed was the way to go. > The installer seemed to be OK about this but when I went to start PythonWin > I could not actually find anything to start. I think I may be missing > something here. Is PythonWin a separate installation of Python with an > IDE/GUI ? Or is PythonWin simply something to sit over the top of a (any) > Python installation. > > I'm a bit lost, as you may tell so any help would be greatly accepted. > > Many thanks. > > Dave Shea > Wellington > New Zealand. > - Original Message - > From: "Danny Yoo" <[EMAIL PROTECTED]> > To: "Dave Shea" <[EMAIL PROTECTED]> > Cc: > Sent: Monday, October 17, 2005 5:17 PM > Subject: Re: [Tutor] IDLE will not appear under Win95 (Python 2.4.2) > > > > > > > > On Sat, 15 Oct 2005, Dave Shea wrote: > > > > > Python installed without a complaint. However, when I fire up IDLE, > > > there is an hour glass shown for a couple of seconds, then nothing else > > > happens. When I fire up Python (command line) no problem, the DOS box > > > opens and Python starts. I've tried re-starting, using Explorer instead > > > of the Start menu, all the usual voodoo but still the IDLE refuses to > > > start. > > > > Hi Dave, > > > > According to: > > > > http://python.org/2.4.2/bugs.html > > > > IDLE might not work well if Python has been installed into Program Files. > > > > Do you know if you've done this? If so, try reinstalling and just leave > > the installation path at the defaults (Python should install under > > "C:\PYTHON24", I think.) > > > > IDLE has unfortunately been a bit problematic in the Python 2.4 release, > > so if you continue to run into issues, I'd second Alan's suggestion about > > trying Pythonwin instead. > > > > > > Good luck! > > > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setting
Did you install from the python.org download or from activestate. If you have a .chm file I am guessing activestate. For some reason the normal docs that you get with the python.org distributin (the "official" one) are only found as a chm file. I suggest you get the python.org installer and carefully install to a temp directory, and copy across the html files in Doc, or remove activestate, install python.org and then add in the win32all extensions. I would suggest the first option for sheer ease. (in fact on windows i would suggest keeping the .chm and using that, cmd.exe is quite poor in command line reading and copying so that .chm is my favourtie way of looking up documentation) HTH. On 10/19/05, Shi Mu <[EMAIL PROTECTED]> wrote: > I have installed Python 2.3 and I type "help()" and then "Keywords". > I get a list of words. And it says that I can enter any of the words > to get more help. I enter > "and" and I get the following error message: > "Sorry, topic and keyword documentation is not available because the Python > HTML documentation files could not be found. If you have installed them, > please set the environment variable PYTHONDOCS to indicate their location." > > but I have set both the environment variable, with the path to be > C:\Python23\Doc which includes python23.chm > Why I still got the above error message? > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -- Paul Brian m. 07875 074 534 t. 0208 352 1741 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor