Re: Software Needs Less Idiots

2006-05-21 Thread Jeffrey Schwab
David Steuber wrote:
> "PofN" <[EMAIL PROTECTED]> writes:
> 
>> Xah Lee wrote:
>>> Software needs philosophers.
>> No, software neds less idiots. So please take your medication and
>> change profession.
> 
> Perhaps fewer would do.

Thank you.  I didn't want to be "that guy."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python, equivalent of set command

2006-03-27 Thread Jeffrey Schwab
loial wrote:
> In unix shell script I can do the following to get the status and
> values returned by a unix command
> 
> OUTPUT=`some unix command`
> STATUS=$?
> if [ $STATUS -ne 0 ]
> then
>   exit 1
> else
>   set $OUTPUT
>   VAL1=$1
>   VAL2=$2
>   VAL3=$3
> fi
> 
> How can I achieve the same in python?
> 
> I know how to run it via the os.system command and return the status,
> but how do I return the values too?

http://docs.python.org/lib/node241.html

6.8.3.1 Replacing /bin/sh shell backquote

output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

The popen object also has a 'returncode' attribute.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I use a conditional in a variable declaration?

2006-03-19 Thread Jeffrey Schwab
Georg Brandl wrote:
> Jeffrey Schwab wrote:
>> [EMAIL PROTECTED] wrote:
>>
>>> I want the equivalent of this:
>>>
>>> if a == "yes":
>>>answer = "go ahead"
>>> else:
>>>answer = "stop"
>>>
>> def mux(s, t, f):
>>  if s:
>>  return t
>>  return f
> 
> But be aware that this is not a complete replacement for a syntactic
> construct. With that function, Python will always evaluate all three
> arguments, in contrast to the and/or-form or the Python 2.5 conditional.

Absolutely true, and I should have mentioned it.  In languages that 
allow ?: syntax, I rarely rely on its short-circuit effect, but it 
certainly is a significant difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I use a conditional in a variable declaration?

2006-03-18 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:

> I want the equivalent of this:
> 
> if a == "yes":
>answer = "go ahead"
> else:
>answer = "stop"
> 
> in this more compact form:
> 
> a = (if a == "yes": "go ahead": "stop")
> 
> is there such a form in Python? I tried playing around with lambda
> expressions, but I couldn't quite get it to work right.

Rather than lambda, this merits a named function.  You only have to 
define it once.

def mux(s, t, f):
 if s:
 return t
 return f

def interpret(a):
 answer = mux(a == "yes", "go ahead", "stop")
 print answer

interpret("yes")# Prints "go ahead."
interpret("no") # Prints "stop."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there no end to Python?

2006-03-18 Thread Jeffrey Schwab
Jeffrey Schwab wrote:
> Steve Holden wrote:
>> No need for flames. I'll content myself with pointing out that most 
>> 1.5.2 programs will run unchanged in 2.5, so the backwards 
>> compatibility picture is very good. Nobody makes you use the new 
>> features!
> 
> They do if you ever want to read their code.  The point of view you've 
> just summarized is what causes languages to become write-only.

Sorry, that came out a lot ruder than I meant it.

I've always heard that Python was extremely easy to learn.  I'm still 
fairly new to the language, though (2.2), and I have not found it any 
easier to learn than Perl or Ruby.  It's great that all these new 
features have been added, but if I want power at the expense of 
intuitive language constructs, I'll stick to C++.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there no end to Python?

2006-03-18 Thread Jeffrey Schwab
Steve Holden wrote:
> kpp9c wrote:

>> I find that if i use
>> other folks code, collaborate, or get help from other folks i still
>> have to know all the new constructs that i don't often use, and i
>> really struggle with iterators and generators and some of the newer
>> things and folks seem to have fallen in love with ridiculously complex
>> list comprehensions. (i'll admit i love the list comprehensions too,
>> but too a point)
>>
>> Don't get me wrong, i LOVE Python, but since 2.2 or so the language has
>> started to get some feature creep and is starting to evolve
>> exponentially fast and while all that pre 2.2 code is really readable
>> still, i see some stuff now that really really hurts my brain. We see
>> less silly lambdas than we used to, and Python is more powerful than
>> ever, but i think there has been a cost too. Python has become harder
>> to read and *MUCH* harder to learn all of a sudden.
>>
>> Personally i would like to see the core Python language evolve more
>> slowly and see work on packages, modules and DOCS!!

> No need for flames. I'll content myself with pointing out that most 
> 1.5.2 programs will run unchanged in 2.5, so the backwards compatibility 
> picture is very good. Nobody makes you use the new features!

They do if you ever want to read their code.  The point of view you've 
just summarized is what causes languages to become write-only.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python execution problem

2006-03-17 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> Using OSX 10.4.5
> 
> This is more of a unix/tcsh question than a python question.
> Somehow I got to the point where I have two files 'a.py' and 'b.py'
> which have identical contents and permissions, but one refuses to
> execute:
> 
> [blah:/Library/WebServer/CGI-Executables] me% a.py
> tcsh: a.py: Command not found.
> [blah:/Library/WebServer/CGI-Executables] me% b.py
> okay
> [blah:/Library/WebServer/CGI-Executables] me%
> 
> Could someone enlighten me about how the shell knows to execute a
> script? I always assumed it was just the extension, but this seems to
> prove me wrong.

It checks each directory in your path for an executable file with the 
name you specified.  Each file has a set of associated bits to tell 
whether it is executable (or readable or writable), and by whom.  To add 
  execute permission to a.py, try this:

chmod +x a.py

FYI, it's not a great idea to rely on the current directory (.) being in 
your path.  You might want to type it explicitly, e.g ./a.py instead of 
a.py.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-17 Thread Jeffrey Schwab
Fredrik Lundh wrote:
> Joel Hedlund wrote:
> 
>> I've been thinking about these nested generator expressions and list
>> comprehensions. How come we write:
>>
>> a for b in c for a in b
>>
>> instead of
>>
>> a for a in b for b in c
>>
>> More detailed example follows below.
>>
>> I feel the latter variant is more intuitive. Could anyone please explain the
>> fault of my logic or explain how I should be thinking about this?
> 
> out = [a for b in c for a in b]
> 
> can be written
> 
> out = [a
> for b in c
> for a in b]
> 
> which is equivalent to
> 
> out = []
> for b in c:
> for a in b:
> out.append(a)
> 
> in other words, a list comprehension works exactly like an ordinary for
> loop, except that the important thing (the expression) is moved to the
> beginning of the statement.

Which is utterly counter-intuitive, the opposite of Perl, and remains 
one of the most confusing and surprising things I have encountered in 
Python so far.

And nobody start yelling that Python is not Perl.  We all know Python is 
not Perl, nor should it be.  If you want different for the sake of 
different, though, go try MOO or something.  Here:

http://en.wikipedia.org/wiki/Esoteric_programming_language
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: The Concepts and Confusions of Pre-fix, In-fix, Post-fix and Fully Functional Notations

2006-03-16 Thread Jeffrey Schwab
SamFeltus wrote:
> """Not that Mr. Lee has ever shown much interest in feedback, but you
> pretty well have stick to vanilla ASCII to get your notation through
> unmangled on newsgroups."""
> 
> It is the 21st century, so having to do that oughta inspire some sort
> of well earned anti Unix rant...
> 
> :)

Not anti-Unix. 
Anti-failure-to-use-appropriate-datatypes-for-the-task-at-hand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-16 Thread Jeffrey Schwab
Derek Basch wrote:
>> Depending on the types of the containers in question, you could use:
>>
>>  len(zoo) * len(animal)
> 
> I think this would give me the total iterations but I wouldn't be able
> to get a running count. Correct?

Correct.  If you need a running count, maintain a counter (or enumerate()).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting nested loop iterations

2006-03-16 Thread Jeffrey Schwab
Derek Basch wrote:
> What is the best way to count nested loop iterations? I can only figure
> to use an index but that seems kludgy.
> 
> index = 0
> for animal in zoo:
> for color in animal:
> index += 1

Depending on the types of the containers in question, you could use:

len(zoo) * len(animal)



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


Re: why does close() fail miserably on popen with exit code -1 ?!

2006-03-03 Thread Jeffrey Schwab
Tobiah wrote:

> phase:toby:~> echo 'exit -1' | bash
> phase:toby:~> echo $?
> 255

http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/exitcodes.html


Exit Code Number:  255 [1]
Meaning:   Exit status out of range
Example:   exit -1
Comments:  exit takes only integer args in the range 0 - 255


[1] Out of range exit values can result in unexpected exit codes. An 
exit value greater than 255 returns an exit code modulo  256. For 
example, exit 3809 gives an exit code of 225  (3809 % 256 = 225).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort one list using the values from another list

2006-02-26 Thread Jeffrey Schwab
Brian Blais wrote:
> Hello,
> 
> I have two lists, one with strings (filenames, actually), and one with a 
> real-number
> rank, like:
> 
> A=['hello','there','this','that']
> B=[3,4,2,5]
> 
> I'd like to sort list A using the values from B, so the result would be 
> in this example,
> 
> A=['this','hello','there','that']
> 
> The sort method on lists does in-place sorting.  Is there a way to do 
> what I want here?

If A has no duplicate elements, you could create a hash mapping A's 
elements to their respective precedences, then provide a sort criterion 
that accessed the hash.  Alternatively, you could do something like this:

from operator import itemgetter
result = map(itemgetter(0), sorted(zip(A, B), key=itemgetter(1)))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spaces at ends of filenames or directory names on Win32

2006-02-25 Thread Jeffrey Schwab
Larry Bates wrote:
> Jeffrey Schwab wrote:
> 
>>Larry Bates wrote:
>>
>>
>>>IMHO leading and/or trailing spaces in filenames is asking for
>>>incompatibilities with cross-platform file access.
>>
>>With what platforms specifically?
>>
>>
>>>Much like
>>>using single-quote in filenames which are perfectly legal in
>>>DOS/Windows, but Linux doesn't like much.
>>
>>Uh...  What Linux are you using?  And what FS?
>>
>>$ touch "'" && ls
>>'
>>$ rm "'"
>>$
> 
> 
> I stand corrected if you put double quotes around filenames
> it does work.  That to me means that single quotes
> in filenames are somehow "different" than other characters.
> You must handle these filenames differently (at least from
> the command line).  Thanks for pointing this out.

Sure, no problem.  FYI, the quotes are to keep my shell, which happens 
to be bash, from trying to interpret the quote.  If I were renaming a 
file by clicking the icon in a Windows-like GUI, or using a file 
manager, there would be no need for the quote.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Temporary" Variable

2006-02-24 Thread Jeffrey Schwab
Steven D'Aprano wrote:
> On Fri, 24 Feb 2006 00:24:25 +, Jeffrey Schwab wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>>On Thu, 23 Feb 2006 12:05:59 -0800, darthbob88 wrote:
>>>
>>>My comments inserted inline.
>>>
>>>
>>>
>>>
>>>>#!/usr/bin/python
>>>>#simple guessing game, with numbers
>>>>import random
>>>>spam = random.randint(1, 100)
>>>
>>>
>>>It is bad programming practice to give variables uninformative joke names.
>>
>>Lighten up.  This isn't the middle of a 100-KLOC corporate monstrosity, 
>>it's a 1/2-page usenet post.
> 
> 
> The original poster is also a newbie who was having trouble with the
> difference between strings and ints. If Guido called a variable spam,
> I wouldn't presume to correct him. When Newbie McNew does it, it might
> very well be because he doesn't know any better.

Sorry if I snapped at you.  But you didn't "correct" him, as he what he 
did wasn't wrong.  You just talked down to him.

> Just out of curiosity, when do you think is the right time to begin
> teaching programmers good practice from bad? Before or after they've
> learnt bad habits?

I'm not convinced the OP has a "bad habit."  Frankly, I prefer postings 
that have a sense of humor.  I wouldn't want to see this turned into a 
purely techical forum.

import random
print ", ".join(['spam' for i in range(random.randint(1, 9))] +
['bacon', 'eggs', 'and']), 'spam'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Temporary" Variable

2006-02-23 Thread Jeffrey Schwab
Steven D'Aprano wrote:
> On Thu, 23 Feb 2006 12:05:59 -0800, darthbob88 wrote:
> 
> My comments inserted inline.
> 
> 
> 
>>#!/usr/bin/python
>>#simple guessing game, with numbers
>>import random
>>spam = random.randint(1, 100)
> 
> 
> It is bad programming practice to give variables uninformative joke names.

Lighten up.  This isn't the middle of a 100-KLOC corporate monstrosity, 
it's a 1/2-page usenet post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Jeffrey Schwab
Larry Bates wrote:

> IMHO leading and/or trailing spaces in filenames is asking for
> incompatibilities with cross-platform file access.

With what platforms specifically?

> Much like
> using single-quote in filenames which are perfectly legal in
> DOS/Windows, but Linux doesn't like much.

Uh...  What Linux are you using?  And what FS?

$ touch "'" && ls
'
$ rm "'"
$
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new wooden door step - fixing and finishing

2006-02-22 Thread Jeffrey Schwab
Jeffrey Schwab wrote:
> jkn wrote:
> 
>> Hi all
>> I'm considering having a go at replacing the wooden door step to
>> our back door. The original is loose and rotting.
>>
>> I'm sure some of this will be clearer when I remove the (metal) door
>> frame - how is such a step fixed? Vertical frame fixings?
> 
> 
> Depends on your layout manager.  Btw, you don't have to use Metal:  Java 
> frames support native L&F.
> 
>> Also, any suggestions for treating/finishing such an item, subject to
>> heavy use,
> 
> 
> Lots of unit testing.
> 
>> to prevent future rot?
> 
> 
> Good documentation, especially javadocs.
> 
>> I was wondering about treating it
>> wilth liberal amounts of Teak Oil or similar...
> 
> 
> Some people, when confronted with a problem, think "I know, I’ll use 
> Teak Oil."  Now they have two problems.

Forgot what group I was in.  Kindly replace any Java-specific witticisms 
with appropriately pythonic humor.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new wooden door step - fixing and finishing

2006-02-22 Thread Jeffrey Schwab
jkn wrote:
> Hi all
> I'm considering having a go at replacing the wooden door step to
> our back door. The original is loose and rotting.
> 
> I'm sure some of this will be clearer when I remove the (metal) door
> frame - how is such a step fixed? Vertical frame fixings?

Depends on your layout manager.  Btw, you don't have to use Metal:  Java 
frames support native L&F.

> Also, any suggestions for treating/finishing such an item, subject to
> heavy use,

Lots of unit testing.

> to prevent future rot?

Good documentation, especially javadocs.

> I was wondering about treating it
> wilth liberal amounts of Teak Oil or similar...

Some people, when confronted with a problem, think "I know, I’ll use 
Teak Oil."  Now they have two problems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list assignment

2006-02-22 Thread Jeffrey Schwab
Raymond Hettinger wrote:
>> [spam, ham] = ['yum', 'YUM']
>>
>>I don't see how this is any different than a tuple unpacking assignment:
>>
>> >>> a, b = 1, 2
> 
> 
> It's not different.  They are ways of writing the same thing.

TMTOWTDI, after all. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to force creation of a .pyc?

2006-02-22 Thread Jeffrey Schwab
mrstephengross wrote:
> I would like to distribute a python program, but only in .pyc form (so
> that people cannot simply look at my code). Is there a way to do this?
> I've read up a little on the logic by which python creates .pyc's, and
> it sounds like python requires the main executed program to be in .py
> format. Any ideas?

Make a dummy script to import your main module.  The resulting pyc can 
be fed directly to the Python interpreter.

<-->
# main.py : My main source code.  I cleverly will distribute only the
# byte code, such that no one knows my secrets.  D'oh!  You caught me
# monologging again...

if __name__ == "__main__":
print "Ha!  Now you can't see me."
<-->
# dummy.py : Imports the main module to create main.pyc.

import main
<-->
[some client's prompt]% python main.py
Ha!  Now you can't see me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic coin flipper program - logical error help

2006-02-22 Thread Jeffrey Schwab
wes weston wrote:
> DannyB wrote:
> 
>> I'm just learning Python.  I've created a simple coin flipper program -

...

> Dan,
>Looping is easier with:
> for x in range(100):
>if random.randint(0,1) == 0:
>   heads += 1
>else:
>   tails += 1
> 

Or, continuing with that theme:

for x in range(N):
heads += random.randint(0, 1)

As in:

import random
N = 100
heads = 0
for x in range(N):
heads += random.randint(0, 1)
print "%d heads and %d tails." % (heads, N - heads)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: That's really high-level: bits of beautiful python

2006-02-22 Thread Jeffrey Schwab
Max wrote:
> I have a friend who has been programming in C for many years, and he is 
> a great fan of the language. However, he (and I) are about to start a 
> python course, and he has been asking me a lot of questions. He often 
> responds to my answers with "Urgh! Object-orientation!" and suchlike.

After "many years" of C programming, he's still wary of object orientation?

> But today we were discussing the problem of running externally-provided 
> code (e.g. add-on modules). Neither of us knew how to do it in C, though 
> I suggested using DLLs.

It depends on how the module was provided, and on the platform and tool 
chain being used to build the code.  It's typically not too hard on a 
given platform, once you get used to it, but there's certainly no single 
correct answer.

> However, I quickly installed python on his 
> laptop and coded this:
> 
> exec "import %s as ext_mod" % raw_input("Module: ")
> ext_mod.do()

exec'ing raw_input'd code gives me the willies.

> And created to sample modules with do() functions to demonstrate. He was 
> impressed ("That's really high-level" were his words).

It is cool, isn't it?  :)

> I was just thinking perhaps we should create some kind of collection of 
> bits of "impressive" code like this.

Do you mean something like the ASPN Cookbooks?

http://aspn.activestate.com/ASPN/Cookbook/

If you keep track of some examples of "cool" stuff, I'll format them and 
get some web space to post them.  Try to give credit for each example.

> He also liked 99 Bottles in one line:
> 
> print '\n'.join(["%d bottles of beer on the wall." % i for i in 
> range(100,0,-1)])

A little shorter:

for i in range(99, 0, -1): print("%d bottles of beer on the wall." % i)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does close() fail miserably on popen with exit code -1 ?!

2006-02-22 Thread Jeffrey Schwab
Atanas Banov wrote:
> Jeffrey Schwab wrote:
> 
>>_PyPclose returns the exit status of the popened process (the popenee?),
>>or -1 on error.  Of course, if the status is supposed to be -1, there's
>>some confusion.
> 
> 
> yes, that's what i thought the root of the problem is.
> 
> 
>>In the snippet of code below (from Modules/posixmodule.c), result has
>>been initialized to the output of fclose, which in your case is 0.  The
>>comment is particularly handy.
>>
> 
> 
> 
>>  /* Indicate failure - this will cause the file object
>>   * to raise an I/O error and translate the last
>>   * error code from errno.  We do have a problem with
>>   * last errors that overlap the normal errno table,
>>   * but that's a consistent problem with the file object.
>>   */
> 
> 
> the piece you quoted is from the unix #ifdef part, i think. there is
> another version of the pypclose for windows below that.
> 
> in any event i think such behaviour is a bug - just because in unix
> exit codes are limited to 0..255 (and returned multiplied by 256)
> doesnt mean other OSes should suffer because of design flow in
> _PyPclose, right?
> 
> throwing an IOError "no error" doesnt help.
> 
> is there a bug database for python where i can check if this was
> discussed?

Yes, there's a bug database linked from python.org; search the main page 
for "Bugs".

Here's the most (seemingly) relevant bug report I can find:
http://sourceforge.net/tracker/index.php?func=detail&aid=602245&group_id=5470&atid=105470
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does close() fail miserably on popen with exit code -1 ?!

2006-02-20 Thread Jeffrey Schwab
Atanas Banov wrote:
> i ran onto this weirdness today: seems like close() on popen-ed
> (pseudo)file fails miserably with exception instead of returning exit
> code, when said exit code is -1.
> 
> here is the simplest example (under Windows):
> 
> 
print popen('exit 1').close()
> 
> 1
> 
print popen('exit -1').close()
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> IOError: (0, 'Error')
> 
print popen('exit -2').close()
> 
> -2
> 
> has anyone have idea why is that?

_PyPclose returns the exit status of the popened process (the popenee?), 
or -1 on error.  Of course, if the status is supposed to be -1, there's 
some confusion.

In the snippet of code below (from Modules/posixmodule.c), result has 
been initialized to the output of fclose, which in your case is 0.  The 
comment is particularly handy.

if (result != EOF &&
waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
{
/* extract exit status */
if (WIFEXITED(exit_code))
{
result = WEXITSTATUS(exit_code);
}
else
{
errno = EPIPE;
result = -1;
}
}
else
{
/* Indicate failure - this will cause the file object
 * to raise an I/O error and translate the last
 * error code from errno.  We do have a problem with
 * last errors that overlap the normal errno table,
 * but that's a consistent problem with the file object.
 */
result = -1;
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: define loop statement?

2006-02-18 Thread Jeffrey Schwab
Jeffrey Schwab wrote:

> class Loop:
> def __init__(self, n):
> self.n = n
> def __call__(self):
> self.n = self.n - 1
> return self.n != 0
> 
> 
> if __name__ == '__main__':
> loop = Loop(10)
> while loop:

Whoops.  Should be "while loop()".

> print "OK"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: define loop statement?

2006-02-18 Thread Jeffrey Schwab
David Isaac wrote:
> I would like to be able to define a loop statement
> (nevermind why) so that I can write something like
> 
> loop 10:
> do_something
> 
> instead of
> 
> for i in range(10):
> do_something
> 
> Possible?  If so, how?

Ruby and Smalltalk are both good at this kind of thing, since they have 
syntactic support for associating a block with each method call.  In 
Python, I think you just have to do a little more setup.  How about 
something like this?

class Loop:
def __init__(self, n):
self.n = n
def __call__(self):
self.n = self.n - 1
return self.n != 0


if __name__ == '__main__':
loop = Loop(10)
while loop:
print "OK"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shortest prime number program

2006-02-11 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> swisscheese wrote:
> 
>>r=range(2,99)
>>m=[x*y for x in r for y in r]
>>[x for x in r if not x in m]
> 
> 
> How about:
> 
> [2]+[x for x in range(1,99) if 2**x%x==2]

43.

I'll be chewing on this one for a while.  Thank you. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OS.MKDIR( ) Overwriting previous folder created...

2006-02-02 Thread Jeffrey Schwab
Ernesto wrote:
> I couldn't find this with a search, but isn't there a way to overwrite
> a previous folder (or at least not perform osmkdir( ) if your program
> detects it already exists).  Thanks !

Would something like this help?

import os

def failsafe_mkdir(dirname):
try: os.mkdir(dirname)
except:  return False
else:return True


if __name__ == "__main__":
dirname = 'adir'
if failsafe_mkdir(dirname):
print "ok\n"
else:
print "couldn't create %s\n" % dirname
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: triple quoted strings as comments

2006-01-31 Thread Jeffrey Schwab
Steve Holden wrote:
> dmh2000 wrote:
> 
>> I recently complained elsewhere that Python doesn't have multiline
>> comments.
> 
> 
> Personally I think it's a win that you couldn't find anything more 
> serious to complain about :-)

+1 QOTW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: While loop - print several times but on 1 line.

2006-01-26 Thread Jeffrey Schwab
Danny wrote:
> Great! It's been solved.
> 
> The line, as Glaudio said has a "," at the end and that makes it go onto 
> one line, thanks so much man!
> 
> var = 0
> while <= 5:
> print a[t[var]],
> var = var +1
> prints perfectly, thanks so much guys.


Looping over indexes is kinda unpythonic in its own right.  Is there 
something magical about the number 5?

for e in t:
print a[e],
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice : how do you iterate with an acc ?

2005-12-02 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> hello,
> 
> i'm wondering how people from here handle this, as i often encounter
> something like:
> 
> acc = []# accumulator ;)
> for line in fileinput.input():
> if condition(line):
> if acc:#1
> doSomething(acc)#1
> acc = []
> else:
> acc.append(line)
> if acc:#2
> doSomething(acc)#2
> 
> BTW i am particularly annoyed by #1 and #2 as it is a reptition, and i
> think it is quite error prone, how will you do it in a pythonic way ?

Could you add a sentry to the end of your input?  E.g.:

for line in fileinput.input() + line_that_matches_condition:

This way, you wouldn't need a separate check at the end.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-21 Thread Jeffrey Schwab
Donn Cave wrote:
> In article <[EMAIL PROTECTED]>,
>  Jeffrey Schwab <[EMAIL PROTECTED]> wrote:
> 
> 
>>Yes it is.  Memory is only one type of resource.  There are still files 
>>and sockets to close, pipes to flush, log messages to be printed, GDI 
>>contexts to free, locks to release, etc.  In C++, these things are 
>>generally done by destructors, which are called automatically and 
>>deterministically.  I am not a Python Guru, but in Perl, Java, and other 
>>languages that have built-in garbage collectors, these tasks have to be 
>>done explicitly.  I find that this forces a procedural approach, even in 
>>an otherwise object-oriented program.
>>
>>If you want something like automatic garbage collection in C++, I 
>>recommend the use of Factories with destructors that release the 
>>Factories' products.  The zeitgeist in c.l.c++.moderated seems to prefer 
>>the use of smart (reference-counted) pointers, which also rely on 
>>destructors to release resources automatically.  Plentry of free, 
>>open-source implementations are available.
> 
> 
> You may be gratified to learn that Python's main storage model
> is reference counted objects, and when an object falls out of
> all referenced scopes its finalizers run immediately.

Thanks, that's good to know!  For some reason I had it in my head that 
Python always used mark & sweep.  I'm used to ref-counted collection in 
Perl, but I never relied on it because of a nagging (probably 
ill-founded) worry about cyclic references.  Does Python have any way 
around this?  Is there a Python equivalent to C++ destructors?

> This is however true only of the C implementation.  The Java
> implementation naturally has Java's limitations in this matter,
> so documentation generally avoids the issue.  The C implementation
> has been around for over a decade, wonder if it had any influence
> on your C++ zeitgeist?

Possibly.  Python has really caught on with the C++ crowd in a way that 
other languages never did.  I'm not sure why; not that I don't love 
Python, but there are other good, dynamic languages that haven't made 
the same in-roads.

I think Java has had a big influence, too.  People just don't seem to 
want to be bothered with thinking about object life cycles at all.  This 
seems unfortunate to me, because cleanup still has to be done, so it 
just ends up getting moved outside the objects where it belongs.  I 
think this hurts abstraction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-21 Thread Jeffrey Schwab
Fredrik Lundh wrote:
> Jeffrey Schwab wrote:
> 
> 
>>>>>the problem isn't determining who owns it, the problem is determining
>>>>>who's supposed to release it.  that's not a very common problem in a
>>>>>garbage-collected language...
>>>>
>>>>Yes it is.  Memory is only one type of resource.
>>>
>>>Python's garbage collector deals with objects, not memory.
>>
>>But you don't want to spin and wait for the garbage collector to release
>>the object that happens to be holding a thread lock...
> 
> 
> no, but arguing that sockets and thread locks are objects that suffer
> from ownership problems is rather silly.

Why?  Are those resources somehow less important than memory?

> if their use isn't localized to a
> single function or a single manager object, your design is flawed.

!

I disagree.  Suppose some code is written to work with any file-like 
object.  Now suppose a file-like object is passed in that represents 
some URL.  The first time the object is read, the object opens a 
suitable network connection.  When is it safe to close that connection? 
  The client code can't say, because it doesn't even know any network 
connection has been opened.  In a language with deterministic 
destructors, the destructor can be relied on to close the connection as 
soon as the object goes out of scope.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-21 Thread Jeffrey Schwab
Fredrik Lundh wrote:
> Jeffrey Schwab wrote:
> 
> 
>>>the problem isn't determining who owns it, the problem is determining
>>>who's supposed to release it.  that's not a very common problem in a
>>>garbage-collected language...
>>
>>Yes it is.  Memory is only one type of resource.
> 
> 
> Python's garbage collector deals with objects, not memory.

But you don't want to spin and wait for the garbage collector to release 
the object that happens to be holding a thread lock...

>>I am not a Python Guru
> 
> 
> from the sound of it, you haven't written serious programs in any of the
> languages you mention.

You would be wrong there. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about list

2005-11-20 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> Shi Mu wrote:
> 
>>How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
>>Thanks!
> 
> 
> You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
> from
> the list?  You might want to look at:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
> 
> 
import * from xpermutations
[x for x in UniqueCombinations ([1,2,4], 2)]
> 
> [[1, 2], [1, 4], [2, 4]]
> 
> That web page also gives urls to other recipies that do the same thing.

Dang, that's better than my version.

$ ./combinations.py 2 1 2 4
[['1', '2'], ['1', '4'], ['2', '4']]

def combinations( universe, n=None ):

 """
 Return all possible combinations of length "n," where the
 elements of each combination are taken from the list "universe."
 """

 result = []

 if n == None:
 n = len( universe )

 if n > len( universe ):
 # No combination of elements can have cardinality
 # greater than universe, which is by definition the list
 # of all possible elements.
 pass
 elif n < 0:
 # No combination can have negative cardinaltiy.
 pass
 elif n == 0:
 # Only the empty combination has cardinality 0.
 result.append( [ ] )
 else:   # 0 < n <= len( universe )
 for i in xrange( len( universe ) ):
 elem = universe[i]
 post = universe[i+1:]
 for c in combinations( post, n - 1 ):
 choice = [ elem ]
 choice.extend( c )
 result.append( choice )

 return result

if __name__ == "__main__":

 import sys

 if len( sys.argv ) < 2:
 sys.stderr.write(
 "usage: %s  [elements ...]\n" % sys.argv[0] )
 sys.exit(1)

 n = int( sys.argv[1] )
 print repr( combinations( sys.argv[2:], n ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-20 Thread Jeffrey Schwab
Fredrik Lundh wrote:
> Jeffrey Schwab wrote:
> 
> 
>>>Is it correct to say that the typical ownership problem, which
>>>frequently arises in C++, does not occur normally in Python?
>>
>>What "typical ownership problem" do you feel frequently arises in C++?
>>If you are referring to the sometimes difficult task of determining
>>which object owns a particular resource, why would it occur less in
>>Python than in C++?
> 
> 
> the problem isn't determining who owns it, the problem is determining
> who's supposed to release it.  that's not a very common problem in a
> garbage-collected language...

Yes it is.  Memory is only one type of resource.  There are still files 
and sockets to close, pipes to flush, log messages to be printed, GDI 
contexts to free, locks to release, etc.  In C++, these things are 
generally done by destructors, which are called automatically and 
deterministically.  I am not a Python Guru, but in Perl, Java, and other 
languages that have built-in garbage collectors, these tasks have to be 
done explicitly.  I find that this forces a procedural approach, even in 
an otherwise object-oriented program.

If you want something like automatic garbage collection in C++, I 
recommend the use of Factories with destructors that release the 
Factories' products.  The zeitgeist in c.l.c++.moderated seems to prefer 
the use of smart (reference-counted) pointers, which also rely on 
destructors to release resources automatically.  Plentry of free, 
open-source implementations are available.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ownership problem?

2005-11-20 Thread Jeffrey Schwab
Gabriel Zachmann wrote:
> Is it correct to say that the typical ownership problem, which 
> frequently arises in C++, does not occur normally in Python?

What "typical ownership problem" do you feel frequently arises in C++? 
If you are referring to the sometimes difficult task of determining 
which object owns a particular resource, why would it occur less in 
Python than in C++?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PATH environment variable

2005-11-20 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> O/S: Win2K
> Vsn of Python:2.4
> 
> Based on a search of other posts in this group, it appears as though
> os.environ['PATH'] is one way to obtain the PATH environment variable.
> 
> My questions:
> 1) is it correct that os.environ['PATH'] contains the PATH environment
> variable?
> 2) are there other ways to obtain the PATH environment variable? if so,
> is one way of obtaining the PATH environment variable preferable to
> another way?
> 

That's the best way because it's portable.  If you didn't have 
os.environ, you might be able to get PATH but reading the output of some 
subprocess, e.g:

import commands
path = commands.getoutput('echo $PATH')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate HTML

2005-11-14 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> hi
> i have fucntion that generates a HTML page
> 
> def genpage(arg1,arg2):
>print ''' BLAH BLAH.%s %s
>   ''' % (arg1, arg2)
> 
>print '''  blah blah... %s %s
> 
>   ''' % (arg1,arg2)'
> 
> The func is something like that, alot of open''' and closing ''' triple
> quotes. anyway, i wish to print all these into a HTML output file so
> that when i click on it, it shows me the html page. How can i do that?
> 
> i tried
> f = open("output.html","w")
> f.write ( 'print ''' 
> I am stuck at above after doing a lot of f.write for every line of HTML
> . Any betterways to do this in python?
> 
> something like here documents in a shell script where it can also be
> directed to a file.
> thanks
> 

Why not just redirect the output of your Python script from the shell? 
E.g.:

python generate_html.py > output.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Job - PYTHON Engineers, BitTorrent, Inc., San Francisco, CA

2005-11-11 Thread Jeffrey Schwab
camdenjobs wrote:
> PYTHON Engineers, BitTorrent, Inc., San Francisco, CA
> 
> Interested candidates should forward their resumes to 

...

> Please understand that due to the large volume of responses, I will 
> not be able to acknowledge each of you individually.


Now, that's confidence!

May such optimism always be fulfilled. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonising the vim (e.g. syntax popups) -> vimpst

2005-11-09 Thread Jeffrey Schwab
Roman Roelofsen wrote:
>>Evening,
>>
>>Is there a decent way to get that help into vim? Or like showing docstrings
>>or help that I get through pydoc on request? I've been working myself
>>through a pile of vim macros/plugins but couldn't find even one which
>>simplifies programming in Python. Further issues would be handling the
> 
> 
> Hi Christoph,
> Hi Vim users,
> 
> The last 5 days I´ve been working on a code-completion/calltips plugin for 
> vim. It´s working pretty good but not finished yet. I will anounce the first 
> beta version on this mailling list. I hope during the next week.
> 
> I recorded a swf-video so that you can take a look at the current status.
> Link: http://www.tuxed.de/vimpst/video.tar.gz
> 
> Note that it is not necessary to generate symboltable files, etc. Everything 
> is done "on demand". It is even possible to change the python implementation 
> e.g. CPython, Jython, IronPython.
> 
> It is also possible to add some "special feature" interceptor. Currently this 
> is working for SQLObject:
> Lets say you have the class User and the attribute username is a alternate ID.
> Then, the method User.byUsername("...") will always return a User object. 
> vimpst checks this and provides a suitable help.

Right on!  Good luck!  Can't wait!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers and str

2005-11-09 Thread Jeffrey Schwab
Tuvas wrote:
> Wait, one more question. If the number is something like:
> 
> 1.32042
> 
> It is like
> "1.32 stuff"
> 
> I would like it's size to remain constant. Any way around this?

s/%g/%f

 >>> print "%.4f stuff" % 1.3241414515
1.3241 stuff
 >>> print "%.4f stuff" % 1.32042
1.3204 stuff
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating numbers and str

2005-11-09 Thread Jeffrey Schwab
Tuvas wrote:
> I would like to limit a floating variable to 4 signifigant digits, when
> running thorugh a str command. Ei,
> 
> 
> x=.13241414515
> y=str(x)+" something here"
> 
> But somehow limiting that to 4 sign. digits. I know that if you use the
> print statement, you can do something like %.4d, but how can I do this
> with converting the number to a string? Thanks!

%d for a floating-point type?  Is that right?

Anyway, ITYW:

"%.4g" % x

E.g:

 >>> x=.13241414515
 >>> y="%.4g something here" % x
 >>> print y
0.1324 something here
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonising the vim (e.g. syntax popups)

2005-11-09 Thread Jeffrey Schwab
Christoph Haas wrote:
> Evening,
> 
> I'm an addicted vim user and don't really use the IDLE for anything more 
> than calculations where I'm too lazy to start KCalc. But one feature is 
> very pretty: the built-in help for function calls while you type. Like you 
> enter...
> 
> var1,var2=mystring.split(
> ...and the IDLE shows me a popup saying...
> "S.split([sep [,maxsplit]]) -> list of strings
> 
> Is there a decent way to get that help into vim? Or like showing docstrings 
> or help that I get through pydoc on request? I've been working myself 
> through a pile of vim macros/plugins but couldn't find even one which 
> simplifies programming in Python. Further issues would be handling the 
> indentation - maybe a plugin which syntax colors different levels of 
> indentation so I don't have to use my plastic ruler on the screen. ;) 
> Perhaps some more experienced Python/Vim users have a tip which macro sets 
> help most here.

Vim is my editor of choice, too.  I've even gone back to Vim from Eclipse.

I believe what you want are "tags."

http://www.vmunix.com/vim/tags.html

I have not tried these in Vim yet, although I did use etags with Emacs 
(before I discovered the miracle of Vim).

If you get context-sensitive help to work properly in Vim, please let me 
know!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python doc problem example: gzip module (reprise)

2005-11-09 Thread Jeffrey Schwab
Mike Meyer wrote:
> "Xah Lee" <[EMAIL PROTECTED]> writes:
> 
> 
>>Newsgroups: comp.lang.perl.misc
>>PS: I won't cross-post as I'm not subscribed to the Python group.
> 
> 
> Very wisely done. Then from Xah Lee, we get;
> 
> 
>>I have cross posted it for you.
> 
> 
> Proving once again that he's stupider than spam. Please help google
> find him that way by adding this link to your pages:
> 
>   http://xahlee.org/";>stupider than spam
> 
>   thank you,
>   http://mail.python.org/mailman/listinfo/python-list


Re: Invoking Python from Python

2005-11-08 Thread Jeffrey Schwab
John Henry wrote:
> Hi all,
> 
> I have a need to create a Python script on the fly from another Python
> program and then execute the script so created.  Do I need to invoke
> Python through os.spawnl or is there a better way?

Could you import the generated script?  This might be the way to go if, 
e.g., you're generating a "template" configuration file that might 
subsequently be edited by a human being.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which feature of python do you like most?

2005-11-08 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> which feature of python do you like most?
> 
> I've heard from people that python is very useful.
> Many people switch from perl to python because they like it more.
> 
> I am quite familiar with perl, I've don't lots of code in perl.
> Now, I was curious and interested in the python people.
> They certainly made their best choice from perl to python.
> 
> but i have no interesting python experence before, thought i've read a
> few chapters
> of a python tutorial book. The things are much like the perl one.
> 
> I have no idea why people are so facinating with python.
> So I post this question:  What do you use in your dairy work with
> python?
> what is the thing that python makes you happy?
> 
> 
> I certainly don't want to miss a language if it's so great!
> can anyone share your happy experence with python?
> 

I love Perl.  I have started using Python more, partially because it's 
in vogue, but largely because hastily written code seems to come out 
"cleaner."  One certainly can write clear, maintainable code in Perl, 
but doing so in Python feels a bit more natural.  For example:

- Object orientation was a design goal of Python, but had to
  be retrofitted onto Perl.

- Every module I write in Perl contains:

use warnings;   # Should have been the default.
use strict; # Check for dubious constructs.

# Probably some export code like this:
our @ISA = qw( Exporter );
our @EXPORT_OK = (
# ...
);

# "Real" code.
# ...

1   # Return good value on import.

  In Python, none of this is necessary.

- Python knows what indentation means, so I get to skip a
  lot of curly braces.


For one-liners, I still use Perl, specifically because:

- I don't have to import "os" and "sys" modules just
  to basic tasks like issuing system commands.

- Perl will auto-vivify variables with reasonable
  default values.  E.g., if I ++$count, Perl has
  enough intuition to know that I wanted $count
  initialized to zero.

- Perl lets me use very clean syntax for subroutine
  invocation, e.g. by skipping parentheses and being
  aware of (list or scalar) context.

Hope this helps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using python for writing models: How to run models in restricted python mode?

2005-11-07 Thread Jeffrey Schwab
vinjvinj wrote:
> I have so many things to do to get this to production and writing a
> mini language would be a full project in itself. :-<.
> 
> Is there an easy way to do this? If not, I'll go with the steps
> outlined in my other post.

Do you really think it will be faster to start parsing Python code, 
looking for potentially dangerous constructs?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Which Version of Linux

2005-11-05 Thread Jeffrey Schwab
[EMAIL PROTECTED] wrote:
> ok, i m going to use Linux for my Python Programs, mainly because i 
> need to see what will these fork() and exec() do. So, can anyone tell 
> me which flavour of linux i should use, some say that Debian is more 
> programmer friendly, or shold i use fedora, or Solaris. Because these 
> three are the only ones i know of that are popular and free.

Solaris isn't Linux, but it is good.  I've never installed it from 
scratch, though.

I might get lambasted for suggesting this, but try Slackware.  It will 
let you do a very minimal installation, which means there's less stuff 
that can go wrong.  It also has nice, beginner-friendly FAQs to help you 
get started.  Like the other distros already suggested, it comes with 
the graphical desktop environments Gnome and KDE, too.

If at all possible, have another computer available with a working 
internet connection and a floppy disc drive or CD burner.

Like Maciej said, if you have a buddy nearby who is already an expert on 
a particular distro, try that distro.  This is especially true for 
distros like Gentoo that have...  their own way of doing things. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python doc problem example: gzip module (reprise)

2005-11-05 Thread Jeffrey Schwab
Xah Lee wrote:

> i've read the official Python tutorial 8 months ago, have spent 30
> minutes with Python 3 times a week since, have 14 years of computing
> experience, 8 years in mathematical computing and 4 years in unix admin
> and perl

I can wiggle my ears.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when and how do you use Self?

2005-11-03 Thread Jeffrey Schwab
bruno at modulix wrote:
> Steven D'Aprano wrote:
> 
>>On Thu, 03 Nov 2005 10:14:23 +0100, bruno at modulix wrote:
>>
>>
>>
>>>Tieche Bruce A MSgt USMTM/AFD wrote:
>>>
>>>
I am new to python,



Could someone explain (in English) how and when to use self?

>>>
>>>Don't use self. Use other.
>>
>>
>>Are you serious? 
> 
> 
> Are you seriously wondering if I am serious ?

I was also wondering.  What's the problem you see with the identifier 
"self?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extracting numbers from a file, excluding words

2005-11-01 Thread Jeffrey Schwab
Steve Horsley wrote:
> Kristina Kudriašova wrote:
> 
>> 1 Nov 2005 09:19:45 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>>
>>> Hi, I have a file with this content:
>>>
>>>  z zzz z
>>> ...
>>> xxx xx x 34.215
>>> zzz zz 
>>> ...
>>>
>>
>> Hi,
>>
>> I'd suggest doing this:
>>
>> f = file('...')
>> for line in f:
>> if 'xxx xx x' in line:
>> var = float(line[len('xxx xx x'):].strip())
>> f.close()
> 
> 
> I think I prefer "if line.startswith('xxx xx x'):" . 
> Feels cleaner to me.

Especially if any "z" lines might include the magic pattern.
-- 
http://mail.python.org/mailman/listinfo/python-list