Re: Has anyone used davlib by Greg Stein?

2006-07-21 Thread Guido Goldstein

Hi!

On Tue, 18 Jul 2006 15:06:55 +0200
  Joel Hedlund <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I want to PUT files to a authenticated https WebDAV server from within
> a python script. Therefore I put "python dav" into google, and the
> davlib module by Greg Stein (and Guido?) came up. It seems to be soild
> but has very little docs. Has anyone worked with this? Is it any good? 
> Where can I find some good docs for it?

I don't know any documentation for it.
But I know that there is another DAV lib around at
  http://www.infrae.com/download/pydavclient

It is also not fully documented but might fit your needs.

Cheers
  Guido G.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie needs constructive suggestions

2006-07-21 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> What is the idiomatically appropriate Python way to pass, as a
> "function-type parameter", code that is most clearly written with a local
> variable?
> 
> For example, map takes a function-type parameter:
> 
> map(lambda x: x+1, [5, 17, 49.5])
> 
> What if, instead of just having x+1, I want an expression that is most
> clearly coded with a variable that is needed only inside the lambda, e.g.
> if I wanted to use the name "one" instead of 1:
> 
> map(lambda x: (one = 1  x+one), [5, 17, 49.5])
 
For a simple constant expression, your example is how it's done most
frequently. When it gets more complicated the classic trick is to use a
default argument:

>>> map(lambda x, delta=2**10: x+delta, [5, 17, 49.5])
[1029, 1041, 1073.5]

A closure works equally well:

>>> def make_adder(delta):
... def add(x):
... return x + delta
... return add
...
>>> map(make_adder(42), [5, 17, 49.5])
[47, 59, 91.5]

So does a callable class...

>>> class Adder(object):
... def __init__(self, delta):
... self.delta = delta
... def __call__(self, x):
... return x + self.delta
...
>>> map(Adder(321), [5, 17, 49.5])
[326, 338, 370.5]

which has the advantage that it can maintain state between calls (e. g. if
you were to build an accumulator it would be your only clean option).

In the real world the first two are most common, but they are only used when
the variable is not for immediate consumption:

# wrong
>>> adders = [lambda x: x + delta for delta in range(3)]
>>> [a(0) for a in adders]
[2, 2, 2]

# fixed
>>> adders = [lambda x, delta=delta: x + delta for delta in range(3)]
>>> [a(0) for a in adders]
[0, 1, 2]

> Do I
> 
>   d) give up on using Python and go back to Scheme, or

If you stick with Python your students can soon start to experiment with
concepts and algorithms, and at the same time you provide them with a tool
that may be useful in their daily work (think scipy).

Peter

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


Re: Nested function scope problem

2006-07-21 Thread Josiah Manson
I just did some timings, and found that using a list instead of a
string for tok is significantly slower (it takes 1.5x longer). Using a
regex is slightly faster for long strings, and slightly slower for
short ones. So, regex wins in both berevity and speed!

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


Re: Python newbie needs constructive suggestions

2006-07-21 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

>   b) give up on using an anonymous function and create a named "successor"
>   function with "def",

This is what you have to do. For some reason mr van Rossum has this aversion
to anonymous functions, and tries to cripple them as much as possible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-21 Thread Josiah Manson
Thank you for your corrections to the previous code. Your regex
solution is definitely much cleaner. Referring to your other
suggestions, is the advantage of using a list of chars instead of
adding to a string just a bow to big-O complexity, or are there other
considerations? First I had tried appending to the string, but it seems
they are immutable. It seems that using a list for a string isn't a
very clear way to represent a mutable string.

Although I gladly accept that using a regex is the best solution to
this problem, I am still interested in knowing how to access the
variables in a containing function. It seems that there should be some
keyword akin to global that would expose them, or some other method. I
have read that python uses nested scopes (or at least was planning to
in 2.2), so I wonder what I am missing.

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


Re: New to threads. How do they work?

2006-07-21 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Grant Edwards wrote:

> On 2006-07-21, Lawrence D'Oliveiro <[EMAIL PROTECTED]>
> wrote:
>> In message <[EMAIL PROTECTED]>, gel
>> wrote:
>>
>>> I am attempting to understand threads to use in a network app which I
>>> am writing.
>>
>> It is written, somewhere in the philosophy of *nix programming, that
>> threads are a performance hack, to be avoided wherever possible. Use
>> processes in preference to threads.
> 
> I've never understood the aversion people seem to have to
> threads.

Perhaps because with threads, data is shared by default. Whereas with
processes, it is private by default, and needs to be explicitly shared if
you want that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested function scope problem

2006-07-21 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Justin 
Azoff wrote:

> Simon Forman wrote:
>> That third option seems to work fine.
> 
> Well it does, but there are still many things wrong with it
> 
> if len(tok) > 0:
> should be written as
> if(tok):

I prefer the first way. Besides, your way is sub-optimal.
-- 
http://mail.python.org/mailman/listinfo/python-list


Linux Kernel Testing--Why Python

2006-07-21 Thread Lawrence D'Oliveiro
Just came across this article
 from the
Ottawa Linux Symposium, which mentions (among other things) Martin Bligh's
presentation on the automated testing system used for the Linux kernel:

The test system is written in Python, and he discussed at length why
Python was chosen as the language for the system. He also spent some
time showing the audience test output from the system, and discussed why
other languages were not suitable for the test system.

He described Python as a language that meets the requirements for the
task because it is a language that is easy to modify and maintain, that
is not write-only, that has exception handling, is powerful but not
necessarily fast, is easy to learn, and has wide libraries of modules to
leverage.

He described Perl as a write-only language, and said that while people
can do amazing things with the shell, it is not appropriate for the
purpose. He said with a grin that he has a lot of respect for what
people can do in the shell, but none for choosing to do it that way in
the first place.

One thing he particularly likes about Python, he said, is its usage of
indentation. Unlike other languages, Bligh noted, Python is read by the
computer the same way as it is read by a person, resulting in fewer
bugs.

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


Re: Nested function scope problem

2006-07-21 Thread Justin Azoff
Simon Forman wrote:
> That third option seems to work fine.

Well it does, but there are still many things wrong with it

if len(tok) > 0:
should be written as
if(tok):

tok = ''
tok = toc + c
should be written as
tok = []
tok.append(c)
and later
''.join(toc)

anyway, the entire thing should be replaced with something like this:
import re
def breakLine(s):
splitters = '?()&|:~,'
chars = '^ \t\n\r\f\v%s' % splitters
regex = '''(
(?:[%s])
|
(?:[%s]+))''' % (splitters, chars)
return re.findall(regex, s,re.VERBOSE)

That should be able to be simplified even more if one were to use the
character lists built into the regex standard.

-- 
- Justin

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


Re: random shuffles

2006-07-21 Thread bryanjugglercryptographer

Boris Borcic wrote:
> does
>
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?
>
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes.

You would be mistaken (except for the trivial case of 2 elements).

In m uniform, independant, random 2-way choices, there are 2**m
equally probable outcomes. We can map multiple random outcomes
to the same final output, but each will still have probability of the
form
n/2**m, where n is an integer.

A random permutation requires that we generate outputs with
probability 1/(n!). For n>2, we cannot reach the probability using a
limited number of 2-way choices.


Have you ever looked at the problem of making a perfectly uniform
1-in-3 choice when the only source of randomness is a perfect random
bit generator? The algorithms terminate with probability 1, but are
non-terminators in that there is no finite number of steps in which
they must terminate.


-- 
--Bryan

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


Re: Nested function scope problem

2006-07-21 Thread Simon Forman
Gerhard Fiedler wrote:
> On 2006-07-21 21:05:22, Josiah Manson wrote:
>
> > I found that I was repeating the same couple of lines over and over in
> > a function and decided to split those lines into a nested function
> > after copying one too many minor changes all over. The only problem is
> > that my little helper function doesn't work! It claims that a variable
> > doesn't exist. If I move the variable declaration, it finds the
> > variable, but can't change it. Declaring the variable global in the
> > nested function doesn't work either.
> >
> > But, changing the variable in the containing scope is the whole purpose
> > of this helper function.
> >
> > I'm new to python, so there is probably some solution I haven't
> > encountered yet. Could you please suggest a nice clean solution? The
> > offending code is below. Thanks.
>
> I'm no Python specialist, so here's just some guesses... I don't know how
> to make variables known inside the inner function. It seems just using the
> names there overrides the outside names. It also seems that local variables
> are in some kind of dictionary; so maybe you can access them through that
> somehow.
>
> One other solution (a bit ugly) would be to make this a class with two
> static methods (breakLine and _addTok) and two static attributes (_ls and
> _tok).
>
> Still another (also ugly) would be to pass both tok and ls to addTok() and
> pass tok back out again. (I think ls doesn't have to be passed back,
> because it is a list and so its data gets modified. tok's data doesn't get
> modified, so local changes don't propagate to the outside.)
>
> Gerhard

That third option seems to work fine.

def breakLine(s):
"""Break a string into a list of words and symbols.
"""

def addTok(tok, ls):
if len(tok) > 0:
ls.append(tok)
tok = ''
return tok

ls = []
tok = ''
splitters = '?()&|:~,'
whitespace = ' \t\n\r'

for c in s:
if c in splitters:
tok = addTok(tok, ls)
ls.append(c)
elif c in whitespace:
tok = addTok(tok, ls)
else:
tok = tok + c

tok = addTok(tok, ls)

return ls

#some tests to make sure it works
print breakLine('carolina(Prada):cat(X,Y)')
print breakLine('trouble :bird (X ) &cat ( Y )')
print breakLine('?trouble')

# Prints:
['carolina', '(', 'Prada', ')', ':', 'cat', '(', 'X', ',', 'Y', ')']
['trouble', ':', 'bird', '(', 'X', ')', '&', 'cat', '(', 'Y', ')']
['?', 'trouble']

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


Re: Language Design: list_for scope?

2006-07-21 Thread Carl Banks
guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
>
> Q: What is the scope of the testlist in a list_for?
>
> For example;
> Instead of;
>   for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>   for x in dict and dict[x]=="thing":
> x is undefined.

In the above two examples, x is a regular variable (global or local
depending on whether it's in a function).  It will remain undefined
until the first time something gets assigned to it.

In your first example (where you appear to have left out a for), it get
bound inside the list comprehension, after evaluating 'dict' but before
evaluating the test 'dict[x]=="thing"'.

I doubt the second example does what you want it to, but here's what
happens.  Python tries to evaluate the expression 'dict and
dict[x]=="thing"' first, before assigning anything to x.  Because that
expression uses x, you get an undefined error.  If it hadn't had the
undefined error, it would have tried to iterate over the result (which
would have been True or False), which would have raised a TypeError
exception.


> And why doesn't this work:
>   for x in dict if dict[x]=="thing":

Because it would would just be another way to spell:

for x in dict:
if dict[x] == "thing:

Yes, we've heard all the arguments before.  The Python language
designers like to have only one way to do things when they can, and in
this case they felt that none of the objections (an extra level of
indentation or unsightly continue) warranted a new spelling.

I recall there was to be a (prerejected) PEP submitted about this
recently, but it doesn't appear to be up.


> Any insights/hints on why it is broken?

It's not broken :)


Carl Banks

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


Re: Python newbie needs constructive suggestions

2006-07-21 Thread Justin Azoff
[EMAIL PROTECTED] wrote:
> What is the idiomatically appropriate Python way to pass, as a "function-type 
> parameter", code that is most clearly written with a local variable?
>
> For example, map takes a function-type parameter:
>
>map(lambda x: x+1, [5, 17, 49.5])
>
> What if, instead of just having x+1, I want an expression that is most 
> clearly coded with a variable that is needed _only_ inside the lambda, e.g. 
> if I wanted to use the name "one" instead of 1:
>
>map(lambda x: (one = 1  x+one), [5, 17, 49.5])

I believe most people would just write something like this:

def something():
#local helper function to add one to a number
def addone(x):
one = 1
return x+one
return map(addone, [5, 17, 49.5])

-- 
- Justin

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


Re: Python newbie needs constructive suggestions

2006-07-21 Thread faulkner
optional arguments.
map(lambda x, one=1: x + one, ...)

it is entirely possible, however, to implement let in python.
def let(**kw):
sys._getframe(2).f_locals.update(kw)

def begin(*a):
return a[-1]

map(lambda x: begin(let(one=1), x+one), range(10))

i really should warn you, though, that most pythoneers will cringe at
code like that, no matter how well they understand it. write python in
python, and you'll have more friends.


[EMAIL PROTECTED] wrote:
> What is the idiomatically appropriate Python way to pass, as a "function-type 
> parameter", code that is most clearly written with a local variable?
>
> For example, map takes a function-type parameter:
>
>map(lambda x: x+1, [5, 17, 49.5])
>
> What if, instead of just having x+1, I want an expression that is most 
> clearly coded with a variable that is needed _only_ inside the lambda, e.g. 
> if I wanted to use the name "one" instead of 1:
>
>map(lambda x: (one = 1  x+one), [5, 17, 49.5])
>
> This sort of thing is of course straightforward in many other languages with 
> anonymous functions (Scheme, Haskell, Smalltalk, etc), and I saw in the 
> archives the discussion from 2003 about "How do I get Scheme-like let 
> bindings in Python". Many of the answers seem to boil down to "You should not 
> write Scheme programs in Python, you should write Python programs in Python". 
> As someone new to Python, I'd like a little more detail on this, so I'm 
> asking _what_ I should do when I want to pass, to something like map, code 
> that is most clearly expressed with a local variable?
>
> Do I
>
>   a) give up on using a local variable and just substitute the value in its 
> place (going back to my original use of map),
>
>   b) give up on using an anonymous function and create a named "successor" 
> function with "def",
>
>   c) give up on making "one" local to the lambda and create it in the scope 
> in which I'm calling map, even if I don't otherwise need it there,
>
>   d) give up on using Python and go back to Scheme, or
>
>   e) do something else clever and Pythonic that I don't know about yet?
>
> What is the idiomatically correct way to do this in Python?
>
> Thanks for any constructive advice you can give,
>   Dave Wonnacott
>
>
> P.S., For those who want a bit more context about what I'm doing, I'll 
> provide it -- anyone else is welcome to skip the rest of this message.
>
>
> As you may guess, I am in the process of learning Python. I have some 
> experience with C/C++ and Scheme and other forms of Lisp, as well as passing 
> familiarity with a bunch of other languages.
>
> I teach an introductory CS course in which I cover a variety of topics that I 
> believe are central to computer science and can be expressed in any language, 
> such as algorithm design, unit and integration testing, writing code that 
> maintains an invariant property of a set of variables. However, I do not like 
> the "language-free" or "all-pseudocode" approach to teaching -- I believe all 
> examples should be shown in a real language, and that the code should be as 
> true to the customary idioms of that language as possible. This limits my 
> choice of language somewhat, since I include elements of functional 
> programming, imperative programming, and object-oriented programming -- I'm 
> not happy doing things like cramming functions into unnecessary classes in 
> Java. However, I currently believe that Python will be at least as good as 
> C++ for what I want to do, and am exploring the details of how it would work 
> out.
>
> One of the things I'm doing is discussing various styles of thinking about 
> the execution of an algorithm, specifically as a process of textual 
> substitution of equals for equals (as one would generally do in Haskell or 
> other functional languages, or in mathematics) or a sequence of ordered steps 
> to be followed (as one would generally do in imperative languages). Note 
> that, while Haskell programmers may say that substitution is the true way 
> that their programs are executed, and C++ programmers may say that a sequence 
> of ordered steps is what's "really going on", the actual process of going 
> from your source code to the output of your program can be blending of these 
> two techniques -- for example, a C++ compiler may perform substitution where 
> it is legal to do so, producing a machine language program that is executed 
> _mostly_ in order (though a processor may commute the order of execution 
> where it is legal to do so). Anyway, in almost any language, there are _some_ 
> ways to per!
 fo!
>  rm substitutions without changing the result of a piece of code (e.g. 
> substituting the value of a variable that is only assigned once, for each of 
> its uses), and some things that can be visualized in terms of execution of 
> steps even if one wishes to do so (even in a language like Haskell).
>
> The question of the use of variables inside a lambda is relevant to m

Re: How to use pdb?

2006-07-21 Thread tron . thomas

R. Bernstein wrote:
> Perhaps what you are looking for is:
>   python /usr/lib/python2.4/pdb.py Myprogram.py

I tried this and it did not work.  pdb did not load the file so it
could be debugged.

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


Re: How to use pdb?

2006-07-21 Thread tron . thomas

peter wrote:
> I haven't tried to use pdb myself, but this looks fairly helpful ...
>
> http://www.ferg.org/papers/debugging_in_python.html
>
> good luck
>
> Peter

That link was indeed helpful.  I was finally able to debug the program

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


Re: Nested function scope problem

2006-07-21 Thread Gerhard Fiedler
On 2006-07-21 21:05:22, Josiah Manson wrote:

> I found that I was repeating the same couple of lines over and over in
> a function and decided to split those lines into a nested function
> after copying one too many minor changes all over. The only problem is
> that my little helper function doesn't work! It claims that a variable
> doesn't exist. If I move the variable declaration, it finds the
> variable, but can't change it. Declaring the variable global in the
> nested function doesn't work either.
> 
> But, changing the variable in the containing scope is the whole purpose
> of this helper function.
> 
> I'm new to python, so there is probably some solution I haven't
> encountered yet. Could you please suggest a nice clean solution? The
> offending code is below. Thanks.

I'm no Python specialist, so here's just some guesses... I don't know how
to make variables known inside the inner function. It seems just using the
names there overrides the outside names. It also seems that local variables
are in some kind of dictionary; so maybe you can access them through that
somehow.

One other solution (a bit ugly) would be to make this a class with two
static methods (breakLine and _addTok) and two static attributes (_ls and
_tok).

Still another (also ugly) would be to pass both tok and ls to addTok() and
pass tok back out again. (I think ls doesn't have to be passed back,
because it is a list and so its data gets modified. tok's data doesn't get
modified, so local changes don't propagate to the outside.)

Gerhard

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


Ann: Crunchy Frog 0.6

2006-07-21 Thread André
Crunchy Frog (version 0.6) has been released.

Crunchy Frog is an application that transforms an html-based Python
tutorial into an interactive session within a browser window.  The
interactive embedded objects include:
* a Python interpreter;
* a simple code editor, whose input can be executed by Python;
* a special "doctest" mode for the code editor;
* a graphics canvas which can be drawn upon using a simple api.
* simple sounds can be generated and played with all of the above.

A comprehensive set of examples are included in the package, as well
as two "standard Python tutorials" (mini-sorting HowTo, and regular
expression HowTo) which have been adapted for use with Crunchy Frog.

Requirements:
Python 2.4+ (it might work, but has not been tested with earlier
versions)
Elementtree; (a link is provided in the included docs)
Firefox 1.5+

The website address is http://crunchy.sourceforge.net
The files can be downloaded from
http://sourceforge.net/project/showfiles.php?group_id=169458

André and Johannes

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


Re: regular expression - matches

2006-07-21 Thread John Machin
On 22/07/2006 9:25 AM, John Machin wrote:

Apologies if this appears twice ... post to the newsgroup hasn't shown 
up; trying the mailing-list.

> On 22/07/2006 2:18 AM, Simon Forman wrote:
>> John Salerno wrote:
>>> Simon Forman wrote:
>>>
 Python's re.match() matches from the start of the string,  so if you
> 
> (1) Every regex library's match() starts matching from the beginning of 
> the string (unless of course there's an arg for an explicit starting 
> position) -- where else would it start?
> 
> (2) This has absolutely zero relevance to the "match whole string or 
> not" question.
> 
 want to ensure that the whole string matches completely you'll probably
 want to end your re pattern with the "$" character (depending on what
 the rest of your pattern matches.)
> 
> *NO* ... if you want to ensure that the whole string matches completely, 
> you need to end your pattern with "\Z", *not* "$".
> 
> Perusal of the manual would seem to be indicated :-)
> 
>>> Is that necessary? I was thinking that match() was used to match the
>>> full RE and string, and if they weren't the same, they wouldn't match
>>> (meaning a begin/end of string character wasn't necessary). That's 
>>> wrong?
> 
> Yes. If the default were to match the whole string, then a metacharacter 
> would be required to signal "*don't* match the whole string" ... 
> functionality which is quite useful.
> 
>>
>> My understanding, from the docs and from dim memories of using
>> re.match() long ago, is that it will match on less than the full input
>> string if the re pattern allows it (for instance, if the pattern
>> *doesn't* end in '.*' or something similar.)
> 
> Ending a pattern with '.*' or something similar is typically a mistake 
> and does nothing but waste CPU cycles:
> 
> C:\junk>python -mtimeit -s"import 
> re;s='a'+80*'z';m=re.compile('a').match" "m(s)"
> 100 loops, best of 3: 1.12 usec per loop
> 
> C:\junk>python -mtimeit -s"import 
> re;s='a'+8000*'z';m=re.compile('a').match" "m(s)"
> 10 loops, best of 3: 1.15 usec per loop
> 
> C:\junk>python -mtimeit -s"import 
> re;s='a'+80*'z';m=re.compile('a.*').match" "m(s)"
> 10 loops, best of 3: 1.39 usec per loop
> 
> C:\junk>python -mtimeit -s"import 
> re;s='a'+8000*'z';m=re.compile('a.*').match" "m(s)"
> 1 loops, best of 3: 24.2 usec per loop
> 
> The regex engine can't optimise it away because '.' means by default 
> "any character except a newline" , so it has to trundle all the way to 
> the end just in case there's a newline lurking somewhere.
> 
> Oh and just in case you were wondering:
> 
> C:\junk>python -mtimeit -s"import 
> re;s='a'+8000*'z';m=re.compile('a.*',re.DOTALL).match" "m(s)"
> 100 loops, best of 3: 1.18 usec per loop
> 
> In this case, logic says the '.*' will match anything, so it can stop 
> immediately.
> 
>>
>> I'd test this, though, before trusting it.
>>
>> What the heck, I'll do that now:
>>
> import re
> re.match('ab', 'abcde')
>> <_sre.SRE_Match object at 0xb6ff8790>
> m = _
> 
> ??? What's wrong with _.group() ???
> 
> m.group()
>> 'ab'
> print re.match('ab$', 'abcde')
>> None
>>
> 
> HTH,
> John
> 
> 
> 

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


Nested function scope problem

2006-07-21 Thread Josiah Manson
I found that I was repeating the same couple of lines over and over in
a function and decided to split those lines into a nested function
after copying one too many minor changes all over. The only problem is
that my little helper function doesn't work! It claims that a variable
doesn't exist. If I move the variable declaration, it finds the
variable, but can't change it. Declaring the variable global in the
nested function doesn't work either.

But, changing the variable in the containing scope is the whole purpose
of this helper function.

I'm new to python, so there is probably some solution I haven't
encountered yet. Could you please suggest a nice clean solution? The
offending code is below. Thanks.

def breakLine(s):
"""Break a string into a list of words and symbols.
"""
def addTok():
if len(tok) > 0:
ls.append(tok)
tok = ''

ls = []
tok = ''
splitters = '?()&|:~,'
whitespace = ' \t\n\r'

for c in s:
if c in splitters:
addTok()
ls.append(c)
elif c in whitespace:
addTok()
else:
tok = tok + c

addTok()

return ls

#some tests to make sure it works
print breakLine('carolina(Prada):cat(X,Y)')
print breakLine('trouble :bird (X ) &cat ( Y )')
print breakLine('?trouble')

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


Re: How to recognise "generator functions" ?

2006-07-21 Thread John J. Lee
imho <[EMAIL PROTECTED]> writes:

> Georg Brandl ha scritto:
> 
>  f.func_code.co_flags
> > 67
>  g.func_code.co_flags
> > 99
> > => 32 (CO_GENERATOR in compiler.consts) is the flag that indicates a
> > generator code object.
> > Georg
> 
> What a fast reply!
> Thank You very much! :-)

Georg, that was cruel <0.2 wink>

Seriously, does anybody have any sensible reason to *use* this
information?  Maybe some dynamic code-analysis tool or something?


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


Python newbie needs constructive suggestions

2006-07-21 Thread davew-python
What is the idiomatically appropriate Python way to pass, as a "function-type 
parameter", code that is most clearly written with a local variable?

For example, map takes a function-type parameter:

   map(lambda x: x+1, [5, 17, 49.5])

What if, instead of just having x+1, I want an expression that is most clearly 
coded with a variable that is needed _only_ inside the lambda, e.g. if I wanted 
to use the name "one" instead of 1:

   map(lambda x: (one = 1  x+one), [5, 17, 49.5])

This sort of thing is of course straightforward in many other languages with 
anonymous functions (Scheme, Haskell, Smalltalk, etc), and I saw in the 
archives the discussion from 2003 about "How do I get Scheme-like let bindings 
in Python". Many of the answers seem to boil down to "You should not write 
Scheme programs in Python, you should write Python programs in Python". As 
someone new to Python, I'd like a little more detail on this, so I'm asking 
_what_ I should do when I want to pass, to something like map, code that is 
most clearly expressed with a local variable?

Do I

  a) give up on using a local variable and just substitute the value in its 
place (going back to my original use of map),

  b) give up on using an anonymous function and create a named "successor" 
function with "def",

  c) give up on making "one" local to the lambda and create it in the scope in 
which I'm calling map, even if I don't otherwise need it there,

  d) give up on using Python and go back to Scheme, or

  e) do something else clever and Pythonic that I don't know about yet?

What is the idiomatically correct way to do this in Python?

Thanks for any constructive advice you can give,
Dave Wonnacott


P.S., For those who want a bit more context about what I'm doing, I'll provide 
it -- anyone else is welcome to skip the rest of this message.


As you may guess, I am in the process of learning Python. I have some 
experience with C/C++ and Scheme and other forms of Lisp, as well as passing 
familiarity with a bunch of other languages.

I teach an introductory CS course in which I cover a variety of topics that I 
believe are central to computer science and can be expressed in any language, 
such as algorithm design, unit and integration testing, writing code that 
maintains an invariant property of a set of variables. However, I do not like 
the "language-free" or "all-pseudocode" approach to teaching -- I believe all 
examples should be shown in a real language, and that the code should be as 
true to the customary idioms of that language as possible. This limits my 
choice of language somewhat, since I include elements of functional 
programming, imperative programming, and object-oriented programming -- I'm not 
happy doing things like cramming functions into unnecessary classes in Java. 
However, I currently believe that Python will be at least as good as C++ for 
what I want to do, and am exploring the details of how it would work out.

One of the things I'm doing is discussing various styles of thinking about the 
execution of an algorithm, specifically as a process of textual substitution of 
equals for equals (as one would generally do in Haskell or other functional 
languages, or in mathematics) or a sequence of ordered steps to be followed (as 
one would generally do in imperative languages). Note that, while Haskell 
programmers may say that substitution is the true way that their programs are 
executed, and C++ programmers may say that a sequence of ordered steps is 
what's "really going on", the actual process of going from your source code to 
the output of your program can be blending of these two techniques -- for 
example, a C++ compiler may perform substitution where it is legal to do so, 
producing a machine language program that is executed _mostly_ in order (though 
a processor may commute the order of execution where it is legal to do so). 
Anyway, in almost any language, there are _some_ ways to perfo!
 rm substitutions without changing the result of a piece of code (e.g. 
substituting the value of a variable that is only assigned once, for each of 
its uses), and some things that can be visualized in terms of execution of 
steps even if one wishes to do so (even in a language like Haskell).

The question of the use of variables inside a lambda is relevant to my 
understanding of the contexts in which one can think of Python programs in 
terms of substitution, as well as my learning of proper Python idioms.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Application Generators

2006-07-21 Thread Steve Hannah

I know that this is an older thread, but I came across it on Nabble.com. 
Just wanted add some updated info on Walter's observations about Dataface
(http://fas.sfu.ca/dataface) .  It is much further along in development now
and it does support authentication now. 

Just wanted to follow this up in case people come across this post.

Best regards

Steve Hannah

walterbyrd-2 wrote:
> 
> In case anybody is interested, here is an update on my reviews for code
> generators:
> 
> AppGini & PHPMagic. ($35 - $70) Cheap and easy to use,   but not very
> functional. Okay if you are making flat-file, unsecure, CRUD. No
> authentication. No real relational functionallity. No event triggers.
> 
> PHPRunner. ($199). Some authentication, but only one level. Some
> relational capabilities, not great. Event triggers. Fairly easy to use,
> but if you want to relate two or  more tables, you have to hand code
> the sql, which sort of defeats the purpose.
> 
> dbQwikSite ($140 - $200). Slow and diffecult to work with. In fact, I
> couldn't get it to work at all.
> 
> dataface (free). Interesting new project. Huge potential. But, not
> really completed yet. Relational capabilities, and has event triggers.
> No authentication yet. Not easy to work with.
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
-- 
View this message in context: 
http://www.nabble.com/Application-Generators-tf1380271.html#a5441842
Sent from the Python - python-list forum at Nabble.com.

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


Re: Isn't there a better way?

2006-07-21 Thread John J. Lee
Peter Otten <[EMAIL PROTECTED]> writes:
[...]
> Not sure if this is better, but you can use OptionParser to set attributes
> on arbitrary objects, including your Processor instance:
[...]

I'd guess it's not worth the mental overhead required when you
discover the next argument no longer fits this scheme.  Or the mess
when you start lying to yourself about what the interface of Processor
should be, just so you can implement it like this.

Still, better than just passing 'options' (from options, args =
parser.parse_args()) to all your functions / classes, which... well,
only makes sense if you get paid by the hour, and think that way, too
;-)


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


Re: How to automate user input at the command prompt?

2006-07-21 Thread M�ta-MCI
Hi!

I had try with pipes & subprocess. Unfortunaly, when dos-commandline show a 
text who question for Yes/No, this text is not available in subprocess/pipe 
;  => and block!
And then, I can't send "Y" to the stdin...

I test with:
 MD  TOTO
 RD  TOTO/S

(I know,  RD TOTO/S/Q run Ok, but I search another solution).

*sorry for my bad english*

Michel Claveau






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


Re: An optparse question

2006-07-21 Thread John J. Lee
"T" <[EMAIL PROTECTED]> writes:
[...]
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:
> 
> % myprog.py -h
>  THIS IS NEWLY INSERTED STRING 
> usage: myprog.py [options] input_file
> 
> 
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file

HelpFormatter is what you need.  Seems undocumented in the official
docs, but doesn't look risky to use (famous last words).  Seems just
that nobody got around to documenting it.

import optparse

class NonstandardHelpFormatter(optparse.HelpFormatter):

def __init__(self,
 indent_increment=2,
 max_help_position=24,
 width=None,
 short_first=1):
optparse.HelpFormatter.__init__(
self, indent_increment, max_help_position, width, short_first)

def format_usage(self, usage):
return " THIS IS NEWLY INSERTED STRING \nusage: 
%s\n" % usage

def format_heading(self, heading):
return "%*s%s:\n" % (self.current_indent, "", heading)

parser = optparse.OptionParser(
usage="%prog [options] input_file",
formatter=NonstandardHelpFormatter())
parser.parse_args()


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


Re: How to automate user input at the command prompt?

2006-07-21 Thread Roger Upole
If you have the Pywin32 extensions installed, you can use the
win32console module to send keystrokes directly to a command
prompt via WriteConsoleInput.

Roger

<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>
> I'm working on a scirpt to be used on a windows machine and I need to
> automate a user's input on the command prompt.  For example I'm using
> os.system('mycommand') to excute the commands I want.  However some of
> these command will prompt for a confirmation of yes or no from user.
> Is there anything in python that will allow my script to automate these
> input
> Another example is let  say if i type "format c:\" on the command
> prompt it will warn me and ask me to type 'y' to continue.  I can use
> the os.system to automate the "format c:\" but is there a way to
> automate the 'y' input part.  I try searching for help on the Interent
> but cant seem find any info on how to do this with Python.  Can someone
> give me some confirmation if what I want to do is possible or not.
> Thanks in advance for any help.
> 


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


Re: How to automate user input at the command prompt?

2006-07-21 Thread Gerhard Fiedler
On 2006-07-21 19:39:52, [EMAIL PROTECTED] wrote:

> Cameron Laird wrote:
>> I suspect there are easier approaches--but probably won't have time
>> before Monday to explain.  For now, I counsel the original poster
>> not to be discouraged.
> 
> Although I have not find the solution I need yet, thanks to the
> suggestions so far I'm actually a bit more optimistic than before that
> there might actually be a way to do what I want.

Until Cameron explains... maybe you can work out something with pipes (on
the program's stdin, stdout and stderr). Not sure how that would look like
in Python, though, and it almost for sure won't work with all command line
programs. (There are different ways how a program can read user input.)

Gerhard

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread gert365

Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >
> >In that case, the OP can probably use cygwin's version of python.
> >pexpect definitely works there.
>   .
>   .
>   .
> I suspect there are easier approaches--but probably won't have time
> before Monday to explain.  For now, I counsel the original poster
> not to be discouraged.

Although I have not find the solution I need yet, thanks to the
suggestions so far I'm actually a bit more optimistic than before that
there might actually be a way to do what I want.

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>In that case, the OP can probably use cygwin's version of python.
>pexpect definitely works there.
.
.
.
I suspect there are easier approaches--but probably won't have time
before Monday to explain.  For now, I counsel the original poster
not to be discouraged.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Track keyboard and mouse usage

2006-07-21 Thread [EMAIL PROTECTED]
Hello dfaber,

I had the same problem not long ago. I tried to use the Xlib since its
obvious the X server  has all the events but I couldn't have the mouse
events if my app was out of focus. If you have a way to do that I'm
really interested.

Anyway I found this to be a good introduction to Xlib:
http://users.actcom.co.il/~choo/lupg/tutorials/xlib-programming/xlib-programming.html#preface

Since I didn't find a way to do it I went down to the source of the
events which are provided by the evdev drivers:
http://en.wikipedia.org/wiki/Evdev

Fortunately you can use Python to access it:
http://svn.navi.cx/misc/trunk/python/evdev/

First you need to know your input devices, search the eventX in
relation to your device here:
cat /proc/bus/input/devices

Then you can do:
sudo python evdev.py /dev/input/eventX  # where X is the event number
in relation to your device (kb is usually zero)

It works well but there is two problems with this solution:
- the root access is annoying (but I'll have to try Diez suggestion)
- The X event number of the mouse can change from a PC to another one
(you need to check the PC first with that cat command and search for
your "mouse"

francois





dfaber wrote:
> Hi all,
>  I have been searching for a keyboard and mouse tracker on linux. I've
> read solutions (watch at sourceforge) which look at /proc/interrupts to
> check keyboard or mouse activity. I also read one post where "watch"
> seems to have difficulty tracking usb keyboards and mice. So, I'm out
> of ideas here.
>
> My goal are:
> 1. Check keyboard activity. I'm not interested in logging which keys
> are pressed or record them.
> 2. Monitor mouse activity. I want to know the pointer position,
> left-clicks, right-clicks, middle-mouse button usage.
>
> I know that these things can be done in a GUI environment. I am looking
> for some approach that helps me do this system-wide.
>
> Any suggestions would be welcome. Again, I am looking for trackers on
> Linux based machines.

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


OT Re: getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread David Reed

On Jul 21, 2006, at 4:20 PM, Steve M wrote:

> In case you haven't heard Microsoft is suing SCO for stealing his
> Internet concepts and letters and numbers, so you should probably just
> ditch OpenServer and get Debian like all the smart people have done.
>
> I guess the quality of SCO software has declined over the last  
> forty or
> fifty years and they had to have David Boies compile libsocket and  
> that
> is probably why this broken symbol problem is happenig.
>
> I'm sorry if you cannot switch from the SCO platform, in which case
> this message may not be very helpful. Have a nice day!

This is way off-topic, but it's SCO that is suing IBM and IBM  
countersuing SCO. It appears that Microsoft was helping bankroll  
SCO's lawsuit. If you want to see how it's going, look at a graph of   
the SCOX (the ticker symbol) stock price since 2003 (paying close  
attention to the more recent price as the judge has started ruling on  
discovery issues). It was in 2003 when they started claiming everyone  
using Linux owed them money and they sued IBM for billions of  
dollars. Also see groklaw.net if you really want to know more about  
it. In the interest of full disclosure, I made money shorting SCOX  
stock from mid 2003 to mid 2004 (borrowed and sold at $11, bought  
back at $5).

Dave

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


Re: An optparse question

2006-07-21 Thread dan . gass

> Nope.  That only *nearly* does what T wants.  The usage message will
> still be printed immediately *after* the 'usage: ' string.
>
> >>> parser = OptionParser(usage=usage)
> >>> parser.print_help()
> usage:  THIS IS NEWLY INSERTED STRING
> usage: lopts.py [options] input_file
>
> options:
>   -h, --help  show this help message and exit

Yes, I see what T meant now.  Behavior expectations (assumptions) has a
way of clouding one's vision.

Thanks

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


Re: An optparse question

2006-07-21 Thread Steve Holden
T wrote:
> fuzzylollipop wrote:
> 
>>you can make the usage line anything you want.
>>
>>...
>>usage = 'This is a line before the usage line\nusage %prog [options]
>>input_file'
>>parser = OptionsParser(usage=usage)
>>parser.print_help()
>>...
>>
> 
> 
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:
> 
> % myprog.py -h
>  THIS IS NEWLY INSERTED STRING 
> usage: myprog.py [options] input_file
> 
> 
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file
> 
Do a Google search for "monkey patching". You probably want to 
monkey-patch the class's usage method.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: random shuffles

2006-07-21 Thread Raymond Hettinger

Boris Borcic wrote:
> does
>
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?
>
> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort, I'd say the answer is yes. But I don't feel quite 
> confortable
> with the intuition... can anyone think of a more solid argumentation ?


Try this:

x.sort(key=lambda x: random.random())


Raymond

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


Re: Coding style

2006-07-21 Thread Bruno Desthuilliers
Lawrence D'Oliveiro a écrit :
> In message <[EMAIL PROTECTED]>, Georg Brandl wrote:
> 
> 
(snip)

>>Other than in PHP, Python has clear rules when an object of a builtin type
>>is considered false (i.e. when it's empty). So why not take advantage of
>>this?
>  
> Because the clearest rule of all is that True is true, and False is false,
> and that's all I want to have to remember.

I somewhat agree with Laura Craighton (cf Donn's post above in this 
thread). Things were clearer when there was no boolean type in Python, 
and we just had the difference between 'nothing' (empty sequence, zero 
numeric, None) and 'something' (almost anything else).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread Simon Forman

John Salerno wrote:
> Thanks guys!

A pleasure.  : )

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


Re: An optparse question

2006-07-21 Thread Simon Forman
[EMAIL PROTECTED] wrote:
> > No, that affects the string printed only *after* the "usage = " string.
> >  What I would like to do is insert some string *before* the "usage = "
> > string, which is right after the command I type at the command prompt.
> > So I would like to make it look like this:
>
> The example was fine (except for a typo) as far as demonstrating the
> concept.  Try this corrected version:
>
> from optparse import OptionParser
>
> usage = ' THIS IS NEWLY INSERTED STRING
> \nusage: %prog [options] input_file'
> parser = OptionParser(usage=usage)
> parser.print_help()

Nope.  That only *nearly* does what T wants.  The usage message will
still be printed immediately *after* the 'usage: ' string.

>>> parser = OptionParser(usage=usage)
>>> parser.print_help()
usage:  THIS IS NEWLY INSERTED STRING
usage: lopts.py [options] input_file

options:
  -h, --help  show this help message and exit


I had the same problem, and in order to get something printed before
the usage message, I found one easy-ish way was to subclass the
Formatter passed in to the Parser.

IMHO, optparse does a tricky task well, but it's implemented in a hard
to follow, inflexible manner.  My "favorite" pet peeve is that the
options "dictionary" it returns isn't a dict.  I wound up doing this to
it to get something [I considered] useful:

o, a = parser.parse_args()
o = o.__dict__.copy()


Peace,
~Simon

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


using array as execute parameter in dbapi

2006-07-21 Thread gglegrp112
Is it possible to send an array as a parameter for an execute method in
dbapi2 module?


I'm using adodbapi and try to perfrom the following SQL query:
 select * from item where storeid in ('01', '02')

When I use direct string formating it works:

 a=('01','02')
cur.execute('select * from item where storeid in %s' % a.__repr__())

but trying to use parameter does not work:

 cur.execute('select * from item where storeid in ?', a)
 cur.execute('select * from item where storeid in ?', (a,))
 cur.execute('select * from item where storeid in ?', ([a],)

and even this does not work:
 cur.execute('select * from item where storeid in ?', a.__repr__())
 cur.execute('select * from item where storeid in ?',
(a.__repr__(),))

surprisingly, this get executed be returns wrong result:
 cur.execute('select * from item where storeid in (\'?\'),
"','".join(a))
I guess the question mark gets escaped by the quotes the parameter is
ignored.

Regards,

Magdy Salam

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


Re: An optparse question

2006-07-21 Thread Simon Forman
T wrote:
> fuzzylollipop wrote:
> >
> > you can make the usage line anything you want.
> >
> > ...
> > usage = 'This is a line before the usage line\nusage %prog [options]
> > input_file'
> > parser = OptionsParser(usage=usage)
> > parser.print_help()
> > ...
> >
>
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:
>
> % myprog.py -h
>  THIS IS NEWLY INSERTED STRING 
> usage: myprog.py [options] input_file
>
>
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file

It's possible, but it ain't easy:

from optparse import OptionParser, _, IndentedHelpFormatter

class MyFormatter(IndentedHelpFormatter):
pre_usage = "Hi there!\n"
def format_usage(self, usage):
return _("%susage: %s\n") % (self.pre_usage, usage)

parser = OptionParser(formatter=MyFormatter())


The above filthy hack will print "Hi there!" before the usual usage
message.

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread [EMAIL PROTECTED]

In that case, the OP can probably use cygwin's version of python.
pexpect definitely works there.

Mike Kent wrote:
> [EMAIL PROTECTED] wrote:
> > You may want to look at pexpect:
> >
> > http://pexpect.sourceforge.net/
> >
> > But I am not sure about its support on windows.
>
> To the best of my recent investigation, and an email exchange with the
> author of pexpect, it is NOT supported under Windows.

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


Re: An optparse question

2006-07-21 Thread dan . gass
> No, that affects the string printed only *after* the "usage = " string.
>  What I would like to do is insert some string *before* the "usage = "
> string, which is right after the command I type at the command prompt.
> So I would like to make it look like this:

The example was fine (except for a typo) as far as demonstrating the
concept.  Try this corrected version:

from optparse import OptionParser

usage = ' THIS IS NEWLY INSERTED STRING
\nusage: %prog [options] input_file'
parser = OptionParser(usage=usage)
parser.print_help()

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


Re: getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread Steve M
In case you haven't heard Microsoft is suing SCO for stealing his
Internet concepts and letters and numbers, so you should probably just
ditch OpenServer and get Debian like all the smart people have done.

I guess the quality of SCO software has declined over the last forty or
fifty years and they had to have David Boies compile libsocket and that
is probably why this broken symbol problem is happenig.

I'm sorry if you cannot switch from the SCO platform, in which case
this message may not be very helpful. Have a nice day!

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


Re: An optparse question

2006-07-21 Thread T
fuzzylollipop wrote:
>
> you can make the usage line anything you want.
>
> ...
> usage = 'This is a line before the usage line\nusage %prog [options]
> input_file'
> parser = OptionsParser(usage=usage)
> parser.print_help()
> ...
>

No, that affects the string printed only *after* the "usage = " string.
 What I would like to do is insert some string *before* the "usage = "
string, which is right after the command I type at the command prompt.
So I would like to make it look like this:

% myprog.py -h
 THIS IS NEWLY INSERTED STRING 
usage: myprog.py [options] input_file


options:
  -h, --help show this help message and exit
  -v, --verboseprint program's version number and exit
  -o FILE   Output file

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


Re: Note on PEP 299

2006-07-21 Thread bearophileHUGS
Faulkner:
> http://home.comcast.net/~faulkner612/programming/python/mainer.py

It's a bit of magic, I'll test it more, but it seems to work binding
the main() with Psyco too.
I have changed it a little (removed argv passed to the main and the
import of type, etc).
I don't know if/when I'll use it, but it seems nice enough.

Bye,
thank you,
bearophile

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


Re: How to automate user input at the command prompt?

2006-07-21 Thread Mike Kent

[EMAIL PROTECTED] wrote:
> You may want to look at pexpect:
>
> http://pexpect.sourceforge.net/
>
> But I am not sure about its support on windows.

To the best of my recent investigation, and an email exchange with the
author of pexpect, it is NOT supported under Windows.

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


Re: what's wrong with this if statement?

2006-07-21 Thread John Salerno
Philippe Martin wrote:

> Check the type of self.time: unicode - you need to convert it to int
> first ... plus your timer will need to be shutdown when you're done.

Ah, of course! Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to automate user input at the command prompt?

2006-07-21 Thread [EMAIL PROTECTED]

You may want to look at pexpect:

http://pexpect.sourceforge.net/

But I am not sure about its support on windows.

[EMAIL PROTECTED] wrote:
> I'm working on a scirpt to be used on a windows machine and I need to
> automate a user's input on the command prompt.  For example I'm using
> os.system('mycommand') to excute the commands I want.  However some of
> these command will prompt for a confirmation of yes or no from user.
> Is there anything in python that will allow my script to automate these
> input
> Another example is let  say if i type "format c:\" on the command
> prompt it will warn me and ask me to type 'y' to continue.  I can use
> the os.system to automate the "format c:\" but is there a way to
> automate the 'y' input part.  I try searching for help on the Interent
> but cant seem find any info on how to do this with Python.  Can someone
> give me some confirmation if what I want to do is possible or not.
> Thanks in advance for any help.

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


Re: An optparse question

2006-07-21 Thread fuzzylollipop

T wrote:
> I have a short program using optparse.OptionParser that prints out help
> message with -h flag:
>
> % myprog.py -h
> usage: myprog.py [options] input_file
>
> options:
>   -h, --help show this help message and exit
>   -v, --verboseprint program's version number and exit
>   -o FILE   Output file
>
>
> My question is, is there a way to print a blank line (or any string)
> before "usage: myprog.py [options] input_file" ?  I tried using
> callbacks without success.  I think somehow I need to modify the
> behavior of optparse.OptionParser.print_usage() function?

you can make the usage line anything you want.

...
usage = 'This is a line before the usage line\nusage %prog [options]
input_file'
parser = OptionsParser(usage=usage)
parser.print_help()
...

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


Re: what's wrong with this if statement?

2006-07-21 Thread Philippe Martin
John Salerno wrote:

> Here's the full code, but you can probably safely ignore most of it,
> especially the wxPython stuff:
> 
> ---
> 
> import wx
> 
> 
> class MyFrame(wx.Frame):
> 
>  def __init__(self):
>  wx.Frame.__init__(self, parent=None, id=wx.ID_ANY)
>  panel = wx.Panel(self)
> 
>  mainSizer = wx.BoxSizer(wx.VERTICAL)
>  inputSizer = wx.BoxSizer(wx.HORIZONTAL)
> 
>  self.count = 0
>  self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
>  self.status = wx.StaticText(panel, wx.ID_ANY, 'test')
>  prompt = wx.StaticText(panel, wx.ID_ANY, 'Time:')
>  self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
>  self.start = wx.Button(panel, wx.ID_ANY, 'Start')
>  self.timer = wx.Timer(self)
> 
>  mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.TOP,
> border=10)
>  mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL,
> border=10)
>  mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER)
>  inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
>  inputSizer.Add(self.input, flag=wx.ALL, border=10)
>  inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)
> 
>  self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
>  self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)
> 
>  panel.SetSizer(mainSizer)
> 
>  def OnStart(self, event):
>  self.time = self.input.GetValue()
>  self.timer.Start(1000)
> 
>  def OnTimer(self, event):
>  self.count += 1
>  if self.count < self.time:
>  self.progress.SetValue(self.count)
>  self.status.SetLabel(str(self.count))
> 
> 
> class MyApp(wx.App):
> 
>  def OnInit(self):
>  frame = MyFrame()
>  self.SetTopWindow(frame)
>  frame.Show()
>  return True
> 
> 
> if __name__ == '__main__':
>  app = MyApp(redirect=False)
>  app.MainLoop()
> 
> 
> 
> The code in question is mainly this:
> 
> def OnTimer(self, event):
>  self.count += 1
>  if self.count < self.time:
>  self.progress.SetValue(self.count)
>  self.status.SetLabel(str(self.count))
> 
> When I run the program, the progress bar and the status label continue
> to increase even after self.count has (presumably) become larger than
> self.time. Why is this? All I do is enter in '10' as the value to test
> it, and it keeps counting even beyond 10.



Check the type of self.time: unicode - you need to convert it to int
first ... plus your timer will need to be shutdown when you're done.

Regards,

Philippe


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


An optparse question

2006-07-21 Thread T
I have a short program using optparse.OptionParser that prints out help
message with -h flag:

% myprog.py -h
usage: myprog.py [options] input_file

options:
  -h, --help show this help message and exit
  -v, --verboseprint program's version number and exit
  -o FILE   Output file


My question is, is there a way to print a blank line (or any string)
before "usage: myprog.py [options] input_file" ?  I tried using
callbacks without success.  I think somehow I need to modify the
behavior of optparse.OptionParser.print_usage() function?

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


Re: function v. method

2006-07-21 Thread fuzzylollipop

Antoon Pardon wrote:

> Suppose I am writing my own module, I use an underscore, to
> mark variables which are an implementation detail for my
> module.
>
> Now I need to import an other module in my module and need access
> to an implementation variable from that module. So now I have
> variables with an underscore which have two different meanings:

you don't understand what "implementation detail" means, it means it is
NOT part of the public API and no client code should ever use it.

If you reference _vara in your code and it is in someone elses module
you don't understand YOU ARE NOT SUPPOSED TO DO THAT!

>   1) This is an implemantation detail of this module, It is the
>  users of my module who have to be extra carefull using it.

Users of your module should NEVER KNOW any of the _ or __ stuff exists
to begin with.

>   2) This is an implemantation detail of the other module,
>  I should be extra carefull using it.

You should NEVER use it.

> And I find variable starting or ending with an underscore ugly. :-)
>
> --
> Antoon Pardon

But like my previous post states, you can mark stuff private in Java
all you want, you can still access. Having the compiler or runtime
enforce that just adds an extra step to turn that enforcement off.

You can do the same thing, in C++.

So WHY does a language need this enforcement.

And the "large code base" needs the "robustness" is not a valid
argument.

Since Apple has proven this NOT to be the case with Cocoa which is in
Objective-C and "knows about access control but doesn't really use
them"

Anyone that things a language HAS to have these constructs enforced by
the compiler or runtime, lacks disipline.

Python has exactly what every other language EFFECTIVELY has, a common
way to document  or "tag" what is _private but might need "Friend"
access, and what is REALLY __private.

If you don't like this, then that is your problem go use a language
that gives you that false sense of secuirty, don't expect it to change.

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


what's wrong with this if statement?

2006-07-21 Thread John Salerno
Here's the full code, but you can probably safely ignore most of it, 
especially the wxPython stuff:

---

import wx


class MyFrame(wx.Frame):

 def __init__(self):
 wx.Frame.__init__(self, parent=None, id=wx.ID_ANY)
 panel = wx.Panel(self)

 mainSizer = wx.BoxSizer(wx.VERTICAL)
 inputSizer = wx.BoxSizer(wx.HORIZONTAL)

 self.count = 0
 self.progress = wx.Gauge(panel, wx.ID_ANY, 100, size=(300, 20))
 self.status = wx.StaticText(panel, wx.ID_ANY, 'test')
 prompt = wx.StaticText(panel, wx.ID_ANY, 'Time:')
 self.input = wx.TextCtrl(panel, wx.ID_ANY, size=(20, 20))
 self.start = wx.Button(panel, wx.ID_ANY, 'Start')
 self.timer = wx.Timer(self)

 mainSizer.Add(self.progress, flag=wx.ALIGN_CENTER | wx.TOP, 
border=10)
 mainSizer.Add(self.status, flag=wx.ALIGN_CENTER | wx.ALL, 
border=10)
 mainSizer.Add(inputSizer, flag=wx.ALIGN_CENTER)
 inputSizer.Add(prompt, flag=wx.ALIGN_CENTER)
 inputSizer.Add(self.input, flag=wx.ALL, border=10)
 inputSizer.Add(self.start, flag=wx.ALIGN_CENTER)

 self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
 self.Bind(wx.EVT_BUTTON, self.OnStart, self.start)

 panel.SetSizer(mainSizer)

 def OnStart(self, event):
 self.time = self.input.GetValue()
 self.timer.Start(1000)

 def OnTimer(self, event):
 self.count += 1
 if self.count < self.time:
 self.progress.SetValue(self.count)
 self.status.SetLabel(str(self.count))


class MyApp(wx.App):

 def OnInit(self):
 frame = MyFrame()
 self.SetTopWindow(frame)
 frame.Show()
 return True


if __name__ == '__main__':
 app = MyApp(redirect=False)
 app.MainLoop()



The code in question is mainly this:

def OnTimer(self, event):
 self.count += 1
 if self.count < self.time:
 self.progress.SetValue(self.count)
 self.status.SetLabel(str(self.count))

When I run the program, the progress bar and the status label continue 
to increase even after self.count has (presumably) become larger than 
self.time. Why is this? All I do is enter in '10' as the value to test 
it, and it keeps counting even beyond 10.
-- 
http://mail.python.org/mailman/listinfo/python-list


On Computing and Its People

2006-07-21 Thread Xah Lee
Hi all,

in the past years, i have written few hundreds of essays and tutorials
on computing. Now, i've but a index page to this collection:
http://xahlee.org/Periodic_dosage_dir/skami_prosa.html

many of these, originated from online forum. The writing style is
enticing and the content astute.

also, as many of you may know, in the past month there's some
controversy regarding me, that resulted in a small web hosting company
kicking me out, giving the legal reason of _no reason_ as by the
contract agreement (with a 30 days notice in advance). I feel there's
some public obligation to give this update. More details is at
http://xahlee.org/Periodic_dosage_dir/t2/harassment.html

i have been busy in the past month so i haven't wrote anything new
(regarding computing). Recently i started to do Java again, and will
probably soon complete the other sections of this exposition:
What are OOP's Jargons and Complexities
http://xahlee.org/Periodic_dosage_dir/t2/oop.html

   Xah
   [EMAIL PROTECTED]
 ∑ http://xahlee.org/

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

Re: How to automate user input at the command prompt?

2006-07-21 Thread M�ta-MCI
Hi!

Same problem. I had search, long time, with popenX, with subprocess. I don't 
have, actually, any solution...

Suggestion: the first which finds prevents the others...

@+

Michel Claveau



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


How to automate user input at the command prompt?

2006-07-21 Thread gert365

I'm working on a scirpt to be used on a windows machine and I need to
automate a user's input on the command prompt.  For example I'm using
os.system('mycommand') to excute the commands I want.  However some of
these command will prompt for a confirmation of yes or no from user.
Is there anything in python that will allow my script to automate these
input
Another example is let  say if i type "format c:\" on the command
prompt it will warn me and ask me to type 'y' to continue.  I can use
the os.system to automate the "format c:\" but is there a way to
automate the 'y' input part.  I try searching for help on the Interent
but cant seem find any info on how to do this with Python.  Can someone
give me some confirmation if what I want to do is possible or not.
Thanks in advance for any help.

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


PyGTK Classes Problems

2006-07-21 Thread Tom Grove
I can't seem to get a function to continue after I call another gtk 
window class.  Basically I need to grab a date from a calendar in one 
windows and insert that value into an entry box on the calling window.

Calling Window:
import winCal

def getDate(self, widget):
cimsCal.winCal.dateSelected = 
"DATE"   

cimsCal.winCal()


print 
"TEST"  
  

self.wTree.get_widget("entDate").set_text(cimsCal.winCal.dateSelected)

WinCal Class:
#!/usr/bin/env python

import 
sys 
 

import 
pygtk   
 

import 
gtk 
 

import 
gtk.glade   
 




# Create a class which is the actual program to be 
run 
class 
winCal(gtk.Window): 
  

# 
Globals 
  

dateSelected = 
""  
 




# This is where we hook in our glade file and connect to the gui 
stuff 
def 
__init__(self): 


gladefile = 
"cimsGui/cimsgui.glade" 

self.windowname = 
"winCal" 
self.wTree = gtk.glade.XML(gladefile, 
self.windowname) 



# Create a dictionary of function 
calls
dic = { "on_calendar1_day_selected_double_click" : 
self.giveDate   

}   






self.wTree.signal_autoconnect(dic)  






gtk.main()  





# Start 
Functions   


def giveDate(self, 
widget): 

self.dateSelected = 
self.wTree.get_widget("calendar1").get_date()  

self.wTree.get_widget("winCal").destroy()   





if __name__ == 
'__main__': 
 

app = winCal()

After I do this cimsCal.winCal() the print "TEST" never happens.  What 
am I doing wrong.  

-- 
Tom Grove

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


Re: Isn't there a better way?

2006-07-21 Thread Bruno Desthuilliers
T wrote:
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()

> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

What's wrong with:

foo = Parse_Option()
bar = Processor()
bar.run(foo.options.index, foo.options.output)

-- 
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: using names before they're defined

2006-07-21 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi
> 
> 
(snip)
> 
def get_class_by_name(name):
 return globals()[name]
>>>
>>Q&D way to retrieve the class object (Python's classes are themselves
>>objects) known by it's name (as a string).
> 
> 
> ok, so it actually returns the class object itself.
> One thing that confuses me is that objects have a name (self.name)

They dont - unless you give them one:

>>> class Foo(object): pass
...
>>> Foo.name
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: type object 'Foo' has no attribute 'name'
>>> f = Foo()
>>> f.name
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'Foo' object has no attribute 'name'
>>>

classes, functions and modules have a __name__ attribute, but that's
something else...

> but
> object instances also have a name (e.g. myspecialturbine = turbine(...)

Actually, this is the other way round: names refers ('are bound to')
objects. Think of namespaces (the global or local one...) as dicts
holding name:ref-to-object pairs (that's mostly what they are FWIW).
Different names can refer to the same object. The object itself doesn't
know anything about this.

>  how do I discover the name 'myspecialturbine' ?). 

>From within the object refered by this name ? Short answer : you can't.

> And object
> instances have a class name too ('turbine'). 

Nope, they have a class, which itself as a __name__ attribute, which is
the name that was used when "creating" the class object (ie: usually
when the 'class' statement is eval'd at module load time).

> Aaargh, too many names!
> what if just want to know what the name of the instance is (in this
> case 'myspecialturbine'?)

you just named it so yourself, ie:
  myspecialturbine = SpecialTurbine()

Else, no way. You can of course give a name when instanciating the object:

class Named(object):
  def __init__(self, name):
self.name = name

n1 = Named('n1')
print n1.name
=> n1

But this doesn't mean there's any correspondance between this name and a
name in the current (or any other) namespace:

toto = n1
n1 = "lalala"
print toto.name
=> n1

locals()[toto.name] is toto
=> False


-- 
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: random shuffles

2006-07-21 Thread Paul Rubin
Boris Borcic <[EMAIL PROTECTED]> writes:
> To be more convincing... assume the algorithm is optimal and calls

That assumption is not even slightly realistic.  Real-world sorting
algorithms almost never do a precisely minimal amount of comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Design: list_for scope?

2006-07-21 Thread guthrie


Larry Bates wrote:

> First things first:
> 
> Don't name a variable "dict" because if you do it shadows
> the built in dict function (same goes for list, str, ...).
> This WILL bite you later, so start now by not naming
> variables by any built in names.
-- Thanks, got it!
> 
> Now to your question:
> 
> for x in : requires  be an iterable
> (e.g. list, tuple, iterable class instance, etc) so there
> is something that it can loop over one object at at time.
> 
> 
>>for x in [ x in dict if dict[x]=="thing" ]:
> 
> 
> needs to be written (if I'm understanding what you are
> doing) as:
> 
> for x in [x for x in d if d[x]=="thing"]:
-- Ywes, I understand the syntax, but think it is repetitive and cumbersome.

Just note the "for x in x for x in ..."
   no new semantics of the desired iteration set given, all redundant 
syntax.

I still wonder why one cannot qualify a for list iteration object with 
an list_if

Greg


>>For example;
>>Instead of;
>> for x in [ x in dict if dict[x]=="thing" ]:
>>in this:
>> for x in dict and dict[x]=="thing":
>>x is undefined.
>>
>>And why doesn't this work:
>>for x in dict if dict[x]=="thing":
>>
>>Any insights/hints on why it is broken?
>>
>>Thanks,
>>Gregory
>>
>>http://docs.python.org/ref/grammar.txt:
>>list_for ::=
>> "for" expression_list "in" testlist
>>  [list_iter]
>>testlist ::=
>> test ( "," test )* [ "," ]
>>list_iter ::=
>> list_for | list_if
>>list_if ::=
>> "if" test [list_iter]
>>
>>
>>== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet
>>News==
>>http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
>>Newsgroups
>>= East and West-Coast Server Farms - Total Privacy via Encryption =


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Isn't there a better way?

2006-07-21 Thread T

T wrote:
> > I don't know what both classes do [snip]
>
> foo basically gets values for verbose (a True or False) and index (an
> integer) from command line options, using
> optparse.OptionParser.add_option() and
> optparse.OptionParser.parse_args()
>
> I would like bar to access the values of verbose and index.  Is there
> another way?

Sorry... I meant to say:

"foo basically gets values for index (an integer) and output (a string)"

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


Re: function v. method

2006-07-21 Thread Gerhard Fiedler
On 2006-07-20 18:10:21, danielx wrote:

>>> When supporting documents aren't sufficient to learn an api (I'm sure
>>> this never happens, so just humor me), you can always turn to
>>> interactive Python.
>>
>> ...and source code...
> 
> *shudders* What happened to all the goodness of abstraction?

Abstraction as you seem to use it requires complete docs of the interface.
Which is what you said you don't have... So the original abstractor broke
the abstraction when publishing insufficient docs, not the one who looks
into the sources to find out what actually happens. 

(This independently of the merits of abstraction.)

Gerhard

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


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 
> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

To be more convincing... assume the algorithm is optimal and calls
cmp(x,y). Either the previous calls (+ assuming order relation) give no 
conclusion as to the possible result of the call, in which case the result 
can't 
contradict an order relation; or the previous calls (+assumption) provide only 
partial information; iow the algorithm knows for example x<=y and needs to 
determine which of xy".

But is it possible for a sort algorithm assuming an order relation to attain eg 
x<=y but neither xhttp://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-21 Thread Gerhard Fiedler
On 2006-07-21 09:00:43, Antoon Pardon wrote:

> So we have code with certain shudder characteristics. And instead
> of trying to help the OP with his problem, some people react
> to the shudder and come with all sort of comments that might be
> true if the code as shown was production code, but which totally
> miss the point the code was illustrating and thus aren't much
> helpfull.

In general, I'd say that in this case the example was not well-chosen.
After such a "shudder removal", a poster should IMO review what caused the
shudder, and rephrase the original problem without the shudder. That might
take a few iterations, but in general, either one or more of the "shudder
removals" actually address the OP's issue, maybe without any individual
helper understanding all of the problem (due to incomplete example code),
or the iterations lead to a code that's "shudder free" and still shows the
original problem -- now usually in a clearer form, because free of other
issues that are not relevant to the OP's point.

E.g. if someone makes a suggestion that is valid with the example code I
posted but not with the real code I have, I need to post an updated example
code that introduces a restriction similar to the one I actually have,
which then correctly invalidates the formerly valid suggestion -- and helps
getting more helpful responses. This is a process that in the past has
taught me a lot (not Python, but that's just because I'm too new here :).
Once you get good at this process, it often helps you find the problem even
before posting, because boiling code down to what the /real/ problem is can
show you a lot you otherwise miss.

(In case that sounds too general -- it is . But it answers a general
point...)

Gerhard

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


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 

read "by /the assumption of an order relation/ and previous comparisons"

> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

- this - the idea that /if/ the algorithm was optimal it would only sample the 
random comparison function up to a system of answers consistent with an order 
relation - is actually what prompted my question,
iow "is it good for anything ?"

Best, BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Design: list_for scope?

2006-07-21 Thread Paddy

guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
>
> Q: What is the scope of the testlist in a list_for?
>
> For example;
> Instead of;
>   for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>   for x in dict and dict[x]=="thing":
> x is undefined.
>
> And why doesn't this work:
>   for x in dict if dict[x]=="thing":
>
> Any insights/hints on why it is broken?
>
> Thanks,
> Gregory
> 
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>   "for" expression_list "in" testlist
>[list_iter]
> testlist ::=
>   test ( "," test )* [ "," ]
> list_iter ::=
>   list_for | list_if
> list_if ::=
>   "if" test [list_iter]
>
>
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =

It is hard to answer your "Why doesn't this wirk question|", and it
must be hard to approach Python as a new user by looking at the
grammer.
Why not try looking at examples, trying them out in the Idle IDE, and
only then compare  your working examples to the grammer?

Here is a page with examples you could type in or vary in the
interpreter:

http://nltk.sourceforge.net/tutorial/advpython/nochunks.html#list_comprehensions

Cheers, Paddy.

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


Re: Language Design: list_for scope?

2006-07-21 Thread Larry Bates
First things first:

Don't name a variable "dict" because if you do it shadows
the built in dict function (same goes for list, str, ...).
This WILL bite you later, so start now by not naming
variables by any built in names.

Now to your question:

for x in : requires  be an iterable
(e.g. list, tuple, iterable class instance, etc) so there
is something that it can loop over one object at at time.

>for x in [ x in dict if dict[x]=="thing" ]:

needs to be written (if I'm understanding what you are
doing) as:

for x in [x for x in d if d[x]=="thing"]:

[ x for x in dict if dict[x]=="thing" ] is a list
comprehension that will resolve to a list of keys from the
dictionary where the values are "thing".  This way
the result of the list comprehension is a list which is
something the outside for loop can iterate over.

Example:

>>> d={1:'x',2:'thing',3:'thing',4:'thing',5:'thing', \
   6:'z',7:'thing',8:'thing',9:'y'}

>>> [x for x in d if d[x]=="thing"]
[2, 3, 4, 5, 7, 8]

-Larry Bates


guthrie wrote:
> I'm pretty new to Python, and trying to parse the grammar.
> 
> Q: What is the scope of the testlist in a list_for?
> 
> For example;
> Instead of;
>  for x in [ x in dict if dict[x]=="thing" ]:
> in this:
>  for x in dict and dict[x]=="thing":
> x is undefined.
> 
> And why doesn't this work:
> for x in dict if dict[x]=="thing":
> 
> Any insights/hints on why it is broken?
> 
> Thanks,
> Gregory
> 
> http://docs.python.org/ref/grammar.txt:
> list_for ::=
>  "for" expression_list "in" testlist
>   [list_iter]
> testlist ::=
>  test ( "," test )* [ "," ]
> list_iter ::=
>  list_for | list_if
> list_if ::=
>  "if" test [list_iter]
> 
> 
> == Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet
> News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
> Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Semantics of propagated exceptions

2006-07-21 Thread Michael J. Fromberger
In article 
<[EMAIL PROTECTED]>,
 Thomas Lotze <[EMAIL PROTECTED]> wrote:

> Suppose you have a function f which, as part of its protocol, raises some
> standard exception E under certain, well-defined circumstances. Suppose
> further that f calls other functions which may also raise E. How to best
> distinguish whether an exception E raised by f has the meaning defined by
> the protocol or just comes from details of the implementation?

My recommendation is to define your own exception type(s), and have f 
raise it (them) for errors that are truly generated by f.  Or, if you 
really want to use one of the existing exception types, then perhaps you 
can catch the exceptions from functions called by f, within f itself, 
and raise some other error (or suppress the errors, if appropriate).

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Thanks for these details. BB

Tim Peters wrote:
> [ Boris Borcic]
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>
>> pick a random shuffle of x with uniform distribution ?
> 
> Say len(x) == N.  With Python's current sort, the conjecture is true
> if and only if N <= 2.
> 
>> Intuitively, assuming list.sort() does a minimal number of comparisons to
>> achieve the sort,
> 
> No idea what that could mean in a rigorous, algorithm-independent way.
> 
>> I'd say the answer is yes. But I don't feel quite confortable
>> with the intuition... can anyone think of a more solid argumentation ?
> 
> If a list is already sorted, or reverse-sorted, the minimum number of
> comparisons needed to determine that is N-1, and Python's current sort
> achieves that.  It first looks for the longest ascending or descending
> run.  If comparison outcomes are random, it will decide "yes, already
> sorted" with probability 1/2**(N-1), and likewise for reverse-sorted.
> When N > 2, those are larger than the "correct" probabilities 1/(N!).
> So., e.g., when N=3, the sort will leave the list alone 1/4th of the
> time (and will reverse the list in-place another 1/4th).  That makes
> the identity and reversal permutations much more likely than "they
> should be", and the bias is worse as N increases.
> 
> Of course random.shuffle(x) is the intended way to effect a
> permutation uniformly at random.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Paul Rubin wrote:
> Boris Borcic <[EMAIL PROTECTED]> writes:
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>> pick a random shuffle of x with uniform distribution ?
> 
> You really can't assume anything like that.  Sorting assumes an order
> relation on the items being sorted, which means if a < b and b < c,
> then a < c.  If your comparison operation doesn't preserve that
> property then the sort algorithm could do anything, including looping
> forever or crashing.

Not if it does the minimum number of comparisons to achieve the sort, in which 
case it won't ever call cmp() if the result is pre-determined by the order 
relation and previous comparisons, so that it will never get from this 
comparison function a system of answers that's not consistent with an order 
relation. That's obvious at least in the case where random.random() == 0.5 
never 
occurs (and at first sight even the latter case shouldn't change it).

Best, BB
--
"On naît tous les mètres du même monde"



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


Language Design: list_for scope?

2006-07-21 Thread guthrie
I'm pretty new to Python, and trying to parse the grammar.

Q: What is the scope of the testlist in a list_for?

For example;
Instead of;
  for x in [ x in dict if dict[x]=="thing" ]:
in this:
  for x in dict and dict[x]=="thing":
x is undefined.

And why doesn't this work:
for x in dict if dict[x]=="thing":

Any insights/hints on why it is broken?

Thanks,
Gregory

http://docs.python.org/ref/grammar.txt:
list_for ::=
  "for" expression_list "in" testlist
   [list_iter]
testlist ::=
  test ( "," test )* [ "," ]
list_iter ::=
  list_for | list_if
list_if ::=
  "if" test [list_iter]


== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread John Salerno
Simon Forman wrote:
> John Salerno wrote:
>> Simon Forman wrote:
>>
>>> Python's re.match() matches from the start of the string, so if you
>>> want to ensure that the whole string matches completely you'll probably
>>> want to end your re pattern with the "$" character (depending on what
>>> the rest of your pattern matches.)
>> Is that necessary? I was thinking that match() was used to match the
>> full RE and string, and if they weren't the same, they wouldn't match
>> (meaning a begin/end of string character wasn't necessary). That's wrong?
> 
> My understanding, from the docs and from dim memories of using
> re.match() long ago, is that it will match on less than the full input
> string if the re pattern allows it (for instance, if the pattern
> *doesn't* end in '.*' or something similar.)
> 
> I'd test this, though, before trusting it.
> 
> What the heck, I'll do that now:
> 
 import re
 re.match('ab', 'abcde')
> <_sre.SRE_Match object at 0xb6ff8790>
 m = _
 m.group()
> 'ab'
 print re.match('ab$', 'abcde')
> None
> 
> 
> Yup!  That's the case.
> 
> Peace,
> ~Simon
> 

Thanks guys!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread Simon Forman
John Salerno wrote:
> Simon Forman wrote:
>
> > Python's re.match() matches from the start of the string, so if you
> > want to ensure that the whole string matches completely you'll probably
> > want to end your re pattern with the "$" character (depending on what
> > the rest of your pattern matches.)
>
> Is that necessary? I was thinking that match() was used to match the
> full RE and string, and if they weren't the same, they wouldn't match
> (meaning a begin/end of string character wasn't necessary). That's wrong?

My understanding, from the docs and from dim memories of using
re.match() long ago, is that it will match on less than the full input
string if the re pattern allows it (for instance, if the pattern
*doesn't* end in '.*' or something similar.)

I'd test this, though, before trusting it.

What the heck, I'll do that now:

>>> import re
>>> re.match('ab', 'abcde')
<_sre.SRE_Match object at 0xb6ff8790>
>>> m = _
>>> m.group()
'ab'
>>> print re.match('ab$', 'abcde')
None


Yup!  That's the case.

Peace,
~Simon

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


Re: regular expression - matches

2006-07-21 Thread Steve Holden
John Salerno wrote:
> Simon Forman wrote:
> 
> 
>>Python's re.match() matches from the start of the string, so if you
>>want to ensure that the whole string matches completely you'll probably
>>want to end your re pattern with the "$" character (depending on what
>>the rest of your pattern matches.)
> 
> 
> Is that necessary? I was thinking that match() was used to match the 
> full RE and string, and if they weren't the same, they wouldn't match 
> (meaning a begin/end of string character wasn't necessary). That's wrong?

That's wrong. In this context match just means you got to the end of the 
pattern. However, if you don't want to add the "$" to the end of the 
patterns, you could instead check that

   m.endpos == len(s)

where m is the match object and s is the subject string.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Isn't there a better way?

2006-07-21 Thread Peter Otten
T wrote:

> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

Not sure if this is better, but you can use OptionParser to set attributes
on arbitrary objects, including your Processor instance:

>>> class Processor(object):
... def __init__(self):
... self.verbose = False
... self.index = 42
...
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option("-v", "--verbose", action="store_true")

>>> parser.add_option("-i", "--index", type="int")

>>> p = Processor()
>>> parser.parse_args(args=["-i75", "-v"], values=p)
(<__main__.Processor object at 0x40298e0c>, [])
>>> p.verbose, p.index
(True, 75)

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


Re: using names before they're defined

2006-07-21 Thread davehowey
Hi

> Also, I gave the example using Python code as 'config' format, but any
> structured enough text format could do, ie JSON, XML, or even ini-like:
>
> # schema.ini
> objects = turbine1, frobnicator2
>
> [turbine1]
> class=Turbine
> upstream=frobnicator2
> downstream=
>

yes, I like the idea of using .ini type file format or XML, very much.
There are parser available which will automatically building python
objects from this, won't they (like configparser)? I'll have to get
reading over the weekend...

> >>def get_class_by_name(name):
> >>  return globals()[name]
> >
>
> Q&D way to retrieve the class object (Python's classes are themselves
> objects) known by it's name (as a string).

ok, so it actually returns the class object itself.
One thing that confuses me is that objects have a name (self.name) but
object instances also have a name (e.g. myspecialturbine = turbine(...)
 how do I discover the name 'myspecialturbine' ?). And object
instances have a class name too ('turbine'). Aaargh, too many names!
what if just want to know what the name of the instance is (in this
case 'myspecialturbine'?)

Right. I'll have a go at pulling all this together over the weekend
hopefully. Hurrah! Thanks for all the help, to everyone.
Dave

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


Re: regular expression - matches

2006-07-21 Thread John Salerno
Simon Forman wrote:

> Python's re.match() matches from the start of the string, so if you
> want to ensure that the whole string matches completely you'll probably
> want to end your re pattern with the "$" character (depending on what
> the rest of your pattern matches.)

Is that necessary? I was thinking that match() was used to match the 
full RE and string, and if they weren't the same, they wouldn't match 
(meaning a begin/end of string character wasn't necessary). That's wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Isn't there a better way?

2006-07-21 Thread Steve Holden
T wrote:
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
> 
> 
> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???
> 
The standard way would be to have the Processor class's __init__() 
method take two arguments which it would then assign to the appropriate 
instance attributes. You could, of course, provide default values if you 
felt so inclined.

Then you could just use

bar = Processor(foo.options.index, foo.options.output)

or something similar. That's better anyway, as it seems to make the 
coupling more explicit. What would you do if the index and output values 
were just stored in plain variables?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Isn't there a better way?

2006-07-21 Thread T
> I don't know what both classes do [snip]

foo basically gets values for verbose (a True or False) and index (an
integer) from command line options, using
optparse.OptionParser.add_option() and
optparse.OptionParser.parse_args()

I would like bar to access the values of verbose and index.  Is there
another way?

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


Re: range() is not the best way to check range?

2006-07-21 Thread Steve Holden
Paul Boddie wrote:
[...]
> Regardless of whether myslice inherits from object or not, there's no
> persuading the interpreter that it is a genuine slice, and remember
> that we can't subclass slice (for some reason unknown). So, it would
> appear that the interpreter really wants instances from some specific
> set of types (presumably discoverable by looking at list_subscript in
> listobject.c) rather than some objects conforming to some interface or
> protocol, and perhaps it is implemented this way for performance
> reasons.
> 
> In any case, in the core of Python some types/classes are more equal
> than others, and for whatever reason the duck typing breaks down - a
> case of "malbik endar" [1] that you just have to be aware of, I
> suppose.
> 
  >>> class mySlice(types.SliceType):
  ...   pass
  ...
Traceback (most recent call last):
   File "", line 1, in 
TypeError: Error when calling the metaclass bases
 type 'slice' is not an acceptable base type
  >>>

Indeed.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: New to threads. How do they work?

2006-07-21 Thread Grant Edwards
On 2006-07-21, Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:
> In message <[EMAIL PROTECTED]>, gel
> wrote:
>
>> I am attempting to understand threads to use in a network app which I
>> am writing.
>
> It is written, somewhere in the philosophy of *nix programming, that threads
> are a performance hack, to be avoided wherever possible. Use processes in
> preference to threads.

I've never understood the aversion people seem to have to
threads.  Especially in Python they seem very straightforward
to use and easy to understand.  I find IPC between processes is
much more work to do and difficult to get right.

Maybe it's just because threads are what I'm used to, since
I've been using them for 20+ years -- most of the platforms for
which I write don't have "processes".

-- 
Grant Edwards   grante Yow!  INSIDE, I have the
  at   same personality disorder
   visi.comas LUCY RICARDO!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Paul Rubin
Boris Borcic <[EMAIL PROTECTED]> writes:
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
> pick a random shuffle of x with uniform distribution ?

You really can't assume anything like that.  Sorting assumes an order
relation on the items being sorted, which means if a < b and b < c,
then a < c.  If your comparison operation doesn't preserve that
property then the sort algorithm could do anything, including looping
forever or crashing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread James Oakley
On Friday 21 July 2006 10:57 am, abcd wrote:
> yea i saw thatguess I was trusting that my regex was accurate :)
> ...b/c i was getting a Matcher when I shouldnt have, but i found that
> it must be the regex.

http://kodos.sourceforge.net/

Makes regex generation and debugging much easier.

-- 
James Oakley
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Isn't there a better way?

2006-07-21 Thread rony steelandt
Le Fri, 21 Jul 2006 07:51:15 -0700, T a écrit :

> 
> I am using an optparse to get command line options, and then pass them
> to an instance of another class:
> 
> 
> 
> # Class that uses optparse.OptionParser
> foo = Parse_Option()
> 
> # Class that does the real work
> bar = Processor()
> 
> bar.index = foo.options.index
> bar.output  = foo.options.output
> bar.run()
> 
> 
> 
> This works, but it feels hokey or unnatural to "pass" data from one
> class to another.  Isn't there a better way???

I don't know what both classes do, but can this be a solution ?


class Processor(Parse_Option)
self.index = self.option.index
self.output = self.option.output

def run(self):
# code

bar.run()


Rony

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


Re: Note on PEP 299

2006-07-21 Thread faulkner
http://home.comcast.net/~faulkner612/programming/python/mainer.py
turns
if __name__ == '__main__': sys.exit(main(sys.argv))
into
import mainer

[EMAIL PROTECTED] wrote:
> I don't like much the syntax of:
> if __name__ == '__main__':
>
> Some time ago I have read this PEP:
> http://www.python.org/dev/peps/pep-0299/
>
> And why it was refused:
> http://mail.python.org/pipermail/python-dev/2006-March/062955.html
>
> I think the name of the standard main function may be just main(), so
> there isn't the problem with the import (and *maybe* the problem with
> multiple Python versions can be ignored with Python 3.0).
>
> If a module contains the main(), the main() is executed when the module
> is run alone. Otherwise you can import the module, with the main()
> function managed as a normal function.
> 
> Bye,
> bearophile

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


Re: Accessors in Python (getters and setters)

2006-07-21 Thread Ed Jensen
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Which puts us to the next question: the sealing itself doesn't do 
> anything to restrict the code, the SecurityManager does. Which AFAIK is 
> something hooked into the VM. Now, I'm not on sure grounds here on how 
> to altere its behaviour, but I'd say if we're talking me working on a 
> secure application that introduces its own SecurityManager, I'm still 
> the one in control. I could use your lib, turn off privacy, and fiddle 
> around.
> 
> If things were the other way round, and I'd have to work in a restricted 
> context, it actually might be that someone restricted private access 
> (because he owns the VM!). But then - he'd also be able to forbid 
> threading or file access or all kinds of things that I'd otherwise be 
> used to work with which will suddenly make my code burst in flames.
> 
> And if we are honest: the most problematic cases of abused code aren't 
> the ones of strangers exploiting your code, but instead your fellow 
> coders at the other department. Which most probably means that they 
> aren't restrained by security management anyway.
> 
> To summarize: it might be possible to jump through a few hoops to 
> increase the security. But in 99.9% of cases this doesn't happen, as it 
> would increase complexity by orders of magnitude - for a comparatively 
> small gain (talking about private declarations. The sandbox-restrictions 
> of Java for running applets certainly are worth it).

Interesting stuff!  And thanks for the link from your earlier post.

Where I work, this little discovery will actually help us stop jumping
through some hoops we've been jumping through to unit test private
methods.

It also gives us more to think about since we had been assuming
private could not be circumvented.

Thanks Diez.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Isn't there a better way?

2006-07-21 Thread T

I am using an optparse to get command line options, and then pass them
to an instance of another class:



# Class that uses optparse.OptionParser
foo = Parse_Option()

# Class that does the real work
bar = Processor()

bar.index = foo.options.index
bar.output  = foo.options.output
bar.run()



This works, but it feels hokey or unnatural to "pass" data from one
class to another.  Isn't there a better way???

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


Re: regular expression - matches

2006-07-21 Thread Simon Forman
abcd wrote:
> how can i determine if a given character sequence matches my regex,
> completely?
>
> in java for example I can do,
> Pattern.compile(regex).matcher(input).matches()
>
> this returns True/False whether or not input matches the regex
> completely.
>
> is there a matches in python?

Yes.  It's called match and it's in the re module
(http://docs.python.org/lib/module-re.html)

Python's re.match() matches from the start of the string, so if you
want to ensure that the whole string matches completely you'll probably
want to end your re pattern with the "$" character (depending on what
the rest of your pattern matches.)

HTH,
~Simon

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


Re: regular expression - matches

2006-07-21 Thread abcd
yea i saw thatguess I was trusting that my regex was accurate :)
...b/c i was getting a Matcher when I shouldnt have, but i found that
it must be the regex.

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


Re: ConfigParser: what read('non-existent-filename') returns in 2.3.x?

2006-07-21 Thread Chris Lambacher
On Thu, Jul 20, 2006 at 02:01:08PM -0700, Danil Dotsenko wrote:
> Chris Lambacher wrote:
> > On Thu, Jul 20, 2006 at 10:50:40AM -0700, Danil Dotsenko wrote:
> >> Wrote a little "user-friedly" wrapper for ConfigParser for a KDE's
> >> SuperKaramba widget.
> >> (http://www.kde-look.org/content/show.php?content=32185)
> >> 
> >> I was using 2.4.x python docs as reference and
> >> ConfigParser.read('non-existent-filename') returns [] in 2.4.x
> > http://docs.python.org/lib/RawConfigParser-objects.html
> > That agrees with the docs since read returns a list of successfully parsed
> > filenames.  Note the docs also say this was added in 2.4.
> 
> I just looked at the 
> http://www.python.org/doc/2.3.5/lib/RawConfigParser-objects.html
> (note the version number) and see the following:
> "If none of the named files exist, the ConfigParser instance will contain an
> empty dataset." Which to me means []. To the least of it, the statement
> should be clarified, but I would still kindly prefer to have someone
> respond / confirm the procedure bellow gives different results in 2.3.x.
That says nothing about the return value.  It says that the ConfigParser
object will contain an empty data set, ie:
config.sections() == []
NOT 
config.read(['doesnotexist.cfg']) == []

since config.read does not explicitly return anything, and therefore you get
None. 
> 
> >> >>> import ConfigParser
> >> >>> cfg = ConfigParser.ConfigParser()
> >> >>> a = cfg.read('adsfasfdasfd')
> >> >>> a, len(a), type(a)
> >> ([], 0, )
> 
> Thx in advance.
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression - matches

2006-07-21 Thread Tim Chase
abcd wrote:
> how can i determine if a given character sequence matches my regex,
> completely?
> 
> in java for example I can do,
> Pattern.compile(regex).matcher(input).matches()
> 
> this returns True/False whether or not input matches the regex
> completely.
> 
> is there a matches in python?

 >>> import re
 >>> 'match' in dir(re)
True
 >>> help(re.match)
Help on function match in module sre:

match(pattern, string, flags=0)
 Try to apply the pattern at the start of the string, returning
 a match object, or None if no match was found.


For more info, see

http://docs.python.org/lib/module-re.html

-tkc





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


regular expression - matches

2006-07-21 Thread abcd
how can i determine if a given character sequence matches my regex,
completely?

in java for example I can do,
Pattern.compile(regex).matcher(input).matches()

this returns True/False whether or not input matches the regex
completely.

is there a matches in python?

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


Re: range() is not the best way to check range?

2006-07-21 Thread Paul Boddie
Antoon Pardon wrote:
>

[Subclasses of list or slice for ranges]

> Except that if you write your own class from scratch, you can't use
> it as a slice. For a language that is supposed to be about duck typing
> I find it strange that if I make my own class with a start, stop and
> step attribute, that python barfs on it when I want to use it as a
> slice.

[s2 has start, stop, step...]

> >>> lst[s2]
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: list indices must be integers

In fact, the duck typing seems only to really work outside the
interpreter and the various accompanying built-in classes. Consider a
class similar to the one you defined with the name myslice (for
clarity) and with the apparently necessary indices method; consider it
used as follows:

>>> range(0, 10)[myslice(1, 5, 2)]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: list indices must be integers

Here, we start to believe that only traditional index or slice notation
will work. However, we did come across the built-in slice class before;
consider this:

>>> range(0, 10)[slice(1, 5, 2)]
[1, 3]

Regardless of whether myslice inherits from object or not, there's no
persuading the interpreter that it is a genuine slice, and remember
that we can't subclass slice (for some reason unknown). So, it would
appear that the interpreter really wants instances from some specific
set of types (presumably discoverable by looking at list_subscript in
listobject.c) rather than some objects conforming to some interface or
protocol, and perhaps it is implemented this way for performance
reasons.

In any case, in the core of Python some types/classes are more equal
than others, and for whatever reason the duck typing breaks down - a
case of "malbik endar" [1] that you just have to be aware of, I
suppose.

Paul

[1] http://www.sciamanna.com/island/pop/2004_07_13/280_malbik_endar.htm

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


Re: random shuffles

2006-07-21 Thread Tim Peters
[ Boris Borcic]
> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>
> pick a random shuffle of x with uniform distribution ?

Say len(x) == N.  With Python's current sort, the conjecture is true
if and only if N <= 2.

> Intuitively, assuming list.sort() does a minimal number of comparisons to
> achieve the sort,

No idea what that could mean in a rigorous, algorithm-independent way.

> I'd say the answer is yes. But I don't feel quite confortable
> with the intuition... can anyone think of a more solid argumentation ?

If a list is already sorted, or reverse-sorted, the minimum number of
comparisons needed to determine that is N-1, and Python's current sort
achieves that.  It first looks for the longest ascending or descending
run.  If comparison outcomes are random, it will decide "yes, already
sorted" with probability 1/2**(N-1), and likewise for reverse-sorted.
When N > 2, those are larger than the "correct" probabilities 1/(N!).
So., e.g., when N=3, the sort will leave the list alone 1/4th of the
time (and will reverse the list in-place another 1/4th).  That makes
the identity and reversal permutations much more likely than "they
should be", and the bias is worse as N increases.

Of course random.shuffle(x) is the intended way to effect a
permutation uniformly at random.
-- 
http://mail.python.org/mailman/listinfo/python-list


getaddrinfo not found on SCO OpenServer 5.0.5

2006-07-21 Thread edcdave
I'm trying to get MoinMoin 1.5.4 running with Python 2.3.4 (installed
from an SCO Skunkworks binary). Python 2.3.4 (#1, Aug 27 2004,
18:22:39) [GCC 2.95.3 20030528 (SCO/p5)] on sco_sv3

One of the MoinMoin modules attempts to import cgi and triggers this
traceback:

Traceback (most recent call last):
  File "./moin.cgi", line 43, in ?
from MoinMoin.request import RequestCGI
  File "/usr/moin/lib/python2.3/site-packages/MoinMoin/request.py",
line 10, in ?
import os, re, time, sys, cgi, StringIO
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/cgi.py", line 39, in
?
import urllib
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/urllib.py", line 26,
in ?
import socket
  File "/opt/K/SCO/python/2.3.4/usr/lib/python2.3/socket.py", line 44,
in ?
import _socket
ImportError: dynamic linker: /usr/bin/python: relocation error: symbol
not found: getaddrinfo; referenced from:
/opt/K/SCO/python/2.3.4/usr/lib/python2.3/lib-dynload/_socketmodule.so

getaddrinfo is not supported in OpenServer 5, but it is available under
the UDK. That is, the function is present in /udk/usr/lib/libsocket.so.
I've tried adjusting LD_LIBRARY_PATH without success. My questions:

1) I've seen mention of native vs. Python getaddrinfo implementations.
If that's true, how can I force the program to use the Python one?

2) Is there an option to not use the BSD Library function?

3) Finally, is there a trick to searching for shared libaries?

Thanks,
Dave Harris

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


Re: question about what lamda does

2006-07-21 Thread Bruno Desthuilliers
danielx wrote:
> Bruno Desthuilliers wrote:
> 
>>danielx wrote:
>>(snip)
>>
>>
>>>Python's lambda really can't be as powerful as Lisp's because Python
>>>does not have expressions that do case analysis (this is not lambda's
>>>fault, of course ;). The reason is that you really want to put each
>>>case on its own set of lines.

An expression can span several lines.

> This enhances readability at the expense
>>>of terseness. Since Python's statements are terminated by a newline, 

or by a ';'

> it
>>>would be rather awkward to have a kind of expression where good style
>>>calls for it to be spread out accross multiple lines.

I must be pretty dumb, but I don't see how this relate to the problem of
case analysis in lambda expressions ?

>>>You can try to simulate these kinds expressions using into a list or
>>>dictionary, but this becomes rather messy. I think the only way to get
>>>this done properly is to use eval. For example:
>>>
>>>def recursiveFunction(args):
>>>  ...  # do stuff...
>>>  choices = { True:"0", False:"recurisveFunction(newArgs)" }
>>>  return eval( choices[predicate] )
>>
>>Why do you want to use eval here ?
>>
>>
>>>The reason that you need eval is that you want to prevent any cases
>>>from being executed until you decide which one you want.
>>
>>What about:
>>
>>def recursiveFunction(args):
>>... # do stuff...
>>... # that defines 'newArgs' and 'predicate' of course ...
>>return (recursiveFunction, lambda x: 0)[predicate](newArgs)
> 
> 
> Sure, that works, but don't take things so literally.

Sorry for being pragmatic !-)

> For instance, if
> you have a bunch of cases, you might not way to apply the same set of
> arguments to all of them.

return {
  'case1' : lambda: someFunc(args1),
  'case2' : lambda: someFunc(args2),
  'case3' : lambda: someOtherFunc(args1, arg42),
}.get(predicate, lambda: 0)()

Still no need for eval()...

Now of course there are limits to the exercice, and we're still far away
from ML-like pattern matching or Lisp 'case' forms. As you noted, Python
is a statement-based language, not an expression-based one like Lisp.
This makes a definitive difference.

> Also, let's not get distracted from the main point about how doing case
> analysis in an expression is ugly,

Ugliness is in the eyes of the beholder 

> making lambda's weaker in Python
> than in the language which inspired them.

The fact is that Python "lambdas" are *not* Lisp lambdas. Python
"lambdas" are mostly a handy trick to turn a *simple* expression into a
 closure - and definitively not a basic building block of the language.

Daniel, I of course do agree that Python lambdas are nothing near Lisp
lambdas - FWIW, Python is not Lisp neither -, but that looks like an
apple and banana comparison to me... IMHO, the most obvious problem with
Python lambdas is the word "lambda" !-)


-- 
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: Checking File permissions

2006-07-21 Thread Tal Einat

Anoop wrote:
> Hi All
>
> Please tell me how to check the existence of a file and the read
> permission to the file using python script
>
> Thanks for ur inputs
>
> Anoop

os.access(path, mode) does just this, check it out.

Cross-platform-ness isn't a problem, the docs say it is available for
Windows, Unix and Mac, and I've used it without a hitch on Win2k, WinXP
and various Linux and Unix platforms.

>>> help(os.access)
Help on built-in function access in module nt:

access(...)
access(path, mode) -> 1 if granted, 0 otherwise

Use the real uid/gid to test for access to a path.  Note that most
operations will use the effective uid/gid, therefore this routine
can
be used in a suid/sgid environment to test if the invoking user has
the
specified access to the path.  The mode argument can be F_OK to
test
existence, or the inclusive-OR of R_OK, W_OK, and X_OK.

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


Re: Since there was talk of if-then-else not being allowed in lambda expressions, the following is from "Dive into Python"

2006-07-21 Thread Peter Otten
Bruno Desthuilliers wrote:

> But isn't allowed in a lambda !-)
 
Then tear out that lambada page, too, I was tempted to say, but I will
desist. For now...

Peter

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


Re: random shuffles

2006-07-21 Thread Iain King

Dustan wrote:
> Boris Borcic wrote:
> > does
> >
> > x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
> >
> > pick a random shuffle of x with uniform distribution ?
> >
> > Intuitively, assuming list.sort() does a minimal number of comparisons to
> > achieve the sort, I'd say the answer is yes. But I don't feel quite 
> > confortable
> > with the intuition... can anyone think of a more solid argumentation ?
>
> Why not use the supplied shuffle method?
>
> random.shuffle(x)

or check out this thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/766f4dcc92ff6545?tvc=2&q=shuffle

Iain

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


  1   2   >