[Tutor] Changing what you've already printed

2005-06-22 Thread Ed Singleton
Is it possible (and easy) to change something you've already printed
rather than print again?

For example, if I'm making a little noughts and crosses game and I
print the board:

   |   |   
   |   |   
___|___|___
   |   |   
   |   |   
___|___|___
   |   |   
   |   |   
   |   |   

Then the computer has it's go, and rather than print the board out
again and have the previous empty board appear higher up, I want to
just add a X to the board I've already created.

Eg.


   |   |   
   |   |   
___|___|___
   |   |   
   | X |   
___|___|___
   |   |   
   |   |   
   |   |   

I've programs do this on the command line in Linux, so I assume it
must be possible.  (I don't mind making my programs Linux only so
that's not a problem).

Any clues or pointers to documentation gratefully recieved.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing what you've already printed

2005-06-22 Thread Ed Singleton
Yeah I think curses looks like it will do what I want.  It doesn't
look particularly easy to use (the [y,x] format is going to trip me up
a lot) but I think I could write myself a simple interface to it that
would make it simpler for me to use.

Pierre's '/r' char thing isn't enough for what I want to do, but it's
well worth knowing.

Thanks All

Ed

On 6/22/05, Wolfram Kraus <[EMAIL PROTECTED]> wrote:
> Curses might help you:
> http://docs.python.org/lib/module-curses.html
> 
> Take a look at the Demo-directory which is included in the Python
> source-package. There is a curses subdir in it which might get you started.
> 
> HTH,
> Wolfram
> 
> Ed Singleton wrote:
> > Is it possible (and easy) to change something you've already printed
> > rather than print again?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Mixing generator expressions with list definitions

2007-04-18 Thread Ed Singleton
I would like to be able to do something along the lines of:

>>> my_list = [1, 2, x for x in range(3,6), 6]

However this doesn't work.  Is there any way of achieving this kind of thing?

I tried:

>>> my_list = [1, 2, *(x for x in range(3,6)), 6]

which also doesn't work.

I wrote a quick function that allows me to use the generator
expression as long as it is the last argument:

>>> def listify(*args):
... return [arg for arg in args]
...
>>> my_list = listify(1,2, *(x for x in range(3,6)))

but obviously this limits me to using it only at the end of a list.

Any clues on this greatly appreciated.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mixing generator expressions with list definitions

2007-04-18 Thread Ed Singleton
On 4/18/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > I would like to be able to do something along the lines of:
> >
> >>>> my_list = [1, 2, x for x in range(3,6), 6]
> >
> > However this doesn't work.  Is there any way of achieving this kind of 
> > thing?
>
> my_list = [1, 2] + range(3,6) + [6]

I thought I'd got past the point where there were stupidly simple
answers to my questions ;)  Oh well.  Thanks yet again, Kent.

> or, to build it in steps,
> my_list = [1, 2]
> my_list.extent(range(3, 6))
> my_list.append(6)

Yeah, that's how I had ben doing it.  I don't really like it for some
reason, though I'm not clear why I don't like it.  I think maybe
because it's quite verbose so it's a bit difficult for me to read it
afterwards, and makes typos more likely ;)

> By the way I can't think of any reason to write "x for x in range(3, 6)"
> instead of just "range(3, 6)". range() returns a list which can be used
> almost anywhere the generator expression can be. If you need an explicit
> iterator use iter(range(3, 6)).

Sorry, I oversimplfied my example.  I'm actually doing:

widgets = [(organisation_widget,(),{'organisation':organisation})]
widgets.extend([(event_widget,(),{'event':event}) for event in
organisation.events])
widgets.append((event_form,(),{'values':values}))

so that later on I can just iterate through the widgets like so:

for (widget, args, kwargs) in widgets:
widget.display(*args, **kwargs)

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multiple Simultaneous Loops

2005-09-15 Thread Ed Singleton
I roughly want to be able to do:

for f, x in bunch_of_files, range(z):

so that x iterates through my files, and y iterates through something else.

Is this something I can do?

If so, what would be the best way to create a range of indeterminate length?

If not, is there a nice way I can do it, rather than than incrementing
a variable (x = x + 1) every loop?

Or maybe can I access the number of times the loop has run?  ('x = x +
1' is so common there must be some more attractive shortcut).

So far in learning Python I've founbd that when I feel you should be
able to do something, then you can.  This seems a pretty intuitive
thing to want to do, so I'm sure it must be possible, but I can't find
anything on it.

Many thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple Simultaneous Loops

2005-09-15 Thread Ed Singleton
Wonderful, thank you all of you.

zip, enumerate, and count seem to do everything I want, though I do think

for f, x in bunch_of_files, range(z):

is a little more intuitive than

for f, x in zip(bunch_of_files, range(z)):

Thanks

Ed

On 15/09/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > I roughly want to be able to do:
> >
> > for f, x in bunch_of_files, range(z):
> >
> > so that x iterates through my files, and y iterates through something else.
> >
> > Is this something I can do?
> 
> In the general case use zip():
> for f, x in zip(bunch_of_files, range(z)):
> 
> In this case, where the second item is just the index to the loop, use 
> enumerate() instead of range() and zip()
> for x, f in enumerate(bunch_of_files):
> 
> > If so, what would be the best way to create a range of indeterminate length?
> 
> itertools.count() generates an "unlimited" sequence.
> 
> > If not, is there a nice way I can do it, rather than than incrementing
> > a variable (x = x + 1) every loop?
> >
> > Or maybe can I access the number of times the loop has run?  ('x = x +
> > 1' is so common there must be some more attractive shortcut).
> 
> enumerate()
> 
> > So far in learning Python I've founbd that when I feel you should be
> > able to do something, then you can.
> 
> Yep :-)
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Editors (particualrly Vim)

2005-09-21 Thread Ed Singleton
I've been trying to decide which editor to use to edit Python (on
Windows mostly).

My wishlist of features would be:

- automatic code formatting (indentation etc)
- collapsible code (to collapse def's etc)
- automatic code coloring (that's easily changeable)
- auto-completion of namespaces
- easy to run scripts from the editor (a shortcut key to run them or something)

As I also do a lot of html, css and javascript it would be cool to
have an editor that could also handle them, in which case I would want
the same features for those languages, as well as the ability to write
macros, scripts, etc in python.

Having looked at loads of editors, I've ended up looking at emacs and vim.

Emacs seems too difficult with not enough support for using the mouse.

Vim seemed better, and I get the impression that it is possible to use
python to script the editor, but I can't find much information on
using vim as a python editor on windows.

My various questions are:

What other features should I be looking for?

What would be the best editor for a beginner to start using, with a
view to the long term?

Where can I find some authoritative information about setting emacs or
vim up as a fully featured python editor?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Editors (particualrly Vim)

2005-09-21 Thread Ed Singleton
I don't believe there's any kinds of wars on this mailing group.  :)

I found this Python Vim code completion thing in my searches today:
http://freshmeat.net/projects/pydiction/

Don't know how good it is, but it looks like it'd do the job.

Ed

On 21/09/05, Gabriel Farrell <[EMAIL PROTECTED]> wrote:
> Uh oh, looks like you're begging for an editor war.
>
> That said, I'm in the vim camp.  It can do everything you specified
> for all of the languages you mention (well, I'm not sure about
> collapsible code...web search...aha![1]).  After using it for four
> years, I'm still learning new tricks (see, for example, this page I
> found today on indentation[2]).
>
> vim's extendable with python scripts, but a lot of what you need for
> coding is already built in.  I find most of my info either in the help
> manual that comes with it (:h) or at vim.org.
>
> gsf
>
> [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> [2] http://www.vim.org/tips/tip.php?tip_id=83
>
>
> On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > I've been trying to decide which editor to use to edit Python (on
> > Windows mostly).
> >
> > My wishlist of features would be:
> >
> > - automatic code formatting (indentation etc)
> > - collapsible code (to collapse def's etc)
> > - automatic code coloring (that's easily changeable)
> > - auto-completion of namespaces
> > - easy to run scripts from the editor (a shortcut key to run them or 
> > something)
> >
> > As I also do a lot of html, css and javascript it would be cool to
> > have an editor that could also handle them, in which case I would want
> > the same features for those languages, as well as the ability to write
> > macros, scripts, etc in python.
> >
> > Having looked at loads of editors, I've ended up looking at emacs and vim.
> >
> > Emacs seems too difficult with not enough support for using the mouse.
> >
> > Vim seemed better, and I get the impression that it is possible to use
> > python to script the editor, but I can't find much information on
> > using vim as a python editor on windows.
> >
> > My various questions are:
> >
> > What other features should I be looking for?
> >
> > What would be the best editor for a beginner to start using, with a
> > view to the long term?
> >
> > Where can I find some authoritative information about setting emacs or
> > vim up as a fully featured python editor?
> >
> > Thanks
> >
> > Ed
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Editors (particualrly Vim)

2005-09-22 Thread Ed Singleton
Okay, I've also found this:
http://cream.sourceforge.net/features.html

Which is amazing!  It's an easy-to-use mod for Vim.  It's modeless and
lots of other doubtless heretical things, but it includes an
outstanding auto-complete mode for text files!  Ctrl-Space auto
completes the word you're typing based on what you've already written
in the file.

I've also been trying SPE and that looks to be the most pleasing
editor so far.  It's also written in Python (AFAICT) which will
probably have benefits in the future.

Ed

On 21/09/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
> I don't believe there's any kinds of wars on this mailing group.  :)
>
> I found this Python Vim code completion thing in my searches today:
> http://freshmeat.net/projects/pydiction/
>
> Don't know how good it is, but it looks like it'd do the job.
>
> Ed
>
> On 21/09/05, Gabriel Farrell <[EMAIL PROTECTED]> wrote:
> > Uh oh, looks like you're begging for an editor war.
> >
> > That said, I'm in the vim camp.  It can do everything you specified
> > for all of the languages you mention (well, I'm not sure about
> > collapsible code...web search...aha![1]).  After using it for four
> > years, I'm still learning new tricks (see, for example, this page I
> > found today on indentation[2]).
> >
> > vim's extendable with python scripts, but a lot of what you need for
> > coding is already built in.  I find most of my info either in the help
> > manual that comes with it (:h) or at vim.org.
> >
> > gsf
> >
> > [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> > [2] http://www.vim.org/tips/tip.php?tip_id=83
> >
> >
> > On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > > I've been trying to decide which editor to use to edit Python (on
> > > Windows mostly).
> > >
> > > My wishlist of features would be:
> > >
> > > - automatic code formatting (indentation etc)
> > > - collapsible code (to collapse def's etc)
> > > - automatic code coloring (that's easily changeable)
> > > - auto-completion of namespaces
> > > - easy to run scripts from the editor (a shortcut key to run them or 
> > > something)
> > >
> > > As I also do a lot of html, css and javascript it would be cool to
> > > have an editor that could also handle them, in which case I would want
> > > the same features for those languages, as well as the ability to write
> > > macros, scripts, etc in python.
> > >
> > > Having looked at loads of editors, I've ended up looking at emacs and vim.
> > >
> > > Emacs seems too difficult with not enough support for using the mouse.
> > >
> > > Vim seemed better, and I get the impression that it is possible to use
> > > python to script the editor, but I can't find much information on
> > > using vim as a python editor on windows.
> > >
> > > My various questions are:
> > >
> > > What other features should I be looking for?
> > >
> > > What would be the best editor for a beginner to start using, with a
> > > view to the long term?
> > >
> > > Where can I find some authoritative information about setting emacs or
> > > vim up as a fully featured python editor?
> > >
> > > Thanks
> > >
> > > Ed
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Remaking Vim in Python (was Python Editors)

2005-09-23 Thread Ed Singleton
I'd like a little advice on whether I'm being really stupid here.

Having researched editors and stuff, I've not quite found what I'm
looking for, though Vim comes close (except that it's extremely
difficult to work out what to do with it).

My instinct was to try and write a small program similar to vim, but
in Python.  The very basics should be quite easy.  If I start a system
that is very easily expandable then as and when I need further
functionality I can add it in.

html colourisation and auto-completion should be easy enough to add
using a html parser, but what about python?  Is there a python module
that can parse python code and is reasonably easy to use?  Also, css?

I know it would be ambitious to try and do this, but is it stupidly ambitious?

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] find data in html file

2005-09-28 Thread Ed Singleton
On 27/09/05, lmac <[EMAIL PROTECTED]> wrote:
> Hi there,
> i have a base-question. If i want to read some kind of data out of a line
> which i know the start-tag and the end-tag in an html-file how do i
> recognize
> if it's more than one line ?
>
> Example:
>
> Some textlinktext . DATA  etc.
>
> I would use >text as the starting tag to localize the beginning of the DATA.
> And then  as the ending tag of the DATA. But if there is \n then
> there are more than
> one line.

Hopefully it's just a typo or something, but you appear to have your
ending  and  tags the wrong way round.

You should be closing the cell before you close the row.

How do you want to get the data out?  This case is simple enough that
you could do a lazy (non-greedy) regex statement for it.  Something
like "([\s|\S]+?)" would do it.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] htmllib

2005-10-05 Thread Ed Singleton
I want to dump a html file into a python object.  Each nested tag
would be a sub-object, attributes would be properties.  So that I can
use Python in a similar way to the way I use JavaScript within a web
page.

I looked at htmllib, but the documentation seems quite limited, and as
far as I can tell, I would have to write code for every single
potential tag in my page.

Is there a way to do this, or access the DOM through Python or something?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] htmllib

2005-10-05 Thread Ed Singleton
You're like some kind of god!

That's exactly what I need.

Thanks

Ed

On 05/10/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > I want to dump a html file into a python object.  Each nested tag
> > would be a sub-object, attributes would be properties.  So that I can
> > use Python in a similar way to the way I use JavaScript within a web
> > page.
>
> I don't know of a way to run Python from within a web page. But if you want 
> to fetch an HTML page from a server and work with it (for example a 
> web-scraping app), many people use BeautifulSoup for this. If you have 
> well-formed HTML or XHTML you can use an XML parser as well but BS has the 
> advantage of coping with badly-formed HTML.
> http://www.crummy.com/software/BeautifulSoup/
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Saving command line keyed input?

2005-10-21 Thread Ed Singleton
A quick tip for the Windows command line.

Ctrl-C, Ctrl-A etc don't work, neither does right-clicking
(menu-click).  However, right-clicking does work on the blue title
bar.

Right-click on the blue title bar and then go down to Edit and then
you can Select All.  Then right-click on the blue title bar again and
go down to Edit and then Copy.

If at any point you right click in the black part of the window or do
a Ctrl key sequence, it deselects all your text.  Very unintuitive, as
it is completely different to every other Windows app.  (I think they
do it on purpose to stop people wanting to use the Command Line).

Ed

On 19/10/05, CPIM Ronin <[EMAIL PROTECTED]> wrote:
> I know that one should use IDLE or a choosen editor for any substantial
> Python coding! However, if one  happens to have written some interesting
> doodlings on the regular command line interface (under Windows XP in my
> case), is there an easy way to save ALL input to date into a selected file?
>
> For example:
> >>>class work_center:
>  def __init__(self,x_name):
> self.name = x_name
>
> >>>x = work_center("machine press")
> >>>
>
>   ---  What do I do to save the above work into a file named "mywork.py"
>
> Thanks.
>
> RC
>
> _
> On the road to retirement? Check out MSN Life Events for advice on how to
> get there! http://lifeevents.msn.com/category.aspx?cid=Retirement
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about an re

2005-10-27 Thread Ed Singleton
OR tests for the truth of the first thing then the truth of the second.

The first part of your OR is always true, so it doesn't test the second.

What you really want to do is look for a digit and then look for more
digits or a slash and some more digits.

So:

: \d(\d+|/\d+)

but this is easier by just allowing an optional slash in the digits:

: \d+/?\d*

ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more digits.

http://www.regular-expressions.info/ is a brilliant tutorial on regexs
and http://www.weitz.de/regex-coach/ is a great program for testing
them out before you put them in your code.

Hope this helps

Ed

On 27/10/05, ->Terry<- <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
> os - Slackware
> py - 2.4.1
>
> I'm trying to grab the value 10 in
>
> Visibility: 10 mile(s):0
>
> but sometimes the value looks like
>
> Visibility: 1/2 mile(s):0
>
> My not working regex looks like
>
> re.compile(': \d+|: \d/\d')
>
> If I'm understanding right, this should match either or,
> but it doesn't work for the fractional reading.
>
> Can someone steer me in the right direction and explain
> what I'm doing wrong?
>
> Thanks much,
> - --
>  Terry
>
>   ,-~~-.___. Terry Randall 
>  / |  ' \
> <   )0Linux Counter Project User# 98233
>  \_/, ,-'
>   //
>/  \-'~;/~~~(0)
>   /  __/~|   /  |   If only Snoopy had Slackware...
> =( __| (|
>
> "He is your friend, your partner, your defender, your dog.
> You are his life, his love, his leader. He will be yours,
> faithful and true, to the last beat of his heart. You owe
> it to him to be worthy of such devotion."-- Unknown
>
>   (Best viewed with a mono-spaced font.)
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.2.7 (GNU/Linux)
>
> iD8DBQFDYFhdQvSnsfFzkV0RAoPyAJ4jfwjWJ1eoqDatB6Hmg07XbUMGLQCeP/eQ
> ognaRmmfxNlDW249jRqYE2g=
> =Txx/
> -END PGP SIGNATURE-
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Passing Functions or Code as Parameters

2005-10-27 Thread Ed Singleton
How can I pass a block of code to a function for it to perform within itself?

For example, I wrote a small function that recurses through a
directory structure but keeps a track of the depth:

from path import path

def traverse(directory, depth=0):
thedir = path(directory)
for item in thedir.files():
##  Do stuff relative to the depth
for item in thedir.dirs():
traverse(item,depth+1)

What I want to do is something like:

from path import path

def traverse(directory, depth=0, things_to_do()):
thedir = path(directory)
for item in thedir.files():
things_to_do(depth)
for item in thedir.dirs():
traverse(item,depth+1)

Is this possible?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OT - Re: Can anyone help me?

2005-10-28 Thread Ed Singleton
You can actually increase your chance of winning in the English lottery.

If two many tickets win a prize in one draw, the lowest prize (£10 for
three numbers) is not paid out.

Also the jackpot is shared between all the winning tickets (6 numbers)
some sets of numbers like 1,2,3,4,5,6 are chosen by over 20,000 people
a week.  You would share the jackpot with 20,000 other people.

Picking random numbers makes you less likely to chose the same numbers
as everyone else.

Incidently, the odds of winning the jackpot are 1 in 14 million
(roughly).  I've seen the jackpot go up to £25million which makes it
theoretically a good bet.

Ed

On 28/10/05, bob <[EMAIL PROTECTED]> wrote:
> At 07:07 PM 10/27/2005, Nathan Pinno wrote:
> >Hey all,
> >I am trying to create a program that draws 6 numbers between 1 and 49 at
> >random for creating lottery tickets. I want to have a better chance when I
> >play.
>
> Define "better chance". Lottery odds are how many tickets you buy relative
> to how many tickets everyone else has bought. No program will improve or
> degrade your odds. The only way you can reduce your odds is to buy more
> than one ticket with the same numbers.
>
> Keep in mind that a lottery is as truly random as one can get (assuming no
> rigging). There is no memory of past outcomes involved nor of better
> guessing techniques.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rename files with numbers

2005-11-01 Thread Ed Singleton
Sorry, wrong list.

Many apologies.

Ed

On 01/11/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
> The best free app I've found for this is MusicBrainz [www.musicbrainz.com].
>
> This has a huge database of obsessively correct details of albums
> which can be formatted in anyway you choose.  It can automatically
> recognise which song an MP3 is!
>
> This is a similar script I wrote to renumber files in sequential
> order.  It assumes that everything before the first underscore can be
> replaced.
>
> from path import path
> import re
>
> def renumberfiles(filesdir, startnum=1):
> d = path(filesdir)
> print d
> x = startnum
> for f in d.files():
> fname = f.name.split('_', 1)
> fname = str(x).zfill(2) + "_" + fname[-1]
> fname = re.sub(r" ",r"_",fname)
> fname = re.sub(r"__",r"_",fname)
> x = x + 1
> print f.name, "==>",
> f.rename(f.parent + "\\" + fname)
> print fname
>
> As you can see, I use the path module rather than os.path.  it's a
> much more intuitive way of handling files.
>
> http://www.jorendorff.com/articles/python/path/
>
> Ed
>
> On 01/11/05, Dave Benjamin <[EMAIL PROTECTED]> wrote:
> > On Mon, 31 Oct 2005, Micah Elliott wrote:
> >
> > > On Oct 31, Micah Elliott wrote:
> > >> Now I need to go beautify my collection.  :-)
> > >
> > > While a fun exercise, there are probably already dozens (or
> > > thousands?) of utilities in existence that do this and much more.
> >
> > Seconded. I initially considered writing a script to rename a huge pile of
> > MP3 files, but halfway through, I thought, "there's *got* to be a better
> > way". I found this app: http://www.softpointer.com/tr.htm
> >
> > Bought it the next day. Holy crap, what a gigantic timesaver. It looks up
> > albums based on track lengths, downloads titles from freedb and Amazon,
> > does ID3 tagging, renaming, moves files into separate directories... I
> > busted through about 20 gigs of MP3s in three days. I kid you not.
> >
> > If this is just a fun toy Python project, don't let me discourage you, but
> > if you have more than a handful of albums to rename, trust me. This
> > problem has been solved.
> >
> > Here's a list of apps, including Tag&Rename, that can query freedb:
> > http://www.freedb.org/freedb_aware_apps.php
> >
> > --
> >   .:[ dave benjamin: ramen/[sp00] ]:.
> >\\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rename files with numbers

2005-11-01 Thread Ed Singleton
The best free app I've found for this is MusicBrainz [www.musicbrainz.com].

This has a huge database of obsessively correct details of albums
which can be formatted in anyway you choose.  It can automatically
recognise which song an MP3 is!

This is a similar script I wrote to renumber files in sequential
order.  It assumes that everything before the first underscore can be
replaced.

from path import path
import re

def renumberfiles(filesdir, startnum=1):
d = path(filesdir)
print d
x = startnum
for f in d.files():
fname = f.name.split('_', 1)
fname = str(x).zfill(2) + "_" + fname[-1]
fname = re.sub(r" ",r"_",fname)
fname = re.sub(r"__",r"_",fname)
x = x + 1
print f.name, "==>",
f.rename(f.parent + "\\" + fname)
print fname

As you can see, I use the path module rather than os.path.  it's a
much more intuitive way of handling files.

http://www.jorendorff.com/articles/python/path/

Ed

On 01/11/05, Dave Benjamin <[EMAIL PROTECTED]> wrote:
> On Mon, 31 Oct 2005, Micah Elliott wrote:
>
> > On Oct 31, Micah Elliott wrote:
> >> Now I need to go beautify my collection.  :-)
> >
> > While a fun exercise, there are probably already dozens (or
> > thousands?) of utilities in existence that do this and much more.
>
> Seconded. I initially considered writing a script to rename a huge pile of
> MP3 files, but halfway through, I thought, "there's *got* to be a better
> way". I found this app: http://www.softpointer.com/tr.htm
>
> Bought it the next day. Holy crap, what a gigantic timesaver. It looks up
> albums based on track lengths, downloads titles from freedb and Amazon,
> does ID3 tagging, renaming, moves files into separate directories... I
> busted through about 20 gigs of MP3s in three days. I kid you not.
>
> If this is just a fun toy Python project, don't let me discourage you, but
> if you have more than a handful of albums to rename, trust me. This
> problem has been solved.
>
> Here's a list of apps, including Tag&Rename, that can query freedb:
> http://www.freedb.org/freedb_aware_apps.php
>
> --
>   .:[ dave benjamin: ramen/[sp00] ]:.
>\\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
> --
> http://mail.python.org/mailman/listinfo/python-list
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Inheriting from parent object

2005-11-14 Thread Ed Singleton
I want to create a property that will inherit it's value from the same
property in it's parent object, but will check it's parent's propety
everytime it is called.  But that can be over-ridden, and I don't have
to know what the objects parent is.

For example:

object.x = 3
object.subobject.x = inherit()
print object.subobject.x #prints 3
object.x = 4
print object.subobject.x #prints 4
object.subobject.x = 5
print object.subobject.x #prints 5

What could I put in the inherit() function that would look for the
same property of it's parent and return that, whilst keeping it as
general as possible?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newb ?

2005-11-17 Thread Ed Singleton
These both work (though neither is very graceful).

text = "hello"
message = ""

for i in range(len(text)):
   message = message + text[(len(text)-i-1)]

print message


lst = list(text)
newstr = ""

for item in text:
   newstr += (lst.pop())

print newstr

On 16/11/05, Chad Everett <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> Have a problem here with a challenge from a book I am reading.
> Any help is much appreciated.
>
> I am trying to run a program that asks the user for a statement and then
> prints it out backwards.
> this is what I have.
> It does not print anything out.  I assume that I have something out of whack
> with my high and low statements.
>
> Thanks for you help.
>
>
> print "\n\nWelcome to the Backwards Message Display."
> print
> message = raw_input("\nPlease Enter a Message.")
>
> high = len(message)
> low = -len(message)
> print
> print message[high:low]
> print
> print raw_input("Please Press Enter to Exit")
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Inheriting from parent object

2005-11-22 Thread Ed Singleton
Thanks for this.  I hadn't really considered that I would have to
explicitly store parent/child relationships.

Having been browsing for something else, I came across this page about
Unifying types and classes:
http://www.python.org/2.2.3/descrintro.html

>From it, it looks like I could do something like:

class Page(object):

def __init__(self, parent):
self.__header = None
self.parent = parent

def getheader(self):
if not self._header and self.parent:
return self.parent.header
else:
return self.__header

def setheader(self, header):
self.__header = header

header = property(getheader, setheader)

Which I think would end up doing exactly what I want.

I still don't think I'm clear on the use of self though.  Can I only
use it in class definitions?

I think it might be that

myPage = Page(parentPage)

is highly deceptive.  Shouldn't it really be:

new Page(myPage, parentPage)

or

myPage = new Page(myPage, parentPage)

or am I getting really, really confused?

Ed



On 15/11/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >>Sorry, I didn't really explain myself clearly.
>
> Thats OK its easy to get buried in the depths and
> forget everyone else is coming at it cold. But
> the use of non standard terms confused things
> even more!
>
> >>I want to create a kind of website ...
> >>I want to have a root object, which
> >>has page objects.  The page objects
> > will have various properties
> >like header, footer, body and an order
>
> Sounds like a job for classes. Create a
> Page class with the various properties.
> Initialise objects with their parent
> (ie containing) object.
>
> >>to inherit the attribute from their parent page (ie if it is
> >>root.chapter3.page5 then chapter3 is the parent of page5).
>
> >>I guess the psuedo code would be:
> >>
> >>def inherit()
> >>return this.parent.attribute
> >>
>
> Just put code like this in the init method:
>
> Class Page:
>def __init__(self, parent = None):
>   self.parent = parent # and handle default too!
>def getHeader(self):
>   return self.parent.header
>
> etc...
>
> Then create
>
> Chapter3 = Page()
> Chapter3.header = '''some long string here'''
> Chapter3.getHeader()
> p2 = Page(Chapter3)
> p2.getHeader()  # returns Chapter3.header
>
> etc
>
> >>(I know Python doesn't really have a 'this'
>
> But it does have self and you can use
> this if you prefer!
>
>
> >>knowing who the function was called by).
>
> Thats not really needed if you use objects.
> Although self does point at the specific
> Page whose method is being invoked.
>
> HTH,
>
> Alan G
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Modifying Source Code while Program is Running

2005-11-24 Thread Ed Singleton
Is it feasible to change a program's source code whilst it is running
without having to restart the program?  Is it feasible to get a
program to change it's own source code while it is running?

For example, if you have a web server such as CherryPy that will
(hopefully) be running for months at a time and you want to be able to
change classes without having to restart the server.  Or if you want
to allow users of the site to edit a class through the web and see the
changes to the site immediately?

Can a python program change a class, change all the objects already
created by that class and save the modified class definition, so that
if the program were restarted it would return to exactly the same
state? (assuming all objects were saved to a database or somesuch).

Does anyone have any good links to implementations of this?  I assume
someone's already done it before.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-24 Thread Ed Singleton
On 24/11/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > Is it feasible to change a program's source code whilst it is running
> > without having to restart the program?  Is it feasible to get a
> > program to change it's own source code while it is running?
> >
> > For example, if you have a web server such as CherryPy that will
> > (hopefully) be running for months at a time and you want to be able to
> > change classes without having to restart the server.  Or if you want
> > to allow users of the site to edit a class through the web and see the
> > changes to the site immediately?
>
> This is hard. IIRC CherryPy has a way to automatically restart the server 
> when a module changes, which is not what you ask for but at least it is 
> automatic. A couple of recent threads on comp.lang.python have talked about 
> this:
>
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/8bb4efbe726c4ab5/848860f76210be69
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/7b34c30c5833a9b0/4ed71bb7c5a97b57
>
> Kent

Hmmm, that's discouraging.  Do you know if it's feasible to just keep
changes to code in memory synchronised with changes nto the source
code?  So rather than reload source code, make sure that the source
code reflects what is running in memory?

For example if your program is running, and you make a change to a
class, is it possible to create the necessary class definition and
save it to a file?

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-25 Thread Ed Singleton
On 24/11/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > Is it feasible to change a program's source code whilst it is running
> > without having to restart the program?  Is it feasible to get a
> > program to change it's own source code while it is running?
>
> You can change a class while it is running.
> >
> > For example, if you have a web server such as CherryPy that will
> > (hopefully) be running for months at a time and you want to be able to
> > change classes without having to restart the server.  Or if you want
> > to allow users of the site to edit a class through the web and see the
> > changes to the site immediately?
>
> The auto-restart feature of CherryPy might do this for you. Also if the 
> changes to the site are to a template such as Cheetah, those usually 
> autoreload.
> >
> > Can a python program change a class, change all the objects already
> > created by that class and save the modified class definition, so that
> > if the program were restarted it would return to exactly the same
> > state? (assuming all objects were saved to a database or somesuch).
>
> You can have persistent objects using for example SQLObject or ZODB,
> >
> > Does anyone have any good links to implementations of this?  I assume
> > someone's already done it before.
>
> It sounds like maybe you come from a background in Smalltalk, or maybe you 
> should look at Smalltalk. In Smalltalk the whole environment is dynamic and 
> can be saved and restored easily.
Just had a quick look at Smalltalk, and at first glance the overview
of the ideas behind it seems amazing, but the language seems quite
ugly, and it seems to be very IDE led.

> For Python, I think you will do better if you narrow your requirements. 
> Python is very dynamic - classes can be changed at runtime, or reloaded if 
> you are careful - and there are several good ways to persist state. If you 
> can be more specific about what you really need there may be a solution for 
> you.

What I want to do seems quite simple to me in concept, but is seeming
more and more as if it would be hard to implement.

I want to create a small simple CMS for my website.  Users will be
able to add and edit basic pages.  Pages can have sub-pages (no need
for folders cause a folder and an index.html can be unified into one
concept).

Users will also be able to create new types of pages, maybe a
PressReleasePage for example.  PressReleases would be based on a
normal page but might have extra attributes such as Author, Abstract
or DateToBeReleased.

This immediately seemed to me to be a case for classes.  You provide a
way for a user to create a new class by subclassing the page class
(from their point of view probably through adding a few new fields to
a form).  Later if they change their mind they can edit the class by
adding or removing attributes.

However it doesn't really seem that Python is suited to this.  Indeed
it doesn't really seem that Python is suited to a persistent
environment.  Having a program running for a long time (months) is
possible certainly, but it seems to be fighting against the language
rather than working with it.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-25 Thread Ed Singleton
On 24/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
> There are many ways of doing this, few of them very nice IMHO.
>
> > without having to restart the program?  Is it feasible to get a
> > program to change it's own source code while it is running?
>
> Yes, you can overwrite an existing module then call reload
> from within the program.
>
> > For example, if you have a web server such as CherryPy that will
> > (hopefully) be running for months at a time and you want to be able to
> > change classes without having to restart the server.
>
> Yes that would be feasible., preferrably in response to an admin
> page where you could fill in a list of modules to be reloaded...
> But you neeed to be very careful not to break any of the interfaces,
> the Liskov Substitution Principle must be strictly observed.
>
> > to allow users of the site to edit a class through the web and
> > see the changes to the site immediately?
>
> Extremely dangerous but the same principle would apply,
> simply load the existing module into an editor pane then save
> the modified version and reload it.
>
> > Can a python program change a class,
>
> Yes as above.
>
> > change all the objects already created by that class
>
> Trickier and potentially involves some low level poking that
> should not be encouraged IMHO! :-)

> > and save the modified class definition, so that
> > if the program were restarted it would return to exactly the same
> > state? (assuming all objects were saved to a database or somesuch).
>
> If the LSP is adhered to its feasible but I don't intend to try any
> such thing! It would be full of pitfalls and an almosyt certain recipe
> for reliability problems that would be impossible to find.
> Self modifying code sounds like a good idea but there is a very
> good reason why its almost never used in production software!

Well, self-modifying isn't inherently necessary.  What I guess I
really need is persistent classes as well as persistent objects.

I always tend to think of classes as templates for objects rather than
factories.  In my mind, object methods are just calls to the class
which are evaluated every time they are called.  Objects should be
strict instances of classes that can't be modified except for the
values of their attributes.

I think I can actually achieve this to some degree by doing:

Class Page(object):
def print(self):
printPage(self)

And have all my methods call functions (passing on parameters as
necessary).  That way if I change a function, it will be changed for
every instance of every object of that class.

And couldn't I write a function that would add functions or attributes
to classes and objects?

def addAttribute(class, attribute, starting value):
# add it to the class
# iterate through all objects already created by the class
# add attribute to object

Am I trying to use the wrong language for this?  I love Python but I
seem to keep coming up against lots of practical issues with it and I
really don't want to bother with practical issues.  I just want to
define the behaviours I want without having to bother with how the
computer is actually going to handle them.

I guess it's very much a "I don't care how it works!" attitude, which
is probably a corollary to "premature optimisation is the root of all
evil".  Ignore all issues of memory and speed and create something
highly abstract that allows you to define your solution.  Then work
down from there and start worrying about speed and memory and
practical issues later (or hopefully never).

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-25 Thread Ed Singleton
On 25/11/05, Ismael Garrido <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
>
> >I want to create a small simple CMS for my website.  Users will be
> >able to add and edit basic pages.  Pages can have sub-pages (no need
> >for folders cause a folder and an index.html can be unified into one
> >concept).
> >
> >Users will also be able to create new types of pages, maybe a
> >PressReleasePage for example.  PressReleases would be based on a
> >normal page but might have extra attributes such as Author, Abstract
> >or DateToBeReleased.
> >
> >
> >
> Store the fields in a database, make a factory class that gets those
> fields and generates a page accordingly.
>
> I agree with Kent, what you're trying seems way too abstract.

Weirdly, I'd just realised that SQLObject does most of what I'm
thinking about.  It allows you to update a class and that will affect
all the objects already instantiated.  It has class persistence in
that it will rebuild the class on startup from the columns in your
table so your 'live' changes will be there after you restart the
server.  Though all that is only for the data in the class.

Each method could just contain a call to a function (as I mentioned
above) all the functions could be contained in a module, which would
make it easy to update them as it appears to be easy enough to reload
a module.

The only thing you wouldn't really be able to do is add or remove
methods, which I guess is fine for the moment.

The only thing I'm not sure of is whether SQLObject can store
properties (as in managed attributes) which I need to do for the
'inherit from parent' attribute that I mentioned is a previous thread:

class Page(object):

   def __init__(self, parent):
   self.__header = None
   self.parent = parent

   def getheader(self):
   if not self._header and self.parent:
   return self.parent.header
   else:
   return self.__header

   def setheader(self, header):
   self.__header = header

   header = property(getheader, setheader)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-26 Thread Ed Singleton
On 25/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > Just had a quick look at Smalltalk, and at first glance the overview
> > of the ideas behind it seems amazing, but the language seems quite
> > ugly, and it seems to be very IDE led.
>
> Adherents will defend its simplicity but I confess I strugglred for
> a long time with SmallTalk before learning to love it :-) And yes
> it is IDE led although the IDE can be 'removed' when deploying
> applications. But much depends on the implementation, my favourite
> for PCs is Dolphin SmallTalk from ObjectArts. Its not a traditional
> SmallTalk (ala Xerox SmallTalk 80) but very much one for the '90's

I'm definitely going to investigate it further, as it does seem
interesting, but I remember the first time I looked into Python, I
read the tutorial and was quite bemused as it didn't seem like I'd
learned anything.  It was all so obvious that I didn't feel there was
anything to learn.

As it was I was able to very quickly plunge much deeper and end up
asking lots of difficult questions that in any other language you
wouldn't approach for many years.

> > This immediately seemed to me to be a case for classes.
> > You provide a way for a user to create a new class by
> > subclassing the page class (from their point of view
> > probably through adding a few new fields to
> > a form).
>
> That might be part of the problem, if you think of a class in terms
> of its data attributes then that is nearly always the wrong starting
> point. Classes express behaviour, the data is only there to support
> the behaviour. Thats why methods are polymorphic but not attributes.

If classes express behaviour, then what expresses the structure of the
data?  (ie what attributes there are going to be and what values they
are likely to accept).

You need (the option of) a data definition in order to generalise. 
Using my web server example from earlier, you need to be able to say
that for any type of page, whatever it's attributes, you can create a
web form to search for that type of page by iterating through it's
attributes and creating a relevant form field for each type.

> So you think of a class having an interface and users extending
> or modifying the behaviour, not the data. If you follow that route
> you might find you don't need to write self modifying code,
> you simply load new classes with a common interface into an
> existing hook structure.

I definitely had the opposite in mind.  The behaviours of all the
classes would be the same (and would be fairly simple, a method for
rendering the page with a template, a method to update the data based
on a form submission).  Users would basically be able to change the
data structure (add and remove attributes).

> > However it doesn't really seem that Python is suited to this.  Indeed
> > it doesn't really seem that Python is suited to a persistent
> > environment.
>
> What makes you think that? Most persistent environments
> (ie long running server processs) are written in C/C++ (or
> maybe Java nowadays) which are far less dynamic than Python.

I'm sure Python is quite possibly the least worst at this, but that
doesn't make it good at it.

> > Having a program running for a long time (months) is
> > possible certainly, but it seems to be fighting against the language
>
> Not at all, at least no more than in languages like C which require
> recoding, recompiling, stopping and then restarting the server to
> make changes. Thats why a simple framework with loadable
> modules it usally preferred to self modifying code!

Again, I'm sure it is better than C, but I definitely have had the
feeling that this is not something the language was designed for, and
that not many other people seem to be trying it.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-26 Thread Ed Singleton
On 25/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
>
> Hi Ed,
>
> This is a longish response because you are raising some
> very interesting (and deep) issues from a computer science
> point of view.
>
> > Well, self-modifying isn't inherently necessary.  What I guess I
> > really need is persistent classes as well as persistent objects.
>
> Python classes can be persistent just like any other object,
> theres nothing intrinsically different between a class object
> and any other kind of object (except that classes as objects
> are kind of mind bending as a concept!)
>
> > I always tend to think of classes as templates for objects rather
> > than factories.
>
> They are both.
>
> > In my mind, object methods are just calls to the class which
> > are evaluated every time they are called.
>
> The methjods are function attributes of a class which are selected
> by the class dispatch mechanism in response to messages sent to
> instances. In Python that means the getattr() methods look up
> the right method in response to receipt of a message.
>
> > Objects should be strict instances of classes that can't be
> > modified except for the values of their attributes.
>
> Attributes in a pure OOP language include both the contained data
> and functions. In other workds methods can be added/removed and
> modified as well as the data. In fact many would argue that the
> internal data not only cannot be modified externally but should not
> even be seen - the Data Hiding school of thought.
>
> > Class Page(object):
> >def print(self):
> > printPage(self)
>
> What does that gain you?
>
> > And have all my methods call functions (passing on parameters as
> > necessary).  That way if I change a function, it will be changed for
> > every instance of every object of that class.
>
> You mean like this:
>
> >>> class C:
> ...   def m(self): print 'm'
> ...
> >>> def f(o): print 'other m'
> ...
> >>> c = C()
> >>> c.m()
> m
> >>> C.m = f
> >>> c.m()
> other m
> >>>
>
> > And couldn't I write a function that would add functions or attributes
> > to classes and objects?
>
> Of course, just like I did there.
>
> > Am I trying to use the wrong language for this?  I love Python but I
> > seem to keep coming up against lots of practical issues with it
>
> Python is a pretty good language for this kind of thing,
> its just that this kind of thing is intrinsically difficult.
> The only lanuages I know of which are better than Python
> at it are Lisp and Smalltalk (and even Smalltalk
> has some limitations compared to Python). Do you have
> experience of a language which is more flexible in this regard?
> I'm curious because you seem to assume that its almost
> normal to be able to do these things, whereas in my
> experience its usually impossible rather than just difficult...

My background is in languages that are horrifically worse than python,
but I'm overly demanding I guess.  I think I have a good instinct for
what computers should be doing for me.  Everytime I'm doing something
repetitious I get exasperated because I know the computer should be
performing the repetitions rather than me.

I had the misfortune a couple of days ago of having to knock up a
couple of web pages in ASP.  A very basic search form, results page
and details page.  I had to open up a connection to the database, open
a recordset, concatenate a strings to make an SQL query, etc, etc.

It was horrible.  I copied and pasted a lot of the code, but even so
it involved doing ridiculous amounts of unnecessary work.

Maybe I'm just lazy, but then most progress has been made by people
who were either curious or lazy.

> > define the behaviours I want without having to bother with how the
> > computer is actually going to handle them.
>
> Believe it or not thats been the holy grail of language
> designers since the days of COBOL - The Common Business
> Oriented Language - which allowed business people to
> write theitr own programmes in "standard, everyday English",
> like:
>
> PROGRAM ID - HELLO
>
> PROCEDURE DIVISION
>MAIN-LINE-MODULE
>MOVE 0 TO COUNTER
>OPEN INPUT IN-FILE
>PERFORM READ IN-FILE UNTIL END-OF-FILE = "YES"
>ADD 1 TO COUNTER
>DISPLAY "LINE NUMBER ", COUNTER
>CLOSE IN-FILE
>STOP RUN.
>
> At the time it was considered revolutionary and programmers
> trembled at the prospect of instant redundancy. As it happened
> your average businessman found COBOL about as readable as pigin
> English! But that hasn't stopped us trying...
>
> One thing we have discovered is that the more natural the
> language seems to get the less flexible the language gets.
> Python is the closest I've seen yet to a general purpose
> language that is truly readable, but thats still a long
> way from being plain English! But I digress :-)

I can quite imagine that natural language isn't the way forward,
though I can also imagine that for business reasons readability won't
be the way forward (however I do love readab

Re: [Tutor] Modifying Source Code while Program is Running

2005-11-26 Thread Ed Singleton
On 26/11/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> >>>This immediately seemed to me to be a case for classes.
> >>>You provide a way for a user to create a new class by
> >>>subclassing the page class (from their point of view
> >>>probably through adding a few new fields to
> >>>a form).
> >
> > The behaviours of all the
> > classes would be the same (and would be fairly simple, a method for
> > rendering the page with a template, a method to update the data based
> > on a form submission).  Users would basically be able to change the
> > data structure (add and remove attributes).
>
> It seems to me that rather than having a new class for each type of data, you 
> need a class whose attributes are dynamic. I imagine you could have a list of 
> page types, each of which has a list of attributes. A new page type is 
> created not by defining a new class but by making a new entry in the types 
> table. The data for a page might be as simple as just a dict, or maybe it 
> makes sense to wrap it in a class, but the class would be the same for all 
> pages. A page would be rendered by combining a template with the dict 
> containing its data. Form submissions would be handled by referring to the 
> list of attributes for the type and extracting the corresponding data.
>
> You might have a class to wrap the page data and another one to wrap the 
> types table. These would provide operations on the contained data and be 
> common to all types.
>
> For persistence you could take a couple of approaches. You could persist the 
> lists and dicts directly using pickle or shelve or an object database. You 
> could persist them in a relational database by using a generic table with one 
> row for each data item - the columns would simply be object id, column name 
> and data. SQLite might work very well for this as it allows multiple data 
> types within a single column.
>
> The shift is from looking at the problem as one of dynamic classes, to one of 
> dynamic data. Python is excellent for working with dynamic data!
>
> BTW have you looked at Django? I don't think it is quite as dynamic as you 
> want on the model side but it has a lot of support for quickly generating a 
> presentation of a changing model.
> http://www.djangoproject.com/

>From this and what Alan said, I think I'm starting to get it.  Each
attribute could be an object or an entry in a list.  Each type would
be a collection or list of a particular set of attributes.  The
collection of types would be an object which is easily persisted.

I could pass the type of the page as a parameter when I create it, and
could have a method in the class that looks up the particular type and
adds all the relevant attributes to the object with sensible default
values.  Adding new pagetypes would be easy enough cause they're just
an entry in the types list.

Can you create an object whose default action is to return a certain
value?  For example could I have a header object that where when you
call page.header it returns a value but I can also have
page.header.update().  Or (I think) I know that methods can have
attributes, but can attributes have methods?

I need a bit more time to sit down and think this through (I've gained
a lot of information and at least a little enlightenment over the last
few days), but I think this is really starting to come together.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modifying Source Code while Program is Running

2005-11-26 Thread Ed Singleton
On 26/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
> >> point. Classes express behaviour, the data is only there to support
> >> the behaviour. Thats why methods are polymorphic but not attributes.
> >
> >If classes express behaviour, then what expresses the structure of the
> > data?
>
> Why do you care? If the program behaves as you expect it what does
> it matter what data it uses or how. That should be hidden from you
> inside the classes. Worrying about data is a feature of traditional
> Information Modelling/Structured Analysis style programming,
> OOP is all about inter-communicating objects sending messages to
> each other, each requesting and providing services to the others.

I get this now.  It goes back to what I said earlier about the "I
don't care how it works" philosophy.

Each object doesn't care how any other works.  You could completely
re-engineer the internals of an object and that would be fine as long
as the interface is the same.  As long as the methods and attributes
keep returning sensible values then everything is fine.

However, I'm still slightly uncomfortable with it.  It smells to me a
bit like the "as long as it works, its fine" school of thought.  For
my own sanity and peace of mind I like to have my data structures well
defined, as at the end of the day it's the data that matters (I can
rebuild functionality but data is given to me by other people and can
rarely be gotten back).

> > (ie what attributes there are going to be and what values they
> > are likely to accept).
>
> You need to think about the objects that you pass around as part
> of the messages, but those obnjects are in turn accessed via messages
> so their structure is not important. What does matter is the
> relationships between the objects, and they are related by message
> paths not fixed data relationships. This switch in thinking is the
> fundamental difference between traditional and OOP design.
>
> > You need (the option of) a data definition in order to generalise.
>
> No, you need the ability to modify behaviour.
> Most traditional programmers think in terms of modifying
> behaviour in terms of big if/elif trees
>
> if obj.type == sometype
> doSomeTypeThing()
> elif obj.type == another
> doAnotherTypeTHing
> etc...
>
> Whereas in OOP you simply say
>
> obj.doThing()
>
> And the right kind of doThing will happen because obj
> knows how to respond to that message in the appropriate way.

But writing a different doThing() for each object can be a huge waste
of time.  You want to be able to write one doThing() that is going to
work on each object (of a particular type).  This requires either
knowing that all your objects are going to be similar in some respect,
or writing a huge if..elseif as you mentioned.

Even just saying every object has a doThing() is starting to create a
data structure.

> > Using my web server example from earlier, you need to be able to say
> > that for any type of page, whatever it's attributes, you can create a
> > web form to search for that type of page by iterating through it's
> > attributes and creating a relevant form field for each type.
>
> So you want, for a given page to create a Form and search.
>
> But that's behaviour of the Page, just let it create its own form
> and do its own searches, not your problem. Create the right
> kind of Page and it will do the work for you...

But then I've got to create lots of different behaviours instead of
one simple generalised behaviour.

> > I definitely had the opposite in mind.  The behaviours of all the
> > classes would be the same (and would be fairly simple, a method for
> > rendering the page with a template, a method to update the data based
> > on a form submission).
>
> Thats fair enough and the parent Page class would do just that,
> but the template class would have methods that the Page called,
> and you can subclass or data drive the templates to return the
> appropriate strings to the page. (Since web pages after all are
> just collections of strings - or evenone big string...)
>
> > Users would basically be able to change the
> > data structure (add and remove attributes).
>
> So maybe attributes are objects too? Maybe you page needs
> to know how to handle attributes and you can create pages by
> adding attributes from a pick list, each attribute knowing how
> to render itself and how to respond to searches?

This combined with what Kent said, is what really solved the problem for me.

> There are lots of ways to address this is we think of the world
> in terms of intercommunicating objects not static data structures
> with a few overeaching functions controlling it all.

I've really gained a huge amount just from this one topic.  Not least
of which is that classes aren't necessarily a good answer to OOP
problems.

> > I'm sure Python is quite possibly the least worst at this, but that
> > doesn't make it good at it.
>
> Which brings me back to my original question, what environment
> do you think is go

[Tutor] Accessing next and previous items during iteration

2005-12-16 Thread Ed Singleton
Is it possible to access the next and previous items during an iteration?

I want to use it to iterate through html files in a folder and add
links in to the next and previous pages.

For example

for page in folder:
#add link to previous page
#add link to next page

I'm currently using:

prev = 0
current = 0
next = 0
for page in folder:
prev = current
current = next
next = page
if current:
if prev:
#add link to previous page
#add link to next page
if current:
if prev:
#add link to previous page
#add link to next page

But this seems a really awkward way to do it.

I've considered iterating and dumping them all into a list and then
iterating through the list, but that also seems awkward (having to
iterate twice).

Is there a nice way to do it?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accessing next and previous items during iteration

2005-12-19 Thread Ed Singleton
On 18/12/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > Is it possible to access the next and previous items during an iteration?
>
> This just came up on c.l.python. Bengt Richter has a nice generator-based 
> solution.
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/2e4533f108fbf172/90d87c91dac844d3?hl=en#90d87c91dac844d3

That's perfect!

It's a lovely piece of code as well.  Obvious once you've seen it, but
you wouldn't have thought of it before hand.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List-question

2005-12-19 Thread Ed Singleton
On 19/12/05, Øyvind <[EMAIL PROTECTED]> wrote:
> I have one function that finds some values. Then I want that function to
> find new values based on the values it found first. However, by just
> looping, it starts on an eternal job.
>
> As illustrated in:
> >>> list = [1,2,3]
> >>> list2 = list
> >>> list2
> [1, 2, 3]
> >>> for i in list:
> ... print i
> ... list2.append(4)
> ...
> 1
> 2
> 3
> 4
> 4
> 4 and it will forever continue with 4's.
>
> Why would list be expanded with the values of list2? How can I copy the
> result from one list, and do things with the list without getting it to
> expand?

Because they point to the same thing.

Type "list2 is list" after your other code and see.

You want list2 to be a COPY of list not a pointer to it.  Do this by using

list2 = list.copy()

Slices create a copy, so a shortcut is:

list2 = list[:]


Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List-question

2005-12-19 Thread Ed Singleton
On 19/12/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
> On 19/12/05, Øyvind <[EMAIL PROTECTED]> wrote:
> > I have one function that finds some values. Then I want that function to
> > find new values based on the values it found first. However, by just
> > looping, it starts on an eternal job.
> >
> > As illustrated in:
> > >>> list = [1,2,3]
> > >>> list2 = list
> > >>> list2
> > [1, 2, 3]
> > >>> for i in list:
> > ... print i
> > ... list2.append(4)
> > ...
> > 1
> > 2
> > 3
> > 4
> > 4
> > 4 and it will forever continue with 4's.
> >
> > Why would list be expanded with the values of list2? How can I copy the
> > result from one list, and do things with the list without getting it to
> > expand?
>
> Because they point to the same thing.
>
> Type "list2 is list" after your other code and see.
>
> You want list2 to be a COPY of list not a pointer to it.  Do this by using
>
> list2 = list.copy()
>
> Slices create a copy, so a shortcut is:
>
> list2 = list[:]

Sorry, you need to:

from copy import copy

before you can use copy.

Also, you shouldn't use "list" as a variable name. as it is a built-in
function that converts things to lists.  Use "list1".

That way you can also use list2 = list(list1).

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I make a python script go directory by directory and excecute on files of choice

2006-01-11 Thread Ed Singleton
On 11/01/06, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hi Srinivas -
>
> For walking a directory, you can use os.walk() or os.path.walk(), but
> I prefer the path module here -
> http://www.jorendorff.com/articles/python/path/.

The Path module is excellent, but it's walk still doesn't take into
account the depth of the current file in the folder structure.

If you need that, I wrote (with Kent's help) a simple script that will
take it into account (you need the Path module above for it to work).

def traverse(directory, function, depth=0):
import path
thedir = path.path(directory)
for item in thedir.files():
function(item, depth)
for item in thedir.dirs():
traverse(item,function, depth+1)

It can be used like:

def doprint(item, depth):
print item

traverse(r"C:\Temp", doprint)

Hope it's helpful to someone.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie question re. Functions

2006-02-01 Thread Ed Singleton
On 31/01/06, Jon Moore <[EMAIL PROTECTED]> wrote:
> Improve the function ask_number() so that the function can be called with a
> step value. Make the default value of step 1.
>
> The function looks like this:
>
> def ask_number(question, low, high):
> """Ask for a number within the range"""
> response = None
> while response not in range(low, high):
> response =  int(raw_input(question))
> return response

To be honest, this made sense to me.  I assumed the author wants you
to be able to do the following:

ask_number("Give me an even number between 1 and 10", 1, 10, 2)

The solution would be:

def ask_number(question, low, high, step=1):
"""Ask for a number within the range"""
response = None
while response not in range(low, high, step):
response =  int(raw_input(question))
return response

But I definitely agree that he said it very, very badly.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another try at Python's selfishness

2006-02-03 Thread Ed Singleton
On 3 Feb 2006 03:59:10 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > I still see "newbie-friendliness" as a
> > MAJOR plus for Python -- it increases the chance that users
> > of your software will become contributors.
>
> Yes, I 100% agree to that point!
> But the point is, the current situation is not newbie-friendly (I can
> tell, I am a newbie): I declare a method with 3 parameters but when I
> call it I only pass 2 parameters. That's confusing. If I declare a
> member variable, I write: "self.x  = ValueForX", why can't I be equally
> explicit for declaring member functions?

I have to say that as a newbie, it took me quite a while to get my
head around that extra parameter (self).

It took me ages to work out that:

class A:
   def __init__(self, foo):
   self.foo = foo

a = A("hello")

is actually a shortcut for:

a = A(a, "Hello")

or even:

a = new A(a, "Hello")

I think insisting on:


a = A(a, "Hello")

would be very good for readability, understandability and newbie-friendliness.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another try at Python's selfishness

2006-02-04 Thread Ed Singleton
On 04/02/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > I have to say that as a newbie, it took me quite a while to get my
> > head around that extra parameter (self).
>
> That's OK, its true of most folks, even non newbies!
> It is one area where Python is different to most languages
> who hide the self completely.
>
> > It took me ages to work out that:
> >
> >class A:
> >   def __init__(self, foo):
> >   self.foo = foo
> >
> > a  = A("hello")
> >
> > is actually a shortcut for:
> >
> > a = A(a, "Hello")
>
> > I think insisting on:
> >
> > a = A(a, "Hello")
> >
> > would be very good for readability, understandability and
> > newbie-friendliness.
>
> Only for the constructor.
> Once you have the object itself the method calls wouyld be much less
> readable:
>
> class C:
>   def a(s):pass
>
> c = C()
> c = c.a(c)
> etc
>
> is not descriptive of the concept of passing a message to the object c,
> it looks rather like you are passing the object c to a function which is
> a member of itself, which brings to mind recursion not messages...
>
> Remember that the purpose of writing a class is to *hide* the details of
> its implementation from the user, thus the user never has to use self,
> only the builder. The only reason you are confused is because you
> are both builder and user of the class.

As always Alan, you've managed to make something confusing seem
sensible and logical.

That is the best explanation of this subject I've ever heard.

> But consider file objects, do you ever feel the need to write:
>
> myfile = file(myfile,filename,mode)
>
> or does
>
> myfile = file(filename,mode)
>
> seem more friendly? Is that because you've nbever actually
> seen the constructor code for the file class(*) and so don't
> worry about the presence of self?
> If you did have to pass the object in, wouldn't you be asking
> why you had to pass the object into the file creation method?

I now agree, and (I think) understand completely.

Ed

PS Are there any good tutorials on the more philosophical side of the
object orientedness of Python?  I've read pretty much all the major
tutorials that are commonly linked to, and they often cover HOW to use
classes and stuff, but I'm quite interested in WHY we use classes (and
as I've discovered from you and Kent, WHEN to use classes).   I've
found some general OOP tutorials, but they always seem to use Java or
C which I don't know and don't particularly care to know.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dynamically naming functions

2006-03-10 Thread Ed Singleton
How does one go about creating functions, classes, or callable objects
when you don't know their name in advance? (For example you want to
read their names in from a text file or database).

I want to use this in a few different places.  For example Faces, the
Python Project Management Planner Tool Thingy, uses nested functions
to put tasks within a project:

def MyProject():
start = "2006-03-06"
resource = Me

def Task1():
start = "2006-03-13"

def Task2():
effort = "1w"

I'd like to load these from a database (using SQLObject), but I'm not
sure how I can define the name of the function from a filed in a
database (or read in from a text file).

I'd also like to be able to do this in CherryPy/TurboGears so that I
can create a dynamic site structure based on fields in a database.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically naming functions

2006-03-13 Thread Ed Singleton
On 10/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > How does one go about creating functions, classes, or callable objects
> > when you don't know their name in advance? (For example you want to
> > read their names in from a text file or database).
> >
> > I want to use this in a few different places.  For example Faces, the
> > Python Project Management Planner Tool Thingy, uses nested functions
> > to put tasks within a project:
> >
> > def MyProject():
> > start = "2006-03-06"
> > resource = Me
> >
> > def Task1():
> > start = "2006-03-13"
> >
> > def Task2():
> > effort = "1w"
> >
> > I'd like to load these from a database (using SQLObject), but I'm not
> > sure how I can define the name of the function from a filed in a
> > database (or read in from a text file).
>
> This is truly bizarre use of nested functions. Faces must be looking at
> the compiled function objects to pick this out.

To be honest, this didn't seem that bizarre to me.  If I understand
properly (which I probably don't) functions are just callable objects
like any other callable object (or at least can be treated as such). 
Isn't this just a handy way of creating a nested object structure
that's readable?

> I would look into the Project objects themselves and see if there is a
> way to create them dynamically, rather than trying to build this
> structure dynamically at run time.
> >
> > I'd also like to be able to do this in CherryPy/TurboGears so that I
> > can create a dynamic site structure based on fields in a database.
>
> This seems more practical. I would define a class that is configured by
> the database can be used as a CP model object. Then you can insert the
> class into the CP site structure using setattr().
>
> In general you can set an attribute of an object using setattr():
>setattr(foo, 'bar', 3)
> is the same as
>foo.bar = 3
> but the attribute name is specified as a string so it can be determined
> at runtime.

This makes sense, and I think I can see how I would use it.

To create a bunch of objects from some data (just name and start date):

for fname, startdate in data:
def foo:
start = ""
setattr(foo, __name__, fname)
setattr(foo, start, startdate)

Sorting out the nesting should be fairly straightforward (if the above works).

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically naming functions

2006-03-13 Thread Ed Singleton
On 10/03/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > How does one go about creating functions, classes, or callable objects
> > when you don't know their name in advance? (For example you want to
> > read their names in from a text file or database).
>
> First point, names of functions are no different to names of other things.
>
> def f(x):
> y = blah
> return y
>
> is essentialy the same as saying
>
> f = lambda x: blah...
>
> lambda defines a nameless (aka anonymous) function and then assigns that
> function to the variable called f.
>
> Of course Pythons lambda construct is a bit brain dead so we can achieve
> the same result with just assigning an existing function to a new name
>
> def f(x):
>y = nblah...
>return y
>
> g = f
>
> Now g is a new name that refers to the function called f.

I have to say I assumed that if you then changed f, g would point to
the new f rather than the old f, but I tried it out and it seems
otherwise:

>>> def f(x):
... print x
...
>>> f(1)
1
>>> a = f
>>> a(1)
1
>>> def f(x):
... print x * 2
...
>>> f(1)
2
>>> a(1)
1
>>> b = f
>>> b(1)
2

Which is really cool, except that the names "a" and "b" need to be
decided at run time.

> And with nested function definitions we can write functions that
> return functions:
>
> def makeMultiplyAndAdd(constants):
> def f(x):
> return constant[0] * constant[1] + x
> return f
>
>
> > I'd like to load these from a database (using SQLObject),
> > but I'm not sure how I can define the name of the function
> > from a field in a database (or read in from a text file).
>
> Same way as you would for any other kind of variable.
> This has been discussed many times and there is some trickery you
> can do using the built in dictionaries that Python uses for its namespaces.
> But the biggest proiblem with introducing new names at run time is:
> How does the existing code get to know about those names that
> didn't exist when the code was written? Ypou need to have the code
> go exploring for names, work out what kind ioopf value they hold etc...
> It all gets very messy and complicated and fault prone.
>
> So the normal way to do this is to use a dictionary.
> The dictionary is a collection of names with values asociated with them.
> Those values can be functions or classes or anything else.
>
> Now your code can access the new names by using standard
> dictionary iterators etc. All you need are some conventions around
> how many parameters the functions have, their types etc.
>
> > I'd also like to be able to do this in CherryPy/TurboGears
> > so that I can create a dynamic site structure based on fields
> > in a database.
>
> Dynamic site structure shouldn't need dynamic creation of functions
> although the structure might need to be dynamically loaded into a
> data structure in the code. It might also be a parameter of the functions.

Doesn't CherryPy/TurboGears require Classes and Functions for it's
data structures?  (Or parameters passed to them, of course).

I had been thinking that I would load my whole site at startup, but I
guess it would probably be better to write a function that takes the
parameters and looks up the first to see if it exists as a page, then
looks to see if the second is a child of the first etc.  But this
really feels like something CherryPy should be doing for me.

> But as always remember that dynamic anything usually means
> much harder to maintain. All of your backup/archiving tools and error
> reporting tools etc will need to understand your dynamic structure too.
> Dynamic sounds like fun but usually means grief and is only justified
> as a last resort IMHO!

For website, I can't really see how I can not have a dynamic
structure.  There's no way I'm writing a function for each "folder". 
I do take your point though, however you often find that it's easy to
maintain something dynamic than huge amounts of more static stuff (as
in the difference between hundreds of static web pages and using a cms
of some kind).

> But if you must go dynamic Python is as good a language to do it
> in as you'll get.

That's certainly been my experience so far..

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically naming functions

2006-03-13 Thread Ed Singleton
On 13/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > On 10/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> >
> >>Ed Singleton wrote:
> >>>I want to use this in a few different places.  For example Faces, the
> >>>Python Project Management Planner Tool Thingy, uses nested functions
> >>>to put tasks within a project:
> >>>
> >>>def MyProject():
> >>>start = "2006-03-06"
> >>>resource = Me
> >>>
> >>>def Task1():
> >>>start = "2006-03-13"
> >>>
> >>>def Task2():
> >>>effort = "1w"
> >>>
> >>>I'd like to load these from a database (using SQLObject), but I'm not
> >>>sure how I can define the name of the function from a filed in a
> >>>database (or read in from a text file).
> >>
> >>This is truly bizarre use of nested functions. Faces must be looking at
> >>the compiled function objects to pick this out.
> >
> >
> > To be honest, this didn't seem that bizarre to me.  If I understand
> > properly (which I probably don't) functions are just callable objects
> > like any other callable object (or at least can be treated as such).
> > Isn't this just a handy way of creating a nested object structure
> > that's readable?
>
> Why not just use nested dicts?
>
> MyProject = dict(
>start = "2006-03-06",
>resource = Me,
>Task1 = dict(start = "2006-03-13"),
>Task2 = dict(effort = "1w"),
> )
>
> Maybe the appearance isn't quite as nice but the intent is clear, the
> code to access the data is *much* simpler, and it lends itself to the
> kind of programmatic creation you are trying to do. Take a look at
> task.Task._compile() in the faces source to see the gyrations it takes
> to extract the data in functional form. The Zen of Python says,
>"Explicit is better than implicit"
>"Simple is better than complex"

Point taken.  Dict's are easier.  And the appearance is fine.

I've just discovered with a little playing, that you can do:

>>> def z(v):
... def f(x):
... print x * v
... return f
...
>>> c = z(3)
>>> c(1)
3
>>> funcdict = dict(foo = z(4))
>>> funcdict["foo"](1)
4

Which was obvious enough that I thought of trying it, but surprising
enough that I was really pleased when it worked.

> >>In general you can set an attribute of an object using setattr():
> >>   setattr(foo, 'bar', 3)
> >>is the same as
> >>   foo.bar = 3
> >>but the attribute name is specified as a string so it can be determined
> >>at runtime.
> >
> >
> > This makes sense, and I think I can see how I would use it.
> >
> > To create a bunch of objects from some data (just name and start date):
> >
> > for fname, startdate in data:
> > def foo:
> > start = ""
> > setattr(foo, __name__, fname)
> > setattr(foo, start, startdate)
> >
> > Sorting out the nesting should be fairly straightforward (if the above 
> > works).
>
> No, it won't work. A function attribute is not the same as a local
> variable of the function. What you propose is essentially
> def foo(): pass
> foo.bar = 'data'
>
> but what you need is
> def foo():
>bar = 'data'
>
> which is very different.
>
> faces looks at foo.func_code.co_names to find the names you have used,
> and it actually runs the function with a tracing hook to capture the values.
>
> There doesn't seem to be any other way to define a Task in faces,
> either. You have to actually create functions. I guess this might be a
> good place to use exec - just create the source code for the function
> defs in a string and exec it, then retrieve the function from the global
> namespace and pass it to faces. Then tell me why this API is better than
> using nested dicts.

Agreed, though to be fair the author of faces has probably
overcomplicated the code for handling it (which is a damn shame as it
is really quite a nice project planning tool).  I guess you can't
blindly iterate over the methods of functions, as there are other
methods there that you might not want to use (like setattr and stuff,
maybe?).

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically naming functions

2006-03-14 Thread Ed Singleton
On 13/03/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > For website, I can't really see how I can not have a dynamic
> > structure.  There's no way I'm writing a function for each "folder".
>
> Hmm, this may be a CherryPie concept thing but the vast majority
> of websites do not have dynamic structures. It really shouldn't be
> necessary. Why would you need to write a function per folder,
> simply write one function that takes the folder as an argument.
>
> > I do take your point though, however you often find that it's easy to
> > maintain something dynamic than huge amounts of more static stuff
>
> Very rarely, its easy to do backups of huge amounts of data if you
> know where to find it, its hard to trawl all over a changing structure
> looking for the things that need backing up. Particularly if, when you
> try to restore it, it needs to go in a different place to where you found
> it!

Backing up is generally one of the lesser of my worries.  Maintaining
content is primary.  Unless you are dynamically generating static
pages, they are a nightmare to maintain.  Particularly as it tends to
be quite repetitive.  A large amount of the code on any page is the
same as on any other page (page structure, boilerplate, etc).

I think it's a generally accepted principle that computers are better
at handling thousands of files like that better than humans are.  The
more of the repetitive stuff that can be removed and given to a
computer, the better.

> > in the difference between hundreds of static web pages and using
> > a cms of some kind).
>
> Yes but a CMS normally uses a static structure with dynamic content.
> The templates stored in one place and the content in another. The
> templates know where to look for the content and the content doesn't
> care where the templates are.

I think we might be using different meanings of structure.  I'm
referring to the site structure, as in which page is a parent of which
other page.  The site structure is just another aspect of the content.
 A reference to the parent/child pages is just another attribute like
content and title.

A (good) CMS would create a dynamic structure for the user to browse,
with folders and pages easily creatable and movable, and references to
pages would be dynamic so that if yo0u move a page internal links to
it still work.

> Dynamic content is 'A Good Thing', dynamic structure is usually bad.

But structure is just an aspect of content.

> BTW On the concept of loading your entire site at startup; if you are
> sharing a server you will make yourself very unpopular since you will
> be a huge resource hog. That's why ASP, JSP and other frameworks
> go to a lot of trouble to manage session lengths etc - to free up any
> unused resources and keep server speed up. Loading the structure
> of the site in the form of links might be reasonable, but only load content
> when you absolutely must. This also helps the maintainers update the
> site without restarting it.

I have my own dedicated server, but point taken.  Though I will still
need to reload the structure of the site when the maintainers change
it (adding/removing pages etc).

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using Beautiful Soup to extract tag names

2006-03-14 Thread Ed Singleton
I have (unfortunately) received some data in XML format.  I need to
use it in Python, preferably as a list of dictionaries.  The data is a
flat representation of a table, in the style:


Some Data
Some Data
...


Some Data
Some Data
...

and so on (where tablename is always the same in one file).

It looks like Beautiful Soup would be a good option to quickly change
it into a usable format, but I need to extract the field name (there's
lots and lots of fields) as well as the data, and I can't work out how
to do that in Beautiful Soup.

If anyone can give me some help I'd be grateful, or if they can point
me in the direction of a better solution.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Beautiful Soup to extract tag names

2006-03-14 Thread Ed Singleton
As always Kent, you're amazing.

That will do perfectly.  (Though the ElementTree documentation seems a
bit difficult to get through.  I'm sure I'll get through it
eventually).

Thanks

Ed

On 14/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > I have (unfortunately) received some data in XML format.  I need to
> > use it in Python, preferably as a list of dictionaries.  The data is a
> > flat representation of a table, in the style:
> >
> > 
> > Some Data
> > Some Data
> > ...
> > 
> > 
> > Some Data
> > Some Data
> > ...
> >
> > and so on (where tablename is always the same in one file).
>
> ElementTree makes short work of this:
>
> from elementtree import ElementTree
>
> xml = '''
> 
> Some Data1
> Some Data2
> 
> 
> Some Data3
> Some Data4
> 
> '''
>
> doc = ElementTree.fromstring(xml)
> # use ElementTree.parse() to parse a file
>
> for table in doc.findall('tablename'):
>  for field in table.getchildren():
>  print field.tag, field.text
>
>
> prints:
> fieldname1 Some Data1
> fieldname2 Some Data2
> fieldname3 Some Data3
> fieldname4 Some Data4
>
> If speed is an issue then look at cElementTree which has the same
> interface and is blazingly fast.
> http://effbot.org/zone/element.htm
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Passing Dictionaries to Functions

2006-03-15 Thread Ed Singleton
If I have a dictionary:

mydict{'var1':"a", 'var2':"b"}

and I want to pass it to a function as:

myfunc(var1="a", var2="b")

How would I do it?

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing Dictionaries to Functions

2006-03-15 Thread Ed Singleton
Thanks again.

This does bring up an issue I occaiosionally have with the documentation.

Presumambly myfunc(**mydict) is a fairly trivial thing, but it is very
hard to find when you don't know what you're looking for.  Not sure
what the solution is, but the inability to search for things when you
don't know what they're called is a bit of a stumbling block
sometimes.

Maybe a page that very briefly summarises the 'unsearchable' with
links to fuller descriptions?

Ed

On 15/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > If I have a dictionary:
> >
> > mydict{'var1':"a", 'var2':"b"}
>
> Presumably you mean
>mydict = {'var1':"a", 'var2':"b"}
> >
> > and I want to pass it to a function as:
> >
> > myfunc(var1="a", var2="b")
> >
> > How would I do it?
>
> myfunc(**mydict)
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Converting String to Datetime

2006-03-15 Thread Ed Singleton
I seem to have a lot of questions today.  Sorry.

How can I convert a string in the format "%Y-%m-%d %H:%M:%S" into a
datetime object?

I can work out how to convert it to a time object by:

import time
timestring = "2005-09-01 12:30:09"
time_format = "%Y-%m-%d %H:%M:%S"
mytime = time.strptime(timestring,time_format)

I can't seem to work out how to convert the time object into a
datetime object...

Any help appreciated.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting String to Datetime

2006-03-15 Thread Ed Singleton
Nevermind.  i seem to have found the answer in that wonderful PLEAC
site (I always forget about that.

It appears that the following works:

import time, datetime
timestring = "2005-09-01 12:30:09"
time_format = "%Y-%m-%d %H:%M:%S"
datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format)))

Ed

On 15/03/06, Ed Singleton <[EMAIL PROTECTED]> wrote:
> I seem to have a lot of questions today.  Sorry.
>
> How can I convert a string in the format "%Y-%m-%d %H:%M:%S" into a
> datetime object?
>
> I can work out how to convert it to a time object by:
>
> import time
> timestring = "2005-09-01 12:30:09"
> time_format = "%Y-%m-%d %H:%M:%S"
> mytime = time.strptime(timestring,time_format)
>
> I can't seem to work out how to convert the time object into a
> datetime object...
>
> Any help appreciated.
>
> Thanks
>
> Ed
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Opening .py files in firefox

2006-03-21 Thread Ed Singleton
On 20/03/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> > If the browser tries to execute the script you will need to go to
> > the file types setting in the browser and set .py to plain-text.
> >
> > This is what I need to do ... but, after looking at all the options
> > (within tools->Options), I still can not find a way to do this;
>
> Neither can I! How odd.
>
> > firefox-snafu: when I try to open a file in "my document", firefox
> > splits up the path, interprets the request as a series of files to
> > open, and start to open a number of totally unrelated webpages.
>
> You probably need to mess around with quotes.
>
> Something like "%1" after the exectuable name might do it
> %1 is DOS shorthand for the name of the file... Putting it in
> quotes should stop Firefox splitting the path.
>
> > Thanks for your help, anyway; I'll stick to opening them with an editor
> > for now.
>
> You've got me curious how to do this in Firefox now :-)

On Windows, Go to Run then type Regedit.  Go to HKEY_CLASSES_ROOT and
find .py then change it's Content Type to text/plain.

As far as I am aware this is the default for python files anyway, but
it may have got changed on your computer.

Firefox itself doesn't have a list of MimeTypes under normal
circumstances.  It's mimetypes.rdf is generally empty except for
references to online lists of mimetypes.  (It's stored in your profile
btw, usually [your profile]\Application
Data\Mozilla\Firefox\Profiles\)

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically naming functions

2006-03-27 Thread Ed Singleton
On 26/03/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > How does one go about creating functions, classes, or callable objects
> > when you don't know their name in advance? (For example you want to
> > read their names in from a text file or database).
> >
> > I want to use this in a few different places.  For example Faces, the
> > Python Project Management Planner Tool Thingy, uses nested functions
> > to put tasks within a project:
> >
> > def MyProject():
> > start = "2006-03-06"
> > resource = Me
> >
> > def Task1():
> > start = "2006-03-13"
> >
> > def Task2():
> > effort = "1w"
> >
> > I'd like to load these from a database (using SQLObject), but I'm not
> > sure how I can define the name of the function from a filed in a
> > database (or read in from a text file).
>
> Hi Ed,
>
> I was just wondering how this came out - did you find a way to generate
> these functions dynamically? Or change Faces? Or give up?

I just temporarily delayed the problem.  I'm going to have a look at
trying to change the Faces code to use dictionaries as per your
suggestion, but it would a big task for me (my biggest so far
probably).

(I have a new job that lets me do everything in Python, but sometimes
they direct my efforts towards a particular task, which delays my
working on interesting things).

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Program for outputing the letter backward

2006-03-30 Thread Ed Singleton
On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote:
> --- John Fouhy <[EMAIL PROTECTED]> wrote:
>
> > On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote:
> > > vehicle='car'
> > > index = vehicle[-1]   #the last letter
> > > index_zero = vehicle[0]   #the first letter
> > >
> > > while index >= index_zero:
> > >letter=vehicle[index]
> > >print letter
> > >index -= 1
> > >
> > > The problem is that I get no output here. Could I
> > hear
> > > from you?
> >
> > I can print the letters backwards like this:
> >
> > vehicle = 'car'
> > print vehicle[2]
> > print vehicle[1]
> > print vehicle[0]
> >
> > Output:
> >
> > r
> > a
> > c
> >
> > -
> >
> > This is not very useful, though, because it will
> > only work for strings
> > that are exactly three letters long.  Can you see
> > how to write a loop
> > to produe this output?
> >
> > Hint: the len() function will tell you how long a
> > string is.
> >
> > eg: if vehicle == 'car' then len(vehicle) == 3.
> >
> > --
> > John.
> > ___
>
> Hi John,
>
> I am still 'blind' here.
>
> Please, see below what I did, and what I got:
>
> >>> vehicle='car'
> >>> index = 0
> >>> lenght =len(vehicle)
> >>> last = vehicle[lenght -1]
> >>> while last >= vehicle[0]:
> ... letter = vehicle[index]
> ... print letter
> ... last -= 1
> ...
> c
> Traceback (most recent call last):
>   File "", line 4, in ?
> TypeError: unsupported operand type(s) for -=: 'str'
> and 'int'
>
> As you can see, I am still a newbie...
> Could anyone, please, guide me on this exercise?
> Thanks!
> Hoffmann

A technique I used to find useful when I was very first learning (and
struggling) was to calculate the variables for each pass of the loop
(basically remove all the variable names, just like doing algebra).

So:

>>> vehicle='car'
>>> index = 0
>>> lenght = len(vehicle) # therefore:
>>> lenght = 3
>>> last = vehicle[lenght -1] # therefore:
>>> last = vehicle[2] # therefore:
>>> last = "r"
>>> while "r" >= "c": # first pass
... letter = vehicle[index] # therefore:
... letter = vehicle[0] # therefore:
... letter = "c"
... print letter
... last -= 1 # therefore:
... "r" -= 1 # therefore:
... "r" = "r" - 1 # therefore:
... ERROR

You'll find that that can make it much clearer what is actually
happening.  An alternative is to use lots and lots of print
statements:

>>> vehicle='car'
>>> print vehicle
>>> index = 0
>>> print index
>>> lenght = len(vehicle)
>>> print lenght

and so on...

It would be really good if there was a way to have a "verbose"
interpreter that showed you each of the steps in the process, but I
don't know of any.

For example:

>>> last = vehicle[lenght -1]
last = vehicle[2]
last = "r"
>>>

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] failing to learn python

2006-04-11 Thread Ed Singleton
On 10/04/06, Payal Rathod <[EMAIL PROTECTED]> wrote:
> Hi,
> I am trying to learn Python seriously for almost 2 months but have not
> gotten far at all. Infact, it seems I have not understood even the basic
> concepts itself. I know some shell, sed and awk programming.
> I have tried reading Learning Python - Mark Lutz
> Think C Spy
> A byte of Python
> Non-Programmers Tutorial For Python
> etc.
> But I have not got anything from them. I am feeling that they are
> superficial and do not touch real life problems. Also, not enough
> examples are provided which can help newbies like me.
>
> Can anyone help me, it is pretty pretty frustating thing for last couple
> of months?
>
> With warm regards,
> -Payal

You might find reading real code to be more useful than a tutorial:

Fredrik Lundh's Guide to the Standard Library contains thousands of examples:
http://effbot.org/zone/librarybook-index.htm

PLEAC contains loads of examples to show how to do things:
http://pleac.sourceforge.net/pleac_python/index.html

It all depends what kind of learner you are:
Learn by being taught (read the tutorials)
Learn by doing (think of a project, start trying to do it, then ask
here when you get stuck)
Learn by example (read lots of examples of other people's code to see
how they do it)

I'm very much the kind of person who likes to learn to swim by jumping
as far into the water as he can, then trying to get back to the side. 
It's amazing how well you can do something when you don't have any
choice. ;-)

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Emailid

2006-04-11 Thread Ed Singleton
On 11/04/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Kaushal Shriyan wrote:
> > Hi All
> >
> > I am a ardent fan of python can I have email address for me
> > I mean For example for me it would be
> >
> > [EMAIL PROTECTED]
>
> I don't know how you get a python.org mailing address but I'm sure it's
> not by asking here!

Actually, I can probably help.  If you give your bank details to my
friend in Nigeria, he can get you one.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Database Connectivity

2006-04-11 Thread Ed Singleton
On 11/04/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
> Hi ALL
>
> How do i connect my python program to MySQL DB or Oracle DB or can you
> please specify the URL which gives a detailed explanation on this.

SQLObject is your best bet:
http://www.sqlobject.org/

If you're using MySQL, you will need MySQLdb as well:
http://sourceforge.net/projects/mysql-python

Any questions, just ask.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Force a value to int

2006-04-13 Thread Ed Singleton
Is there a particular way to force a value to be an int by either
converting it with int() or returning a default value.

I've ended up writing my own function to do it, but it seems like the
kind of thing that would be built-in somewhere.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor FAQ?

2006-04-21 Thread Ed Singleton
On 20/04/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Mike Hansen wrote:
> > I'd like to send a big Thank You to Danny, Alan, Kent and others(whos names
> > escape me) for being such an asset to the Python community by relentlessly
> > answering questions on the tutor list.(Do these guys sleep? They must work
> > in shifts.) This list is one of the most civilized and responsive lists I
> > have ever read. When many pop onto the list and ask what may seem like some
> > of the most obvious questions, you guys calmly answer and nudge them in the
> > right direction without ever losing your patience. It's a great list.
>
> Thanks! I do sleep but I have my email tied in to my clock radio so
> whenever an email arrives on the tutor list I am awakened to answer it ;)
> >
> > Anyway, I've been reading the list for a couple of years now, and I wonder
> > if a Tutor FAQ would be helpful. I don't believe one exists. Should there be
> > something on the Python wiki that would list the most common questions to
> > the tutor list along with their answers? It would be a FAQ about the tutor
> > list as well as common questions to the tutor list.
>
> I wonder about this sometimes too. I think it would be good to have a
> place to collect this stuff.
>
> Maybe this could be integrated with the main Python FAQ in a beginner's
> section? Fredrik Lundh is experimenting with a FAQ wiki here:
> http://pyfaq.infogami.com/

Actually I put something about this on PyFAQ just the other day. 
Fredrik was quite keen on the idea, but I've been busy the last couple
of days and haven't got around to doing anything about it.

Mike, if you're volunteering that would be perfect.  If anyone here
has ideas for questions that get asked a lot (like "How do I write a
program that prints a word backwards") then just posting them in this
thread would be a good start.

I assume Kent, Alan and Danny don't mind their answers being reused in
the wiki, but it would probably best to get explicit permission from
them (and other people) to re-use text from their answers.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor FAQ?

2006-04-21 Thread Ed Singleton
On 21/04/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > If anyone here
> > has ideas for questions that get asked a lot (like "How do I write a
> > program that prints a word backwards") then just posting them in this
> > thread would be a good start.
>
> We should be careful about posting solutions to homework problems, which
> this could easily be.

Agreed ;-)

The last couple of times people have asked this, there's been some
really good replies that helped them tease out the solution (what to
think about, how to think about the problem, etc).

I think quite a lot of the answers to some FAQs won't be solutions, but advice.

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor FAQ?

2006-04-22 Thread Ed Singleton
> Yep, I'm volunteering. Forgive my ignorance, but I couldn't seem to figure
> out how to edit/add pages to http://pyfaq.infogami.com/. The tutorial wiki
> has the edit, but the pyfaq page doesn't. I am logged in using my reddit
> login.

I don't think the FAQ is open to public editing yet.  I'm not sure
when it will be, but Fredrik might be able to give a timescale.

I've made a start on adding your questions, but probably won't get to
do much more until tomorrow.

Ed

On 21/04/06, Mike Hansen <[EMAIL PROTECTED]> wrote:
>
>
> > > Maybe this could be integrated with the main Python FAQ in a
> > > beginner's section? Fredrik Lundh is experimenting with a
> > FAQ wiki here:
> > > http://pyfaq.infogami.com/
> >
> > Actually I put something about this on PyFAQ just the other day.
> > Fredrik was quite keen on the idea, but I've been busy the
> > last couple of days and haven't got around to doing anything about it.
> >
> > Mike, if you're volunteering that would be perfect.  If
> > anyone here has ideas for questions that get asked a lot
> > (like "How do I write a program that prints a word
> > backwards") then just posting them in this thread would be a
> > good start.
> >
> > I assume Kent, Alan and Danny don't mind their answers being
> > reused in the wiki, but it would probably best to get
> > explicit permission from them (and other people) to re-use
> > text from their answers.
> >
> > Ed
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> Yep, I'm volunteering. Forgive my ignorance, but I couldn't seem to figure
> out how to edit/add pages to http://pyfaq.infogami.com/. The tutorial wiki
> has the edit, but the pyfaq page doesn't. I am logged in using my reddit
> login.
>
> Below is what little I slapped together last night. I copied the content
> from the Python tutor mailman page for the first question.
>
> =
> Python Tutor FAQ
> -
> What is Python Tutor?
>
> This list is for folks who want to ask questions regarding how to learn
> computer programming with the Python language.
>
> Python (http://www.python.org) is a programming language which many feel is
> a good first language, because it makes it easy to express the fundamental
> concepts of programming such as data structures and algorithms with a syntax
> which many find easy to read and write.
>
> Folks interested in learning about programming with Python are encouraged to
> join, as are folks interested in helping others learn. While the list is
> called tutor, anyone, whether novice or expert, can answer questions.
>
> If individuals wish to start off-line conversations about a particular
> concept and become one-on-one tutor/tutee, that's fine. If either party
> wants to summarize what they learned for others to benefit, that's fine too.
>
> There is a searchable interface to archived Tutor messages on Activestate's
> web site at
> http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor.
>
> To see the collection of prior postings to the list, visit the Tutor
> Archives at http://mail.python.org/pipermail/tutor/
>
> Using Tutor
> To post a message to all the list members, send email to tutor@python.org
>
> -
> I need help; I'm getting an error in my program. What should I do?
>
> If you are getting an error in your Python program that you don't
> understand, post the error message and any relevant code. Post the exact
> error message. Don't paraphrase the error message. The error message has
> details that can help resolve the issue that caused the error.
>
> -
> What is the policy on homework?
>
> Although those on the Python tutor mail list are eager to help, they don't
> want to hand you the answers to your homework. They want to help you find
> the answers. If you are having difficulty with your homework, send a message
> to the list about the problem and what you have tried. The tutors will try
> to nudge you in the right direction.
>
> -
> Why do my replies go to the person who sent the message and not to the list?
>
> This is by design.
> See http://www.unicom.com/pw/reply-to-harmful.html
>
> Also see this explanation
> http://mail.python.org/pipermail/tutor/2005-July/039889.html
>
> =
>
> Unless anyone has any more, I think the above covers the FAQs about the
> tutor list.
>
> Here's some of the FAQs that I came across scanning the list:
>
> ord and chr
> parsing html beautifulsoup
> editors/ides
> getters and setters
> regex match and find
> maxtrix operations
> how do I make an exe out of a python script
> books
> what sho

Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Ed Singleton
On 24/04/06, Etrade Griffiths <[EMAIL PROTECTED]> wrote:
>  Hi
>
>  just feeling my way into Python with a  small app that reads data from
> file, creates objects using that data, stores the objects in a list, loops
> over the list doing comparison tests to filter out various objects.  Here is
> a code snippet:
>
[snip]
>
>  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> return zero so something is going wrong somewhere.  I think I'm either not
> storing the objects correctly or retrieving them correctly but no idea why!
> All suggestions gratefully received!!!

I added some test input to give the code below, and it works fine for
me.  Can you give us some test input that fails for you?  Can you also
show us your test() function as it may the code in there that is
failing.

Ed

class myObj:
def __init__(self,a,b):
self.a=a
self.b=b

def get_a(self):
return self.a

def get_b(self):
return self.b


input = ["1 2 3", "4 5 6"]

L1=[]
nobj=0

for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1

an_obj=myObj(a,b)

L1.append(an_obj)

# Filter data

for i in range(1,nobj):
for x in L1:# ... loop over all objects in list
print "a -> ", x.get_a() # ... get value
of a from current object
print "b -> ", x.get_b()


It returns:

a ->  2
b ->  3
a ->  5
b ->  6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regex across multiple lines

2006-04-27 Thread Ed Singleton
On 26/04/06, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hi Frank, just bear in mind that the pattern:
>
> patObj = re.compile(".*", re.DOTALL)
>
> will match
>
> 
>This is my title
> 
>
> But, it'll also match
>
> 
>This is my title
> 
> Some content here
> 
> Another title; not going to happen with a title tag in HTML, but
> more an illustration
> 
>
> All of that.
>
> Got to watch .* with re.DOTALL; try using .*? instead, it makes it
> non-greedy. Functionality for your current use case won't change, but
> you won't spend ages when you have a different use case trying to
> figure out why half your data is matching. >_<

When you only want a tag like  with no nested tags, I sometimes use:

[^<]*

though for anything but the most trivial cases, it's often better to
use BeautifulSoup

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to *really* copy a list

2006-04-28 Thread Ed Singleton
On 28/04/06, John Fouhy <[EMAIL PROTECTED]> wrote:
> On 28/04/06, kevin parks <[EMAIL PROTECTED]> wrote:
> > In most case you are fine operating on the list in place and altering the
> > existing list. In some cases you want your code to stop molesting your poor
> > mutables and really honestly sincerly copy the dang thing. In this case i am
> > making a function that does odd smmetry mirroring. But i want my orginal 
> > list
> > to remain intact
> >
> > def mirror(seq):
> > """odd symmetry mirroring  [1, 2, 3, 4] --> [1, 2, 3, 4, 3, 2, 1]"""
> > foo=seq[:-1]# copy list, excluding last 
> > element for odd symetry
> > foo.reverse()   # flip it
> > seq.extend(foo)
> > return seq
>
> Hi Kevin,
>
> Your problem is this line:
> seq.extend(foo)
>
> This is the line that mutates your original list.
>
> There are a few ways you could procede here.  One way is to make a
> copy of the argument, like this:
>
> def mirror(seq):
> start = list(seq)
> end = seq[:-1]
> end.reverse()
> start.extend(end)
> return start
>
> Notice that we've not calling any methods on seq, so seq won't be
> changed.  The first line, "start = list(seq)", instructs python to
> build a new list out of the elements of seq.  You could also write
> "start = seq[:]" here --- I'm not sure which is the preferred way.

A little 'gotcha' with this is that if you have nested lists, these
methods don't copy the nested lists, only the outer list (which makes
sense, but can be surprising the first time you encounter it).  If for
some reason you want to copy nested lists, look into deepcopy(),
otherwise you'll be fine.

Also, personally I think list(seq) is better than seq[:] because it
can cope with anything put into it that it could possibly work with
(even dicts and iterators).

>>> def i():
... for n in range(3):
... yield n
...
>>> list(i())
[0, 1, 2]
>>>
>>> d = {'a':1,'b':2}
>>> list(d)
['a', 'b']

>>> i()[:]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsubscriptable object
>>> d[:]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unhashable type

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Unicode problems

2006-08-29 Thread Ed Singleton
I've been having unicode problems in python on Mac OS 10.4.

I googled for it and found a good page in Dive Into Python that I
thought might help
(http://www.diveintopython.org/xml_processing/unicode.html).

I tried following the instructions and set my default encoding using a
sitecustomize.py, but got the following:

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> s = u'La Pe\xf1a'
>>> print s
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in
position 5: ordinal not in range(128)
>>>

As I understand it, that should work.  I tried using different
character sets (like latin-1, etc), but none of them work.

The main problem  I am having is in getting python not to give an
error when it encounters a sterling currency sign (£, pound sign here
in UK), which I suspect might be some wider problem on the mac as when
I type that character in the terminal it shows a # (but in Python it
shows a £).

Any help, or hints greatly appreciated.

Thanks

Ed
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor