Re: Regular Expression: Matching substring

2006-04-13 Thread Fredrik Lundh
"Kevin CH" wrote:

news:[EMAIL PROTECTED]
> Thank you for your reply.
>
> > Perhaps you are using grep, or you have stumbled on the old deprecated
> > "regex" module and are using that instead of the "re" module. Perhaps
> > not as you are using only 2 plain vanilla RE operations which should
> > work the same way everywhere. Perhaps you are having trouble with
> > search() versus match() -- if so, read the section on this topic in the
> > re docs. It's rather hard to tell what you are doing without seeing the
> > code you are using.
>
> Sorry I should have said it up front.  I'm using Kudos (which I'm sure
> uses re module) to test these strings on the pattern, and had the match
> results as I stated.  (search() of course gives me true since the
> pattern appears in the substrings of both strings.)

Python's "match" function doesn't return "true" or "false"; it returns a match
object if the string matches the pattern, and None if not.  since your pattern
can match the empty string, it'll match any target string (all strings start 
with
an empty string), and will never return false.

looks like the "debugger" does a great job of hiding how things really work...





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Fredrik Lundh
Peter Hansen wrote:

> > * learning slices is basic to the language (this lesson shouldn't be
> > skipped)
>
> And yet it doesn't appear to be in the tutorial.

oh, please.

slices are explained in the section on strings, and in the section on lists,
and used to define the behaviour of the list methods in the second section
on lists, ...

> I could have missed it, but I've looked in a number of the obvious places

http://docs.python.org/tut/node5.html#SECTION00514

section 3.1.2 contains an example that shows to remove stuff from a list,
in place.

if you want a clearer example, please consider donating some of your time
to the pytut wiki:

http://pytut.infogami.com/





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Fredrik Lundh
Peter Hansen wrote:

> It's not even clear that extend needs two lines:
>
>  >>> s = range(5)
>  >>> more = list('abc')
>  >>> s[:] = s + more
>  >>> s
> [0, 1, 2, 3, 4, 'a', 'b', 'c']
>
> Okay, it's not obvious, but I don't think s[:]=[] is really any more
> obvious as a way to clear the list.
>
> Clearly .extend() needs to be removed from the language as it is an
> unnecessary extension to the API using slicing

you just flunked the "what Python has to do to carry out a certain operation"
part of the "how Python works, intermediate level" certification.





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: base64

2006-04-13 Thread Jay
I don't know whether it is right yet but it dues what I wanted it to
do now so thank you all,

Oh and sorry for my bad grammar.

One last thing though is that I would like to be able to split the
string up into lines of 89 carictors, I have lookd through the split
methods and all I can find is splitting up words and splitting at a
pacific caricature, I can not see how you split after a number of
caricatures


...START..

from Tkinter import *
from base64 import *

#
#
# Module:   Base64 Encoder / Decoder.py
# Author:   Jay Dee
# Date: 08/04/2006
# Version:  Draft 0.1
# Coments:  A Base64 Encoder / Decoder for converting files into Base64
strings
#
#

class App:
def __init__(self, root):
root.title("Base64 Encoder / Decoder")
#
#   Menu Bar
#
self.menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
self.filemenu = Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Display!",
command=self.Display)
self.filemenu.add_separator()
self.filemenu.add_command(label="Quit!", command=root.quit)
self.menubar.add_cascade(label="File", menu=self.filemenu)
# display the menu
root.config(menu=self.menubar)
#
#   Display B64 Text
#
#   File Input
self.FileInputFrame = Frame(root)
self.FileInputFrame.pack(side=TOP, fill=X)

self.FileInputLine = Entry(self.FileInputFrame,
  bg="white",
  width=70)
self.FileInputLine.pack(side=LEFT, fill=X, expand=1)
#   Display Area
self.DisplayFrame = Frame(root)
self.DisplayFrame.pack(side=TOP, fill=BOTH, expand=1)

self.DisplayText = Text(self.DisplayFrame,
 bg="lightblue",
 width=95,
 height=40)
self.DisplayText.pack(side=LEFT, fill=BOTH, expand=1)

root.bind("",self.Encode)

def Encode(self,event):
'''
Take's the file name from (self.FileInputLine),
opens file,
converts it to base64 then desplays it in (self.DisplayText)
'''
self.DisplayText.delete(1.0,END)

info = self.FileInputLine.get()
if info == "":
self.DisplayText.insert(END, "...Please enter file...")
else:
try:
file = open(info,"rb")
try:
Data = file.read()
Encode = b64encode(Data)
Encode = Encode.split()
self.DisplayText.insert(END, Encode)
except:
self.DisplayText.insert(END, "...Data Erra...")

except:
self.DisplayText.insert(END, "...No Sutch File...")

def Display(self):
'''
Take's the string from (self.DisplayText), Creats a topleval
frame and displays the Data as an image,if that fales it
displays it as text.
'''
info = self.DisplayText.get(1.0,END)
# Display as Image
try:
self.DisplayImage = Toplevel()

self.InfoDisplay = PhotoImage(data=info)
PhotoSize =
[self.InfoDisplay.width(),self.InfoDisplay.height()]

self.DisplayImageCanvas = Canvas(
self.DisplayImage,
width=150,
height=PhotoSize[1] + 15)
self.DisplayImageCanvas.pack(fill=BOTH, expand=1)


self.InfoDisplay2 = self.DisplayImageCanvas.create_image(
PhotoSize[0] / 2 + 10,
PhotoSize[1] / 2 + 10,
image=self.InfoDisplay)
self.InfoDisplay2 = self.DisplayImageCanvas

# Display as Text
except:
self.DisplayBase64Text = Text(
self.DisplayImage,
width=70,
height=30)
self.DisplayBase64Text.pack(fill=BOTH, expand=1)

Decode = b64decode(info)
self.DisplayImageText.insert(END, Decode)


root = Tk()
app = App(root)
root.mainloop()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Duncan Booth
Peter Hansen wrote:

>> * learning slices is basic to the language (this lesson shouldn't be
>> skipped)
> 
> And yet it doesn't appear to be in the tutorial.  I could have missed 
> it, but I've looked in a number of the obvious places, without
> actually going through it (again) from start to finish.  Also,
> googling for "slice site:docs.python.org", you have to go to the
> *sixth* entry before you can find the first mention of "del x[:]" and
> what it does.  I think given the current docs it's possible to learn
> all kinds of things about slicing and still not make the non-intuitive
> leap that "del x[slice]" is actually how you spell "delete contents of
> list in-place". 

Looking in the 'obvious' place in the Tutorial, section 5.1 'More on
Lists' I found in the immediately following section 5.2 'The del 
statement': 

> There is a way to remove an item from a list given its index instead
> of its value: the del statement. Unlike the pop()) method which
> returns a value, the del keyword is a statement and can also be used
> to remove slices from a list (which we did earlier by assignment of an
> empty list to the slice). 

The 'earlier showing assignment of an empty list to a slice' is a reference 
to section 3.1.4 'Lists': 

> Assignment to slices is also possible, and this can even change the
> size of the list: 
> 
> 
 # Replace some items:
> ... a[0:2] = [1, 12]
 a
> [1, 12, 123, 1234]
 # Remove some:
> ... a[0:2] = []
 a
> [123, 1234]
> 

Both of these talk about ways to remove slices from a list. Perhaps the 
wording could be clearer to make it obvious that they can also be used to 
clear a list entirely (using the word 'clear' would certainly help people 
Googling for the answer). So maybe 'this can even change the size of the 
list or clear it completely' would be a good change for 3.1.4.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Duncan Booth
Raymond Hettinger wrote:

> Cons:
> -
> 
> * learning slices is basic to the language (this lesson shouldn't be
> skipped)
> 
also, a clear method would simply clear the entire list. You still need to 
learn the assigning to/deleting slices technique any time you want to clear 
out part of a list.

Every so often I still get an "oh, I didn't know Python could do *that* 
moment", just had one now:

>>> s = range(10)
>>> s[::2] = reversed(s[::2])
>>> s
[8, 1, 6, 3, 4, 5, 2, 7, 0, 9]

I've no idea when I might need it, but it just never occurred to me before 
that you can also assign/del non-contiguous slices.

The symmetry does breaks down a bit here as assigning to an extended slice 
only lets you assign a sequence of the same length as the slice, so you 
can't delete an extended slice by assignment, only by using del.

>>> s = range(10)
>>> del s[::2]
>>> s
[1, 3, 5, 7, 9]
>>> s = range(10)
>>> s[::2] = []

Traceback (most recent call last):
  File "", line 1, in -toplevel-
s[::2] = []
ValueError: attempt to assign sequence of size 0 to extended slice of size 
5
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Georg Brandl
Duncan Booth wrote:
> Peter Hansen wrote:
> 
>>> * learning slices is basic to the language (this lesson shouldn't be
>>> skipped)
>> 
>> And yet it doesn't appear to be in the tutorial.  I could have missed 

> Both of these talk about ways to remove slices from a list. Perhaps the 
> wording could be clearer to make it obvious that they can also be used to 
> clear a list entirely (using the word 'clear' would certainly help people 
> Googling for the answer). So maybe 'this can even change the size of the 
> list or clear it completely' would be a good change for 3.1.4.

I added two examples of clearing a list to the section about slice assignment
and del.

Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Ben Sizer

Luis M. González wrote:
> For those interested in the simplest, easiest and most pythonic web
> framework out there, there's a new page in Wikipedia:
>
> http://en.wikipedia.org/wiki/Karrigell

Why is Wikipedia being abused for software promotion and documentation?
Articles on Wikipedia are supposed to be from a neutral point of view
and purely informative, not biased or instructive.

-- 
Ben Sizer

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread Peter Otten
Peter Hansen wrote:

> I think you could just use getopt or optparse, passing in each line
> after doing a simple .split() on it.  The resulting handling of the
> arguments would be much simpler and cleaner than what you have.
> 
> That won't work perfectly well if you can have quoted arguments with
> spaces in them, however, but the example above does not.

shlex.split() may help with the splitting, e. g.:

>>> shlex.split("alpha beta --gamma 'delta epsilon' zeta\\ eta\n")
['alpha', 'beta', '--gamma', 'delta epsilon', 'zeta eta']

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing defaults to module variables

2006-04-13 Thread Eric Deveaud
Burton Samograd wrote:
>  Hi, 
> 
>  I'm writing an app that stores some user configuration variables in a
>  file ~/.program/config, which it then imports like so:
> 
>  import sys
>  from posix import environ
>  sys.path.append(environ["HOME"]+"/.program")
>  import config
> 
>  I can then access the configuration through code like:
> 
>  login(config.username)

better use some plain text configuration file
check ConfigParser documentation.

>  So I guess the real question is:
> 
>  Is there a way to create a module namespace and populate it
>  before sourcing the file?

if you take a look at how naming space is affected by the variants 
"from module import *" and his conterpart "import module", you will have your
answer.

shortly

if you use "import foo" all the variables/class/functions comming from the
module foo are located in a globlal space dictionary named foo

if you use "form foo import *" all variables/class/functions comming from the
foo module are located in gloabal space naming dictionary.


try this

-=-=-=-=-=-=- consider module foo.py -=-=-=-=-=-=-

my_var = "my var from foo"

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-


hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23) 
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> print my_var
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'my_var' is not defined
  
and now

hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23) 
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo import *
>>> print my_var
my var from foo


this will lead to a solution regarding your problem

hebus:~/tmp > python
Python 2.4.2 (#1, Mar 22 2006, 12:59:23) 
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> my_var = 'some default value'
>>> from foo import *
>>> print my_var
my var from foo


once again, I bet your best choice will be to have some plain text config file

Eric

-- 
 Je voudrais savoir s'il existe un compteur de vitesse (?) pour savoir
 à quelle vitesse on est réellement connecté au FAI et surtout si une
 telle bête existe... où la trouver. 
 -+- RJ in: Guide du Neuneu d'Usenet - Baisse la tête et pédale -+-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Ben Sizer" <[EMAIL PROTECTED]> writes:
> > http://en.wikipedia.org/wiki/Karrigell
> 
> Why is Wikipedia being abused for software promotion and documentation?
> Articles on Wikipedia are supposed to be from a neutral point of view
> and purely informative, not biased or instructive.

Yes, that article needs some rewriting to fit Wikipedia style.  Some
of the content might be better in wikibooks.org instead of Wikipedia.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread Eric Deveaud
News wrote:
>  Hi everyone,
> 
>  My goal is to pull command switches/options from a file and then assign
>  the values to select variables which would eventually be included in a
>  class object.
> 
>  The data file looks something like this but the switches could be in any
>  order and not all may be used.
> 
>  -m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]
> 
>  Also, please keep in mind that the source code will have more than one
>  line in it and each has to be treaded separately.

I suggest you use getopt or optpase to perform this task
those modules are designed to perform what you want, with error checking

import getopt
inp = open("const.txt","r")
for line in inp:
try:
   opt, args = getopt.getopt(iline.split(), 'c:k:m:o:p:s:t:i')
   print opt
   except getopt.GetoptError, msg:
   # handle the error as you need

Eric
-- 
 Je voudrais savoir s'il existe un compteur de vitesse (?) pour savoir
 à quelle vitesse on est réellement connecté au FAI et surtout si une
 telle bête existe... où la trouver. 
 -+- RJ in: Guide du Neuneu d'Usenet - Baisse la tête et pédale -+-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Fredrik Lundh
Ben Sizer wrote:

> > http://en.wikipedia.org/wiki/Karrigell
>
> Why is Wikipedia being abused for software promotion and documentation?
> Articles on Wikipedia are supposed to be from a neutral point of view
> and purely informative, not biased or instructive.

check the page history.  it's already been nominated for speedy removal, but the
Karrigell folks deleted the "prod" template ("it's free software!").

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread bruno at modulix
News wrote:
> Hi everyone,
> 
> My goal is to pull command switches/options from a file and then assign
> the values to select variables which would eventually be included in a
> class object.
>
> The data file looks something like this but the switches could be in any
> order and not all may be used.
> 
> -m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]

Have you looked at optparse ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to install PYCURL 7.15.2 on windows 2003?

2006-04-13 Thread Josef Meile

 > I download it from http://pycurl.sourceforge.net/
 > and then extract it to  D:\usr\pycurl-7.15.2
 > then
 > D:\usr\pycurl-7.15.2>setup.py install --curl-dir=d:\usr\pycurl-7.15.2
 > Using curl directory: d:\usr\pycurl-7.15.2
 > Traceback (most recent call last):
 >   File "D:\usr\pycurl-7.15.2\setup.py", line 197, in ?
 > assert os.path.isfile(o), o
 > AssertionError: d:\usr\pycurl-7.15.2\lib\libcurl.lib
I would say you need to install libcurl first. "--curl-dir"
isn't the directory where you want to install pycurl; it is
the location of the curl library, which isn't implemented in
python.

You can find the binaries (or the sources) here:
http://curl.haxx.se/dlwiz/

Regards
Josef

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Pierre Quentel
I added an entry in Wikipedia for information, just like other Python
web frameworks have already done. If the style doesn't fit Wikipedia's
I'm sorry and willing to learn how to improve it ; the reason I read
was "Obvious, if elaborate, link spam. Really should be speedied, but I
can't find a CSD that fits this". I don't really understand why it's
called a spam, I don't know what a CSD is and I don't know either who
deleted the prod template, not me anyway. I'll take wikipedia people's
advice into account anyway

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread News
bruno at modulix wrote:
> News wrote:
>> Hi everyone,
>>
>> My goal is to pull command switches/options from a file and then assign
>> the values to select variables which would eventually be included in a
>> class object.
>>
>> The data file looks something like this but the switches could be in any
>> order and not all may be used.
>>
>> -m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]
> 
> Have you looked at optparse ?
> 
I have.

In the interactive version of the code, I use:

#
# Parse command line options and automatically build help/usage
#
parser = OptionParser()

parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=1,
help="don't print status messages to stdout")
parser.add_option("-m", dest="qmanager",
help="Queue Manager to inquire against")
parser.add_option("-s", dest="host",
help="Host the que manager resides on")
parser.add_option("-p", dest="port",
help="Port queue manager listens on"),
parser.add_option("-o", dest="object",
help="Queue object being inquired on"),
parser.add_option("-k", dest="key",
help="object attribute to be inquired about"),
parser.add_option("-t", type="string",dest="mto",
help="e-mail address the report will go to"),
parser.add_option("-d", action="store_false",dest="report",
help="optional switch - enabling this sends output
to e-mail")
(options, args) = parser.parse_args()


The module optparse seemed to be aimed at reading from commandline
versus pulling attributes from a read line.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing defaults to module variables

2006-04-13 Thread Luke Plant
Burton Samograd wrote:

> My question is, how can I setup my program defaults so that they can
> be overwritten by the configuration variables in the user file (and so
> I don't have to scatter default values all over my code in try/catch
> blocks)?

The Django web framework happens to do something very like this.
Instead of 'import config' you have to do 'from django.conf import
settings', and you have an environment variable that allows you to
specify the user settings file, but otherwise I think it is pretty much
the same.

The guts of the mechanism is here:

http://code.djangoproject.com/browser/django/branches/magic-removal/django/conf/__init__.py

It has quite a bit of custom Django stuff in there that you can ignore,
but I think the principles should apply.

Luke

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread Eric Deveaud
News wrote:
>  bruno at modulix wrote:
> > 
> > Have you looked at optparse ?
> > 
>  I have.
> 
>  The module optparse seemed to be aimed at reading from commandline
>  versus pulling attributes from a read line.


hu 

lets see 
optparse seems to be reading from commandline. that's not false but not
really true ;-)

point 1:
remember that commandline reading is done thru sys.argv wich provide a a
list of strings

point 2
now consider pulling datas from readline, wich return a string.
if you split this string you'll have a list of string.

point 3
optparse is designed for reading from a list of strings

I let the conclusion to your imagination ;-))


Eric
 -- 
 Salut,Je m'appele sed.je suis etudiant en communication, j'ai lu votre
 message.je viens vous dire un petiit bonjour,et vous laisser mon
 mél: vous pouvez me repondre maintenant si vous étez conecter.
 -+-Guide du Neuneu d'Usenet - La com', elle ne passera pas par moi -+-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: just one more question about the python challenge

2006-04-13 Thread Roel Schroeven
John Salerno schreef:
> Fredrik Lundh wrote:
>> John Salerno wrote:
>>
 At the second, don't rename the file, rename the URL.
>>> Do you mean rename the URL *aside from* the file name?
>> no, the URL you got when you followed georg's instructions will give you
>> some data that you need to manipulate before you can see what it is.  to
>> figure out how to manipulate it, study the *first* image carefully.  what
>> is the person on that page doing?
> 
> Thanks Fredrik. I think my problem lies in not knowing what the 'data' 
> is I need to move on to the next step of the puzzle. I now have 3 
> images, along with gfx file. I know shuffling/unshuffling has something 
> to do with the puzzle, but I haven't figure out what yet. Am I wrong to 
> think that this is another PIL puzzle?

As others have said, you don't need PIL for this one. You need to have a 
look at the data of the gfx file itself (you can do that with some 
simple Python code, though I find it easier to use a hex editor). Focus 
on the start of the data at first. Compare the patterns in the data with 
the data at the start of other image files (JPG, PNG, GIF).

 From another view of how you need to manipulate the bytes, look at what 
the dealer is doing with the cards. Count how many piles he's using.

And I guess you'll be happy to know that puzzle 13 doesn't have anything 
to do with images :)

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Pierre Quentel" <[EMAIL PROTECTED]> writes:
> I added an entry in Wikipedia for information, just like other Python
> web frameworks have already done. If the style doesn't fit Wikipedia's
> I'm sorry and willing to learn how to improve it ; the reason I read
> was "Obvious, if elaborate, link spam. Really should be speedied, but I
> can't find a CSD that fits this". I don't really understand why it's
> called a spam, I don't know what a CSD is and I don't know either who
> deleted the prod template, not me anyway. I'll take wikipedia people's
> advice into account anyway

CSD = criteria for speedy deletion, 

Prod = proposed deletion.  Anyone is allowed to un-prod it, and in
this case someone did.  If nobody un-prods it after 5 days, it gets
deleted automatically.  That doesn't apply here, because the article
did get un-prodded.

Next probably comes AFD, article for deletion.  That's a consensus
process: there's a 5 day community discussion about what to do about
the article and then an admin comes along and implements the decision.

This article will probably get AFD'd (i.e. entered into the discussion
process).  When that happens, I'll recommend keeping the article but
editing it considerably.  Basically it needs to be rewritten as a
straightforward description that doesn't sound like advertising.

If there's an AFD, a notice will appear at the top of the article
announcing the AFD and giving a link to participate in the discussion.
-- 
http://mail.python.org/mailman/listinfo/python-list


List comp bug?

2006-04-13 Thread tasjaevan
I seem to have stumbled across a problem with list comprehensions (or
perhaps it's a misunderstanding on my part)

   [f() for f in [lambda: t for t in ((1, 2), (3, 4))]]

is giving me

   [(3, 4), (3, 4)]

The equivalent using a generator expression:

[f() for f in (lambda: t for t in ((1, 2), (3, 4)))]

is giving me

[(1, 2), (3, 4)]

as expected.

Is this a known bug? I'm using Python 2.4.3

Thanks

James

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comp bug?

2006-04-13 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I seem to have stumbled across a problem with list comprehensions (or
> perhaps it's a misunderstanding on my part)
> 
>[f() for f in [lambda: t for t in ((1, 2), (3, 4))]]

List comprehensions are syntactic sugar for "for" loops.  The
thing to notice is that in "lambda: t", t is unbound.  It's not
the same as the loop index inside the list comp.  Try:

   [f() for f in [lambda t=t: t for t in ((1, 2), (3, 4))]]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread bruno at modulix
News wrote:
> bruno at modulix wrote:
> 
>>News wrote:
>>
>>>Hi everyone,
>>>
>>>My goal is to pull command switches/options from a file and then assign
>>>the values to select variables which would eventually be included in a
>>>class object.
>>>
>>>The data file looks something like this but the switches could be in any
>>>order and not all may be used.
>>>
>>>-m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]
>>
>>Have you looked at optparse ?
>>
> 
> I have.
> 
> In the interactive version of the code, I use:
> 
> #
> # Parse command line options and automatically build help/usage
> #
> parser = OptionParser()
> 
> parser.add_option("-q", "--quiet",
> action="store_false", dest="verbose", default=1,
> help="don't print status messages to stdout")
> parser.add_option("-m", dest="qmanager",
> help="Queue Manager to inquire against")
> parser.add_option("-s", dest="host",
> help="Host the que manager resides on")
> parser.add_option("-p", dest="port",
> help="Port queue manager listens on"),
> parser.add_option("-o", dest="object",
> help="Queue object being inquired on"),
> parser.add_option("-k", dest="key",
> help="object attribute to be inquired about"),
> parser.add_option("-t", type="string",dest="mto",
> help="e-mail address the report will go to"),
> parser.add_option("-d", action="store_false",dest="report",
> help="optional switch - enabling this sends output
> to e-mail")
> (options, args) = parser.parse_args()
> 

So why do you inflict yourself the pain of rewriting all the parsing etc???

> The module optparse seemed to be aimed at reading from commandline
> versus pulling attributes from a read line.

http://www.python.org/doc/2.4.2/lib/optparse-parsing-arguments.html:
"""
The whole point of creating and populating an OptionParser is to call
its parse_args() method:

(options, args) = parser.parse_args(args=None, options=None)

where the input parameters are

args
the list of arguments to process (sys.argv[1:] by default)
"""

what about something like :

 line = myfile.readline()
 options = parser.parse_args(line.split())

But what, if you prefer to rewrite (and maintain) a custom parser doing
exactly the same thing, please do !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftp connection and commands (directroy size, etc)

2006-04-13 Thread Fulvio
Alle 00:05, giovedì 13 aprile 2006, Arne ha scritto:
> a=ftp.sendcmd('Dir')
> By trying to get the directory with 'dir'

Are you sure that the command 'dir" is understood via ftp?
IF I'm not wrong would be 'ls' o list. But since I don't have such psckage on 
my system, it's recommended you read the manual of that or 
read here:

http://www.cs.colostate.edu/helpdocs/ftp.html

Which is the result of google search of "ftp command list" (no quote).

F
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Steven D'Aprano
On Thu, 13 Apr 2006 07:49:11 +, Duncan Booth wrote:

> Raymond Hettinger wrote:
> 
>> Cons:
>> -
>> 
>> * learning slices is basic to the language (this lesson shouldn't be
>> skipped)
>> 
> also, a clear method would simply clear the entire list. You still need to 
> learn the assigning to/deleting slices technique any time you want to clear 
> out part of a list.

A clear method does not *necessarily* clear only the entire list. That's
an choice that can be made. I for one would vote +1 for clear taking an
optional index or slice, or two indices, to clear only a part of the list.



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


how to match n- lists for a common elements.

2006-04-13 Thread Grzegorz Ślusarek
Hi all. I my application i have situation when i have some lists and i 
must get from lists common elements. Exacly i don't know how many list I 
  have so at the moment of creation each of one I append them to one 
list. So I get list wchich consist of lists of objects. And now i want 
to get common objects of this list. How to do it?
Grzegorz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Figure out month number from month abbrievation

2006-04-13 Thread Fulvio
Alle 04:41, giovedì 13 aprile 2006, Fredrik Lundh ha scritto:
> but it also looks as if the meaning of the word "localized" isn't clear to
> you; if you changed the locale, those names will be translated

Mine behave strangely. Linux localized for Italian, but Python (or its 
calander is in english)

??
F
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Steven D'Aprano
On Thu, 13 Apr 2006 09:11:31 +0200, Fredrik Lundh wrote:

> Peter Hansen wrote:
> 
>> It's not even clear that extend needs two lines:
>>
>>  >>> s = range(5)
>>  >>> more = list('abc')
>>  >>> s[:] = s + more
>>  >>> s
>> [0, 1, 2, 3, 4, 'a', 'b', 'c']
>>
>> Okay, it's not obvious, but I don't think s[:]=[] is really any more
>> obvious as a way to clear the list.
>>
>> Clearly .extend() needs to be removed from the language as it is an
>> unnecessary extension to the API using slicing
> 
> you just flunked the "what Python has to do to carry out a certain operation"
> part of the "how Python works, intermediate level" certification.

So implementation details are part of the language now? 

Out of curiosity, are those things that Python has to do the same for
CPython, Jython, IronPython and PyPy?

Personally, I think it is a crying shame that we're expected to be experts
on the specific internals of the Python interpreter before we're allowed
to point out that "only one obvious way to do it" just is not true, no
matter what the Zen says.

>>> L = []
>>> L.append(0)
>>> L[:] = L + [1]
>>> L[:] += [2]
>>> L[len(L):] = [3]
>>> L.__setslice__(len(L), -1, [4])
>>> L.__setslice__(sys.maxint, sys.maxint, [5])
>>> L += [6]
>>> L
[0, 1, 2, 3, 4, 5, 6]

That's at least seven ways to do an append, and it is a double-standard to
declare that slice manipulation is the One and Only True obvious way
to clear a list, but slice manipulation is not obvious enough for
appending to a list.

No doubt under the hood, these seven ways are implemented differently.
They certainly differ in their obviousness, and I'm willing to bet that
practically nobody thinks that the slicing methods are more obvious than
append. Perhaps we're not Dutch. I daresay one method is better, faster,
or more efficient than the others, but remember the warning against
premature optimisation.

Whenever I see "only one obvious way to do it" being used as a knee-jerk
excuse for rejecting any change, my eyes roll. Nobody wants Python to
turn into Perl plus the kitchen sink, but it isn't as if Python is some
absolutely minimalist language with two objects and three functions. There
is no shortage of "more than one way to do it" convenience methods,
functions and even entire modules. And that's why Python is such a fun,
easy to use language: because most things in Python are just convenient.
When you want to append to a list, or insert into a list, you don't have
to muck about with slices, you call the obvious list method.

And so it should be for clearing all or part of a list.



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comp bug?

2006-04-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

>I seem to have stumbled across a problem with list comprehensions (or
> perhaps it's a misunderstanding on my part)
>
>   [f() for f in [lambda: t for t in ((1, 2), (3, 4))]]
>
> is giving me
>
>   [(3, 4), (3, 4)]
>
> The equivalent using a generator expression:
>
>[f() for f in (lambda: t for t in ((1, 2), (3, 4)))]
>
> is giving me
>
>[(1, 2), (3, 4)]
>
> as expected.
>
> Is this a known bug?

no, it's not a bug, it's a consequence of the order in which things are done,
and different visibility rules for the loop variables used in list 
comprehensions
and generator expressions.

both the inner loops generates lambda expressions that return the value of
the "t" variable.

for the list comprehension, "t" is an ordinary variable (part of the surrounding
scope), and since the comprehension is completed before the resulting list is
returned, all lambdas end up referring to the same "t", which is set to the last
value:

>>> x = [lambda: t for t in ((1, 2), (3, 4))]
>>> x
[ at 0x00A87AB0>,  at 0x00A876F0>]
>>> x[0]()
(3, 4)
>>> t = "hello"
>>> x[0]()
'hello'

in contrast, the generator expression uses a local loop variable "t", and only 
fetches
one value from the target sequence for each iteration, so all lambdas will be 
bound
to different objects.

any special reason you need to write this kind of convoluted code, btw?

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Pierre Quentel
Ok, thanks for the information. I have rewritten the page in a more
neutral way and removed the tutorial-like part, I'll put in in wikibooks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to match n- lists for a common elements.

2006-04-13 Thread bruno at modulix
Grzegorz Ślusarek wrote:
> Hi all. I my application i have situation when i have some lists and i
> must get from lists common elements. Exacly i don't know how many list I
>  have so at the moment of creation each of one I append them to one
> list. So I get list wchich consist of lists of objects. And now i want
> to get common objects of this list. How to do it?

http://www.python.org/doc/2.4.2/lib/types-set.html

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Peter Hansen
Alan Morgan wrote:
> Ah, but if you know your basic python then you wouldn't be looking for
> s.clear() in the first place; you'd just use s[:]=[] (or s=[], whichever
> is appropriate).  

One of very first things newcomers learn (I believe, though I don't know 
how soon the tutorial teaches it) is to use "dir()" on objects.  The 
clear() method would show up there and quickly attract attention. 
Neither of the other techniques are likely to be discovered as quickly. 
  (Well, okay, s=[] would be, I'm sure, but to many newcomers that might 
"feel wrong" as the way to empty out a list, but then we're back to 
wondering how often there's really a usecase for doing so.)

> Personally, it seems more *reasonable* to me, a novice python user,
> for s.clear() to behave like s=[] (or, perhaps, for s=[] and s[:]=[] to
> mean the same thing).  The fact that it can't might be an argument for
> not having it in the first place.

Then it's a good reason we had this thread, so you could learn something 
*crucial* to understanding Python and writing non-buggy code: name 
binding versus variables which occupy fixed memory locations like in 
some other languages.  This has to be by far the most frequent area that 
newcomer's trip up.  But that's another story...

-Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread News
bruno at modulix wrote:
> News wrote:
>> bruno at modulix wrote:
>>
>>> News wrote:
>>>
 Hi everyone,

 My goal is to pull command switches/options from a file and then assign
 the values to select variables which would eventually be included in a
 class object.

 The data file looks something like this but the switches could be in any
 order and not all may be used.

 -m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]
>>> Have you looked at optparse ?
>>>
>> I have.
>>
>> In the interactive version of the code, I use:
>>
>> #
>> # Parse command line options and automatically build help/usage
>> #
>> parser = OptionParser()
>>
>> parser.add_option("-q", "--quiet",
>> action="store_false", dest="verbose", default=1,
>> help="don't print status messages to stdout")
>> parser.add_option("-m", dest="qmanager",
>> help="Queue Manager to inquire against")
>> parser.add_option("-s", dest="host",
>> help="Host the que manager resides on")
>> parser.add_option("-p", dest="port",
>> help="Port queue manager listens on"),
>> parser.add_option("-o", dest="object",
>> help="Queue object being inquired on"),
>> parser.add_option("-k", dest="key",
>> help="object attribute to be inquired about"),
>> parser.add_option("-t", type="string",dest="mto",
>> help="e-mail address the report will go to"),
>> parser.add_option("-d", action="store_false",dest="report",
>> help="optional switch - enabling this sends output
>> to e-mail")
>> (options, args) = parser.parse_args()
>>
> 
> So why do you inflict yourself the pain of rewriting all the parsing etc???
> 
>> The module optparse seemed to be aimed at reading from commandline
>> versus pulling attributes from a read line.
> 
> http://www.python.org/doc/2.4.2/lib/optparse-parsing-arguments.html:
> """
> The whole point of creating and populating an OptionParser is to call
> its parse_args() method:
> 
> (options, args) = parser.parse_args(args=None, options=None)
> 
> where the input parameters are
> 
> args
> the list of arguments to process (sys.argv[1:] by default)
> """
> 
> what about something like :
> 
>  line = myfile.readline()
>  options = parser.parse_args(line.split())
> 
> But what, if you prefer to rewrite (and maintain) a custom parser doing
> exactly the same thing, please do !-)
> 

sometimes you can't see the forest .. trees and all that :)

I really appreciate everyones insight on this.

It was very helpful.

OT: I saw several references to "OP". What does this mean?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Peter Hansen
Duncan Booth wrote:
> Peter Hansen wrote:
> Looking in the 'obvious' place in the Tutorial, section 5.1 'More on
> Lists' I found in the immediately following section 5.2 'The del 
> statement': 
> 
>>There is a way to remove an item from a list given its index instead
>>of its value: the del statement. Unlike the pop()) method which
>>returns a value, the del keyword is a statement and can also be used
>>to remove slices from a list (which we did earlier by assignment of an
>>empty list to the slice). 

I saw that section too, but was scanning for any example of wiping out 
the whole list.  As you point out, it's not mentioned.  I don't think 
there's even an example of slicing with no arguments [:] for copying a 
list (i.e. on the right side of the =), and it's reasonable to assume (I 
originally did, as I recall) that this would be some kind of error...

> Both of these talk about ways to remove slices from a list. Perhaps the 
> wording could be clearer to make it obvious that they can also be used to 
> clear a list entirely (using the word 'clear' would certainly help people 
> Googling for the answer). So maybe 'this can even change the size of the 
> list or clear it completely' would be a good change for 3.1.4.

This is quite true.  After all, who imagines when offered a "slice of 
cake" that a slice might be the entire thing!  The concept of "slice" in 
English strongly implies a *subset*, not the whole, so if we're not 
going to get a .clear() method, I do believe that the various uses of 
[:] should be much more explicitly pointed out in the docs.  At least 
we'd have a ready place to point to in the tutorial, instead of this 
discussion cropping up every month.

-Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Fredrik Lundh
Peter Hansen wrote:

> One of very first things newcomers learn (I believe, though I don't know
> how soon the tutorial teaches it)

let's see.  lists are introduced on page 19, a more extensive discussion of 
lists is
found on page 33, the del statement appears on page 34, and the dir() function
is introduced on page 46.

(page numbers from the current pytut PDF copy)

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Pierre Quentel" <[EMAIL PROTECTED]> writes:
> Ok, thanks for the information. I have rewritten the page in a more
> neutral way and removed the tutorial-like part, I'll put in in wikibooks

It's much better now, and I think it won't be deleted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Cannot import htmllib

2006-04-13 Thread geir . smestad
Using Ubuntu Breezy Badger 5.10. I get the following traceback:

-
Traceback (most recent call last):
  File "/home/geir/programmering/htmlparse/formatter.py", line 1, in
-toplevel-
import formatter
  File "/home/geir/programmering/htmlparse/formatter.py", line 2, in
-toplevel-
import htmllib
  File "/usr/lib/python2.4/htmllib.py", line 9, in -toplevel-
from formatter import AS_IS
ImportError: cannot import name AS_IS
-

I have been unable to make the following code execute on my Ubuntu
system, and the error above started occurring after I attempted to
execute it. Libraries were imported successfully:

-
#!/usr/bin/python

import formatter
import htmllib
import urllib
import iface

def fetch(url):
"""Fetches URL to string"""
object = urllib.urlopen(url)
string = object.read()
return string

def plaintext(data, outfile):
"""Formats HTML to plain-text outfile"""
w = formatter.DumbWriter(outfile)
f = formatter.AbstractFormatter(w)
p = htmllib.HTMLParser(f)
p.feed(data)
p.close()
-

I do not have a copy of the traceback, but the final message was
something along the lines of 'str' object does not have attribute
'write'.

As far as I can see, the files formatter.py and htmllib.py are where
they are supposed to be, in /usr/lib/python2.4/.

Geir Smestad

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Pierre Quentel" <[EMAIL PROTECTED]> writes:
> Ok, thanks for the information. I have rewritten the page in a more
> neutral way and removed the tutorial-like part, I'll put in in wikibooks

I don't know if you really want to put the tutorial in wikibooks,
since there's already documentation on karrigell.com.  The idea of
wikibooks is to develop books on the wiki.  That's maybe a reasonable
way to create new documentation, but in this case it would mean you
have two parallel documents being developed separately.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Figure out month number from month abbrievation

2006-04-13 Thread Fredrik Lundh
"Fulvio" wrote:

> > but it also looks as if the meaning of the word "localized" isn't clear to
> > you; if you changed the locale, those names will be translated
>
> Mine behave strangely. Linux localized for Italian, but Python (or its
> calander is in english)

Python defaults to the C locale, which is a minimal english locale.  To change 
this,
you have to tell the locale module

>>> import locale
>>> locale.setlocale(locale.LC_ALL)
'C'
>>> import calendar
>>> list(calendar.month_abbr)
['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
'Nov', 'Dec']

>>> locale.setlocale(locale.LC_ALL, "") # get locale from environment
'sv_SE'
>>> list(calendar.month_abbr)
['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 
'nov', 'dec']

>>> locale.setlocale(locale.LC_ALL, "it_IT") # use explicit locale
'it_IT'
>>> list(calendar.month_abbr)
['', 'gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 
'nov', 'dic']

The point here is that this is a global setting; once you (or someone using 
your code)
change the locale, all locale dependent code changes behaviour.

>>> import locale, string
>>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> locale.setlocale(locale.LC_ALL, "it_IT")
'it_IT'
>>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ

 



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why new Python 2.5 feature "class C()" return old-style class ?

2006-04-13 Thread Wildemar Wildenburger
Petr Prikryl wrote:
> My question: Could the old classes be treated in
> a new Python treated as new classes with "implicit"
> base object? (I know the Zen... ;-)
>
> Example: I use usually a very simple classes. When I add
> "(object)" to my class definitions, the code continues to
> works fine -- plus I have new features to use.
> Why this cannot be done automatically? What could
> be broken in the old code if it was threated so?
>
> Thanks for explanation,
>pepr
Well, apparently this is exactly whats going to happen in the future, 
but not until Python 3.0.
Simple as that.

But I guess I'll just keep adding the (object) appendix even after that, 
so all my class definitions get syntax highlighting. Also it clarifies 
"what the score is" (to paraphrase Bender).

wildemar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread Gerard Flanagan
News wrote:

> OT: I saw several references to "OP". What does this mean?

It's a TOOTKA :-)

You -  The Original Post/Poster.

Gerard

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot import htmllib

2006-04-13 Thread Richard Brodie

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> As far as I can see, the files formatter.py and htmllib.py are where
> they are supposed to be, in /usr/lib/python2.4/.

You probably have aliased it by calling your main program formatter.py,
or something similar. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why new Python 2.5 feature "class C()" return old-style class ?

2006-04-13 Thread Robert Kern
Petr Prikryl wrote:
> "Aahz" wrote...
> 
>>Bruno Desthuilliers wrote:
>>
>>>Aahz a �crit :
> 
> [...]
> 
>Please repeat this 101 times each morning:
>"thou shall not use old-style classes for they are deprecated".

Classic classes are *NOT* deprecated.
>>>
>>>Perhaps not *officially* yet...
>>
>>Not even unofficially.  The point at which we have deprecation is when
>>PEP8 gets changed to say that new-style classes are required for
>>contributions.
> 
> My question: Could the old classes be treated in
> a new Python treated as new classes with "implicit"
> base object? (I know the Zen... ;-)
> 
> Example: I use usually a very simple classes. When I add
> "(object)" to my class definitions, the code continues to
> works fine -- plus I have new features to use.
> Why this cannot be done automatically? What could
> be broken in the old code if it was threated so?

Method resolution order in class hierarchies that have multiple inheritance.

-- 
Robert Kern
[EMAIL PROTECTED]

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Cannot import htmllib

2006-04-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> -
> Traceback (most recent call last):
>  File "/home/geir/programmering/htmlparse/formatter.py", line 1, in
> -toplevel-
>import formatter
>  File "/home/geir/programmering/htmlparse/formatter.py", line 2, in
> -toplevel-
>import htmllib
>  File "/usr/lib/python2.4/htmllib.py", line 9, in -toplevel-
>from formatter import AS_IS
> ImportError: cannot import name AS_IS
> -

> As far as I can see, the files formatter.py and htmllib.py are where
> they are supposed to be, in /usr/lib/python2.4/.

not only that, but according to the traceback, you also have a formatter
module under

/home/geir/programmering/htmlparse

(by default, the current directory is part of the system path).

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot import htmllib

2006-04-13 Thread geir . smestad
Thanks a lot! You are quite right.

(By the way, this is the first time ever I post something to a
newsgroup. Thanks for giving me a good first impression :D)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Mel Wilson
Alan Morgan wrote:
> In article <[EMAIL PROTECTED]>,
> Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>>* s.clear() is more obvious in intent
> 
> Serious question: Should it work more like "s=[]" or more like
> "s[:]=[]".  I'm assuming the latter, but the fact that there is
> a difference is an argument for not hiding this operation behind
> some syntactic sugar. 


It has to work more like s[:]=[]

It's not easy for an object method to bind a whole different 
object to the first object's name.  Generally only 
statements can affect namespaces (hence the uses of del that
everyone remembers.)

Mel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Figure out month number from month abbrievation

2006-04-13 Thread Fulvio
Alle 20:16, giovedì 13 aprile 2006, Fredrik Lundh ha scritto:
> >>> locale.setlocale(locale.LC_ALL, "it_IT")
>
> 'it_IT'

Thank you
Great & kind explanation

F
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Mel Wilson
Steven D'Aprano wrote:
> Convenience and obviousness are important for APIs -- that's why lists
> have pop, extend and remove methods. The only difference I can see between
> a hypothetical clear and these is that clear can be replaced with a
> one-liner, while the others need at least two, e.g. for extend:
> 
> for item in seq: 
> L.append(item)

Both extend and append have one-line slice equivalents,
except that the equivalents have to keep referring to
the length of the list.. (have to keep finding the
len function.)

Mel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2CPP ?

2006-04-13 Thread jpierce

Diez B. Roggisch wrote:
> > 1) Curiosity. I would like to see how well the translation goes.
>
> If there is something that works, it will look awful to the eye.
> Code-generators are generally not very idiomatic - they mapping is to
> localized to e.g. factorize out a more complex loop to something a
> generator might to much better.
>
> I suggest you take a look at pyrex, a python-like language that bridges
> python and C by generating C.
>
> > 2) Efficiency. It is alot quicker to code something in Python. If I can
> >write it in Python and auto-convert it to C++. I would save time
> >coding.
>
> Then let it run in python.
>
> > 3) Education. I would learn more about Python, C++, their similarities and
> > differences.
>
> I also doubt that. digging into generated, non-idiomatic code won't do much
> for you to grasp what is behind Python or C++ as well. Think e.g. of
> templating, a major feature in C++ that certainly won't be utilized by a
> code-generator that does everything based on python C-structures and their
> C-API.
> 
> Regards,
> 
> Diez

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2CPP ?

2006-04-13 Thread jpierce

Diez B. Roggisch wrote:
> > 1) Curiosity. I would like to see how well the translation goes.
>
> If there is something that works, it will look awful to the eye.
> Code-generators are generally not very idiomatic - they mapping is to
> localized to e.g. factorize out a more complex loop to something a
> generator might to much better.
>
> I suggest you take a look at pyrex, a python-like language that bridges
> python and C by generating C.
>
> > 2) Efficiency. It is alot quicker to code something in Python. If I can
> >write it in Python and auto-convert it to C++. I would save time
> >coding.
>
> Then let it run in python.
>
> > 3) Education. I would learn more about Python, C++, their similarities and
> > differences.
>
> I also doubt that. digging into generated, non-idiomatic code won't do much
> for you to grasp what is behind Python or C++ as well. Think e.g. of
> templating, a major feature in C++ that certainly won't be utilized by a
> code-generator that does everything based on python C-structures and their
> C-API.
> 
> Regards,
> 
> Diez

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Peter Hansen
Fredrik Lundh wrote:
> Peter Hansen wrote:
>>One of very first things newcomers learn (I believe, though I don't know
>>how soon the tutorial teaches it)
> 
> let's see.  lists are introduced on page 19, a more extensive discussion of 
> lists is
> found on page 33, the del statement appears on page 34, and the dir() function
> is introduced on page 46.

You're spending a lot of time trying to convince me I'm wrong, yet until 
  Georg did something about it just now, nowhere in those sections did 
it talk about [:] specifically, which is sort of the whole point.  It is 
*not* obvious that although [x:] and [:y] and [x:y] take subsets of 
things, that leaving them both out is either legal or useful.

Thankfully (to Georg), it now is.  (Well, I haven't read it yet, but 
I'll take his word for it.)

-Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


py2exe wx.lib.activexwrapper win32com

2006-04-13 Thread [EMAIL PROTECTED]
I try to create an exe using py2exe, but i've got some troubles. In my
application, i use a flash activex control with wxPython
(wx.lib.activexwrapper). I get the following lines in the log when i
run my executable

Code:
Traceback (most recent call last):
  File "main.py", line 8, in ?
  File "misc.pyc", line 10, in ?
  File "xmlconfig.pyc", line 10, in ?
  File "window.pyc", line 13, in ?
  File "wxPython\lib\activexwrapper.pyc", line 5, in ?
  File "wx\lib\activexwrapper.pyc", line 24, in ?
ImportError: ActiveXWrapper requires PythonWin.  Please install the
win32all-xxx.exe package.

On my XP with the python installation, i don't have any problems. I
really don't understand what happen, PythonWin is an ide, the real name
of the modules is pywin32. I use python 2.3 and wxPython 2.6, py2exe
0.6 with the bundle option. Some modules aren't correctly imported i
guess.

This is my code to import the activex and I makepy the file axflash

if wxPlatform == '__WXMSW__':
from wxPython.lib.activexwrapper import MakeActiveXClass
import axflash

flashControl = axflash

Thanks for your help ;)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread News
Hi everyone,

Just to be complete, my final solution was:

parser = OptionParser()

parser.add_option("-m","--qmanager", dest="qmanager",
help="\t\tQueue Manager to inquire against"),

parser.add_option("-s","--server", dest="host",
help="\t\tHost the que manager resides on"),

parser.add_option("-c","--check",  dest="check",
help="\t\tTest object if it is less/equal/greater"),

parser.add_option("-p","--port", type="string", dest="port",
help="\t\tPort queue manager listens on"),

parser.add_option("-o","--object", dest="object",
help="\t\tQueue object being inquired on"),

parser.add_option("-k", "--key",dest="key",
help="\t\tobject attribute to be inquired about"),

parser.add_option("-t","--to", type="string",dest="mto",
help="\t\te-mail address the report will go to"),

parser.add_option("-q","--quiet", action="store_false",dest="quiet",
help="\t\toptional - just returns the value"),

parser.add_option("-f", "--file",
action="store", type="string", dest="filename",
help="Pull command strings from FILE",
metavar="FILE")

parser.add_option("-d","--display",
  action="store_false",dest="report",
  help="\t\toptional - use sends output to e-mail")

(options, args) = parser.parse_args()

if options.filename is not None:
line = use_file()
(options,args) = parser.parse_args(line.split())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Pierre Quentel" <[EMAIL PROTECTED]> wrote:

> I added an entry in Wikipedia for information, just like other Python
> web frameworks have already done. If the style doesn't fit Wikipedia's
> I'm sorry and willing to learn how to improve it ; the reason I read
> was "Obvious, if elaborate, link spam. Really should be speedied, but I
> can't find a CSD that fits this". I don't really understand why it's
> called a spam, I don't know what a CSD is and I don't know either who
> deleted the prod template, not me anyway. I'll take wikipedia people's
> advice into account anyway

Hi Pierre,

As the guy who put the deletion notice on the article, let me explain how 
this works, and why I did what I did.  My apologies if my comment appeared 
abrupt or rude. 

CSD stands for "Criteria for Speedy Deletion".  It's a set of specific 
rules describing types of articles which don't fit Wikipedia's charter.  If 
an article fits one of the CSD rules, any Wikipedia admin (which I am), can 
delete the article on their own, with no further ado.  Hundreds of articles 
a day are deleted under CSD.  Your article did not meet any of those 
specific rules.  You can read more at http://en.wikipedia.org/wiki/Wp:csd

CSD or not, I still felt that the article was not appropriate for 
Wikipedia.  Wikipedia is an encyclopedia; it's meant to collect, organize, 
and present information about significant things.  It is explicitly NOT 
meant to be used as a tool to promote things, even things which are being 
given away for free.  Wikipedia has become one of the most well-known web 
sites on the Internet, and is thus often used by people with things to 
promote as an easy way to get some free publicity.  That is what your 
article looked like.  I thus took the step of proposing that it be deleted.  
I used a relatively new process which gives people 5 days to object to the 
proposal, and if anybody does, the article is kept.  That's what happened 
here.  It also prompted it to get cleaned up a lot, which is a Good Thing.

The next step I could take would be to bring the article to what's called 
AFD, or Articles For Deletion.  At that point, there would be a more formal 
debate about the pros and cons of the article vis-a-vis Wikipedia's 
charter, and finally some other (neutral) admin would come along and make a 
final determination.  The article has improved enough that I don't think 
I'm going to do that.  It still concerns me that you appear to be using 
Wikipedia to promote your own work, but I'll leave that up to other editors 
to decide what they want to do.

Please don't misunderstand my actions.  I'm all for promoting Python, and 
your Karrigel system looks interesting.  Wikipedia is just not the correct 
forum for such promotion.  There is a fine line between promotion and 
documentation.  It's often difficult to know where that line is, especially 
when you're personally close to a project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Roel Schroeven
Luis M. González schreef:
> For those interested in the simplest, easiest and most pythonic web
> framework out there, there's a new page in Wikipedia:
> 
> http://en.wikipedia.org/wiki/Karrigell

There's something I don't quite get regarding the Karrigell- and 
CherryPy-style frameworks. With PHP or mod_python I can put any number 
of different applications in different directories on a web server, 
which is very convenient: all kinds of things I want to use can live 
perfectly together (static content, webmail, phpmysql etc etc), all 
under Apache which either servers the static content directly or uses 
PHP or Python or Perl or whatever for dynamic content.

If I understand everything correctly, Karrigell is meant to be run as 
its own server which runs one application. I guess I can run different 
Karrigell servers on different ports, and possibly use mod_rewrite to 
forward e.g. http://foo.example.com/app1 and http://foo.example.com/app2 
to different instances. That's absolutely not elegant though, I think. 
Ideally, installing an application should consist of just putting it in 
its directory and making that directory available to the webserver.

How do other people do this? Only one application on each (virtual) 
server? Or is there something I am missing?

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
Roy Smith <[EMAIL PROTECTED]> writes:
> Please don't misunderstand my actions.  I'm all for promoting
> Python, and your Karrigel system looks interesting.  Wikipedia is
> just not the correct forum for such promotion.  There is a fine line
> between promotion and documentation.  It's often difficult to know
> where that line is, especially when you're personally close to a
> project.

I think the current version of the article is ok.  The documentation
(past a few illustrative examples) and most of the advocacy is
removed.  The program itself is notable and the article is now
comparable to other Wikipedia articles about similar programs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-13 Thread bruno at modulix
News wrote:
(snip)
> sometimes you can't see the forest .. trees and all that :)

Yes, been here too... I wrote a CSV parser before realising there was a
pretty good one in the standard lib :(

(snip)
> OT: I saw several references to "OP". What does this mean?

Original Poster

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Roel Schroeven <

[EMAIL PROTECTED]> wrote:
There's something I don't quite get regarding the Karrigell- andCherryPy-style frameworks. With PHP or mod_python I can put any numberof different applications in different directories on a web server,


which is very convenient: [SNIP]How do other people do this? Only one application on each (virtual)
server? Or is there something I am missing?
Karrigell will happily run multiple karrigell "applications" on a
single server .  In your example simply by having
different applications at http://foo.example.com/app1 and 


http://foo.example.com/app2 will do the trick.

HTH :)

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: just one more question about the python challenge

2006-04-13 Thread Jerry
This one threw me for a loop as well.  I looked at that gfx file for a
whole day before I finally understood what was in it.  I only knew to
separate it into five piles because of the hint forums though.  I guess
I'm not intuitive enough.  :)

I too did this challenge without PIL.  Just remember that all files are
just bytes of data.  Hopefully, that idea with the rest of the hints
will help you along.

On a side note, level 13 was really fun.  No images at all (whew!) and
I got to learn something about Python AND the other technology used.

As for level 14 back to images.  I really didn't like this level
and it was the first time that I needed to find a solution.  Yes, I
cheated on this level.  I'm not proud of it.  But as it turns out, my
solution was correct, but I was going in the wrong direction.  I
figured as much from the hints in the forum, but when I reversed my
algorithm, it still ended up wrong.  I didn't realize that there were
four directions you could use to build the image.  I had only accounted
for two and both were not right. *sigh*

On to level 15.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: quiet conversion functions

2006-04-13 Thread Sion Arrowsmith
Tim Chase  <[EMAIL PROTECTED]> wrote:
>def CFloat(value):
>   try:
>   value = float(value)
>   except (ValueError, TypeError):
>   value = 0
>   return value

>>> type(CFloat(None))


I think you want value = 0.0 . And you might also want to consider
what errors you may be masking in silently turning *anything* into
a valid number.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

new-style classes and len method

2006-04-13 Thread Thomas Girod
Hi there.

I'm trying to use new-style classes, but there is something i'm
obviously missing

here it is :

class Data(list):
__slots__ = ["width", "height", "label"]

def __init__(self,width,height,label=None):
list.__init__(self)
self.width = width
self.height = height
self.label = label

def clear(cls):
while len(cls) > 0: del cls[0]
return
clear = classmethod(clear)

#> d = Data(2,2)
#> d.clear()
TypeError: len() of unsized object

off course it was working with :

[...]
def clear(self):
while len(self) > 0: del self[0]
return

So, I guess you can't use "cls" as a replacement for "self". So, what
do I have to use ???

-- 
http://mail.python.org/mailman/listinfo/python-list


trying to grasp OO : newbie Q?

2006-04-13 Thread mitsura
Hi,

I just started with Python and I am new to OO programming.
Here is a simple code:
"
class Obj:
myVar = 1

def __init__(self):
myVar = 2

#


myObj = Obj()

print myObj.myVar
"

The output is of this script is '1'. I would except it to be '2'.
I not understanding something fundamentally here.

Can anybody explain?

With kind regards,

Kris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Fredrik Lundh
Peter Hansen wrote:

> You're spending a lot of time trying to convince me I'm wrong

no, I'm just posting observable facts in response to various "I'm too
lazy to look this up, but I'll assume that things are this way" posts.

> Thankfully (to Georg)

it's fixed in the wiki too...

talking about the wiki, are you and rurpy the same person, btw?  the
implied "I'm going to pretend that you've never done anything to im-
prove the situation" insinuations are getting a bit tiresome...





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Mystilleef
I agree. Lists should have a clear method. But what's shocking is that
it doesn't seem obvious to others. list.clear() is a whole lot more
readable, intuitive, "flowable" and desirable than del list. Or maybe I
haven't had enough coffee this morning. I'd go as far as saying all
container objects should have a clear method. This is the reason why
those Rubyist whine about Python being inconsistent and not being "OO
enough."

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new-style classes and len method

2006-04-13 Thread Thomas Girod
Or maybe I'm mixing up what we call a "classmethod" with what we could
call an "instance method" ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new-style classes and len method

2006-04-13 Thread Paul McGuire
"Thomas Girod" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi there.
>
> I'm trying to use new-style classes, but there is something i'm
> obviously missing
>
> here it is :
>
> class Data(list):
> __slots__ = ["width", "height", "label"]
>
> def __init__(self,width,height,label=None):
> list.__init__(self)
> self.width = width
> self.height = height
> self.label = label
>
> def clear(cls):
> while len(cls) > 0: del cls[0]
> return
> clear = classmethod(clear)
>
> #> d = Data(2,2)
> #> d.clear()
> TypeError: len() of unsized object
>
> off course it was working with :
>
> [...]
> def clear(self):
> while len(self) > 0: del self[0]
> return
>
> So, I guess you can't use "cls" as a replacement for "self". So, what
> do I have to use ???
>

Um, why do you think clear() needs to be a classmethod?  Isn't it supposed
to work on an instance of Data?  If you just remove that "clear =
classmethod(clear)" statement, I think this works as you expect.

(Although your implementation of clear() will work correctly, you might
consider the more efficient "del self[:]" slice operation, instead of your
while loop.)


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Richie Hindle

[Mystilleef]
> Lists should have a clear method. But what's shocking is that
> it doesn't seem obvious to others. list.clear() is a whole lot more
> readable, intuitive, "flowable" and desirable than [the alternatives]

+1 to all of that.

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


DC panel and subpanel

2006-04-13 Thread python
I’m trying to test a system of created one main panel that will house the
wx.DC that will pass that DC to all the attached items and then they will
draw on that DC. With this system you should be able to attach a sub-panel
to it along with any items to that sub-panel as well so that you can have
objects move around.

I basically trying to figure out a good way to build and manage complex
alpha based interfaces by drawing all the items to the main DC by getting
pos and size from other items that are attached to the panel.

I’ve got most of it working…  as you can see from the attached py script,
but some reason, that is a mystery to me, when you scale the window up.
the item2(“sub”) is getting blocked by a white box. I’m not sure where
this box is coming from and not really sure how to get rid of it.

I’m fairly new to python and even newer to wxPython, if I’m going around
my head to scratch my @$$ here please tell me… if there is a simpler way
then please let me know…

Thanks in advanced

-Keith
#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# generated by wxGlade 0.4.1 on Thu Apr 13 21:27:13 2006

import wx

class PaintPanel(wx.Panel):
def __init__(self, parent, id, sub = 0, *args, **kwds):
wx.Panel.__init__(self, parent, id, *args, **kwds)
self.parent = parent
self.sub =sub
self.items = []

## sub = Not DC Panel
if self.sub:
self.parent.AddItem(self)
self.Hide()
else:
pass
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

def AddItem(self, item):
## Add Item
self.items.append(item)

def RemoveItem(self, item):
## Remove Item
for i in self.items:
if(i == item):
self.items.remove(i)

def RemoveAll(self):
## Remove All Items
self.items.clear()

def OnPaint(self, event):
self.sizeX, self.sizeY  = self.GetSize()
print "position is: " + str(self.GetPosition())
print "size is: " + str(self.GetSize())

## Setup Double Buffer DC
buffer = wx.EmptyBitmap(self.sizeX, self.sizeY)
memDC = wx.MemoryDC()
memDC.SelectObject(buffer)
dc = wx.PaintDC(self)
self.PrepareDC(dc)

memDC.SetBackground(wx.Brush("White"))
memDC.Clear()

self.Draw(memDC, self.GetPosition())

## Copy DC from MemoryDC
dc.Blit(0, 0, self.sizeX, self.sizeY,  memDC, 0, 0, wx.COPY, True)

## Clean Up The DC
del memDC
del dc

def Draw(self, dc, pos):
## Draw All Attached Items
for item in self.items:
item.Draw(dc, self.GetPosition())

def OnEraseBackground(self, event):
pass

class PaintItem:
def __init__(self, parent, id, name = ""):
self.parent = parent

self.name = name

self.parent.AddItem(self)
def Draw(self, dc, pos):
dc.SetTextForeground("BLUE")
dc.SetFont(wx.Font(50, wx.SWISS, wx.NORMAL, wx.BOLD))
dc.DrawText( self.name, pos[0], pos[1])

class TestFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame1.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)

self.panel = PaintPanel(self, -1)
item1 = PaintItem(self.panel, -1, name = "main")

self.subPanel= PaintPanel(self.panel, -1, sub = 1)
item2 = PaintItem(self.subPanel, -1, name = "sub")

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrame1.__set_properties
self.SetTitle("frame_2")
# end wxGlade

def __do_layout(self):
# begin wxGlade: MyFrame1.__do_layout
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
grid_sizer_1 = wx.FlexGridSizer(3, 3, 0, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add(self.subPanel, 1, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer_1.Add((20, 20), 0, wx.EXPAND, 0)

grid_sizer_1.Fit(self.panel)
grid_sizer_1.SetSizeHints(self.panel)
grid_sizer_1.AddGrowableRow(0)
grid_sizer_1.AddGrowableRow(1)
grid_sizer_1.AddGrowableRow(2)
grid_sizer_1.AddGrowableCol(0)
grid_sizer_1.AddGrowableCol(1)
grid_sizer_1.AddGrowableCol(2)

self.panel.SetAutoLayout(True)
self.panel.SetSizer(grid_sizer_1)  

Re: trying to grasp OO : newbie Q?

2006-04-13 Thread Azolex
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I just started with Python and I am new to OO programming.
> Here is a simple code:
> "
> class Obj:
>   myVar = 1
> 
>   def __init__(self):
>   myVar = 2
> 
> #
> 
> 
> myObj = Obj()
> 
> print myObj.myVar
> "
> 
> The output is of this script is '1'. I would except it to be '2'.
> I not understanding something fundamentally here.

You want to replace "myVar = 2" by "self.myVar = 2"
to get the result you expect.

> 
> Can anybody explain?
> 

Your "myVar = 1" sets a variable in the namespace of the class

Your "myVar = 2" sets a variable in the local frame of execution of the 
__init__ method, that is invisible outside that frame

Putting "self.myVar = 2" will set a variable in the instance dict that 
will shadow the class variable of the same name when you access myObj.myVar

hth
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editing with emacs/wordstar key bindings.

2006-04-13 Thread Thomas Bartkus
"Carl Banks" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Thomas Bartkus wrote:
> > Does anyone use emacs together with both WordStar key bindings and
python
> > mode?  I'm afraid that Wordstar editing key commands are burned R/O into
my
> > knuckles!
>
> Old Borland C user?

Worse than that!  It starts with Wordstar itself on a terminal to cp/m.
It continued with Borland Pascal -> Delphi.

Wordstar key controls are the only key bindings that are ergonometric on a
qwerty keyboard.  If you do serious typing, you don't break stride to issue
editing commands.

> > I would like to play with emacs for Python editing but I'm having (2)
> > problems.
> >
> >1) When I load a .py file, emacs automatically overrides my
wordstar-mode
> > with python-mode, forcing all the keybindings back to emacs native keys.
> > Why?
> >
> > Why should a python-mode care what key bindings are in use?
>
> Python and wordstar are both major modes.  When python-mode is loaded,
> it replaces (not sits atop of) wordstar-mode; you can't have two major
> modes loaded at the same time.
>
> If you want just want to use wordstar mode, you can prevent Emacs from
> loading python mode by putting -*- mode: wordstar -*- on the first line
> of the Python file (or second line if it uses a #!).  Or, you could
> remove python mode from the auto-mode-alist and interpreter-mode-alists
> in your .emacs file, which I leave as an exercise.

I do notice that I can invoke wordstar-mode *after* loading the .py file and
get the whole enchilada.  The Wordstar key bindings with the syntax
highlighting.
It just strikes me as odd that key bindings should be reasserted by invoking
python-mode.

Perhaps python-mode shouldn't be an emacs "major mode".
We just want syntax highlighting and some minor formatting assist.  Key
bindings have nothing to do with the language. I need to learn how to edit
the key re-assignment out of python-mode.el  .

> >2) We get  for block indentation instead of the spaces I prefer.
>
> In your .emacs file:
>
> (setq indent-tabs-mode nil)

Thank you.  That helps

> > Is there a better python-mode script I should be using other than the
> > default that came with emacs?
>
> I doubt there's one that solves your problem.

Yes.
The *real* problem here is that I need to get down and dirty with emacs/lisp
when all I started looking for was a more robust editor for Python ;-)

> Carl Banks
>


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread J Rice

Someone should correct me if I'm wrong but:

If you add "print myVar" to __init__, you will see that myVar is
assigned to "2" in that function.  It doesn't change the assignment of
"1" in the class because myVar in __init__ is local to __init__.  If
you want to change myVar for the whole class, you need to reference it
as self.myVar.

If you change your __init__ assignment to self.myVar, you will get the
"2" output you expect.  Also note that if you make a new variable in
__init__ (myVar2)and try to get its value with myObj.myVar2, you will
get an error that the variable doesn't exist.  But if you create the
variable using self.myVar2, assigning it to the class, you will be able
to access it.

Check some of the references on variable scope.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new-style classes and len method

2006-04-13 Thread Ben C
On 2006-04-13, Thomas Girod <[EMAIL PROTECTED]> wrote:
> Hi there.
>
> I'm trying to use new-style classes, but there is something i'm
> obviously missing
>
> here it is :
>
> class Data(list):
> __slots__ = ["width", "height", "label"]
>
> def __init__(self,width,height,label=None):
> list.__init__(self)
> self.width = width
> self.height = height
> self.label = label
>
> def clear(cls):
> while len(cls) > 0: del cls[0]
> return
> clear = classmethod(clear)
>
> #> d = Data(2,2)
> #> d.clear()
> TypeError: len() of unsized object
>
> off course it was working with :
>
> [...]
> def clear(self):
> while len(self) > 0: del self[0]
> return
>
> So, I guess you can't use "cls" as a replacement for "self". So, what
> do I have to use ???

You can use cls in a classmethod to refer to the class. You can use any
name you want (well so long as it's not a "reserved word" I suppose).
The same is true of self, it's just a param name (quite unlike
JavaScript's "this"...).

But I don't think it makes sense for clear to be a classmethod, since
you presumably want a method that clears instances of lists?

The error is because you're trying to take the len of the class itself,
not the len of an instance of it.

What you had before was OK. Although you don't need to write the loop,
just del self[:] will do, and you can leave out the return statement if
you want.
-- 
http://mail.python.org/mailman/listinfo/python-list


How do i use ~/.alias within 'ipython -p pysh'?

2006-04-13 Thread noman
Pasting the contents of ~/.alias into ~/.ipython/ipythonrc-pysh causes
all of my normal system aliases to be sourced and used by ipython, but
only the single token aliases work. For example, this alias:

alias l 'ls'

works, but this one:

alias ll 'ls -AhlF'

doesn't work. It replies:

sh: line 1: /tools/bin/ls -AhlF: No such file or directory.

 From the syntax of my aliases, you can see that i'm using a csh
 (tcsh, to be exact), which i'm stuck with, as per the client's
 wishes. The error message above leads me to think that IPython is
 using the Bourne shell under the covers. Is it possible to get it to
 use tcsh? I found that if i convert the 2nd alias above to:

alias ll='ls -AhlF'

(Bourne/bash syntax) it works as i expect in IPython, but i'd rather
not have to maintain 2 different syntax'ed copies of my _many_
aliases. In fact, i really don't want to have 2 copies at all. I'll go
ahead and do that for now, but i was hoping that either:

A) Someone can point out what i'm doing wrong, or

B) It's not my fault, and someone's already found a workaround for
   this minor issue.


thanks in advance,
Eric


PS: Fernando Perez, thank you _very_ much for IPython. 

-- 
  Every normal man must be tempted at times to spit on his hands,
  hoist the black flag, and begin to slit throats.
   H. L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: example of logging w/ user-defined keywords?

2006-04-13 Thread Vinay Sajip
Chris Curvey wrote:

> Several things that I've read lead me to think this is possible, but I
> can't figure out how to do it.  I have some information (a "job
> number")  that I would like logged on every log message, just like the
> time or the severity.
>
> I saw some mail threads that suggested that there was an easy way to do
> this, but I havent' found any examples.  Is there a simple way to do
> this, or do I need to write my own logger subclass?

The latest version in Subversion has an 'extra' keyword argument which
allows almost arbitrary items to be added to a LogRecord. See the
"in-development" docs at

http://docs.python.org/dev/lib/node365.html

and search for "extra".

Best regards,

Vinay Sajip

-- 
http://mail.python.org/mailman/listinfo/python-list


Parse email delivery status notifications (DSN) ?

2006-04-13 Thread Christopher Arndt
(please CC me in you replies if possible, I am not on the list)

Hi,

I am trying to write a script, that processes bounced emails from our
mailing campaigns to remove them from the distribution list and to
update the customer database.

Since our mailing program is not able to set the "Return-Path" header to
a separate address, but always sets it to the "From" address or the
"Reply-To" (if any), I need a way to distinguish DSNs from normal
replies to that mail box.

Is anybody aware of ready solutions to parse DSNs with Python? I would
just need to check if a mail is a DSN and retrieve the failed email address.

I know, this could probably done with the email module and some regexes,
but I would like to avoid ploughing through RFC 3464 to figure out the
formatting rules, if I can.

A quick search on this list and in the Cookbook, did not turn up
anything useful. I guess, mailman should already have code for this, but
can it be used on it's own?

Any pointers appreciated!

Cheers, Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread Ben C
On 2006-04-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just started with Python and I am new to OO programming.
> Here is a simple code:
> "
> class Obj:
>   myVar = 1
>
>   def __init__(self):
>   myVar = 2
>
> #
>
>
> myObj = Obj()
>
> print myObj.myVar
> "
>
> The output is of this script is '1'. I would except it to be '2'.
> I not understanding something fundamentally here.

Good example, it demonstrates these things quite well.

My understanding of this is as follows:

myVar is a class variable, because you define it in the body of the
class statement (not in any method).

In Python, classes and instances can both be thought of as dictionaries,
i.e. sets of key-value pairs.

In this example, Obj is a class and myObj is an instance.

When you write print myObj.myVar, the interpreter looks first in myObj
for a value matching the key "myVar". It doesn't find one there (I
explain why not below). So it continues the search in myObj's class,
which is the class Obj. It does find one there, with the value 1, so
that's what you get.

The myVar that you define in __init__ is not an instance variable, but a
local variable (local to the function __init__). To make an instance
variable you have to use "self" explicitly:

def __init__(self):
self.myVar = 2

If you write it like this, your program will print out 2.

People coming from languages like C++ where this-> is implicit sometimes
forget to write "self."; in Python you always need it to get at the
instance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py2exe wx.lib.activexwrapper win32com

2006-04-13 Thread [EMAIL PROTECTED]
it doesn't work only under windows 98 first edition, still don't know
how to fix this.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: just one more question about the python challenge

2006-04-13 Thread JW
You said:
> Sorry to post here about this again, but the hint forums are dead, and
> the hints that are already there are absolutely no help (mostly it's
> just people saying they are stuck, then responding to themselves saying
> the figured it out! not to mention that most of the hints require
> getting past a certain point in the puzzle before they make sense, and
> i'm just clueless).

I just went to the hint forums:
http://www.pythonchallenge.com/forums/index.php

There are SEVEN pages of clues for level 12.  The most recent post (to
challenge 1) was on April 11, so the forums are most certainly not
dead.  Yes, the hints don't spell out what step they are refering to,
and a certain level of obfuscation is required to avoid giving away
hints.

Many can not be solved in a day - they require reading hints, thinking
hard, then doing something else (reading, working, sleeping) to let the
subconscious chew over the clues.  This is the fun of the challenge -
there is no secret knowledge gained, other than a list of URLs and
passwords.  If this isn't your definition of fun, then you can go on to
other things with a clear conscious.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread Wildemar Wildenburger
J Rice wrote:
> Someone should correct me if I'm wrong but:
> If
> you want to change myVar for the whole class, you need to reference it
> as self.myVar.
>   
wrong: If you want to change myVar for the whole *class*, you need to 
reference it as Obj.myVar (prefix with classname).
self.myVar will change it for that one instance only.

other than that, agreed :)
wildemar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Roel Schroeven
Tim Williams (gmail) schreef:
> 
> 
> On 13/04/06, *Roel Schroeven* < [EMAIL PROTECTED] 
> > wrote:
> 
> 
> 
> There's something I don't quite get regarding the Karrigell- and
> CherryPy-style frameworks. With PHP or mod_python I can put any number
> of different applications in different directories on a web server,
> which is very convenient: 
> 
> [SNIP]
> How do other people do this? Only one application on each (virtual)
> server? Or is there something I am missing?
> 
> 
> Karrigell will happily run multiple karrigell "applications" on a single 
> server .  In your example simply by having different applications at 
> http://foo.example.com/app1 and http://foo.example.com/app2 will do the 
> trick.

But I still need to allocate a port for each one, right? And write 
rewrite rules to rewrite the urls:
  http://foo.example.com/app1 -> http://foo.example.com:port1
  http://foo.example.com/app2 -> http://foo.example.com:port2

I don't like to have to run separate processes for each application, but 
I guess it will work.


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread gry
A perspective that I haven't seen raised here is inheritance.
I often say
mylist = []
if I'm done with the current contents and just want a fresh list.

But the cases where I have really needed list.clear [and laboriously
looked for it and ended up with
   del l[:]
were when the object was my own class that inherits from list, adding
some state and other functionality.  Of course I *could* have added my
own 'clear' function member, but I *wanted* it to behave like a
standard
python list in it's role of maintaining a sequence of processing steps.
So, I end up doing
   del current_process[:]
which, IMO, looks a bit queer, especially when current_process
object is a fairly elaborate data object.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread mitsura
Thanks guys,

It is starting to make much more sense. Most documentation I find about
OO is very academic

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Luis M. González
When you talk about the "Karrigell folks" it looks like there's a bunch
of guys out there ploting to rule the world. It's nothing like that.
I just read Pierre's comments about this article, and decided to post a
message in comp.lang.python to let everybody know about it.

Perhaps my post looked like a sales pitch... well, I'm sorry! I think
Karrigel needs some promotion. It's an excellent product and it's been
almost ignored by the community...

I appreciate all the observations regarding Wikipedia's nature, but I
confess that I'm surprised to see you, "python folks", so annoyed by
this article.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Pierre Quentel
The web server in Karrigell is actually application-independant. An
application is a set of scripts or static files, generally stored in
the same directory ; the server parses the http requests, searches for
a file matching this request, processes the file according to its
extension and sends the response

For instance, the distribution provides a number of demo applications
(a calendar, a wiki server, a forum etc) that can be all used when you
start the server

If you want to add a new application you just have to add the files, it
will run without having to restart the server ; if you modify a script
with a text editor, you see the result of the change the next time you
reload the page

Pierre

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Roel Schroeven <[EMAIL PROTECTED]> wrote:

Tim Williams (gmail) schreef:> Karrigell will happily run multiple karrigell "applications" on a single> server .  In your example simply by having different applications at
> http://foo.example.com/app1 and 
http://foo.example.com/app2 will do the> trick.But I still need to allocate a port for each one, right? And write
rewrite rules to rewrite the urls:  http://foo.example.com/app1 -> 
http://foo.example.com:port1  
http://foo.example.com/app2 -> http://foo.example.com:port2
:)    No  

it is a common misconception that you need seperate ports on a webserver for different "applications" and / or sites 

Generally (ie not karrigell specific),   for *your* example 
you can run them all on the same port - as http://foo.example.com/app1
and http://foo.example.com/app2 

Generally (ie not karrigell specific), even if you are using different
hostnames in the URLs ie  http://www.mydom1.com and
http://www.mydom2.com you still don't need different
ports,  just use virtual-host (or Host-Headers in IIS ) mappings.

In Karrigell you could write the host mappings into a karrigell script
(.ks) application, so you wouldn't  even need to use virtual-hosts
in the config file.  and of course, you could just write a single
.ks  that contains (at least the entry points to ) all your
applications
HTH :)














-- 
http://mail.python.org/mailman/listinfo/python-list

quick surface plots

2006-04-13 Thread buchstaebchen
Hi folks,

I need advice in finding an appropriate python module for 3D surface
plots, such as for the visualization of wave-dynamics...I'd prefer
something capable of being embedded in wxpython frames, as matplotlib
is doing pretty well for 2D, however, I couldn't get a hold of
functions like  there.
vpython hasn't any likewise, while mayavi is way to complex (and
doesn't allow quick animation?)

Any recommendation (or some old threads I failed to look for) ?

thanks for any reply and cheers!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Pierre Quentel
No, in the document root you create a folder "app1" and put all the
files for the first application in it, and a folder "app2" for the
second application

For http://foo.example.com/app1 the server will search for an index
file in this directory and serve it. You can also specify the script
you want : http://foo.example.com/app1/default.py. Same thing for app2
of course. Absolutely no need to start two instances of the server on
different ports

Pierre

-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for thoughts on PyMPI

2006-04-13 Thread Carl J. Van Arsdall
Hey, anyone use the PyMPI suite: http://sourceforge.net/projects/pympi/  ??

I am an engineer doing research with MPI and thought I'd do some digging 
to see if any scripting languages had adopted it yet.  I was just 
looking for general comments and reviews from the community on this 
project, thanks!


-carl

-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Steven Bethard
Raymond Hettinger wrote:
> [Steven Bethard]
>> I think these are all good reasons for adding a clear method, but being
>> that it has been so hotly contended in the past, I don't think it will
>> get added without a PEP.  Anyone out there willing to take out the best
>> examples from this thread and turn it into a PEP?
> 
> Something this small doesn't need a PEP.  I'll just send a note to
> Guido asking for a pronouncement.

Thanks.  It'd be nice to have something to refer to the next time this 
comes up.

> Here's a draft list of pros and cons (any changes or suggestions are
> welcome):
> 
> Pros:
> -
> 
> * s.clear() is more obvious in intent
> 
> * easier to figure-out, look-up, and remember than either s[:]=[] or
> del s[:]
> 
> * parallels the api for dicts, sets, and deques (increasing the
> expecation that lists will too)
>
> * the existing alternatives are a bit perlish
> 

I'd snip the one below.  It doesn't really contribute anything, and was 
sarcastic in the first place. ;)

> * the OP is shocked, SHOCKED that python got by for 16 years without
> list.clear()
> 
> 
> Cons:
> -
> 
> * makes the api fatter (there are already two ways to do it)
> 
> * expanding the api makes it more difficult to write classes that can
> be polymorphically substituted for lists
> 
> * learning slices is basic to the language (this lesson shouldn't be
> skipped)
> 
> * while there are valid use cases for re-using lists, the technique is
> already overused for unsuccessful attempts to micro-optimize (creating
> new lists is surprisingly fast)
> 

In fairness, if we're going to drop the "SHOCKED" comment, we should 
drop the first two clauses of the point below (but the "relevant idiom" 
part is clearly a good point).

> * the request is inane, the underlying problem is trivial, and the
> relevant idiom is fundamental (api expansions should be saved for rich
> new functionality and not become cluttered with infrequently used
> redundant entries)

Other than those minor edits, I think you've pretty much gotten 
everything.  I look forward to a pronouncement.

Thanks again!

STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> It is starting to make much more sense. Most documentation I find about
> OO is very academic

you may find Jay Parlar's new python class tutorial helpful:

http://parlar.infogami.com/pytut_classes_copy

(this is a proposed addition/replacement for the class chapter in the
current tutorial).





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Tim Williams (gmail)
On 13/04/06, Tim Williams (gmail) <[EMAIL PROTECTED]> wrote:
In Karrigell you could write the host mappings into a karrigell script
(.ks) application, so you wouldn't  even need to use virtual-hosts
in the config file.  and of course, you could just write a single
..ks  that contains (at least the entry points to ) all your
applications

Hmm,  out of context this could be misleading so:

In Karrigell you simply put your application into its own
directory  and access it via the  http://domain/app-dirname
-  for however many applications you need.   

Managing different apps through a single .ks script  is just something I have experimented with, but don't use very often.

:)



-- Tim Williams
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Pierre Quentel" <[EMAIL PROTECTED]> writes:
> For http://foo.example.com/app1 the server will search for an index
> file in this directory and serve it. You can also specify the script
> you want : http://foo.example.com/app1/default.py. Same thing for app2
> of course. Absolutely no need to start two instances of the server on
> different ports

But they're the same Python interpreter and so there's no protection
between one application and another, right?  That might be ok for a
single user running multiple apps, but think of PHP hosting farms that
have thousands of users with separate virtual hosts.  It would be
disastrous if they could see each others' data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Karrigel page in Wikipedia

2006-04-13 Thread Paul Rubin
"Luis M. González" <[EMAIL PROTECTED]> writes:
> I appreciate all the observations regarding Wikipedia's nature, but I
> confess that I'm surprised to see you, "python folks", so annoyed by
> this article.

I think it's more "wikipedia folks" (I'm one) who found the original
version of the article annoying by Wikipedia standards.  Wikipedia is
besieged with hucksters trying to propagate marketing fluff through
the encyclopedia and so they react unfavorably to anything that
resembles that type of material.  The current version is much more
suitable as an encyclopedia article.  It just needs a little bit of
grammar and punctuation cleanup, no big deal.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trying to grasp OO : newbie Q?

2006-04-13 Thread John Salerno
[EMAIL PROTECTED] wrote:
> Thanks guys,
> 
> It is starting to make much more sense. Most documentation I find about
> OO is very academic

Couldn't we also say that this issue of namespace scope is a little more 
specific to Python than OOP in general? I could very easily be wrong, 
but I wouldn't want the poster to think that this is how OOP works always.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-13 Thread Fredrik Lundh
Mel Wilson wrote:

> > for item in seq:
> > L.append(item)
>
> Both extend and append have one-line slice equivalents,
> except that the equivalents have to keep referring to
> the length of the list.. (have to keep finding the
> len function.)

fwiw, the *tutorial* defines append and extend in terms of slicing...





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new-style classes and len method

2006-04-13 Thread Thomas Girod
It's alright I found where my mistake came from. I was misunderstanding
the meaning of "classmethod", thinking of it as an instance method.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: just one more question about the python challenge

2006-04-13 Thread John Salerno
JW wrote:

> There are SEVEN pages of clues for level 12.  The most recent post (to
> challenge 1) was on April 11, so the forums are most certainly not
> dead.  

I read those seven pages at least twice and they still don't make much 
sense to me (not to mention that many of the posts are just 
conversational comments anyway, and not hints).

The last post for level 12 was made last year, so I'd call that dead 
enough to be unhelpful.

> passwords.  If this isn't your definition of fun, then you can go on to
> other things with a clear conscious.

Some of them are really fun, some are a pain. But if I had 'other 
things' to use Python on consistently, I would definitely spend more 
time with that.
-- 
http://mail.python.org/mailman/listinfo/python-list


PEP 359: The "make" Statement

2006-04-13 Thread Steven Bethard
Ok, I finally have a PEP number.  Here's the most updated version of the 
"make" statement PEP.  I'll be posting it shortly to python-dev.

Thanks again for the previous discussion and suggestions!


PEP: 359
Title: The "make" Statement
Version: $Revision: 45366 $
Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
Author: Steven Bethard <[EMAIL PROTECTED]>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 05-Apr-2006
Python-Version: 2.6
Post-History: 05-Apr-2006, 06-Apr-2006


Abstract


This PEP proposes a generalization of the class-declaration syntax,
the ``make`` statement.  The proposed syntax and semantics parallel
the syntax for class definition, and so::

make   :


is translated into the assignment::

 = ("", , )

where  is the dict created by executing .
The PEP is based on a suggestion [1]_ from Michele Simionato on the
python-dev list.


Motivation
==

Class statements provide two nice facilities to Python:

   (1) They are the standard Python means of creating a namespace.  All
   statements within a class body are executed, and the resulting
   local name bindings are passed as a dict to the metaclass.

   (2) They encourage DRY (don't repeat yourself) by allowing the class
   being created to know the name it is being assigned.

Thus in a simple class statement like::

  class C(object):
  x = 1
  def foo(self):
  return 'bar'

the metaclass (``type``) gets called with something like::

 C = type('C', (object,), {'x':1, 'foo':})

The class statement is just syntactic sugar for the above assignment
statement, but clearly a very useful sort of syntactic sugar.  It
avoids not only the repetition of ``C``, but also simplifies the
creation of the dict by allowing it to be expressed as a series of
statements.

Historically, type instances (a.k.a. class objects) have been the only
objects blessed with this sort of syntactic support.  But other sorts
of objects could benefit from such support.  For example, property
objects take three function arguments, but because the property type
cannot be passed a namespace, these functions, though relevant only to
the property, must be declared before it and then passed as arguments
to the property call, e.g.::

 class C(object):
 ...
 def get_x(self):
 ...
 def set_x(self):
 ...
 x = property(get_x, set_x, ...)

There have been a few recipes [2]_ trying to work around this
behavior, but with the new make statement (and an appropriate
definition of property), the getter and setter functions can be
defined in the property's namespace like::

 class C(object):
 ...
 make property x:
 def get(self):
 ...
 def set(self):
 ...

The definition of such a property callable could be as simple as::

 def property(name, args, namespace):
 fget = namespace.get('get')
 fset = namespace.get('set')
 fdel = namespace.get('delete')
 doc = namespace.get('__doc__')
 return __builtin__.property(fget, fset, fdel, doc)

Of course, properties are only one of the many possible uses of the
make statement.  The make statement is useful in essentially any
situation where a name is associated with a namespace.  So, for
example, namespaces could be created as simply as::

 make namespace ns:
 """This creates a namespace named ns with a badger attribute
 and a spam function"""

 badger = 42

 def spam():
 ...

And if Python acquires interfaces, given an appropriately defined
``interface`` callable, the make statement can support interface
creation through the syntax::

 make interface C(...):
 ...

This would mean that interface systems like that of Zope would no
longer have to abuse the class syntax to create proper interface
instances.


Specification
=

Python will translate a make statement::

 make   :
 

into the assignment::

  = ("", , )

where  is the dict created by executing .
The  expression is optional; if not present, an empty tuple
will be assumed.

A patch is available implementing these semantics [3]_.

The make statement introduces a new keyword, ``make``.  Thus in Python
2.6, the make statement will have to be enabled using ``from
__future__ import make_statement``.


Open Issues
===

Does the ``make`` keyword break too much code?  Originally, the make
statement used the keyword ``create`` (a suggestion due to Nick
Coghlan).  However, investigations into the standard library [4]_ and
Zope+Plone code [5]_ revealed that ``create`` would break a lot more
code, so ``make`` was adopted as the keyword instead.  However, there
are still a few instances where ``make`` would break code.  Is there a
better keyword for the statement?

**

Currently, there are not many

Re: New Karrigel page in Wikipedia

2006-04-13 Thread Roel Schroeven
Pierre Quentel schreef:
> No, in the document root you create a folder "app1" and put all the
> files for the first application in it, and a folder "app2" for the
> second application
> 
> For http://foo.example.com/app1 the server will search for an index
> file in this directory and serve it. You can also specify the script
> you want : http://foo.example.com/app1/default.py. Same thing for app2
> of course. Absolutely no need to start two instances of the server on
> different ports

I understand that, but I'd like to keep the current situation unchanged 
as much as possible. Currently I have an Apache webserver that serves 
some static content plus some dynamic stuff, with a directory structure 
somewhat like

/var/www/index.html
/var/www/internal
/var/www/phpmyadmin
/var/www/webmail

etc. (/var/www is Apache's DocumentRoot, obviously). Also I regularly 
have some stuff in my homedir

/home//public_html/foo
/home//public_html/bar

to play with stuff.

So, I can't run Karrigell on port 80, since that's already in use by 
Apache. So I need to run Karrigell on another port, and somehow instruct 
Apache to forward some URL's to Karrigell on handle some URL's itself.

For example, suppose I create

/var/www/karrigell1
/var/www/karrigell2

How do I configure everything so that they are accessible via

http://hostname/karrigell1
http://hostname/karrigell2


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >