From ss_jones@hotmail.com Mon May 3 22:49:16 1999 From: ss_jones@hotmail.com (Stephanie Jones) Date: Mon, 03 May 1999 14:49:16 PDT Subject: [Tutor] formatting sql output Message-ID: <19990503214916.98602.qmail@hotmail.com> I am currently trying to format the output of a sql query using the techniques described in the book "Internet Programming with Python" under the subsection "Building an ASCII Table Generator" (pp 65-66). Basically, the result of the query is a tuple called "opened". I then have, following the example in the book: for x in opened: list=[x[0],x[2],x[3],x[1]] printstring=formatfields(list) print printstring def formatfields(list): fieldsformatted=map(fieldformat15,list) return string.joinfields(fieldsformatted, " | ") def fieldformat15(field): return '%-15s' % field However, it doesn't seem to be formatting so that each "field" is 15 characters long. Does my question make sense, and does anyone have an idea why it is doing this? _______________________________________________________________ Get Free Email and Do More On The Web. Visit http://www.msn.com From ivanlan@callware.com Mon May 3 23:13:52 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Mon, 03 May 1999 16:13:52 -0600 Subject: [Tutor] formatting sql output References: <19990503214916.98602.qmail@hotmail.com> Message-ID: <372E1FA0.B063BAB8@callware.com> Hi All-- Stephanie Jones wrote: > > I am currently trying to format the output of a sql query using the > techniques described in the book "Internet Programming with Python" under > the subsection "Building an ASCII Table Generator" (pp 65-66). > Basically, the result of the query is a tuple called "opened". I then have, > following the example in the book: > > for x in opened: > list=[x[0],x[2],x[3],x[1]] > printstring=formatfields(list) > print printstring > > def formatfields(list): > fieldsformatted=map(fieldformat15,list) > return string.joinfields(fieldsformatted, " | ") > > def fieldformat15(field): > return '%-15s' % field > > However, it doesn't seem to be formatting so that each "field" is 15 > characters long. Does my question make sense, and does anyone have an idea > why it is doing this? > The format specification is incorrect. You should use "%15.15s" or "%-15.15s" to force left justification, in addition to padding/clipping. -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From deirdre@deirdre.net Tue May 4 00:37:35 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 3 May 1999 19:37:35 -0400 (EDT) Subject: [Tutor] formatting sql output In-Reply-To: <372E1FA0.B063BAB8@callware.com> Message-ID: On Mon, 3 May 1999, Ivan Van Laningham wrote: > > def fieldformat15(field): > > return '%-15s' % field > > The format specification is incorrect. You should use "%15.15s" or > "%-15.15s" to force left justification, in addition to padding/clipping. Is there a reason not to use return string.ljust(field, 15) ? _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Solving today's problems tomorrow, with yesterday's technology." From ivanlan@callware.com Tue May 4 16:28:59 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Tue, 04 May 1999 09:28:59 -0600 Subject: [Tutor] formatting sql output References: Message-ID: <372F123B.D8F76BB9@callware.com> Hi All-- Deirdre Saoirse wrote: > > On Mon, 3 May 1999, Ivan Van Laningham wrote: > > > > def fieldformat15(field): > > > return '%-15s' % field > > > > The format specification is incorrect. You should use "%15.15s" or > > "%-15.15s" to force left justification, in addition to padding/clipping. > > Is there a reason not to use return string.ljust(field, 15) ? > None whatsoever. Use what is convenient or what pleases you, as long as it does the job. Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From fd98356@bits-pilani.ac.in Wed May 5 08:59:48 1999 From: fd98356@bits-pilani.ac.in (rohit) Date: Wed, 5 May 1999 13:29:48 +0530 (IST) Subject: [Tutor] (no subject) Message-ID: Dear sir , do send some modules through mail so that I can start this language . rohit From Chris.Reay@pareto-partners.com.au Thu May 6 03:33:17 1999 From: Chris.Reay@pareto-partners.com.au (Chris Reay) Date: Thu, 6 May 1999 03:33:17 +0100 Subject: [Tutor] odbc exception handling Message-ID: <55A01F6715D2D211BE8D00600856C4FECB4B@ozntsyd1.ppsydney> Hi I'd like to know how to handle exceptions in the odbc module in PythonWin. This code ... class SentBrokerForecastMgr(BrokerForecastMgr): def add(self, aSentFc): tup = aSentFc.asTuple() sqlStr = self.insertStr % (tup[0], tup[1], tup[2], tup[3]) self.cursor.execute(sqlStr) self.dbc.commit() correctly raises the exception dbi.integrity-error: [Microsoft][ODBC Microsoft Access 97 Driver] The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again. in EXEC when it strikes an integrity error. I can't seem to trap the exception. I try (unintended pun) def add(self, aSentFc): tup = aSentFc.asTuple() sqlStr = self.insertStr % (tup[0], tup[1], tup[2], tup[3]) try: self.cursor.execute(sqlStr) self.dbc.commit() except dbi.integrity-error: print "Integrity error" which yields Traceback (innermost last): File "", line 0, in ? File "FcScripts.py", line 73, in loadWeeklySentimentBrokerForecasts sm.add(eachFc) File "S:\chrisr\PyPrograms\BrokerForecastMgr.py", line 74, in add except dbi.integrity-error: AttributeError: integrity I also try def add(self, aSentFc): tup = aSentFc.asTuple() sqlStr = self.insertStr % (tup[0], tup[1], tup[2], tup[3]) try: self.cursor.execute(sqlStr) self.dbc.commit() except StandardError: print "error" but this doesn't trap the error. What am I doing wrong? Thanks Chris --------------------------------------------------------------- Chris Reay Pareto Partners Australia Pty Ltd Level 49 Governor Phillip Tower 1 Farrer Place Sydney NSW 2000 Phone: (02) 9247 3700 (w) Email: chris.reay@pareto-partners.com.au --------------------------------------------------------------- Warning: The author is not responsible. --------------------------------------------------------------- From da@ski.org Thu May 6 04:13:26 1999 From: da@ski.org (David Ascher) Date: Wed, 5 May 1999 20:13:26 -0700 (Pacific Daylight Time) Subject: [Tutor] odbc exception handling In-Reply-To: <55A01F6715D2D211BE8D00600856C4FECB4B@ozntsyd1.ppsydney> Message-ID: On Thu, 6 May 1999, Chris Reay wrote: > dbi.integrity-error: [Microsoft][ODBC Microsoft Access 97 Driver] The > changes you requested to the table were not successful because they would > create duplicate values in the index, primary key, or relationship. Change > the data in the field or fields that contain duplicate data, remove the > index, or redefine the index to permit duplicate entries and try again. in > EXEC > I can't seem to trap the exception. I try (unintended pun) > > def add(self, aSentFc): > tup = aSentFc.asTuple() > sqlStr = self.insertStr % (tup[0], tup[1], tup[2], tup[3]) > try: > self.cursor.execute(sqlStr) > self.dbc.commit() > except dbi.integrity-error: > print "Integrity error" try (intended pun): except dbi.error: 'integrity-error' can't be an exception name, since it's got a - in it -- it must be the string version of an error. Looking at the Database topic guide, I'm guessing that 'error' will match all DBI errors. --david ascher From geek+@cmu.edu Thu May 6 13:14:55 1999 From: geek+@cmu.edu (geek+@cmu.edu) Date: 6 May 1999 08:14:55 -0400 Subject: [Tutor] odbc exception handling In-Reply-To: Message-ID: --pgp-sign-Multipart_Thu_May__6_08:14:55_1999-1 Content-Type: text/plain; charset=US-ASCII Then spoke up and said: > try (intended pun): > > except dbi.error: Also, you'll need to explicitly do an "import dbi" if you haven't (I can't tell from your code fragment). dbi might have been imported by the ODBC driver, but that doesn't put it in the name space of your code. -- ===================================================================== | JAVA must have been developed in the wilds of West Virginia. | | After all, why else would it support only single inheritance?? | ===================================================================== | Finger geek@cmu.edu for my public key. | ===================================================================== --pgp-sign-Multipart_Thu_May__6_08:14:55_1999-1 Content-Type: application/pgp-signature Content-Transfer-Encoding: 7bit -----BEGIN PGP MESSAGE----- Version: 2.6.2 Comment: Processed by Mailcrypt 3.3, an Emacs/PGP interface iQBVAwUBNzGHv4dzVnzma+gdAQEFAgH+JxQB2HgEwJsa/nHLuEdNK54AD0rGNZII U/E7mDHdzow+HRp7lu/eydiMgnRfmLkXz2+8+Z+rO1qvW1wf9KzO0A== =/XWl -----END PGP MESSAGE----- --pgp-sign-Multipart_Thu_May__6_08:14:55_1999-1-- From Chris.Reay@pareto-partners.com.au Fri May 7 01:29:10 1999 From: Chris.Reay@pareto-partners.com.au (Chris Reay) Date: Fri, 7 May 1999 01:29:10 +0100 Subject: [Tutor] odbc exception handling Message-ID: <55A01F6715D2D211BE8D00600856C4FECB5B@ozntsyd1.ppsydney> Thanks for help from David and geek+. The advice I received was: (a) explicitly import dbi (b) try: except dbi.error: Unfortunately they don't help; here's the walkback ... Traceback (innermost last): File "", line 0, in ? File "FcScripts.py", line 73, in loadWeeklySentimentBrokerForecasts sm.add(eachFc) File "S:\chrisr\PyPrograms\BrokerForecastMgr.py", line 76, in add except dbi.error: AttributeError: error Am I mssing something here? Thanks again Chris > -----Original Message----- > From: David Ascher [SMTP:da@ski.org] > Sent: Thursday, 6 May 1999 13:13 > To: Chris Reay > Cc: 'tutor@python.org' > Subject: Re: [Tutor] odbc exception handling > > On Thu, 6 May 1999, Chris Reay wrote: > > > dbi.integrity-error: [Microsoft][ODBC Microsoft Access 97 Driver] The > > changes you requested to the table were not successful because they > would > > create duplicate values in the index, primary key, or relationship. > Change > > the data in the field or fields that contain duplicate data, remove the > > index, or redefine the index to permit duplicate entries and try again. > in > > EXEC > > > > I can't seem to trap the exception. I try (unintended pun) > > > > def add(self, aSentFc): > > tup = aSentFc.asTuple() > > sqlStr = self.insertStr % (tup[0], tup[1], tup[2], tup[3]) > > try: > > self.cursor.execute(sqlStr) > > self.dbc.commit() > > except dbi.integrity-error: > > print "Integrity error" > > try (intended pun): > > except dbi.error: > > 'integrity-error' can't be an exception name, since it's got a - in it -- > it must be the string version of an error. Looking at the Database topic > guide, I'm guessing that 'error' will match all DBI errors. > > --david ascher > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From da@ski.org Fri May 7 04:16:18 1999 From: da@ski.org (David Ascher) Date: Thu, 6 May 1999 20:16:18 -0700 (Pacific Daylight Time) Subject: [Tutor] odbc exception handling In-Reply-To: <55A01F6715D2D211BE8D00600856C4FECB5B@ozntsyd1.ppsydney> Message-ID: On Fri, 7 May 1999, Chris Reay wrote: > The advice I received was: > > (a) explicitly import dbi > (b) try: except dbi.error: > > Unfortunately they don't help; here's the walkback ... > > Traceback (innermost last): > File "", line 0, in ? > File "FcScripts.py", line 73, in loadWeeklySentimentBrokerForecasts > sm.add(eachFc) > File "S:\chrisr\PyPrograms\BrokerForecastMgr.py", line 76, in add > except dbi.error: > AttributeError: error > > Am I mssing something here? >>> dir(dbi) ['DATE', 'NUMBER', 'RAW', 'ROWID', 'STRING', 'TYPES', '__doc__', '__file__', '__name__', 'dataError', 'dbDate', 'dbRaw', 'dbiDate', 'dbiRaw', 'integrityError', 'internalError', 'noError', 'opError', 'progError'] In other words, "except dbi.integrityError" is most likely to work. [the dbi.error is in the doc, but obviously not in the code =)] --david From 010.Werkstudent@MCHF.SIEMENS.DE Fri May 7 13:08:39 1999 From: 010.Werkstudent@MCHF.SIEMENS.DE (Werkstudent 010) Date: Fri, 7 May 1999 14:08:39 +0200 Subject: [Tutor] (no subject) Message-ID: <809AE76DB183D111BE1300005A40E070580D28@mail.mchf.siemens.de> Hail Monty, who art a heathen, I need to produce software for interthread-communication using threads in python, and havenīt enough thread experience. How do I define the "shared memory" data, and access it from the "thread" or "threading" classes, or pass messages to designated threads (or even designate the other threads). Would you pass me over a demo example? Iīd search the FAQs myself, but I donīt have Internet access here, just E@mail. (Iīm an "external employee", with commensurately disappointing lack of access privileges). David Ungemach, (Werkstudent010) From rbb@nebiometrics.com Sat May 8 03:45:37 1999 From: rbb@nebiometrics.com (Robert Burrows) Date: Fri, 7 May 1999 22:45:37 -0400 (EDT) Subject: [Tutor] reading tables into NumPy Message-ID: Hello, How does one read numbers from a table into a NumPy array? TIA, Robert Burrows rbb@nebiometrics.com From mdu@dancris.com Sun May 9 08:55:42 1999 From: mdu@dancris.com (Du) Date: Sun, 09 May 1999 00:55:42 -0700 Subject: [Tutor] you're help is needed Message-ID: <37353F7E.5290372A@dancris.com> i am a high school student and i have been told to download python, so i downloaded your "python 1.5.2 " and i have no clue how to run it or even where to begin. i don't know whether i downloaded the wrong one or if i need to download another part. i looked in your FAQ section of your web site, and i still did not get the answers to my questions. Please help me by writing me back, or just sending me some helpful directions or tips. thank you for your time -michael du From tismer@appliedbiometrics.com Sun May 9 14:01:31 1999 From: tismer@appliedbiometrics.com (Christian Tismer) Date: Sun, 09 May 1999 15:01:31 +0200 Subject: [Tutor] you're help is needed References: <37353F7E.5290372A@dancris.com> Message-ID: <3735872B.15420703@appliedbiometrics.com> Du wrote: > > i am a high school student and i have been told to download python, > so i downloaded your "python 1.5.2 " and i have no clue how to run it or > even where to begin. i don't know whether i downloaded the wrong one or > if i need to download another part. i looked in your FAQ section of your > web site, and i still did not get the answers to my questions. Please > help me by writing me back, or just sending me some helpful directions > or tips. What is your operating system? Assuming it is Windows, you should download the precompiled Windows version from http://www.python.org and then also the Win32 extensions build 125. You will find a reference to that on the python.org site. Having the py152.exe file, you just need to execute it, and it will install itself. You will start it from the start menu as any other program. You can either start a plain Python session, or an IDLE session which is an interactive GUI framework for Python. After you installed also win32all-125.exe on top of it, you will have a Windows-specific version as well. If you can get this far, try a little and ask us again. If you have a different operating system, let us know. In many cases, pre-built versions for different OSses are available. ciao - chris -- Christian Tismer :^) Applied Biometrics GmbH : Have a break! Take a ride on Python's Kaiserin-Augusta-Allee 101 : *Starship* http://starship.python.net 10553 Berlin : PGP key -> http://wwwkeys.pgp.net PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF we're tired of banana software - shipped green, ripens at home From johnk@meta3.net Sun May 9 14:29:44 1999 From: johnk@meta3.net (John Kleinjans) Date: Sun, 09 May 1999 08:29:44 -0500 Subject: [Tutor] New to this idea (!) In-Reply-To: <214a79fc.2442c52b@aol.com> Message-ID: <3.0.3.32.19990509082944.006c3da0@mail.meta3.net> At 11:40 PM 4/11/99 EDT, you wrote: >Sir/Madam, > I'm fascinated with computer programing, but I have nothing for it to >do with it right now! Any ideas/suggestions on what to write while learning? > I'm using Win 98 (control that grimace, now...it's alright, I know CPR!), >and, as stated before, have nothing to write! Any suggestions would be nice, >and remember that I'm a novice! Thanx! > > Emerson B. Lancaster 1) a calculator that takes in two numbers and adds them 2) take two numbers and add, subtract, multiply, and divide a) check for zero; add "can't divide by zero" message 3) Quadratic formula (Ax^2 + Bx + C = 0): a) get A, B, and C b) calcuate D = B^2 - 4*A*C (D for "determinant") i) if D < 0 then "no real roots" ii) if D == 0 then x = (your answer here) iii) if D > 0 then two roots; x1 and x2 c) change 3bi to return the imaginary roots d) keep getting A, B, and C until the user enters 0 for A (then it's not quadratic any more) 4) take two aspirin and call me in the morning - let us know how it goes. - john From shibumi@MailAndNews.com Sun May 9 21:22:09 1999 From: shibumi@MailAndNews.com (Rajkumar Andrews) Date: Mon, 10 May 1999 01:52:09 +0530 Subject: [Tutor] How to learn Python Message-ID: <3735EE70.22A92A4@hotmail.com> I have come acrosss Python just about a month back. I have linux box at home and am using it to learn Python. I knew c under unix many years back. Can you give me some ideas/links/pointers to what I ought to do to learn about Python? Are there any program listings of real life projects which I could access, for learning purposes only? From deirdre@deirdre.net Mon May 10 04:23:03 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Sun, 9 May 1999 23:23:03 -0400 (EDT) Subject: [Tutor] How to learn Python In-Reply-To: <3735EE70.22A92A4@hotmail.com> Message-ID: There's a lot at www.python.org; you may scrounge around your system and see what you have on your disk that might also be python-based. :) For books, my personal favorite is "Internet Programming with Python." On Mon, 10 May 1999, Rajkumar Andrews wrote: > I have come acrosss Python just about a month back. I have linux box at > home and am using it to learn Python. I knew c under unix many years > back. Can you give me some ideas/links/pointers to what I ought to do > to learn about Python? Are there any program listings of real life > projects which I could access, for learning purposes only? _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From teroc@zianet.com Mon May 10 14:32:00 1999 From: teroc@zianet.com (K P) Date: Mon, 10 May 1999 08:32:00 -0500 Subject: [Tutor] multiple class instances Message-ID: <14133431235539@zianet.com> -------Phoenix-Boundary-07081998- Content-type: text/plain; charset=ISO-8859-1 Content-transfer-encoding: Quoted-printable How can I create multiple class instances (objects=3F) that do not share the same data=3F For example the following class: class Spam: choice =3D "I\'ll have the spam" if I create an instance: spam1 =3D Spam Then reassign a data member: spam1.choice =3D "Do you have anything besides spam=3F" Then create a new instance: spam2 =3D Spam Then print spam2.choice, it will print the value assigned above: spam2.choice 'Do you have anything besides spam=3F' So my question, restated, is how can I have spam1 and spam2 based on Spam, and yet have different data for the same variables/members=3F further example, I would like this be the printout for spam1.choice and spam2.choice: spam1.choice 'Do you have anything besides spam=3F' spam2.choice 'I'll have the spam' disclaimer: It's been awhile since I saw the spam sketch so if I mis-quoted it...... Ken -------Phoenix-Boundary-07081998--- From Corran.Webster@math.tamu.edu Mon May 10 15:43:43 1999 From: Corran.Webster@math.tamu.edu (Corran Webster) Date: Mon, 10 May 1999 09:43:43 -0500 (CDT) Subject: [Tutor] multiple class instances Message-ID: <199905101443.JAA17382@fourier.math.tamu.edu> > How can I create multiple class instances (objects=3F) that do not share > the same data=3F For example the following class: > > class Spam: > choice =3D "I\'ll have the spam" I suspect that you're thinking in C++ terms here - Python is much more dynamic, so the correct place to create instance data is in the __init__ method as follows: class Spam: def __init__(self): self.choice = "I'll have the spam." spam1 = Spam() spam1.choice = "Do you have anything besides spam?" spam2 = Spam() print spam1.choice, spam2.choice > if I create an instance: > > spam1 =3D Spam Note that you aren't creating a class instance here - you're creating another reference to the Spam class. This is probably adding another level of confusion for you. What your code was doing was: * creating a class with a class variable "choice" * creating another reference to the class * changing the value of the class variable * creating a new reference to the class Note that there's only once class here, no instances, and only one variable which just has different names ("Spam.choice", "spam1.choice" and "spam2.choice"). Hope that this helps you understand Python classes a bit better. Corran From a.mueller@icrf.icnet.uk Mon May 10 15:56:32 1999 From: a.mueller@icrf.icnet.uk (Arne Mueller) Date: Mon, 10 May 1999 15:56:32 +0100 Subject: [Tutor] multiple class instances References: <14133431235539@zianet.com> Message-ID: <3736F3A0.FAE4414D@icrf.icnet.uk> Hi, THere are two different types of members: 1. Class members 2. Instance or object members You use class members which means when creating an instance of class Spam and assigning 'I\'ll have the spam' to it's choice member you modify the choice in the CLASS your instance is made from not the instance itself. So when creating a second instance it is based on the 'modified' Spam class. You've to use instance members using the 'self' phenomena ... ;-) . Self refers to the created instance object and not to the class, see below ... K P wrote: > > How can I create multiple class instances (objects?) that do not share > the same data? For example the following class: > > class Spam: > choice = "I\'ll have the spam" > > if I create an instance: > > spam1 = Spam > > Then reassign a data member: > > spam1.choice = "Do you have anything besides spam?" > > Then create a new instance: > > spam2 = Spam > > Then print spam2.choice, it will print the value assigned above: > > spam2.choice > 'Do you have anything besides spam?' > Here's some input/output of interactive python: python> class Spam: ... def __init__(self): ... self.choice = "I\'ll have the spam" ... python> spam1 = Spam() python> spam1.choice = "Do you have anything besides spam?" python> spam1.choice 'Do you have anything besides spam?' python> spam2 = Spam() python> spam2.choice "I'll have the spam" The __init__ function is the constructor of the object which is called when an object is created from class Spam. Each Onject gets it's own member 'choice', mofying 'choice' changes the instance member and not the class. Interanlly the class spam1.choice is translated into: choice(spam1), where spam1 is a reference to the object with name 'spam1' - so it's an unique object in the universe. Browese the FAQ for 'self' and you'll find lots of interesting information about how it works ... Greetings, Arne From cwebster@math.tamu.edu Mon May 10 16:48:34 1999 From: cwebster@math.tamu.edu (Corran Webster) Date: Mon, 10 May 1999 10:48:34 -0500 (CDT) Subject: [Tutor] multiple class instances In-Reply-To: <3736F3A0.FAE4414D@icrf.icnet.uk> Message-ID: <199905101548.KAA11820@radon.math.tamu.edu> > THere are two different types of members: > > 1. Class members > 2. Instance or object members > > You use class members which means when creating an instance of class > Spam and assigning 'I\'ll have the spam' to it's choice member you > modify the choice in the CLASS your instance is made from not the > instance itself. So when creating a second instance it is based on the > 'modified' Spam class. What you've written isn't correct: Python 1.5.2 (#2, Apr 15 1999, 13:12:41) [GCC 2.7.2] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> class Spam: ... choice = "I'll have the spam" ... >>> spam1 = Spam() >>> spam1.choice = "Wibble" >>> spam2 = Spam() >>> print spam2.choice I'll have the spam >>> print spam1.choice Wibble >>> print Spam.choice I'll have the spam >>> Spam.choice = "Do you have anything besides spam?" >>> print spam2.choice Do you have anything besides spam? What happens when you have a class variable and attempt to change it in the manner "instance.var = whatever" is that you create a new instance variable with the new value - the class variable remains unchanged. IOW, you can access a class variable's value as "instance.var", but you can't change the value like that. Ken's problem was compounded by the fact that he wasn't using instances anywhere - notice the parentheses were missing from the "spam1 = Spam" command inthe original code. For people learning python, note that the above sort of trick really obfuscates your code and makes it likely to have hard-to-find errors - if you are using a class variable you should (almost[1]) always refer to it as "class.var" to avoid confusion. Corran [1] Technically methods in Python are special cases of class variables, but you always refer to them as "instance.method" so that you get appropriate behavior. And there can be cases where this sort of behaviour is precisely what you want, but it's magic and confusing, so probably not best for beginners. From deirdre@deirdre.net Mon May 10 17:44:50 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 10 May 1999 12:44:50 -0400 (EDT) Subject: [Tutor] multiple class instances In-Reply-To: <14133431235539@zianet.com> Message-ID: self.choice = 'foo' will create an instance variable for that class. Assigning it to choice will be global across all instances. On Mon, 10 May 1999, K P wrote: > How can I create multiple class instances (objects?) that do not share > the same data? For example the following class: > > class Spam: > choice = "I\'ll have the spam" > > if I create an instance: > > spam1 = Spam > > Then reassign a data member: > > spam1.choice = "Do you have anything besides spam?" > > Then create a new instance: > > spam2 = Spam > > Then print spam2.choice, it will print the value assigned above: > > spam2.choice > 'Do you have anything besides spam?' > > So my question, restated, is how can I have spam1 and spam2 based on Spam, > and yet have different data for the same variables/members? > > further example, I would like this be the printout for spam1.choice and > spam2.choice: > spam1.choice > 'Do you have anything besides spam?' > spam2.choice > 'I'll have the spam' > > disclaimer: > It's been awhile since I saw the spam sketch so if I mis-quoted it...... > Ken > _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From a.mueller@icrf.icnet.uk Mon May 10 17:55:17 1999 From: a.mueller@icrf.icnet.uk (Arne Mueller) Date: Mon, 10 May 1999 17:55:17 +0100 Subject: [Tutor] multiple class instances References: <199905101548.KAA11820@radon.math.tamu.edu> Message-ID: <37370F75.8DEDD24E@icrf.icnet.uk> Corran Webster wrote: > > > THere are two different types of members: > > > > 1. Class members > > 2. Instance or object members > > > > You use class members which means when creating an instance of class > > Spam and assigning 'I\'ll have the spam' to it's choice member you > > modify the choice in the CLASS your instance is made from not the > > instance itself. So when creating a second instance it is based on the > > 'modified' Spam class. > > What you've written isn't correct: I appologize! I don't want to confuse anybody - I'm a tutee (or what's the name of people learning from the tutors?), so plase forgive me. It was more an exercise for myself, and I new that someone of the tutors will correct me if I was wrong ;-) ... . So maybe bith of us Ken and me learned something. > > Python 1.5.2 (#2, Apr 15 1999, 13:12:41) [GCC 2.7.2] on sunos5 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> class Spam: > ... choice = "I'll have the spam" > ... > >>> spam1 = Spam() > >>> spam1.choice = "Wibble" > >>> spam2 = Spam() > >>> print spam2.choice > I'll have the spam > >>> print spam1.choice > Wibble > >>> print Spam.choice > I'll have the spam > >>> Spam.choice = "Do you have anything besides spam?" > >>> print spam2.choice > Do you have anything besides spam? > > What happens when you have a class variable and attempt to change it in > the manner "instance.var = whatever" is that you create a new instance > variable with the new value - the class variable remains unchanged. > > IOW, you can access a class variable's value as "instance.var", but you > can't change the value like that. > > Ken's problem was compounded by the fact that he wasn't using instances > anywhere - notice the parentheses were missing from the "spam1 = Spam" > command inthe original code. Yes, I realized that (too late) ... . > For people learning python, note that the above sort of trick really > obfuscates your code and makes it likely to have hard-to-find errors - > if you are using a class variable you should (almost[1]) always refer to > it as "class.var" to avoid confusion. > Corran > > [1] Technically methods in Python are special cases of class variables, > but you always refer to them as "instance.method" so that you get > appropriate behavior. And there can be cases where this sort of > behaviour is precisely what you want, but it's magic and confusing, so > probably not best for beginners. Hm, I try so summarize what I think've just learned: 1. class Bla: choice = 'default' This is a class variable 2. class variables can be accessed via the Class itself Bla.default 3. or via an instance: x = Bla() x.choice 4. changeing the class variable via the class will not affect the already created instances but the future ones 5. Class variables may be used when a sort of template is needed for certian variables - the instance may change this variable according it's personal needs ..., 6. It's realy difficult to decide when to use an __init__ funtion with 'self.variable' and when to use class variables (they can do the same, can't they?). Sorry for that but it's all bit cryptic for me :-( sorry for confusion and thanks for help, Arne From deirdre@deirdre.net Mon May 10 17:48:33 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 10 May 1999 12:48:33 -0400 (EDT) Subject: [Tutor] multiple class instances In-Reply-To: <199905101443.JAA17382@fourier.math.tamu.edu> Message-ID: On Mon, 10 May 1999, Corran Webster wrote: > I suspect that you're thinking in C++ terms here - Python is much more > dynamic, so the correct place to create instance data is in the __init__ > method as follows: > > class Spam: > def __init__(self): > self.choice = "I'll have the spam." It's only necessary to create it in __init__ if it's necessary for the instantiation of the class. Otherwise, it can be done in any method with the self directive. (I'm more from the C++ school where you'd write a method to fuss with any variables rather than manipulating them directly outside the class definition) _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From cwebster@math.tamu.edu Mon May 10 18:05:36 1999 From: cwebster@math.tamu.edu (Corran Webster) Date: Mon, 10 May 1999 12:05:36 -0500 (CDT) Subject: [Tutor] multiple class instances In-Reply-To: Message-ID: <199905101705.MAA14934@radon.math.tamu.edu> On 10 May, Deirdre Saoirse wrote: > On Mon, 10 May 1999, Corran Webster wrote: > >> I suspect that you're thinking in C++ terms here - Python is much more >> dynamic, so the correct place to create instance data is in the __init__ >> method as follows: >> >> class Spam: >> def __init__(self): >> self.choice = "I'll have the spam." > > It's only necessary to create it in __init__ if it's necessary for the > instantiation of the class. Otherwise, it can be done in any method with > the self directive. (I'm more from the C++ school where you'd write a > method to fuss with any variables rather than manipulating them directly > outside the class definition) Perhaps "correct" was the wrong word - let's just say that the standard Python idiom is to intialise instance variables in the __init__ method. You are of course correct in pointing out that instance variables can be created in any method - in fact they can be created anywhere. For the tutees: spam1 = Spam() spam1.choice2 = "A new instance variable" will create an instance variable in spam1. But no other instance of Spam will even know of its existence. This can be confusing for people used to languages which use declarations heavily. I'd argue that with python, writing accessor functions is often overkill - particularly given that there is only weak data-hiding and protection available. A determined programmer can always mess with your classes and instances. For things like validation/sanity checking of values for variables, there is of course a case for accessors in python. Corran From cwebster@math.tamu.edu Mon May 10 18:58:18 1999 From: cwebster@math.tamu.edu (Corran Webster) Date: Mon, 10 May 1999 12:58:18 -0500 (CDT) Subject: [Tutor] multiple class instances In-Reply-To: <37370F75.8DEDD24E@icrf.icnet.uk> Message-ID: <199905101758.MAA16736@radon.math.tamu.edu> >> > You use class members which means when creating an instance of class >> > Spam and assigning 'I\'ll have the spam' to it's choice member you >> > modify the choice in the CLASS your instance is made from not the >> > instance itself. So when creating a second instance it is based on the >> > 'modified' Spam class. >> >> What you've written isn't correct: > > I appologize! I don't want to confuse anybody - I'm a tutee (or what's > the name of people learning from the tutors?), so plase forgive me. It No problem, and no need to apologise - sorry if I came over as hostile. > was more an exercise for myself, and I new that someone of the tutors > will correct me if I was wrong ;-) ... . So maybe bith of us Ken and me > learned something. Indeed - I got bitten by this one myself when I was learning because it is a bit counter-intuitive - once you discover that there _are_ class variables you sort of expect them to behave in a C++-ish sort of way. > Hm, I try so summarize what I think've just learned: > > 1. > class Bla: > choice = 'default' > > This is a class variable > > 2. class variables can be accessed via the Class itself > Bla.default > > 3. or via an instance: > x = Bla() > x.choice This is right. > 4. changeing the class variable via the class will not affect the > already created instances but the future ones This is not quite the whole story - if you change the class variable "Bla.choice = whatever" then "x.choice" will also change _provided_ you haven't previously changed the value. If you think of variables as references to objects, it's easier to understand what's going on: When you define the class Bla, you create an object (the string "default") in your example, which is referenced by the variable "Bla.choice". When you create instances of Bla, they don't have any object associated with "x.choice" - if you try to access the value, Python says "oh - I don't see an x.choice... but look! x is a Bla, and there's a Bla.choice, I'll use that instead". However, if you try to _set_ x.choice to something (say the string "Wibble"), Python says "oh - I don't see an x.choice... so I'll create a new variable "x.choice" which refers to this object "Wibble"). No whenever you try and access "x.choice", Python says "Aha! I have x.choice right here" and never gets around to noticing that there is also a Bla.choice. Changing Bla.choice will change the object that Bla.choice points to, and it will _appear_ to change the object that any y.choice points to as long as you haven't _changed_ y.choice previously. From a practical standpoint, "y.choice" will give you the current value of "Bla.choice", irrespective of when y was created, until such time as you say "y.choice = whatever". This is much the same sort of behaviour as local function variables, compare: a = 5 #global var def f(): print a #print the global var a def g(): a = 7 #create a local var a print a #print the local var Python is going through the same sort of process here: in f Python says "Oh - there's no local variable a... but look, there is a global variable a, I'll use its value!" In g Python says "Ah, I'll set the local variable a to 7" and then when it comes time to print, Python says "Oh look, a is a local variable, I'll use it's value". So it all makes sense when you think of it this way, but from a C/C++ perspective it's sort of odd. > 5. Class variables may be used when a sort of template is needed for > certian variables - the instance may change this variable according it's > personal needs ..., This is right. But you can also change the template value dynamically should you so desire. > 6. It's realy difficult to decide when to use an __init__ funtion with > 'self.variable' and when to use class variables (they can do the same, > can't they?). Sorry for that but it's all bit cryptic for me :-( The main difference is that class variables allow "retroactive change" of default values as discussed above, instance variables are completely independent of one another. There are also differences when you have _mutable_ objects like lists. Remember that variables are really references to objects, so if the object is mutable and you change it, it will appear to change for all other references to it. For example: Python 1.5.2 (#2, Apr 15 1999, 13:12:41) [GCC 2.7.2] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> class Bla: ... choices = ['spam', 'spam and eggs', 'spam, spam, spam and eggs'] ... >>> x = Bla() >>> x.choices[1] = 'eggs and spam' >>> print Bla.choices ['spam', 'eggs and spam', 'spam, spam, spam and eggs'] Which leads to the infamous default method gotcha: class Bla: def __init__(self, mylist = []): self.mylist = mylist (note: can be any method, not just __init__) For the tutees: the default argument [] is actually an anonymous class variable - so this construct means that for each instance the variable x.mylist refers to the same mutable object >>> x = Bla() >>> y = Bla() >>> print y.mylist [] >>> x.mylist.append('a') >>> print y.mylist ['a'] Everyone gets bitten by this at least once. A good idiom to do what you _want_ to do in this case is: class Bla: def __init__(self, mylist = None): self.mylist = mylist or [] > sorry for confusion and thanks for help, No problem - there's a Zen to Python variables and objects. Once you get it, you're fine, but it's probably the most unintuitive aspect of the language for those who have been trained in something like C or Pascal. Corran From ivanlan@callware.com Mon May 10 19:31:17 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Mon, 10 May 1999 12:31:17 -0600 Subject: [Tutor] Re: New person Question Re Python on WinNT References: <7h714u$hto$1@lure.pipex.net> Message-ID: <373725F5.E4C102EB@callware.com> Hi All-- "Michael P. Reilly" wrote: > > Tim B wrote: > : I am trying to use python for CGI scripts on WinNT running > : Apache web server. Forgive my ignorance but what is the > : #! line I should add at the beginning of my script to make it > : executable? > > Hi, Tim. > > On WinNT, you can safely ignore the "#!" line (called a shebang). It > is principly for UNIX where extensions are not significant (at the OS > level), so the first set of bytes of files are read to determine how > the file should be called (called the magic number). This is a feature > not a bug, since the file must be opened and read to run the program > file anyway, this is generally not considered an issue. > > Windows uses the registry and it's reliance on extensions to get this > affect. If your Python script does not run without this line, I would > look to other problems. > Sorry, but the Apache server on NT *does* implement the #! syntax, and, in fact, requires it. I've been running Apache on NT since Apache brought out the WinNT version. Tim B, you need to track down your Python installation. On my NT system, it lives in C:\Python, so what I put in my Python CGI programs is "#!c:\python\python.exe" ... You will also need to make sure that Apache is configured to recognize your cgi-bin as a legitimate place for CGI programs. Hope this helps, Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From teroc@zianet.com Mon May 10 20:27:40 1999 From: teroc@zianet.com (K P) Date: Mon, 10 May 1999 14:27:40 -0500 Subject: [Tutor] multiple class instances Message-ID: <19264826569644@zianet.com> -------Phoenix-Boundary-07081998- Content-type: text/plain; charset=ISO-8859-1 Content-transfer-encoding: Quoted-printable First, a nice hearty thanks for everyones suggestions, points and help. It taught me a lot! Yes I wass thinking in the c++ form of classes, though I will admit I like Python's implementation much better. The ability to add data variables/members "on the fly" is very intriguing. Some practice seems to be in order so I can remember all this, and use it "correctly". Ken -------Phoenix-Boundary-07081998--- From a.mueller@icrf.icnet.uk Mon May 10 20:44:12 1999 From: a.mueller@icrf.icnet.uk (Arne Mueller) Date: Mon, 10 May 1999 20:44:12 +0100 Subject: [Tutor] multiple class instances Message-ID: <3737370C.52D202C7@icrf.icnet.uk> Hi All - and thanks Corran for the that 'beautyful' help. I mean it wasn't that abstract as your last article - so was able to get most of it ;-). Realy, thank very much! > Which leads to the infamous default method gotcha: > > class Bla: > def __init__(self, mylist = []): > self.mylist = mylist > > (note: can be any method, not just __init__) > > For the tutees: the default argument [] is actually an anonymous class > variable - so this construct means that for each instance the variable > x.mylist refers to the same mutable object > > >>> x = Bla() > >>> y = Bla() > >>> print y.mylist > [] > >>> x.mylist.append('a') > >>> print y.mylist > ['a'] > > Everyone gets bitten by this at least once. A good idiom to do what > you _want_ to do in this case is: > > class Bla: > def __init__(self, mylist = None): > self.mylist = mylist or [] > But z = Bla(['my_own']) get's it's own list object (not only reference). >From this point on it's sort of independent ... (right). Do I have to know that the empty list '[]' in the above example is an anonymous class variable (of class 'list'?) because it's following the python philosophy or do you know that because you had a look in the implementation of python's list class? So python programmers have to be aware of class variables (especially when they're anonymous). Huh, that's realy hard to get but I think it'll become better when writing some python progs :-) . Thanks, Arne From cwebster@math.tamu.edu Mon May 10 21:33:00 1999 From: cwebster@math.tamu.edu (Corran Webster) Date: Mon, 10 May 1999 15:33:00 -0500 (CDT) Subject: [Tutor] multiple class instances In-Reply-To: <3737370C.52D202C7@icrf.icnet.uk> Message-ID: <199905102033.PAA21804@radon.math.tamu.edu> > Hi All - > > and thanks Corran for the that 'beautyful' help. I mean it wasn't that > abstract as your last article - so was able to get most of it ;-). > Realy, thank very much! You're welcome - and sorry if my first reply was a bit cryptic - I wasn't sure just where you were at in your knowledge of python. >> Which leads to the infamous default method gotcha: ^^^^^^ Urg - this should really be "default argument gotcha". Nothing particularly special about methods, that's just where it come up most often. >> class Bla: >> def __init__(self, mylist = []): >> self.mylist = mylist >> >> (note: can be any method, not just __init__) >> >> For the tutees: the default argument [] is actually an anonymous class >> variable - so this construct means that for each instance the variable >> x.mylist refers to the same mutable object >> >> >>> x = Bla() >> >>> y = Bla() >> >>> print y.mylist >> [] >> >>> x.mylist.append('a') >> >>> print y.mylist >> ['a'] [snip] > But z = Bla(['my_own']) get's it's own list object (not only reference). > From this point on it's sort of independent ... (right). Precisely - for z, at least. Other instances can still have the original weird behaviour. > Do I have to know that the empty list '[]' in the above example is an > anonymous class variable (of class 'list'?) because it's following the > python philosophy or do you know that because you had a look in the > implementation of python's list class? It's more because it's following python philosophy, plus a bit of folklore which I picked up in c.l.py that python evaluates default arguments when it defines the function (which is the natural time to do it). This behaviour isn't restricted to lists - you can get it happening with any mutable object such as a dictionary or class instance. Let's have a closer look at the code and see what's going on: class Bla: def __init__(self, mylist = []): self.mylist = mylist When Python rund this, it hits the method definition and says "Aha! mylist has a default value - it's the list object [] - I'd better squirrel away an internal reference to this in case I need it later" >>> x = Bla() When Python sees this is says "Whoa - not enough arguments... but wait, there's a default for mylist - it's this empty list that I held onto earlier. Good thing I remembered." But then it creates x.mylist (aka self.mylist) to point to the same empty list (BTW, there can be more than one different copy of the empty list, there's nothing canonical about it). >>> y = Bla() Same thing happens here, creating y.mylist. So now Python has three references to the single list object - the anonymous internal reference held by Bla.__init__, x.mylist and y.mylist. Use any one of these to mutate the list - by appending or whatever - and all three will appear to change. Such as: x.mylist.append('a') As a side note, the object is not completely anonymous - if you want to see it, have a look at Bla.__init__.im_func.func_defaults and you'll see it's a tuple with the list object as one of it's entries. >>> Bla.__init__.im_func.func_defaults (['a'],) > So python programmers have to be aware of class variables (especially > when they're anonymous). Huh, that's realy hard to get but I think it'll > become better when writing some python progs :-) . I'm not sure how much you need to be aware of them - all you need to know is that you should avoid the sort of default variable as above. It's not really even something to do with class variables. Consider the following: Python 1.5.2 (#2, Apr 15 1999, 13:12:41) [GCC 2.7.2] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> def f(x = []): ... x.append('a') ... print x ... >>> f() ['a'] >>> f() ['a', 'a'] >>> f(['wibble']) ['wibble', 'a'] >>> f() ['a', 'a', 'a'] Same sort of thing is happening here, this time with an anonymous global list (or if you prefer, it's not anonymous, it's hiding in f.func_defaults). You don't really need to understand what's going on here to avoid problems, rather you just need to remember the rule: "Avoid mutable default values in functions and methods" I can't think of a situation where this sort of default argument behaviour would be useful, although I'm sure Tim Peters could come up with one . Corran From tim_one@email.msn.com Tue May 11 04:19:26 1999 From: tim_one@email.msn.com (Tim Peters) Date: Mon, 10 May 1999 23:19:26 -0400 Subject: [Tutor] multiple class instances In-Reply-To: <199905102033.PAA21804@radon.math.tamu.edu> Message-ID: <000201be9b5d$12b0e800$569e2299@tim> [Corran Webster, explaining the unexplainable!] > ... > You don't really need to understand what's going on here to avoid > problems, rather you just need to remember the rule: > > "Avoid mutable default values in functions and methods" > > I can't think of a situation where this sort of default argument > behaviour would be useful, although I'm sure Tim Peters could come up > with one . Everything that isn't forbidden becomes vital to someone <0.5 wink>. One reasonable use is to supply a default for a sequence argument that *isn't* (and never will be) mutated: class Set: def __init__(self, initial=[]): """Set([initial]) -> construct a Set. By default, the Set is empty. If optional arg initial is given, it must be a sequence, and the Set is initialized to contain (only) its elements. """ self.dict = dict = {} for element in initial: dict[element] = 1 # value irrelevant Perfectly safe! Because "initial" is neither changed nor saved away; it's merely examined once and then forgotten. So we can refine your rule to: "Avoid mutable default values in functions and methods, unless they're not and never can be mutated" If the latter is true, they may as well be immutable! The other good use violates even that rule, but in this case the user is never supposed to supply a value: def fac(n, _cache={}): """fac(n) -> factorial of n; n must be >= 0.""" try: return _cache[n] except KeyError: if n < 0: raise ValueError("fac argument must be >= 0: " + `n`) if n <= 1: result = 1L else: result = n * fac(n - 1) _cache[n] = result return result This is a common trick for speeding recursive functions, using _cache to remember the results that have already been computed. You could do this with a global var _cache too, but this way hides the name and-- by making the name local instead of global --happens to slash the time it takes Python to "look the name up". OTOH, if someone calls fac with *two* arguments, it will screw up the function beyond repair. Fair summary: Avoid mutable default values in functions and methods . unless-you-have-a-cool-reason-to-tempt-fate-ly y'rs - tim From lonelysaint@netzero.net Tue May 11 07:06:30 1999 From: lonelysaint@netzero.net (kevin) Date: 11 May 99 01:06:30 -0500 Subject: [Tutor] help with language Message-ID: <199905110507.BAA04603@python.org> i want help man this is hard kid esko ________________________________________________________ NetZero - We believe in a FREE Internet. Shouldn't you? Get your FREE Internet Access and Email at http://www.netzero.net/download/index.html From deirdre@deirdre.net Tue May 11 06:39:17 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 11 May 1999 01:39:17 -0400 (EDT) Subject: [Tutor] help with language In-Reply-To: <199905110507.BAA04603@python.org> Message-ID: On 11 May 1999, kevin wrote: > i want help man this is hard As compared to? Sorry, Python's a pretty easy language.... _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From cwebster@math.tamu.edu Tue May 11 16:35:39 1999 From: cwebster@math.tamu.edu (Corran Webster) Date: Tue, 11 May 1999 10:35:39 -0500 (CDT) Subject: [Tutor] multiple class instances In-Reply-To: <000201be9b5d$12b0e800$569e2299@tim> Message-ID: <199905111535.KAA11659@radon.math.tamu.edu> On 10 May, Tim Peters wrote: > [Corran Webster, explaining the unexplainable!] >> I can't think of a situation where this sort of default argument >> behaviour would be useful, although I'm sure Tim Peters could come up >> with one . [snip sort of example I thought might come up :) ] > The other good use violates even that rule, but in this case the user is > never supposed to supply a value: > > def fac(n, _cache={}): > """fac(n) -> factorial of n; n must be >= 0.""" > try: > return _cache[n] > except KeyError: > if n < 0: > raise ValueError("fac argument must be >= 0: " + `n`) > if n <= 1: > result = 1L > else: > result = n * fac(n - 1) > _cache[n] = result > return result This is truly deviously evil. Thank you. > This is a common trick for speeding recursive functions, using _cache to > remember the results that have already been computed. You could do this > with a global var _cache too, but this way hides the name and-- by making > the name local instead of global --happens to slash the time it takes Python > to "look the name up". OTOH, if someone calls fac with *two* arguments, it > will screw up the function beyond repair. Hmmm... is it really going to be that much faster? Presumably there is some overhead associated with having to find the default value. And of course someone could always clobber your _cache variable if you use a more traditional approach. > Fair summary: Avoid mutable default values in functions and methods . Corran From teroc@zianet.com Wed May 12 14:20:28 1999 From: teroc@zianet.com (K P) Date: Wed, 12 May 1999 08:20:28 -0500 Subject: [Tutor] Another class issue Message-ID: <13293343767166@zianet.com> -------Phoenix-Boundary-07081998- Content-type: text/plain; charset=ISO-8859-1 Content-transfer-encoding: Quoted-printable Remember this disclaimer please: The following is asked by a new programmer, not just in Python terms, but in any language terms. As such the view expressed will be inacurrate, convoluted and generally strange. And now for the questioning: Since class data members/variables can be accessed directly in Python i.e Spam.meat =3D "Mechanically separated chicken", thus negating the need for data access methods i.e Spam.setTypeOfMeat("Mechanically separated chicken"), what would be the reasoning, motivation or whatever to implement classes in Python=3F As I see it (through a maybe narrow/imperfect view), the classes are more akin to a C struct with some functions/methods included (said methods. For exmpale, why create a class such as: class Spam: colour1 =3D "red" colour2 =3D "brown" def colourChange(self, colour): self.colour1 =3D colour when this would do: Spam.colour1 =3D "yellow" If you have followed my convoluted questioning, what I am really asking is this: why use classes in Python=3F What would be the purpose (other than a wrapper for a library, etc)=3F Ken -------Phoenix-Boundary-07081998--- From Christian.Schaller@atd.mchh.siemens.de Wed May 12 15:08:45 1999 From: Christian.Schaller@atd.mchh.siemens.de (Christian.Schaller@atd.mchh.siemens.de) Date: Wed, 12 May 1999 16:08:45 +0200 Subject: [Tutor] extended slicings Message-ID: Hello... Just a dull question: how are extended slicings used? The Python Ref (pp30) just says it is used with mapping objects. Can you please give me an example? Thanks a lot! bye Chris... From joe@strout.net Wed May 12 16:20:33 1999 From: joe@strout.net (Joseph J. Strout) Date: Wed, 12 May 1999 08:20:33 -0700 Subject: [Tutor] Another class issue In-Reply-To: <13293343767166@zianet.com> Message-ID: At 6:20 AM -0700 05/12/99, K P wrote: >what would be the reasoning, motivation or whatever to implement >classes in Python? The benefits of object-oriented programming are numerous! Information hiding is only one; and there are ways to do this in Python as well (it's just that by default, all data members are publicly accessible, which is convenient for beginners and for rapid prototyping). Basically, a class keeps your data and your functions together ("encapsulation"). You don't have to worry about accidentally passing a Foo structure to a function that's expecting a Bar; you just to myObject.Func() and it executes the right thing. Even better, is that one class can "derive" (or "inherit") from another (or several others), extending their functionality by adding new methods, or changing only the methods that need to be changed. (These are the properties of inheritance and polymorphism.) It's hard to explain briefly why this is so amazingly powerful, but you'll discover it as you get more experience programming. >why create a class such as: > >class Spam: > colour1 = "red" > colour2 = "brown" > def colourChange(self, colour): > self.colour1 = colour Why indeed? You have no instance variables here, but only class variables. I use class variables very rarely, and if you had a class with *only* class variables, like the above, there would be not much point in it at all. The sensible class would be this: class Spam: def __init__(self): colour1 = "red" colour2 = "brown" num = 5 Then, as you say, the colourChange method is not really needed. If this is all you need, then fine, the Spam class is basically a data structure. But often you want these things to actually do something. E.g.: def print(self): print "spam "*num Now you can do mySpam = Spam(), then mySpam.print() to see what happens. Now let's explore inheritance. Suppose you want a modified version of Spam for special cases, like this: class SpamWithBeans(Spam): def print(self): print "spam "*(num-1),"baked beans and spam" Now, if you do mySpam = SpamWithBeans(), mySpam.print() will do something slightly different than it does for regular Spam. See what I mean? Cheers, -- Joe ,------------------------------------------------------------------. | Joseph J. Strout Biocomputing -- The Salk Institute | | joe@strout.net http://www.strout.net | `------------------------------------------------------------------' From adeline_j_wilcox@ccMail.Census.GOV Wed May 12 23:05:49 1999 From: adeline_j_wilcox@ccMail.Census.GOV (adeline_j_wilcox@ccMail.Census.GOV) Date: Wed, 12 May 1999 18:05:49 -0400 Subject: [Tutor] ksh and SAS questions Message-ID: <9905129265.AA926546962@smtp-gw1.census.gov> Using a script named recheck.py, I call a ksh script named setcm.ksh. That script exports some shell variables. I would like to substitute the value of one shell variable in particular, named CATI, for the value 199904 in lines 14, 23 and 24. Please note that I want to pass the value of this shell variable to a SAS program with the SYSPARM option in line 23. Can anyone tell me how to get ksh, Python and SAS working together here? I need to get the value of the shell variable into Python and pass it to SAS as well as make other use of its value. BTW, this script is in production, at least until the task is passed to other programmers within a few months. I have neither C programming nor OOP experience. Also very new to Python. Have done a little reading of Lutz 1996 Programming Python. Reference to the Python documentation on the Web could be helpful. Adeline Wilcox 1 #!/usr/local/bin/python 2 #PROGRAM: recheck.py 3 #FUNCTION: execute Barbara's RECHECK program 4 #INPUTS: rofr.txt 5 #OUTPUTS: rofr.sas, ccMail message 6 #CALLS TO: Python os, sys, and string modules, recheck.sas 7 #SPECIAL NOTES: Have not yet figured out how to automate input of the royyyymm file 8 #AUTHOR: Adeline Wilcox DATE: 05Apr99 9 #Written with the assistance of Andrew Kuchling and especially Tim Peters 10 #UPDATED: DATE: 11 import os, sys 12 os.system('/op/ctl/prod/scripts/setcm.ksh') 13 import string 14 sys.stdin = open('/op/ctl/prod/data/ro199904.txt','r') 15 lines = sys.stdin.readlines() 16 for i in range(len(lines)): 17 line = lines[i] 18 lines[i] = "'" + string.rstrip(line) + "'" 19 sys.stdout= open('/op/ctl/prod/data/rofr.sas','w') 20 print "if rofr in (" + string.join(lines, ", ") + ") then output;" 21 #if I dont close the file, SAS does not get quotes around last value of rofr 22 sys.stdout.close() 23 os.system("$SASDIR/sas /op/ctl/prod/prgms/recheck.sas -sysparm 199904 -log /op/ctl/prod/logs/recheck.log.199904") 24 os.system("mailx -s '199904 for you' Adeline.J.Wilcox@ccmail.census.gov < rc199904.txt") From Corran.Webster@math.tamu.edu Wed May 12 23:52:19 1999 From: Corran.Webster@math.tamu.edu (Corran Webster) Date: Wed, 12 May 1999 17:52:19 -0500 (CDT) Subject: [Tutor] ksh and SAS questions Message-ID: <199905122252.RAA20972@fourier.math.tamu.edu> > Using a script named recheck.py, I call a ksh script named > setcm.ksh. That script exports some shell variables. I would like to > substitute the value of one shell variable in particular, named CATI, > for the value 199904 in lines 14, 23 and 24. Please note that > I want to pass the value of this shell variable to a SAS program with the > SYSPARM option in line 23. The os.environ variable gives you access to the UNIX environment variables, so: import os month = os.environ['CATI'] puts the value as a string in the variable month. > Can anyone tell me how to get ksh, Python and SAS working together here? I've appended an updated version of the program which should do what I think you want. I've also fixed up what I think was a major inefficiency by moving the write to the file "rofr.sas" out of the for loop (if this isn't what you want, then you can easily put it back into the loop). I also prettified it a bit. > I have neither C programming nor OOP experience. Also very new to Python. > Have done a little reading of Lutz 1996 Programming Python. Reference > to the Python documentation on the Web could be helpful. The library documentation on www.python.org whould tell you what you need to know about the os module and the os.environ variable. If you have questions about what's going on in the script, please ask. Corran ---- #!/usr/local/bin/python #PROGRAM: recheck.py #FUNCTION: execute Barbara's RECHECK program #INPUTS: rofr.txt #OUTPUTS: rofr.sas, ccMail message #CALLS TO: Python os, sys, and string modules, recheck.sas #AUTHOR: Adeline Wilcox DATE: 05Apr99 #Written with the assistance of Andrew Kuchling and especially Tim Peters #UPDATED: DATE: import os, sys os.system('/op/ctl/prod/scripts/setcm.ksh') # get value of CATI from environment month = os.environ['CATI'] import string sys.stdin = open('/op/ctl/prod/data/ro' + month + '.txt','r') lines = sys.stdin.readlines() for i in range(len(lines)): line = lines[i] lines[i] = "'" + string.rstrip(line) + "'" sys.stdout= open('/op/ctl/prod/data/rofr.sas','w') print "if rofr in (" + string.join(lines, ", ") + ") then output;" #if I dont close the file, SAS does not get quotes around last value of rofr sys.stdout.close() os.system("$SASDIR/sas /op/ctl/prod/prgms/recheck.sas -sysparm " + month + \ " -log /op/ctl/prod/logs/recheck.log." + month) os.system("mailx -s '" + month + " for you' " + \ "Adeline.J.Wilcox@ccmail.census.gov < rc" + month + ".txt") From tim_one@email.msn.com Thu May 13 05:29:35 1999 From: tim_one@email.msn.com (Tim Peters) Date: Thu, 13 May 1999 00:29:35 -0400 Subject: [Tutor] multiple class instances In-Reply-To: <199905111535.KAA11659@radon.math.tamu.edu> Message-ID: <000d01be9cf9$34919b20$fe9e2299@tim> [Tim, abuses the default argument gimmick to give a recursive function memory of what it has already computed] > ... > You could do this with a global var _cache too, but this way hides > the name and-- by making the name local instead of global --happens > to slash the time it takes Python to "look the name up". [Corran Webster] > Hmmm... is it really going to be that much faster? Presumably there is > some overhead associated with having to find the default value. Right, in this example the overall difference was very small; the _cache was referenced only once or twice per call, and per-call overhead is much higher than per-name lookup overhead. The name-hiding tradeoffs are much more important, in that they effect robustness and maintainability, legitimate concerns for any design. I'm ashamed to have even mentioned the nano-optimization! not-that-i'll-apologize-i'm-too-old-for-that-ly y'rs - tim From alan.gauld@bt.com Thu May 13 10:23:14 1999 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 13 May 1999 10:23:14 +0100 Subject: [Tutor] Another class issue Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB24E0995@mbtlipnt02.btlabs.bt.co.uk> > Since class data members/variables can be accessed > directly in Python i.e > Spam.meat = "Mechanically separated chicken", thus negating > the need for > data access methods i.e Spam.setTypeOfMeat("Mechanically separated > chicken"), what would be the reasoning, motivation or > whatever to implement > classes in Python? To do OO programming which is about encapsulation of data and function in a single entity. Whether you access the data directly or via methods is somewhat irrelevant. One of the worst types of OO design is to implement a class(in C++) which has a get/set pair for every data member - this is a huge waste of effort and misses the point of offering a behavioural interface to the class. If the behavioral interface is done properly there will be no need for a programmer to access the internal data, so whether the language permits it or not is academic. To illustrate: A car object has a simple interface to the driver: turn right/left, accelerate, brake, park, switch on/off etc. The driver can *if he wishes* do these things by accessing the component parts of his car (eg bypass the ignition key and hot wire it) but he choooses not to because there is a simpler interface provided. Data hiding is one part of OO programming that is heavily emphasised in C++ etc but is not universally adopted by OO languages - many Lisp OO dialects have no data hiding at all but support other aspects of OO more fully than C++ OO is about how you organise programs - objects requesting services of other objects by senbding messages to them rather than a rigid heirarchy of function calls. Other capabilities, like polymorphism, either through inheritance structures or otherwise enhance the power of that metaphor by making programs extensible in ways that are difficult to achieve using procedural methods/techniques. Alan G. As I see it (through a maybe > narrow/imperfect view), > the classes are more akin to a C struct with some functions/methods > included (said methods. For exmpale, why create a class such as: > > class Spam: > colour1 = "red" > colour2 = "brown" > def colourChange(self, colour): > self.colour1 = colour > > when this would do: > > Spam.colour1 = "yellow" > > If you have followed my convoluted questioning, what I am > really asking is > this: why use classes in Python? What would be the purpose > (other than a > wrapper for a library, etc)? > > Ken > From mike_pope@usa.net Sun May 16 03:18:10 1999 From: mike_pope@usa.net (mike pope) Date: 16 May 99 02:18:10 America/Fort_Wayne Subject: [Tutor] hi Message-ID: <19990516021810.4889.qmail@nwcst068.netaddress.usa.net> In case u didn't know i need help, thats i want this tutorial. So i don't get any e-mail that i don't need ill tell u whats bothering me. I need help making EXE. files. I herd that if i used freeze i would beable to complete this task, but i need help doing it, iv read all of the readme's and manuals but it dosn't work. So if you could give me a good explanation of freeze and a working example and an example of it in affect in a source code, i would be aprecative. ____________________________________________________________________ Get free e-mail and a permanent address at http://www.netaddress.com/?N=1 From SlikWiIIy@aol.com Sun May 16 17:27:29 1999 From: SlikWiIIy@aol.com (SlikWiIIy@aol.com) Date: Sun, 16 May 1999 12:27:29 EDT Subject: [Tutor] HI Message-ID: <8178084a.24704bf1@aol.com> What is a good way to learn PYTHON without having to buy anything? From Jon Cosby" This is a multi-part message in MIME format. ------=_NextPart_000_0005_01BEA04D.9B426BE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi - Is there any way to index sequences with long integers? I see you = can't multiply sequences with long values, or assign them to the range = function. I'd like to be able to apply the following code, for i in range(min, max, 2): if primeTest(i) =3D=3D 1: pl.append(i) return pl to long values for min amd max. Any suggestion? Thanks, Jon Cosby ------=_NextPart_000_0005_01BEA04D.9B426BE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi - Is there any way to index sequences with long = integers? I=20 see you can't multiply sequences with long values, or assign them to the = range=20 function. I'd like to be able to apply the following code,
 
     for i in range(min, max,=20 2):
         if primeTest(i) = =3D=3D=20 1:
          =20 pl.append(i)
     return pl
 
to long values for min amd max. Any suggestion?=20 Thanks,
 
Jon Cosby
------=_NextPart_000_0005_01BEA04D.9B426BE0-- From tim_one@email.msn.com Tue May 18 05:46:07 1999 From: tim_one@email.msn.com (Tim Peters) Date: Tue, 18 May 1999 00:46:07 -0400 Subject: [Tutor] Indexing sequences with long integers In-Reply-To: <000801bea088$611adf20$6a1c9fce@wolfenet.com> Message-ID: <000701bea0e9$57eb11c0$829e2299@tim> [Jon Cosby] > Hi - Is there any way to index sequences with long integers? No, at least none of the builtin sequences. If know the longs have reasonably small values, you can do sequence[int(the_long)] though (which will raise an exception if the long is too big to fit in an int). > I see you can't multiply sequences with long values, or assign them to > the range function. I'd like to be able to apply the following code, > > for i in range(min, max, 2): > if primeTest(i) == 1: > pl.append(i) > return pl > > to long values for min amd max. Any suggestion? i = min while i < max: ... i = i + 2 or for offset in range(0, int(max - min), 2): i = min + offset ... If max-min isn't small enough to fit in an int, you'll die long before the program could have completed anyway . Or you could define your own sequence type, like: class LongRange: def __init__(self, min, max, step): if step == 0: raise ValueError("LongRange step must not be zero.") self.min = min self.max = max self.step = step def __getitem__(self, i): this = self.min + i * self.step if self.step > 0: if this < self.max: return this else: if this > self.max: return this raise IndexError for i in LongRange(1000000000000000L, 1000000000000010L, 2): print i longingly y'rs - tim From michael@mediamanager.com.sg Tue May 18 10:15:43 1999 From: michael@mediamanager.com.sg (Michael Ang) Date: Tue, 18 May 1999 17:15:43 +0800 Subject: [Tutor] Delete file Message-ID: <19990518085623699.AAA140@michael> Hi, I'm new to this list, can someone tell me how to delete file (win95) and check for file exist beside using glob.glob command. Thanks. Michael Ang From da@ski.org Tue May 18 18:55:20 1999 From: da@ski.org (David Ascher) Date: Tue, 18 May 1999 10:55:20 -0700 (Pacific Daylight Time) Subject: [Tutor] Delete file In-Reply-To: <19990518085623699.AAA140@michael> Message-ID: > I'm new to this list, can someone tell me how to delete file > (win95) and check for file exist beside using glob.glob command. The "remove" function in the os module will remove a file: >>> os.remove('foo.txt') and the "exists" function in the os.path module will return 1 or 0 depending on whether the specified path (file or directory) exists: >>> os.path.exists('c:\\winnt') 1 >>> os.path.exists('c:\\winntasdasd') 0 --david ascher From da@ski.org Tue May 18 19:08:48 1999 From: da@ski.org (David Ascher) Date: Tue, 18 May 1999 11:08:48 -0700 (Pacific Daylight Time) Subject: [Tutor] ksh and SAS questions In-Reply-To: <9905129265.AA926546962@smtp-gw1.census.gov> Message-ID: On Wed, 12 May 1999 adeline_j_wilcox@ccMail.Census.GOV wrote: > Using a script named recheck.py, I call a ksh script named > setcm.ksh. That script exports some shell variables. I would like to > substitute the value of one shell variable in particular, named CATI, > for the value 199904 in lines 14, 23 and 24. Please note that > I want to pass the value of this shell variable to a SAS program with the > SYSPARM option in line 23. You may want to modify the environment variable by modifying the os.environ dictionary before the os.system() call. E.g. os.environ['CATI'] = '199904' I don't understand why you think that line 14 has anything to do with environment variables, though -- line 12 does. So I'd put the line above before line 12 and that might do the job. > 12 os.system('/op/ctl/prod/scripts/setcm.ksh') ... > 14 sys.stdin = open('/op/ctl/prod/data/ro199904.txt','r') ... > 23 os.system("$SASDIR/sas /op/ctl/prod/prgms/recheck.sas > -sysparm 199904 -log /op/ctl/prod/logs/recheck.log.199904") > 24 os.system("mailx -s '199904 for you' --david From da@ski.org Tue May 18 19:39:29 1999 From: da@ski.org (David Ascher) Date: Tue, 18 May 1999 11:39:29 -0700 (Pacific Daylight Time) Subject: [Tutor] extended slicings In-Reply-To: Message-ID: On Wed, 12 May 1999 Christian.Schaller@atd.mchh.siemens.de wrote: > Just a dull question: how are extended slicings used? The Python Ref > (pp30) just says it is used with mapping objects. Can you please give me an > example? The only known use of extended slicing (at least known to me =) is the Numeric Python array slicing. By extended slicing I refer to the :: notation (a[1:10:2]). Here's how slicing works in general -- it depends on what's inside the []'s. Let's setup a test class to tell us what it's doing: >>> class TestClass: ... def __getitem__(self, item): ... print "__getitem__ with", item ... def __getslice__(self, start, end): ... print "__getslice__ with", start, end ... and we'll create an instance of this: >>> thing = TestClass() Now, if there's only one thing in the [] (no :'s), then __getitem__ is called, with the "thing" being the argument to __getitem__: >>> thing[1] __getitem__ with 1 If there are two things separated by a :, then the __getslice__ call is invoked, with the two arguments: >>> thing[1:3] __getslice__ with 1 3 If the "end" of the slice is omitted, then sys.maxint is the second argument: >>> thing[1:] __getslice__ with 1 2147483647 if the "beginning" of the slice is omitted, then 0 is the first argument: >>> thing[:4] __getslice__ with 0 4 This is all standard and used all over the place. For extended slicing, things are a little odder -- when three arguments (two :'s) are used, then __getitem__ is called with a slice object as the sole argument. That slice object is a new kind of Python object (recently introduced in the bestiary of types), which has a "constructor" slice() builtin, and has three attributes (start, stop, step). To test it: >>> thing[1:10:2] __getitem__ with slice(1, 10, 2) This is the same as >>> thing[slice(1,10,2)] __getitem__ with slice(1, 10, 2) Examining just what these 'slice' objects are: >>> sampleslice = slice(1,10,2) >>> sampleslice slice(1, 10, 2) >>> dir(sampleslice) ['start', 'step', 'stop'] >>> sampleslice.start 1 >>> sampleslice.step 2 >>> sampleslice.stop 10 What about when some of the "arguments" to the slice are omitted? >>> thing[:10:2] __getitem__ with slice(None, 10, 2) >>> thing[1::2] __getitem__ with slice(1, None, 2) >>> thing[1:10:] __getitem__ with slice(1, 10, None) >>> thing[::] __getitem__ with slice(None, None, None) In other words, omitted arguments are replaced with None. This is different from the slice behavior (and IMHO better). What extended slicing *does* is up to the object, just like for all of the __special__ calls. You can tell from the names of the attributes of slice objects that the motivating notion for them was to define a stepsize, or a stride, of a range. But that's up to you, the programmer, to decide. --david ascher From ron@steckel.com Tue May 18 19:58:29 1999 From: ron@steckel.com (Ron Fountain) Date: Tue, 18 May 1999 14:58:29 -0400 Subject: [Tutor] ok...a newbie question Message-ID: <000601bea160$6bc72c20$3864a8c0@netadmin.steckel.com> What does one do with python (vague enough for yaz)? Ron Fountain Jr. Network Administrator http://www.steckel.com mailto:ron@steckel.com From ivanlan@callware.com Tue May 18 20:26:50 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Tue, 18 May 1999 13:26:50 -0600 Subject: [Tutor] ok...a newbie question References: <000601bea160$6bc72c20$3864a8c0@netadmin.steckel.com> Message-ID: <3741BEFA.513C547E@callware.com> Hi All-- Ron Fountain wrote: > > What does one do with python (vague enough for yaz)? > Anything. Really. I hardly know where to start. The areas where I would *not* use Python are limited to: 1) dredging through great huge text files looking for matches for regular expressions (especially complicated ones). 2) applications where snappy real-time response is required. 3) cooking dinner, cleaning house, suggesting cosmetic makeovers. ... What did you have in mind? For any given computer application, the odds are very good indeed that Python would help, either in the production implementation, prototyping speed, or programmer maintainability. If you'd care to be more specific, there are plenty of people on this list who would be happy to jump in with as many opinions as you are able to handle. The odds are good that whatever you want to do with Python, someone else has at least gotten started and can give you good advice. -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From ron@steckel.com Tue May 18 20:55:50 1999 From: ron@steckel.com (Ron Fountain) Date: Tue, 18 May 1999 15:55:50 -0400 Subject: [Tutor] what to do with python Message-ID: <000d01bea168$6f50ce70$3864a8c0@netadmin.steckel.com> I would like to write scripts that will backup various files, either on the linux box or through the network(grabbing files from other nodes). I would also like to setup a script that would be able to "route" data files according to what kind of file they are. If file = "A" then go here...if file = "B" then do this --type of thing. Is python what i would use, or something else? Ron Fountain Jr. Network Administrator http://www.steckel.com mailto:ron@steckel.com From da@ski.org Tue May 18 20:58:54 1999 From: da@ski.org (David Ascher) Date: Tue, 18 May 1999 12:58:54 -0700 (Pacific Daylight Time) Subject: [Tutor] what to do with python In-Reply-To: <000d01bea168$6f50ce70$3864a8c0@netadmin.steckel.com> Message-ID: On Tue, 18 May 1999, Ron Fountain wrote: > I would like to write scripts that will backup various files, either on the > linux box or through the network(grabbing files from other nodes). I would > also like to setup a script that would be able to "route" data files > according to what kind of file they are. If file = "A" then go here...if > file = "B" then do this --type of thing. > > Is python what i would use, or something else? You could certainly use Python to do this. Modules of interest are "os", "os.path", "sys", "ftplib", etc. (documentation available at www.python.org/doc). -david ascher From ron@steckel.com Tue May 18 21:15:22 1999 From: ron@steckel.com (Ron Fountain) Date: Tue, 18 May 1999 16:15:22 -0400 Subject: [Tutor] how to learn python Message-ID: <001301bea16b$2929cb10$3864a8c0@netadmin.steckel.com> Ok, here is the tuffy! I'm more into hardware and networking than I am programming. I've tinkered w/ basic and cobol. How would I learn python...my guess is to buy the book "Python in a nutshell". Ron Fountain Jr. Network Administrator http://www.steckel.com mailto:ron@steckel.com From da@ski.org Tue May 18 21:24:38 1999 From: da@ski.org (David Ascher) Date: Tue, 18 May 1999 13:24:38 -0700 (Pacific Daylight Time) Subject: [Tutor] how to learn python In-Reply-To: <001301bea16b$2929cb10$3864a8c0@netadmin.steckel.com> Message-ID: On Tue, 18 May 1999, Ron Fountain wrote: > Ok, here is the tuffy! I'm more into hardware and networking than I am > programming. I've tinkered w/ basic and cobol. How would I learn > python...my guess is to buy the book "Python in a nutshell". There is no "Python in a nutshell" book. There is a "Learning Python" in the Nutshell Series of O'Reilly & Associates (which I co-authored). It's an introductory text for Python. It's not a textbook on learning how to program, though, so it may not be ideal -- still, it's probably your best bet for now. --david ascher [standard disclaimers apply] From ivanlan@callware.com Tue May 18 23:03:27 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Tue, 18 May 1999 16:03:27 -0600 Subject: [Tutor] what to do with python References: <000d01bea168$6f50ce70$3864a8c0@netadmin.steckel.com> Message-ID: <3741E3AF.75A79861@callware.com> Hi All-- Ron Fountain wrote: > > I would like to write scripts that will backup various files, either on the > linux box or through the network(grabbing files from other nodes). I would > also like to setup a script that would be able to "route" data files > according to what kind of file they are. If file = "A" then go here...if > file = "B" then do this --type of thing. > > Is python what i would use, or something else? > Python would be ideal for something like this. If the ``other nodes'' are things like NT or Windows, you'd probably have to do some tricks (run an ftp server on them, etc.), but this sort of thing is emininently doable. I would suggest that you obtain Mark Lutz' _Programming Python_ from O'Reilly--he focuses on similar scripting chores, which if not directly applicable would certainly give you pointers. Make sure you have the _Python Pocket Reference_ to go with it, though. -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From deirdre@deirdre.net Tue May 18 23:29:26 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 18 May 1999 18:29:26 -0400 (EDT) Subject: [Tutor] what to do with python In-Reply-To: <000d01bea168$6f50ce70$3864a8c0@netadmin.steckel.com> Message-ID: On Tue, 18 May 1999, Ron Fountain wrote: > I would like to write scripts that will backup various files, either on the > linux box or through the network(grabbing files from other nodes). I would > also like to setup a script that would be able to "route" data files > according to what kind of file they are. If file = "A" then go here...if > file = "B" then do this --type of thing. > > Is python what i would use, or something else? Python is what *I* would use for something like this. If you want to ask a more specific question, I'm sure we could help you better. _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From deirdre@deirdre.net Wed May 19 00:40:32 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 18 May 1999 19:40:32 -0400 (EDT) Subject: [Tutor] how to learn python In-Reply-To: Message-ID: On Tue, 18 May 1999, David Ascher wrote: > There is no "Python in a nutshell" book. There is a "Learning Python" in > the Nutshell Series of O'Reilly & Associates (which I co-authored). It's > an introductory text for Python. It's not a textbook on learning how to > program, though, so it may not be ideal -- still, it's probably your best > bet for now. Imho, MUCH better than Programming Python but my personal favorite is still "Internet Programming with Python." _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From deirdre@deirdre.net Wed May 19 20:36:27 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Wed, 19 May 1999 15:36:27 -0400 (EDT) Subject: [Tutor] San Francisco Python Group: BayPIGgies In-Reply-To: <000d01bea168$6f50ce70$3864a8c0@netadmin.steckel.com> Message-ID: Sorry for the short notice, but we just decided to do this yesterday. :) There will be a meeting of the Bay area Python Interest Group (BayPIGgies) starting tonight at 8pm. Normally, it will meet on the 2nd and 4th Wednesday nights. I know it's only the 3rd weds, but we got this great idea and we wanted to start. Tonight's featured topic (such as it is) will be Gadfly and our Open Source project HellDesk (aka the ticket taker and status tracker) that two of us will be writing. I wanted to call it BOFHtracker. ::sniff:: The meeting will be at 744 Harrison Street (between 3rd and 4th) in the offices behind the CoffeeNet (www.coffeenet.net). Directions can be found on http://linuxmafia.com/bale/ (we will have a page put up real soon now but like I said we just decided to do this yesterday). :) _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Everyone needs the luff of a fine penguin" -- Mikey From Marek Polanski" I connot find anywhere equivalent of 'cls' command. PLEASE HELP!!! TIA Junior. e-mail: junior@supermedia.pl fidonet: 2:480/112.12 --- GoldED/W32 3.0.1 * Origin: Today's magic number is: 24 (2:480/112.12) From ivanlan@callware.com Fri May 21 22:37:24 1999 From: ivanlan@callware.com (Ivan Van Laningham) Date: Fri, 21 May 1999 15:37:24 -0600 Subject: [Tutor] cls References: <19990521210756Z539833-10228+841@mail.supermedia.pl> Message-ID: <3745D214.AFB09509@callware.com> Hi Marek-- Marek Polanski wrote: > > I connot find anywhere equivalent of 'cls' command. PLEASE HELP!!! TIA > > Junior. > Uh, by 'cls' do you mean the DOS command to clear your screen? Why do you need it in Python? Or do you need something like this in Idle? You really need to be more specific, or we can't help you. -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham Callware Technologies, Inc. ivanlan@callware.com http://www.pauahtun.org See also: http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 ---------------------------------------------- From johnh@phm.gov.au Mon May 24 22:16:00 1999 From: johnh@phm.gov.au (John Hirsch) Date: Mon, 24 May 99 16:16:00 EST Subject: [Tutor] Changing Pythonpath Message-ID: <37497B7E@pcmgw.phm.gov.au> Hi How do you make a permanant change to PYTHONPATH in Windows 95. I want Python to look in one of my folders for modules and I can get it to work using sys.path.append(). But this does not make a permanant change to the path so when I exit Python and then come back in the path is reset to what it was and I have to do a sys.path.append() again. I'm sure this is something quite basic but most documentation seems to refer to Unix (using $ PYTHONPATH). Thanks for any help. ---------------------------------------- Jonathan Hirsch Powerhouse Museum Sydney, Australia E-mail : johnh@phm.gov.au Phone: (02) 92170233 ---------------------------------------- From alan.gauld@bt.com Mon May 24 09:56:41 1999 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 24 May 1999 09:56:41 +0100 Subject: [Tutor] cls Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB24E09C1@mbtlipnt02.btlabs.bt.co.uk> > I connot find anywhere equivalent of 'cls' command. PLEASE HELP!!! TIA On Unix: os.system('clear') On DOS: os.system('COMMAND>COM /C CLS') should work. Dunno what the equivalent would be on a Mac.... ;-) Alan G. > > > Junior. > > e-mail: junior@supermedia.pl > fidonet: 2:480/112.12 > --- GoldED/W32 3.0.1 > * Origin: Today's magic number is: 24 (2:480/112.12) > > From tismer@appliedbiometrics.com Mon May 24 12:25:05 1999 From: tismer@appliedbiometrics.com (Christian Tismer) Date: Mon, 24 May 1999 13:25:05 +0200 Subject: [Tutor] Changing Pythonpath References: <37497B7E@pcmgw.phm.gov.au> Message-ID: <37493711.3467C0E7@appliedbiometrics.com> John Hirsch wrote: > > Hi > How do you make a permanant change to PYTHONPATH in Windows 95. > I want Python to look in one of my folders for modules and I can get it > to work using sys.path.append(). But this does not make a permanant > change to the path so when I exit Python and then come back in the path > is reset to what it was and I have to do a sys.path.append() again. I'm > sure this is something quite basic but most documentation seems to refer > to Unix (using $ PYTHONPATH). > Thanks for any help. You have several options. You can of course set the PYTHONPATH environment variable in your autoexec.bat. This setting will prepend all other settings in the Windows registry. Then, in PythonWin, you can use the Path editor to adjust your Path permanently. Unfortunately, new entries cannot be added, but existing ones can be modified. There is one entry per installed extension. You will probably change the main entry. The third way (and this is what I personally like the best) is to have a sitecustomize.py file in your Python main directory. This file can be used to change any setting, including the sys.path, since it will be run on every start of Python. You might also want to read more on path configuration in chapter 3.26 site -- Site-specific configuration hook of the Python Library Reference. The help files are also available in MSHTML format, which is much easier to work with than plain HTML. By adding a single registry key, you can make it appear in PythonWin's help menu. Put the folling lines (after editing) into a .reg file and execute it, and you're done. After you have created such a key, it can also be edited by the PythonWin path tool. REGEDIT4 [HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\1.5\Help] [HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\1.5\Help\Python-MSHTML-Help] @="\\\\orion\\install\\python1.5\\doc\\pythlp.chm" ciao - chris -- Christian Tismer :^) Applied Biometrics GmbH : Have a break! Take a ride on Python's Kaiserin-Augusta-Allee 101 : *Starship* http://starship.python.net 10553 Berlin : PGP key -> http://wwwkeys.pgp.net PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF we're tired of banana software - shipped green, ripens at home From Marek Polanski" I need to write whole tuple (with MANY strings inside) to a file. Problem is, that when I'm trying to do this, python says: >>> f=open('file', 'w') >>> a='blah', 'blahblah', 'blahblahblah' >>> f.write(a) Traceback (innermost last): File "", line 1, in ? TypeError: read-only buffer, list >>> but when I'm trying write only one string (for example f.write(a[0])) everything is OK. Is there any way to do this without making loop writing every string alone? I have Windows 98, Python 1.5.2c1 and file is a low-ascii text file (in case it matter). Junior. e-mail: junior@supermedia.pl fidonet: 2:480/112.12 --- GoldED/W32 3.0.1 * Origin: Today's magic number is: 19 (2:480/112.12) From tim_one@email.msn.com Thu May 27 05:56:50 1999 From: tim_one@email.msn.com (Tim Peters) Date: Thu, 27 May 1999 00:56:50 -0400 Subject: [Tutor] writing tuplet to file In-Reply-To: <19990527031310Z538707-29707+590@mail.supermedia.pl> Message-ID: <000001bea7fd$553a4840$a49e2299@tim> [Marek Polanski] > I need to write whole tuple (with MANY strings inside) to a file. > Problem is, that when I'm trying to do this, python says: > > >>> f=open('file', 'w') > >>> a='blah', 'blahblah', 'blahblahblah' > >>> f.write(a) > Traceback (innermost last): > File "", line 1, in ? > TypeError: read-only buffer, list > >>> Yes, f.write requires a string argument, and you're passing it a tuple (which is not a string ). f.write(str(a)) will work, as will f.write(repr(a)) f.write(`a`) # same thing You may want to use the latter forms if you want to read the tuple back in again later. Also see the pprint module, for "pretty printing" of objects; and maybe the pickle module (if what you're really after is a way to dump a value to a file and read ot back in again later). > ... > I have Windows 98, Python 1.5.2c1 The final Python 1.5.2 was release several weeks ago, so upgrade! > and file is a low-ascii text file (in case it matter). Nope, Python is 8-bit clean, and strings can contain anything (even null bytes). From alan.gauld@bt.com Thu May 27 11:27:06 1999 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 27 May 1999 11:27:06 +0100 Subject: [Tutor] writing tuplet to file Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB24E09CD@mbtlipnt02.btlabs.bt.co.uk> > I have Windows 98, Python 1.5.2c1 > > The final Python 1.5.2 was release several weeks ago, so upgrade! Has anyone else failed to get Tkinter to work under 1.5.2? I uninstalled everythjing and oinstalled 1.5.2 (including the Tk installation) from scratch. Python comes up OK in a DOS box but IDLE fails as do my simple Tkinter scripts which worked under 1.5.1/Tk8.0 I uninstalled 1.5.2 and reinstalled 1.5.1 and Tk8..0 and all is well again. Anyone got any ideas? Alan g. From da@ski.org Thu May 27 17:32:35 1999 From: da@ski.org (David Ascher) Date: Thu, 27 May 1999 09:32:35 -0700 (Pacific Daylight Time) Subject: [Tutor] writing tuplet to file In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB24E09CD@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Thu, 27 May 1999 alan.gauld@bt.com wrote: > Has anyone else failed to get Tkinter to work under 1.5.2? If you give us specific symptoms, we may be able to help. I've had no problems w/ 1.5.2. --david From deirdre@deirdre.net Thu May 27 18:34:20 1999 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Thu, 27 May 1999 13:34:20 -0400 (EDT) Subject: [Tutor] writing tuplet to file In-Reply-To: <000001bea7fd$553a4840$a49e2299@tim> Message-ID: On Thu, 27 May 1999, Tim Peters wrote: > [Marek Polanski] > > I need to write whole tuple (with MANY strings inside) to a file. > > Problem is, that when I'm trying to do this, python says: > > > > >>> f=open('file', 'w') > > >>> a='blah', 'blahblah', 'blahblahblah' > > >>> f.write(a) > > Traceback (innermost last): > > File "", line 1, in ? > > TypeError: read-only buffer, list > > >>> > > Yes, f.write requires a string argument, and you're passing it a tuple > (which is not a string ). > > f.write(str(a)) f.write(string.join(a, '\t')) would probably give something closer to the desired result: creating a tab-delimited string of the tuple (thus keeping the parts separate). _Deirdre * http://www.linuxcabal.org * http://www.deirdre.net "Perl is just not the answer to all problems. If all you have is a hammer, the whole world looks like your thumb." George Bonser on Python From jerry.alexandratos@quansoo.com Mon May 31 20:29:05 1999 From: jerry.alexandratos@quansoo.com (Jerry Alexandratos) Date: Mon, 31 May 1999 15:29:05 -0400 Subject: [Tutor] Help with ARGV parsing Message-ID: I'm new to Python. But I really like what I see so far. I'm looking to write and rewrite some scripts. I'm having some trouble trying to figure out how to parse command-line arguments under Python. Can anyone provide me with some pointers? Thanks in advance... --Jerry name: Jerry Alexandratos || Open-Source software isn't a phone: 302.521.1018 || matter of life or death... email: jalexand@perspectives.net || ...It's much more important || than that! From ivnowa@hvision.nl Mon May 31 21:19:04 1999 From: ivnowa@hvision.nl (Hans Nowak) Date: Mon, 31 May 1999 22:19:04 +0200 Subject: [Tutor] Help with ARGV parsing In-Reply-To: Message-ID: <199905312017.WAA13689@axil.hvision.nl> On 31 May 99, Jerry Alexandratos wrote: > I'm new to Python. But I really like what I see so far. I'm looking to > write and rewrite some scripts. I'm having some trouble trying to > figure out how to parse command-line arguments under Python. > > Can anyone provide me with some pointers? The most straightforward way is to look at sys.argv, a list which contains the command line arguments. Try this very tiny program: ---begin--->8------ import sys print sys.argv[1:] ---end----->8------ Now call this little script on the command line with various arguments, and see what happens. showargs.py 1 2 3 just yields ['1', '2', '3'], but showargs.py 1 "hello world" 2 yields ['1', 'hello world', '2'] Some more experimenting won't hurt. :o) Note that each element of sys.argv is a string. Also note that I used a slice, sys.argv[1:]. The 0th argument of the list is the name of the calling program. If you need more sophisticated parsing, you can take a look at the getopt module. You can specify switches and such. I think there are also a few third party modules around which also deal with parsing of the command line. Veel liefs, --Hans Nowak (ivnowa@hvision.nl) Homepage: http://fly.to/zephyrfalcon From Marek Polanski" I have finished my small program, and I would like to compile it to .exe file. How can I do this? I'm running W98, Python 1.5.2c1 Marek Polanski e-mail: junior@supermedia.pl fidonet: 2:480/112.12 --- GoldED/W32 3.0.1 * Origin: Today's magic number is: 14 (2:480/112.12)