Re: q: console widgets for *nix and windows?

2005-11-15 Thread aum
On Mon, 14 Nov 2005 20:56:36 +, Grant Edwards wrote:

>> Can anyone please recommend a widget library for text console,
>> that works not only on *nix systems but windows /as well/?
>> I'm looking for something a bit higher-level than pure curses,
>> preferably with a gui-like set of widgets, event loop, handler
>> methods etc.
> 
> http://tvision.sourceforge.net/

Thanks - but the python wrapper (pytvision.sf.net) is pretty broken,
particularly the windows build.

Any other suggestions?

Looking for:
 - builds ok under gcc on linux and mingw on win32
 - has python wrapper available that builds with the same tools
 - works
 - can use the win32 cmd.exe console

I've tried urwid over wvision, but still no luck.

My main need is to create a user interface compatible with blind users'
screen reader programs - for both linux and win32.

-- 
Cheers
aum


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


Re: more newbie help needed

2005-11-15 Thread bruno at modulix
Steve Holden wrote:
> john boy wrote:
> 
>> using the following program:
>>  
>> fruit = "banana"
>> index = 0
>> while index < len (fruit):
>>  letter = fruit[index-1]
>>  print letter
>>  index= index -1
>>  

>> this program is supposed to spell "banana" backwards and in a vertical
>> patern...it does thisbut after spelling "banana" it gives an error
>> message:

(snip)


> Note, however, that there are more pythonic ways to perform this task.
> You might try:
> 
> for index in range(len(fruit)):
>   letter = fruit[-index-1]
>   print letter
> 
> as one example. I'm sure other readers will have their own ways to do
> this, many of them more elegant.

let's see... what about:

  for c in reversed(fruit): print c

or:

  print "\n".join(reversed(fruit))



-- 
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


string help

2005-11-15 Thread john boy
using the following program:
 
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
    print letter + suffix
    if prefixes == "O" or "Q"
   print letter + "u" + suffix
 
For this program I am trying to combine the individual letters with the suffix to form names...but for O and Q I need to add in a "u" so the spelling is correct...I am having a hard time pulling just the O and Q out of the list of letters for manipulation...instead it is adding "u" to all the letters when combining with the suffix...apparently its due the fact that O and Q are present in the entire "string"..anybody have some suggestions for this??...
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

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

Is Python worth it??

2005-11-15 Thread john boy
I have started out trying to learn Python for my first programming language.  I am starting off with the book "how to think like a computer scientist."  I spend about 4-5 hrs a day trying to learn this stuff.  It is certainly no easy task.  I've been at it for about 1-2 weeks now and have a very elementary picture of how Python works.  I am teaching myself from home and only recieve help from this forum.  Can anybody give me a timeframe as to how long it usually takes to pick something like this up, so I can maybe figure out a way to pace myself?  I can dedicate a good amount of time to it everyday.  Any advice on what is the best way to learn Python?  I am a fairly educated individual with a natural sciences degree (forestry), so I also have a decent math background.  Are there any constraints mathematically or logic "wise" that would prevent me from building a firm grasp of this language?
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

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

how to think like a computer scientist

2005-11-15 Thread john boy
Does anyone know if there is an "answer key" to all of the exercises in "how to think like a computer scientist"sure would be a lot easier to refer to that instead of tying up this forum with questions about exercises I'm sure that have been asked before
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

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

Re: Addressing the last element of a list

2005-11-15 Thread Antoon Pardon
Op 2005-11-14, Mike Meyer schreef <[EMAIL PROTECTED]>:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> Op 2005-11-10, Mike Meyer schreef <[EMAIL PROTECTED]>:
>>> [Context recovered from top posting.]
>>> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
 Daniel Crespo wrote:
> Well, I hope that newcomers to Python don't confuse himselves :)
 This mutable/immutable object and name/variable is confusing.
>>> Only if you have to overcome a conviction that variables behave in a
>>> different way. If you've never seen them behave another way, or have
>>> already gotten used to this model from another language (it dates back
>>> to the 60s, if not the late 50s), then it's no problem. I'm sure the
>>> problem exists in the opposite direction, except that few people
>>> travel that route.
>>> Most OO languages do the name/variable thing, but some of the popular
>>> ones aren't consistent about it, giving some types "special" status,
>>> so that sometimes "a = b" causes b to be copied onto a, and sometimes
>>> it causes a to become a pointer to b. I find a consistent approach is
>>> preferable.
>> But what about a consistent approach, that allows choice.
>
> It's been done in other languages. But it requires more care than one
> would think.

That is possible.

>> Like having an assignment operator (let use @= for it) next to a
>> (re)bind operator.
>>
>> We could then have something like the following.
>>
>> a = 5
>> b = a
>> a @= 7
>> b ==> would result in 7.
>
> You've just overwritten the object referred to by the token "5" in the
> source code with the value 7, so you get:
>
> print 5
> 7
>
> Not exactly a desirable outcome, but some language implementations
> have allowed this kind of thing in the past. You either have to make
> all objects mutable, or disallow assignment to immutable objects,
> which sort of defeats the purpose.

You have a valid point, but I think a different approach is possible.
Don't make the distinction between mutable and immutable types but
between mutable and immutable objects. So an int wouldn't be an
immutable type, but 5 would be an immutable object.

So the code above I gave would throw an exception, but the following
might work.

a @= 5
b = a
b @= 7
a ==> would result in 7.

> Another approach is to have a special object type if you want to allow
> assignment to the object it refers to. That's what Python does now, it
> just doesn't have a syntax just to support that. If it did, your
> example might look like:
>
> a := 5
> b = @a
> a := 7
> @b ==> would result in 7

Could it also work the other way? By somehow manipulating b change a?

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


Re: Addressing the last element of a list

2005-11-15 Thread Antoon Pardon
Op 2005-11-14, Bengt Richter schreef <[EMAIL PROTECTED]>:
> On 14 Nov 2005 11:20:53 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>>Op 2005-11-14, Paul Rubin schreef :
>>> Antoon Pardon <[EMAIL PROTECTED]> writes:
 We could then have something like the following.
 
 a = 5
 b = a
 a @= 7
 b ==> would result in 7.
>>>
>>> Ouch!  :-(((
>>>
>>> Can't you live with
>>>
>>> a = [5]
>>> b = a
>>> a[0] = 7
>>>
>>> so b[0] is now 7.
>>
>>And what do I have to do, in case of the following:
>>
>>a = [3, 5]
>>b = a[0]
>>b @= 7
>>a ==> would result in [7, 5]
>>
>>This may seem contrived, but in combination with
>>parameters it could be usefull.
>>
>>Something like:
>>
>>a = [3, 5]
>>
>>def treat(b):
>>  lots of code
>>  b @= new_value
>>
>>f(a[0])
>>a ==> would result in [7, 5]
>>
>>-- 
> You may be interested in reviewing
>
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3
>
> before continuing this topic ;-)

It is a rather long thread. You want to avoid this one becomes of
comparable length?

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


Re: Addressing the last element of a list

2005-11-15 Thread Chris Mellon
On 11/14/05, Bengt Richter <[EMAIL PROTECTED]> wrote:
> On 14 Nov 2005 11:20:53 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
> >Op 2005-11-14, Paul Rubin schreef :
> >> Antoon Pardon <[EMAIL PROTECTED]> writes:
> >>> We could then have something like the following.
> >>>
> >>> a = 5
> >>> b = a
> >>> a @= 7
> >>> b ==> would result in 7.
> >>
> >> Ouch!  :-(((
> >>
> >> Can't you live with
> >>
> >> a = [5]
> >> b = a
> >> a[0] = 7
> >>
> >> so b[0] is now 7.
> >
> >And what do I have to do, in case of the following:
> >
> >a = [3, 5]
> >b = a[0]
> >b @= 7
> >a ==> would result in [7, 5]
> >
> >This may seem contrived, but in combination with
> >parameters it could be usefull.
> >
> >Something like:
> >
> >a = [3, 5]
> >
> >def treat(b):
> >  lots of code
> >  b @= new_value
> >
> >f(a[0])
> >a ==> would result in [7, 5]
> >
> >--
> You may be interested in reviewing
>
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3
>
> before continuing this topic ;-)

I read that thread, and am glad I did before asking like I was going
to, if only to avoid being yelled at for not understanding Python
variables ;)

I understand them, I really do, and I know why they act the way they
do, but I still wanted a reference type for binding GUI objects to
data values - for example, a spinner control to an int value. In C++,
I do it by passing a pointer to an int to the control and letting it
do its thing. Theres no simple obvious way to do the same thing in
Python - I ended up by passing a namespace(any object) and an
attribute (by name) and then setting it via setattr in in the control,
which is non-obvious and icky.

>
> Regards,
> Bengt Richter
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Brian van den Broek
Shi Mu said unto the world upon 2005-11-15 01:30:
>>Hey Ben,
>>
>>first, as expected, the other two answers you received are better. :-)
>>
>>Sets are much better optimized for things like membership testing than
>>are lists. I'm not competent to explain why; indeed, I keep
>>overlooking them myself :-(



>>
>>Best,
>>
>>Brian vdB
> 
> is it possible to modify the codes to compare the two lists with not
> necessarily consecutive numbers?
> For example,
> lisA=[1,2,5,9]
> lisB=[9,5,0]
> compare A and b will get true because the two lists have 5 and 9
> together though they are indifferent order.
> Best Regards,
> Robert
> 

Sure, but rather than repair a less than best first approach, better 
to do it with sets:

 >>> lisA=[1,2,5,9]
 >>> lisB=[9,5,0]
 >>> lisC=[9,5,0,1]
 >>> def intersection_has_two(sequence1, sequence2):
 set1, set2 = set(sequence1), set(sequence2)
 return len(set1.intersection(set2)) == 2

 >>> intersection_has_two(lisA, lisB)
True
 >>> intersection_has_two(lisA, lisC)
False

Sets make stuff easy. (I have got to remember that :-) The only reason 
to make that a function is the one liner gets a bit long for my taste:

 >>> len(set(lisA).intersection(set(lisB))) == 2
True
 >>>

Best,

Brian vdB

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


Re: compare list

2005-11-15 Thread Brian van den Broek
Ben Bush said unto the world upon 2005-11-15 01:24:



> 
>  Unfortunately, the indents got screwed up along the way. But the part
> 
>>of my code you asked about was:
>>
>>for item in list1:
>>if item in list2:
>>if item + 1 in list1 and item + 1 in list2:
>>return True
>>
>>In some detail:



>>Does that clarify it?
>>
>>Finally, your response to Alex would have been much more useful if
>>you'd quoted the error rather than just asserting that you got an
>>error :-)
>>
>>Best,
>>
>>Brian vdB

Hi Ben,

first, while there are those on the list/n.g. who differ, the 
majoritarian view is that top posting isn't a good thing. At minimum, 
if someone bothered to correct it, it would be nice if in a further 
follow-up you didn't top-post again :-)

Second, you might find the tutor list really helpful. It is where I 
learned most of what I know, and I still read it more than c.l.p. It 
is very newbie friendly.

As for your question:

 >> Hi Brian,
 >
 > regarding "if item + 1 in list1 and item + 1 in list2:",
 > my understanding is this will check whether the following item in 
each list
 > is the same. How does the code permit the situation that the order 
does not
 > matter?
 > For example, for lisA and lisB, the comparison is true and the two 
lists
 > have 5 and 6 but different order.
 >  lisA=[1,2,3,4,5,6,9]
 > lisB=[1,6,5]
 >  Many Thanks!


There are two distinct issues that might be the source of your 
confusion. I will be explicit about both; pardon if only one applied.

 >>> num_list = [1, 42, 451]
 >>> for item in num_list: print item, type(item)

1 
42 
451 
 >>>

Iterating over a list as I did makes item refer to each list member in 
turn. So, item + 1 doesn't refer to the next item (except by accident 
as it were when two items are sequential ints). Rather, it refers to 
int that results from adding 1 to the int that is item.

You might be thinking of list index notation instead:

 >>> index = 1
 >>> num_list[index], num_list[index + 1]
(42, 451)
 >>>

(General tip: putting a print or two in my original code would have 
cleared that up very quickly.)

So, that cleared up, are you wondering why item + 1 suffices, instead 
of both item + 1 and item - 1?

If so, consider that it the list1 has both n and n - 1 in it and we 
iterate over list1 checking each case, eventually item will refer to n 
- 1. In that case, item + 1 = n and we are covered after all. I did as 
I did in my original code thinking it was probably quicker to have 
only one test and pay the cost that there might be a quicker exit from 
the iteration were I to test both item + 1 and item - 1. f it 
mattered, I'd test for speed. Of course, if speed mattered and I could 
ever remember to use sets :-) I'd follow Alex and Duncan's suggestions 
instead!

If that doesn't clear it up, give yourself a few short lists and run 
test cases having inserted print statements to see what is going on. 
To stop it all from whizzing by too fast, put in

raw_input("Hit enter and I'll keep working")

somewhere in the loops to slow things down.

HTH,

Brian vdB

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


Re: string help

2005-11-15 Thread Miki Tebeka
Hello John,

>using the following program:
> 
> 
> 
>prefixes = "JKLMNOPQ"
> 
>suffix = "ack"
> 
>for letter in prefixes:
> 
>print letter + suffix
> 
>if prefixes == "O" or "Q"
 if (letter == "O") or (letter == "Q"):
> 
>   print letter + "u" + suffix

HTH.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys


pgpAuvVLaeMj2.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: string help

2005-11-15 Thread Simon Brunning
On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> using the following program:
>
> prefixes = "JKLMNOPQ"
> suffix = "ack"
> for letter in prefixes:
> print letter + suffix
> if prefixes == "O" or "Q"

Here you need:

if prefixes == "O" or prefixes ==  "Q"

>print letter + "u" + suffix
>
> For this program I am trying to combine the individual letters with the
> suffix to form names...but for O and Q I need to add in a "u" so the
> spelling is correct...I am having a hard time pulling just the O and Q out
> of the list of letters for manipulation...instead it is adding "u" to all
> the letters when combining with the suffix...apparently its due the fact
> that O and Q are present in the entire "string"..anybody have some
> suggestions for this??...

It's not because "O and Q are present in the entire string" - it's
because your expression

prefixes == "O" or "Q"

evaluates as

(prefixes == "O") or ("Q")

Since a string containing a value always evaluates as true, your
expression was always true, too.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Ben Bush
On 11/15/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
Ben Bush said unto the world upon 2005-11-15 01:24:
>>  Unfortunately, the indents got screwed up along the way. But the part>>>of my code you asked about was:for item in list1:>>if item in list2:>>if item + 1 in list1 and item + 1 in list2:
>>return TrueIn some detail:>>Does that clarify it?Finally, your response to Alex would have been much more useful if
>>you'd quoted the error rather than just asserting that you got an>>error :-)Best,Brian vdBHi Ben,first, while there are those on the list/n.g. who differ, the
majoritarian view is that top posting isn't a good thing. At minimum,if someone bothered to correct it, it would be nice if in a furtherfollow-up you didn't top-post again :-)Second, you might find the tutor list really helpful. It is where I
learned most of what I know, and I still read it more than c.l.p. Itis very newbie friendly.As for your question:>> Hi Brian,>> regarding "if item + 1 in list1 and item + 1 in list2:",
> my understanding is this will check whether the following item ineach list> is the same. How does the code permit the situation that the orderdoes not> matter?> For example, for lisA and lisB, the comparison is true and the two
lists> have 5 and 6 but different order.>  lisA=[1,2,3,4,5,6,9]> lisB=[1,6,5]>  Many Thanks!There are two distinct issues that might be the source of yourconfusion. I will be explicit about both; pardon if only one applied.
>>> num_list = [1, 42, 451]>>> for item in num_list: print item, type(item)1 42 451 >>>Iterating over a list as I did makes item refer to each list member in
turn. So, item + 1 doesn't refer to the next item (except by accidentas it were when two items are sequential ints). Rather, it refers toint that results from adding 1 to the int that is item.You might be thinking of list index notation instead:
>>> index = 1>>> num_list[index], num_list[index + 1](42, 451)>>>(General tip: putting a print or two in my original code would havecleared that up very quickly.)
So, that cleared up, are you wondering why item + 1 suffices, insteadof both item + 1 and item - 1?If so, consider that it the list1 has both n and n - 1 in it and weiterate over list1 checking each case, eventually item will refer to n
- 1. In that case, item + 1 = n and we are covered after all. I did asI did in my original code thinking it was probably quicker to haveonly one test and pay the cost that there might be a quicker exit from
the iteration were I to test both item + 1 and item - 1. f itmattered, I'd test for speed. Of course, if speed mattered and I couldever remember to use sets :-) I'd follow Alex and Duncan's suggestionsinstead!
If that doesn't clear it up, give yourself a few short lists and runtest cases having inserted print statements to see what is going on.To stop it all from whizzing by too fast, put inraw_input("Hit enter and I'll keep working")
somewhere in the loops to slow things down.HTH,Brian vdB
Brian,
Really appreciate your help!!!
Ben-- Thanks!Ben Bush 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is Python worth it??

2005-11-15 Thread Simon Brunning
On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> I have started out trying to learn Python for my first programming language.
>  I am starting off with the book "how to think like a computer scientist."
> I spend about 4-5 hrs a day trying to learn this stuff.  It is certainly no
> easy task.  I've been at it for about 1-2 weeks now and have a very
> elementary picture of how Python works.  I am teaching myself from home and
> only recieve help from this forum.  Can anybody give me a timeframe as to
> how long it usually takes to pick something like this up, so I can maybe
> figure out a way to pace myself?  I can dedicate a good amount of time to it
> everyday.  Any advice on what is the best way to learn Python?  I am a
> fairly educated individual with a natural sciences degree (forestry), so I
> also have a decent math background.  Are there any constraints
> mathematically or logic "wise" that would prevent me from building a firm
> grasp of this language?

Keep at it.

Everyone is different, so don't worry about how long it takes you vs.
how long others might take. If you have no programming background,
there's a lot to learn. Using Python is a good choice, I think, 'cos
it gets a lot of extranious crud that many other languages insist on
out of your way, but there's still a lot to learn.

The best way to learn? Go through the tutorials - but if you get an
idea for a mini-project of your own, don't be afraid to dive off and
give it a go. Try to solve you own problems for a while, 'cos that's a
valuable skill, but don't get to the point of frustration. Ask for
help here or on the tutor mailing list[1].

And have fun.

[1] http://mail.python.org/mailman/listinfo/tutor

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about invalid syntax

2005-11-15 Thread adDoc's networker Phil

. I've been schooled with various versions of several languages,
but I'm just now learning python:
I've not yet personally experienced any python debugger .

. I understand the python`IDLE (integrated DeveL Envir)
 comes with the std distro, and here is the part in the doc's 
that you might find encouraging:

google( python idle debugger faq)
[EMAIL PROTECTED] http://www.python.org/doc/faq/programming.html#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc

"(

General Questions
1.1.1   Is there a source code level debugger with breakpoints, single-stepping, etc.? Yes.

The IDLE -- includes a graphical debugger. 
(see folder path: Tools/scripts/idle),
 
There is documentation for the IDLE debugger 
at http://www.python.org/idle/doc/idle2.html#Debugger

PythonWin 
includes a GUI debugger
 based on pdb (python`s std command-line debug)
. The Pythonwin debugger colors breakpoints 
and has quite a few cool features such as debugging non-Pythonwin
programs. A reference can be found at
http://www.python.org/windows/pythonwin/
. Recent versions of PythonWin are available as a part of
 the 
ActivePython distribution 
(see http://www.activestate.com/Products/ActivePython/index.html).
)-python.org

. another thing I plan to get into
 since I'm interested in taming xp,
is 
    iPython, [EMAIL PROTECTED] http://ipython.scipy.org/

. there are many reasons for this,
but the one most relevant to your needs at the moment
(avoiding mysterious error msg's)
is this:
"(
# Automatic indentation of code as you type 
-- (merely having inconsistent spaces or a tab-space mixture can cause unexpected syntax msg's, I'm told)

# Verbose and colored exception traceback printouts
. Easier to parse visually, and in verbose mode they produce a lot of useful debugging information

# Easy debugger access
to rapidly isolate the source of a bug:

. You can set IPython to call up the Python debugger (pdb) every time there is an uncaught exception
. This drops you inside the code which triggered the exception 
with all the data live and it is possible to navigate the stack 
. The %run magic command -with the -d option- 
can run any script under pdb's control,
 automatically setting initial breakpoints for you.

[. other features that interest me include: ]

# Offers a flexible framework inspired by the likes of Mathematica, IDL and Mathcad 
# Session logging (you can then later use these logs as code in your programs).
# Session restoring: logs can be replayed to restore a previous session to the state where you left it.
# Filesystem navigation, via a magic %cd command, 
along with a persistent bookmark system (using %bookmark) 
for fast access to frequently visited directories.
# The ability to expand python variables when calling the system shell
. In a shell command, any python variable prefixed with $ is expanded
. A double $$ allows passing a literal $ to the shell (for access to shell and environment variables like $PATH).
)-scipy.org

On 11/14/05, Ben Bush <[EMAIL PROTECTED]> wrote:

On 11/14/05, adDoc's networker Phil <[EMAIL PROTECTED]
> wrote:
. maybe you could separate your code into parts { python std, pythonwin-specific},and then use a debugger to know most of the problem sources?
(I'm not familiar with pythonwin, I assume it's a superset of python std) .

On 11/14/05, Ben Bush <
[EMAIL PROTECTED] > wrote:


When I run scripts in PythonWin,
sometimes will get the message of invalid syntax error.
How can I check which error I made?
For example, in VB, you might got the wrong place highlighted and help message too.
-- 
which IDE do you use to run Python?Thanks!Ben Bush 

-- American Dream Documentshttp://www.geocities.com/amerdreamdocs/home/"(real opportunity starts with real documentation)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: compare list

2005-11-15 Thread Shi Mu
On 11/15/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> Shi Mu said unto the world upon 2005-11-15 01:30:
> >>Hey Ben,
> >>
> >>first, as expected, the other two answers you received are better. :-)
> >>
> >>Sets are much better optimized for things like membership testing than
> >>are lists. I'm not competent to explain why; indeed, I keep
> >>overlooking them myself :-(
>
> 
>
> >>
> >>Best,
> >>
> >>Brian vdB
> >
> > is it possible to modify the codes to compare the two lists with not
> > necessarily consecutive numbers?
> > For example,
> > lisA=[1,2,5,9]
> > lisB=[9,5,0]
> > compare A and b will get true because the two lists have 5 and 9
> > together though they are indifferent order.
> > Best Regards,
> > Robert
> >
>
> Sure, but rather than repair a less than best first approach, better
> to do it with sets:
>
>  >>> lisA=[1,2,5,9]
>  >>> lisB=[9,5,0]
>  >>> lisC=[9,5,0,1]
>  >>> def intersection_has_two(sequence1, sequence2):
> set1, set2 = set(sequence1), set(sequence2)
> return len(set1.intersection(set2)) == 2
>
>  >>> intersection_has_two(lisA, lisB)
> True
>  >>> intersection_has_two(lisA, lisC)
> False
>
> Sets make stuff easy. (I have got to remember that :-) The only reason
> to make that a function is the one liner gets a bit long for my taste:
>
>  >>> len(set(lisA).intersection(set(lisB))) == 2
> True
>  >>>
>
> Best,
>
> Brian vdB
it does not work.
>>> len(set(lisA).intersection(set(lisB))) == 2
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'set' is not defined
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal for adding symbols within Python

2005-11-15 Thread Ben Sizer
Grant Edwards wrote:
> In the situations described, I always use strings
> and have never felt the need for something else:

...

> I don't think I even understand what the objection is.  What is
> needed is a code fragment that shows how the use of strings is
> untenable.

myObject.value = 'value1'

#... 100 lines of code elided...

if myObject.value = 'Value1':
do_right_thing()
else:
do_wrong_thing()


I don't actually think string use is 'untenable', but it is definitely
more error-prone. With some sort of named object on the right hand side
you will at least get a helpful NameError.

-- 
Ben Sizer.

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


Re: Parse file into array

2005-11-15 Thread Andrew Nelis
If it helps, there's a builtin module for figuring out mimetypes;

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

>>> import mimetypes
>>> mimetypes.guess_type('.gif')
('image/gif', None)


Cheers,

Andy.

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


AJAX => APAX? Or: is there support for python in browsers?

2005-11-15 Thread Roger Erens
Hello,

I remember that the first time I read about Python as a programming
language was when reading the W3C's HTML 4.01 specification a few years
ago. In the section on objects, images and applets
(http://www.w3.org/TR/html401/struct/objects.html) an example was given
like

http://www.miamachina.it/analogclock.py";>


This user agent cannot render Python applications.


It's also in the XHTML2.0 specification. Now, is this just a theoretical
example? Or is there a browser that _does_ support python scripts? Or do
we have to place our bets on the Mozilla 1.9 milestone with hard work
being done by Mark Hammond?

I'm asking because of all the AJAX hype going on. I'd like rather not
delve too deep into JavaScript and use Python instead.

Any insights to be shared?

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


[ANN] Data Plotting Library DISLIN 9.0

2005-11-15 Thread Helmut Michels
I am pleased to announce version 9.0 of the data plotting software
DISLIN.

DISLIN is a high-level and easy to use plotting library for
displaying data as curves, bar graphs, pie charts, 3D-colour plots,
surfaces, contours and maps. Several output formats are supported
such as X11, VGA, PostScript, PDF, CGM, WMF, HPGL, TIFF, GIF, PNG,
BMP and SVG.

The software is available for several C, Fortran 77 and Fortran 90
compilers. Plotting extensions for the interpreting languages Perl,
Python and Java are also supported for the most operating systems.

DISLIN distributions and manuals in PDF, PostScript and HTML format
are available from the DISLIN home page

  http://www.dislin.de

and via FTP from the server

  ftp://ftp.gwdg.de/pub/grafik/dislin

All DISLIN distributions are free for non-commercial use.

  ---
   Helmut Michels
   Max Planck Institute for
   Solar System Research   Phone: +49 5556 979-334
   Max-Planck-Str. 2   Fax  : +49 5556 979-240
   D-37191 Katlenburg-Lindau   Mail : [EMAIL PROTECTED]

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


Re: how to think like a computer scientist

2005-11-15 Thread Simon Brunning
On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> Does anyone know if there is an "answer key" to all of the exercises in "how
> to think like a computer scientist"sure would be a lot easier to refer
> to that instead of tying up this forum with questions about exercises I'm
> sure that have been asked before

Dunno. But I do know tou won't learn that much just looking at the
answers. You'll come on a lot faster by getting it wrong, working out
*why* you've got it wrong, and fixing it.

Don't worry about asking questions. That's what the list and
(especially) the tutor list are for.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SciPy python 2.4 wintel binaries

2005-11-15 Thread jelle
Claudio,

Thanks a lot for this link!

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


Re: compare list

2005-11-15 Thread Simon Brunning
On 15/11/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> it does not work.
> >>> len(set(lisA).intersection(set(lisB))) == 2
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'set' is not defined

'set' is introduced as a built-in at Python 2.4. If you have 2.3,
there's an analogous module.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal for adding symbols within Python

2005-11-15 Thread Steven D'Aprano
On Tue, 15 Nov 2005 01:57:53 -0800, Ben Sizer wrote:

>> I don't think I even understand what the objection is.  What is
>> needed is a code fragment that shows how the use of strings is
>> untenable.
> 
> myObject.value = 'value1'
> 
> #... 100 lines of code elided...
> 
> if myObject.value = 'Value1':
> do_right_thing()
> else:
> do_wrong_thing()
> 
> 
> I don't actually think string use is 'untenable', but it is definitely
> more error-prone. With some sort of named object on the right hand side
> you will at least get a helpful NameError.

It is moments like this that I'm not too proud to admit I learnt some good
techniques from Pascal:

# define some pseudo-constants
RIGHT_THING = 'value1'
WRONG_THING = 'some other value'
INCHES_TO_FEET = 12
CM_TO_METRES = 100

# ...

myObject.value = RIGHT_THING
 
#... 100 lines of code elided...

if myObject.value = RIGHT_THING:
do_right_thing()
else:
do_wrong_thing()


It isn't always appropriate or necessary to define "constants" (and I
sometimes wish that Python would enforce assign-once names), but they can
help avoid some silly mistakes.



-- 
Steven.

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


Re: generate HTML

2005-11-15 Thread s99999999s2003
hi thanks for all the help
actually i am doing it the hard way

alist = [ 'TEST',
'',
'blah' ]

f = open('test.html",'w')
f.writelines(alist)
f.close()

but everytime i hit
...
alist = [ '
ValueError: unsupported format character '"' (0x22) at index 14

what does it mean?

i tried alist = [ 'TEST'] on the
IDE and it works

thanks.

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


Re: compare list

2005-11-15 Thread Shi Mu
On 11/15/05, Simon Brunning <[EMAIL PROTECTED]> wrote:
> On 15/11/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> > it does not work.
> > >>> len(set(lisA).intersection(set(lisB))) == 2
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > NameError: name 'set' is not defined
>
> 'set' is introduced as a built-in at Python 2.4. If you have 2.3,
> there's an analogous module.
>
> --
> Cheers,
> Simon B,
> [EMAIL PROTECTED],
> http://www.brunningonline.net/simon/blog/
>
Yes, i am using python 2.3,
I have used from sets import *
but still report the same error:
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > NameError: name 'set' is not defined
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string help

2005-11-15 Thread Steven D'Aprano
On Tue, 15 Nov 2005 09:35:00 +, Simon Brunning wrote:

> On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
>> using the following program:
>>
>> prefixes = "JKLMNOPQ"
>> suffix = "ack"
>> for letter in prefixes:
>> print letter + suffix
>> if prefixes == "O" or "Q"
> 
> Here you need:
> 
> if prefixes == "O" or prefixes ==  "Q"

Or you could do this:

if prefixes in ("O", "Q"):

or even:

if prefixes in "OQ":


The first example compares prefixes with "O" and then "Q", the second
looks to see if prefixes is a substring of "OQ". In this case, they will
both have the same effect.


-- 
Steven.

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


Re: compare list

2005-11-15 Thread Simon Brunning
On 15/11/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> Yes, i am using python 2.3,
> I have used from sets import *
> but still report the same error:
> > > Traceback (most recent call last):
> > >   File "", line 1, in ?
> > > NameError: name 'set' is not defined

I said analogous, not identical. try (untested):

from sets import Set as set

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Richie Hindle

[Shi]
> Yes, i am using python 2.3,
> I have used from sets import *
> but still report the same error:
> > > Traceback (most recent call last):
> > >   File "", line 1, in ?
> > > NameError: name 'set' is not defined

It's 'Set', not 'set'.  Try this:

>>> import sets
>>> dir(sets)

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


Re: Python obfuscation

2005-11-15 Thread Ben Sizer
Mike Meyer wrote:
> "Ben Sizer" <[EMAIL PROTECTED]> writes:
> > Decompyle (http://www.crazy-compilers.com/decompyle/ ) claims to be
> > pretty advanced. I don't know if you can download it any more to test
> > this claim though.
>
> No, it doesn't claim to be advanced. It claims to be good at what it
> does. There's no comparison with other decompilers at all. In
> particular, this doesn't give you any idea whether or not similar
> products exist for x86 or 68k binaries.

That's irrelevant. We don't require a citable source to prove the
simple fact that x86 binaries do not by default contain symbol names
whereas Python .pyc and .pyo files do contain them. So any
decompilation of (for example) C++ code is going to lose all the
readable qualities, as well as missing any symbolic constants,
enumerations, templated classes and functions, macros,  #includes,
inlined functions, typedefs, some distinctions between array indexing
and pointer arithmetic, which inner scope a simple data variable is
declared in, distinctions between functions/member functions declared
as not 'thiscall'/static member functions, const declarations, etc.

> I've dealt with some very powerfull disassemblers and
> decompilers, but none of them worked on modern architectures.

You can definitely extract something useful from them, but without
symbol names you're going to have to be working with a good debugger
and a decent knowledge of how to use it if you want to find anything
specific. Whereas Python could give you something pretty obvious such
as:

   6 LOAD_FAST0 (licensed)
   9 JUMP_IF_FALSE9 (to 21)

> > It makes a lot of difference when you're hunting around for something
> > or trying to understand a bit of code. Python bytecode (or at least,
> > the output from dis) is also a lot more straightforward than x86 or 68K
> > assembly to decipher.
>
> I'm not convinced of the former. I'll grant you half of the
> latter. 68K machine language is fairly straightforward. On the other
> hand, it's also seems to be irrelevant. What platform are you
> developing for that's still based on the 68K?

There are several embedded/portable devices based on 68K derivatives.
That's not really the point though. I chose 68K assembly as an example
as it's considered to be simpler than x86 assembly, yet it's still
significantly more complex and less readable than the output from
dis.dis()

> > The term I should
> > probably have used was 'distribute usable additional copies'.
>
> My question still stands, though - and unanswered.

I'm not really sure where we're going here. I have made the point that
I am not obliged to make my software copyable to facilitate your right
to copy it any more than any given newspaper is obliged to publish you
to facilitate your right to free speech. Therefore I find it hard to
see how anything is infringing upon a right here.

My interest lies in being able to use encrypted data (where 'data' can
also include parts of the code) so that the data can only be read by my
Python program, and specifically by a single instance of that program.
You would be able to make a backup copy (or 20), you could give the
whole lot to someone else, etc etc. I would just like to make it so
that you can't stick the data file on Bittorrent and have the entire
world playing with data that was only purchased once.

> But we can be
> explicit if you want: How do you do that without requiring that your
> software be given special consideration in the distaster recovery and
> preparedness planning?

I should state that I am not at all claiming a "one size fits all"
policy for software development. Firstly, from a personal point of view
I am talking about simple consumer entertainment software which is not
mission critical or anything like it. For more important software,
there will surely be different expectations and requirements. In my
case, providing a free download of any lost executables or data upon
presentation of a legitimate license key should be adequate.

-- 
Ben Sizer.

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


Re: compare list

2005-11-15 Thread Ben Bush

On 11/15/05, Simon Brunning <[EMAIL PROTECTED]> wrote:
On 15/11/05, Shi Mu <[EMAIL PROTECTED]> wrote:
> Yes, i am using python 2.3,> I have used from sets import *> but still report the same error:> > > Traceback (most recent call last):> > >   File "", line 1, in ?
> > > NameError: name 'set' is not definedI said analogous, not identical. try (untested):from sets import Set as set--Cheers,Simon B,
[EMAIL PROTECTED],http://www.brunningonline.net/simon/blog/--http://mail.python.org/mailman/listinfo/python-list

an error reported:
Traceback (most recent call last):  File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript    exec codeObject in __main__.__dict__  File "C:\temp\try.py", line 8, in ?
    from sets import Set as setImportError: cannot import name Set>>> -- Thanks!Ben Bush 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Post/View Open Source Jobs

2005-11-15 Thread Scott David Daniels
Superior Staffing Solutions wrote:
 > Post/View Open Source Jobs
 > http://groups.yahoo.com/group/opensourcejobs
 >
 >
If you have jobs to announce, there is a jobs forum on python.org.
If you are advertising a web site, like other trolls, you should
curl up and 

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Simon Brunning
On 15/11/05, Ben Bush <[EMAIL PROTECTED]> wrote:
> an error reported:
> Traceback (most recent call last):
>   File
> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "C:\temp\try.py", line 8, in ?
> from sets import Set as set
> ImportError: cannot import name Set
> >>>

Works for me. You don't have a sets module of your own, do you? Try
this, and report back what you see:

import sets
print sets.__file__
print dir(sets)

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compare list

2005-11-15 Thread Ben Bush

On 11/15/05, Simon Brunning <[EMAIL PROTECTED]> wrote:
On 15/11/05, Ben Bush <[EMAIL PROTECTED]> wrote:> an error reported:
> Traceback (most recent call last):>   File> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",> line 310, in RunScript> exec codeObject in __main__.__dict__
>   File "C:\temp\try.py", line 8, in ?> from sets import Set as set> ImportError: cannot import name Set> >>>Works for me. You don't have a sets module of your own, do you? Try
this, and report back what you see:import setsprint sets.__file__print dir(sets)--Cheers,Simon B,[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
 
I found I named the following python file as sets.py, which brought the problem (is that right?). i changed it to other name and it works.But the logic output is wrong.
from sets import Set as setlisA=[1,2,5,9]lisB=[9,5,0,2]lisC=[9,5,0,1]def two(sequence1, sequence2):   set1, set2 = set(sequence1), set(sequence2)   return len(set1.intersection(set2)) == 2
print two(lisA,lisB)
False(should be true!)-- Thanks!Ben Bush 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: compare list

2005-11-15 Thread Richie Hindle
Ben,

> But the logic output is wrong.
> from sets import Set as set
> lisA=[1,2,5,9]
> lisB=[9,5,0,2]
> lisC=[9,5,0,1]
> def two(sequence1, sequence2):
> set1, set2 = set(sequence1), set(sequence2)
> return len(set1.intersection(set2)) == 2
> print two(lisA,lisB)
> False(should be true!)

Slow down.  The intersection of A and B is [2, 5, 9].

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: compare list

2005-11-15 Thread Simon Brunning
On 15/11/05, Ben Bush <[EMAIL PROTECTED]> wrote:
> I found I named the following python file as sets.py, which brought the
> problem (is that right?). i changed it to other name and it works.
> But the logic output is wrong.
> from sets import Set as set
> lisA=[1,2,5,9]
> lisB=[9,5,0,2]
> lisC=[9,5,0,1]
> def two(sequence1, sequence2):
>set1, set2 = set(sequence1), set(sequence2)
>return len(set1.intersection(set2)) == 2
>  print two(lisA,lisB)
> False(should be true!)

It looks to me like A and B have three members in common - 2, 5 and 9.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3-dimensional plot in Python?

2005-11-15 Thread Frithiof Andreas Jensen

"questions?" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I want to make a 3d plot. x is a vector(discrete), y is also a
> vector(discrete), for each pairwise x,y I have a value z(x,y)(it is not
> a function, just discrete values for each pair of x,y)
>
> I want to show them on a two dimensional plot by showing z(x,y) with
> colors.
>
> Thanks for any hint
>

SciPy is your friend: Provides interfaces to several plot engines, including
gnuplot.


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


Re: codecs

2005-11-15 Thread André Malo
* TK <[EMAIL PROTECTED]> wrote:

> sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout)
> What does this line mean?

"Wrap stdout with an UTF-8 stream writer".
See the codecs module documentation for details.

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


codecs

2005-11-15 Thread TK
Hi there,

sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout)

What does this line mean?

Thanks.

o-o

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


Background process for ssh port forwarding

2005-11-15 Thread Jesse Rosenthal
Hello all,

I'm writing a script which will backup data from my machine to a server
using rsync. It checks to see if I am on the local network. If I am, it
runs rsync over ssh to 192.168.2.6 using the pexpect module to log in.
That's the easy part.

Now, when I'm not on the local network, I first want to open up an ssh
connection to do port forwarding, so something like this:

def hostforward():
#This is based on the assumption that the passfile is the gnus
#authinfo file, or has a similar format...
f = open(PASS_FILE, "r")
f_list = f.read().split(' ')
f.close()
#Now, we get the entry after "password" (be slicker to make it a
#dictionary, but maybe wouldn't work as well).
pass_index = f_list.index('password') + 1
forwardpass = f_list[pass_index]
#now we connect
command = 'ssh -l %s -L 2022:%s:22 %s' % \
  (login, my_server, forwarding_server)
connection = pexpect.spawn(command)
connection.expect('.*assword:')
connection.sendline(forwardpass)

If I end this with 'connection.interact()', I will end up logged in to the
forwarding server. But what I really want is to go on and run rsync to
localhost port 2022, which will forward to my_server port 22. So, how can
I put the ssh connection I set up in hostforward() in the background?
I need to make sure that connection is made before I can run the rsync
command.

I've looked at threading, but that seems excessive. There must be an
easier way. Whatever I do, though, I'll need to use pexpect to spawn the
processes, since I'll need to log in to ssh servers with a password.

Thanks for any help.

--Jesse


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


Python for Gaim

2005-11-15 Thread Boichenko Sergey

Hello everybody.

We wrote a Python plugin for Gaim. Now you can write plugins for Gaim and use 
Python.
ALL Gaim API are available for developers under Python.

You can download this on http://sourceforge.net/projects/pygaim 
Please include it as a plugin for GAIM(like perl)

Best regards,
Sergey

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


Re: compare list

2005-11-15 Thread [EMAIL PROTECTED]

Simon Brunning wrote:
> On 15/11/05, Ben Bush <[EMAIL PROTECTED]> wrote:
> > I found I named the following python file as sets.py, which brought the
> > problem (is that right?). i changed it to other name and it works.
> > But the logic output is wrong.
> > from sets import Set as set
> > lisA=[1,2,5,9]
> > lisB=[9,5,0,2]
> > lisC=[9,5,0,1]
> > def two(sequence1, sequence2):
> >set1, set2 = set(sequence1), set(sequence2)
> >return len(set1.intersection(set2)) == 2
> >  print two(lisA,lisB)
> > False(should be true!)
>
> It looks to me like A and B have three members in common - 2, 5 and 9.
>
Any chance that while "two" performs correctly for what is intended, it
is not what the OP wants ?

Seems that he only thins the "5,9"/"9,5" are the common case, thus
expect 2 ?

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


Re: generate HTML

2005-11-15 Thread Jim
Perhaps you are trying to do this:
  'text to go here: %s' % ('text',)
?  For that you need a double-quoted string:
  "text to go here: %s" % ('text',)
(or triple-doubles: """ .. """ as you noted).

Jim

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


Re: 3-dimensional plot in Python?

2005-11-15 Thread Robert Kern
Frithiof Andreas Jensen wrote:
> "questions?" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> 
>>I want to make a 3d plot. x is a vector(discrete), y is also a
>>vector(discrete), for each pairwise x,y I have a value z(x,y)(it is not
>>a function, just discrete values for each pair of x,y)
>>
>>I want to show them on a two dimensional plot by showing z(x,y) with
>>colors.
>>
>>Thanks for any hint
> 
> SciPy is your friend: Provides interfaces to several plot engines, including
> gnuplot.

Those interfaces are long since deprecated. Please use matplotlib instead.

http://matplotlib.sf.net

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


RE: Is Python worth it??

2005-11-15 Thread Sells, Fred
I second what others have said about the tutorials.  I have not read "how to
think like a ..." but from other posting here I have reservations about it
as a starting point.

-Original Message-
From: Simon Brunning [mailto:[EMAIL PROTECTED]
Sent: Tuesday, November 15, 2005 4:42 AM
To: john boy
Cc: [email protected]
Subject: Re: Is Python worth it??


On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> I have started out trying to learn Python for my first programming
language.
>  I am starting off with the book "how to think like a computer scientist."
> I spend about 4-5 hrs a day trying to learn this stuff.  It is certainly
no
> easy task.  I've been at it for about 1-2 weeks now and have a very
> elementary picture of how Python works.  I am teaching myself from home
and
> only recieve help from this forum.  Can anybody give me a timeframe as to
> how long it usually takes to pick something like this up, so I can maybe
> figure out a way to pace myself?  I can dedicate a good amount of time to
it
> everyday.  Any advice on what is the best way to learn Python?  I am a
> fairly educated individual with a natural sciences degree (forestry), so I
> also have a decent math background.  Are there any constraints
> mathematically or logic "wise" that would prevent me from building a firm
> grasp of this language?

Keep at it.

Everyone is different, so don't worry about how long it takes you vs.
how long others might take. If you have no programming background,
there's a lot to learn. Using Python is a good choice, I think, 'cos
it gets a lot of extranious crud that many other languages insist on
out of your way, but there's still a lot to learn.

The best way to learn? Go through the tutorials - but if you get an
idea for a mini-project of your own, don't be afraid to dive off and
give it a go. Try to solve you own problems for a while, 'cos that's a
valuable skill, but don't get to the point of frustration. Ask for
help here or on the tutor mailing list[1].

And have fun.

[1] http://mail.python.org/mailman/listinfo/tutor

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


_winreg doc unclear on DeleteValue()

2005-11-15 Thread rtilley
A portion from the _winreg Documnetation:
-
DeleteValue(key, value)
 1. Removes a named value from a registry key. --> OK
 2. key is an already open key, or one of the predefined HKEY_* 
constants. --> OK
 3. value is a string that identifies the value to remove. --> 
misleading
--

When I use EnumValue like this:

Value_Name, Value, Type = EnumValue(key, index)

I expect to use DeleteValue like this (as per the docs):

DeleteValue(open_run_key, Value)

When in fact, I should use it like this:

DeleteValue(open_run_key, Value_Name)

Perhaps this is nitpicking and I'm the only person in the world that 
finds the docs a bit mis-leading here, if so, just disregard this post.

rbt

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


Re: Is Python worth it??

2005-11-15 Thread jmdeschamps

Simon Brunning wrote:
> On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> > I have started out trying to learn Python for my first programming language.
> >  I am starting off with the book "how to think like a computer scientist."
> > I spend about 4-5 hrs a day trying to learn this stuff.  It is certainly no
> > easy task.  I've been at it for about 1-2 weeks now and have a very
> > elementary picture of how Python works.  I am teaching myself from home and
> > only recieve help from this forum.  Can anybody give me a timeframe as to
> > how long it usually takes to pick something like this up, so I can maybe
> > figure out a way to pace myself?  I can dedicate a good amount of time to it
> > everyday.  Any advice on what is the best way to learn Python?  I am a
> > fairly educated individual with a natural sciences degree (forestry), so I
> > also have a decent math background.  Are there any constraints
> > mathematically or logic "wise" that would prevent me from building a firm
> > grasp of this language?
>
> Keep at it.
>
> Everyone is different, so don't worry about how long it takes you vs.
> how long others might take. If you have no programming background,
> there's a lot to learn. Using Python is a good choice, I think, 'cos
> it gets a lot of extranious crud that many other languages insist on
> out of your way, but there's still a lot to learn.
>
> The best way to learn? Go through the tutorials - but if you get an
> idea for a mini-project of your own, don't be afraid to dive off and
> give it a go. Try to solve you own problems for a while, 'cos that's a
> valuable skill, but don't get to the point of frustration. Ask for
> help here or on the tutor mailing list[1].
>
> And have fun.
>
> [1] http://mail.python.org/mailman/listinfo/tutor
>
> --
> Cheers,
> Simon B,
> [EMAIL PROTECTED],
> http://www.brunningonline.net/simon/blog/

Here's another reference:
http://www.awaretek.com/tutorials.html
Tutorials are sorted by type, and the first type is 'beginners' but it
really depends on the level of hand-holding you wish. Your background
suggest that you should look at something like Richard Baldwin's Learn
to Program Using Python (no programming experience required)...

Good luck.

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


simulating #include in python

2005-11-15 Thread Nick Craig-Wood
We are currently investigating whether to move the data files from our
application into python for ease of maintenance.  Each data item turns
into a class definition with some class data.  The python approach
looks great, but there is one feature that we'd like to have.

Currently the data files can include other data files.  Typically
thats used to import standard definitions from somewhere else (rather
like #include in C - conceptually its a completely textual import).
We use them something like this

  include("../../standard_definitions")
  include("../shared_definitions")

  class A(base_from_standard_definitions): pass
  class B(A): pass

  include("more_definitions")

The includes act much more like #include than import - all the symbols
from the file before the include() must be available to the included
file and the included file must export all its symbols back to the
parent.

These can of course be re-arranged to work in a pythonic way using
'from x import *' and putting "../.." on sys.path instead of the
includes.  However there are over 500 of these files so I'd prefer a
more automatic solution which doesn't require re-arrangement in the
interim. (The re-arrangement is needed because "more_definitions"
above might refer to A, B or anything defined in
standard/shared_definitions leading to mutually recursive imports and
all the pain they cause)

I have implemented a working prototype, but it seems such a horrendous
bodge that there must surely be a better way!  I'd really like to be
able to run an __import__ in the context of the file thats running the
include() but I haven't figured that out.

Here is the code (avert your eyes if you are of a sensitive nature ;-)
Any suggestions for improvement would be greatly appreciated!

def include(path):

# Add the include directory onto sys.path
native_path = path.replace("/", os.path.sep)
directory, module_name = os.path.split(native_path)
if module_name.endswith(".py"):
module_name = module_name[:-3]
old_sys_path = sys.path
if directory != "":
sys.path.insert(0, directory)

# Introspect to find the parent
# Each record contains a frame object, filename, line number, function
# name, a list of lines of context, and index within the context.
up = inspect.stack()[1]
frame = up[0]
parent_name = frame.f_globals['__name__']
parent = sys.modules[parent_name]

# Poke all the current definitions into __builtin__ so the module
# uses them without having to import them
old_builtin = __builtin__.__dict__.copy()
overridden = {}
poked = []
for name in dir(parent):
if not (name.startswith("__") and name.endswith("__")):
if hasattr(__builtin__, name):
overridden[name] = getattr(__builtin__, name)
else:
poked.append(name)
setattr(__builtin__, name, getattr(parent, name))

# import the code
module =  __import__(module_name, parent.__dict__, locals(), [])

# Undo the modifications to __builtin__
for name in poked:
delattr(__builtin__, name)
for name, value in overridden.items():
setattr(__builtin__, name, value)

# check we did it right! Note __builtin__.__dict__ is read only so
# can't be over-written
if old_builtin != __builtin__.__dict__:
raise AssertionError("Failed to restore __builtin__ properly")

# Poke the symbols from the import back in
for name in dir(module):
if not (name.startswith("__") and name.endswith("__")):
setattr(parent, name, getattr(module, name))

# Restore sys.path
sys.path = old_sys_path

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where can I find an example that uses FTP standard library?

2005-11-15 Thread Larry Bates
Pick up a copy of the Python Cookbook, it is full of examples.

You also might want to check out this site:

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

It contains 100's of code samples that might help.

The archives of this list are also a good place to look.
Google is also your friend.  I entered python ftplib example
and turned up several examples like:

http://postneo.com/stories/2003/01/01/beyondTheBasicPythonFtplibExample.html

-Larry Bates

QuadriKev wrote:
> I am fairly new to programming in Python.  There are a number of cases
> where I would like to see examples of programs written.  I like to
> write them on Windows and in some cases put them on my Linux server to
> do something useful.
> 
> I am also interested in using Telnet to check services and things on
> the Linux server.  Can someone give me direction on the best place for
> examples?  Full example of something written with GTK or wxPython would
> be very interesting also.
> 
> TIA
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AJAX => APAX? Or: is there support for python in browsers?

2005-11-15 Thread Larry Bates
Roger Erens wrote:
> Hello,
> 
> I remember that the first time I read about Python as a programming
> language was when reading the W3C's HTML 4.01 specification a few years
> ago. In the section on objects, images and applets
> (http://www.w3.org/TR/html401/struct/objects.html) an example was given
> like
> 
> http://www.miamachina.it/analogclock.py";>
> 
> 
> This user agent cannot render Python applications.
> 
> 
> It's also in the XHTML2.0 specification. Now, is this just a theoretical
> example? Or is there a browser that _does_ support python scripts? Or do
> we have to place our bets on the Mozilla 1.9 milestone with hard work
> being done by Mark Hammond?
> 
> I'm asking because of all the AJAX hype going on. I'd like rather not
> delve too deep into JavaScript and use Python instead.
> 
> Any insights to be shared?
> 
> Cheers,
> Roger

Take a look at this kit:

http://www.mochikit.com/

It seems that this is a python programmer that has created JavaScript
functions that "feel" a lot like Python.  May just be a transitional
way to go, but I thought it was interesting anyway.

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


Sending an event from a python COM server to a VB COM client

2005-11-15 Thread Gary Kshepitzki
Hello
I am trying to send an event from a Python COM server to a VB (or VB.NET) 
COM client.
I am a newbie both in VB and in python.
Can anyone give me a simple (but complete) code example both of the Python 
server side and the VB client side for raising a single event.

Any answer would be highly appreciated.
Regards
Gary


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


Re: simulating #include in python

2005-11-15 Thread Peter Otten
Nick Craig-Wood wrote:

> I'd really like to be able to run an __import__ in the context of the file
> thats running the include() but I haven't figured that out. 

execfile()?

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


A way for launch an app monitor

2005-11-15 Thread Daniel Crespo
Hello,

I'm in the way for creating an application and its monitor. Yes, there
are 2 applications: The main app, and a monitor. The last one monitors
the main application for keeping it alive, and viceversa. But if I
close the main app, I want to close the monitor.

That is very easy under nt systems, but in 98 is a little more tricky
because of the problem with closing processes.

For example, I can't use the following code on a win98 machine:

def FindPID(exename):
"""
usage:
pid=FindPID("pythonw.exe")
print pid
"""
a = os.popen4('tasklist /FI "IMAGENAME eq '+exename+'"')
a[0].flush()
try:
info=a[1].readlines()[3].split()
except:
info=[exename,"NotFound"]
return info[1] #PID

because the "tasklist" command doesn't exist on win98. Also, I tried to
install the kill.exe and a dont-remember-dll (from the Win98 Resource
Kit), but it doesn't work.

So my solution (need help on this) is that I have been thinking on
letting the monitor listen for socket connection. Through this, the
main app can tell him to close when the main app closes correctly. Do
you think this is well thought? Any suggestions?

Daniel

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


A way for closing an app monitor

2005-11-15 Thread Daniel Crespo
Hello,

I'm in the way for creating an application and its monitor. Yes, there
are 2 applications: The main app, and a monitor. The last one monitors
the main application for keeping it alive, and viceversa. But if I
close the main app, I want to close the monitor.

That is very easy under nt systems, but in 98 is a little more tricky
because of the problem with closing processes.

For example, I can't use the following code on a win98 machine:

def FindPID(exename):
"""
usage:
pid=FindPID("pythonw.exe")
print pid
"""
a = os.popen4('tasklist /FI "IMAGENAME eq '+exename+'"')
a[0].flush()
try:
info=a[1].readlines()[3].split()
except:
info=[exename,"NotFound"]
return info[1] #PID

because the "tasklist" command doesn't exist on win98. Also, I tried to
install the kill.exe and a dont-remember-dll (from the Win98 Resource
Kit), but it doesn't work.

So my solution (need help on this) is that I have been thinking on
letting the monitor listen for socket connection. Through this, the
main app can tell him to close when the main app closes correctly. Do
you think this is well thought? Any suggestions?

Daniel

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


Re: q: console widgets for *nix and windows?

2005-11-15 Thread Grant Edwards
On 2005-11-15, aum <[EMAIL PROTECTED]> wrote:
> On Mon, 14 Nov 2005 20:56:36 +, Grant Edwards wrote:
>
>>> Can anyone please recommend a widget library for text console,
>>> that works not only on *nix systems but windows /as well/?
>>> I'm looking for something a bit higher-level than pure curses,
>>> preferably with a gui-like set of widgets, event loop, handler
>>> methods etc.
>> 
>> http://tvision.sourceforge.net/
>
> Thanks - but the python wrapper (pytvision.sf.net) is pretty broken,
> particularly the windows build.

Sorry about that, I've never tried it under python.  I tried a
C demo under linux a few years back.

> Any other suggestions?

I'm not aware of Python support for it, but there's also the
"Curses Development Kit" (CDK).  IIRC, it's a little
lower-level that what you're asking for, but I'm not really
aware of anything else.

http://www.vexus.ca/products/CDK/
http://invisible-island.net/cdk/


-- 
Grant Edwards   grante Yow!  Could I have a drug
  at   overdose?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal for adding symbols within Python

2005-11-15 Thread Grant Edwards
On 2005-11-15, Ben Sizer <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> In the situations described, I always use strings
>> and have never felt the need for something else:
>
> ...
>
>> I don't think I even understand what the objection is.  What is
>> needed is a code fragment that shows how the use of strings is
>> untenable.
>
> myObject.value = 'value1'
>
> #... 100 lines of code elided...
>
> if myObject.value == 'Value1':
> do_right_thing()
> else:
> do_wrong_thing()
>
> I don't actually think string use is 'untenable', but it is
> definitely more error-prone. With some sort of named object on
> the right hand side you will at least get a helpful NameError.

I don't see how that's an argument in favor of the proposal
being discussed.  Aren't $Value1 and $value1 both legal and
distinct symbols in the proposed syntax?  Won't you have the
exact same issue that you do with mis-typing strings?

-- 
Grant Edwards   grante Yow!  .. Do you like
  at   "TENDER VITTLES?"?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


wxpython and EVT_KILL_FOCUS

2005-11-15 Thread Stefanie Wagner
Hello, I am fighting with EVT_KILL_FOCUS for quite a time now and I
don't succeed at all.

Situation:

If a user leaves a textfield the entered information should be checked
and an additional window should be opened to make a search possible to
complete the entry.

Basic solution:

def __init__(...):
  ...
  self.artikelnrBox = wxTextCtrl(self.bestelldialog, -1, artikelnr,
wxPoint(60,290), wxSize(60, -1))
  ...
  EVT_KILL_FOCUS(self.artikelnrBox, self.OnArtikel)
  ...

def OnArtikel(self,event):
  event.Skip()
  
  artikelnr = self.artikelnrBox.GetValue().strip()
  ...
  dialog =
dialog_stamm_artikel.ArtikelSucheDialog(self.bestelldialog,artikelnr)
  ergebnis,artikelid = dialog.GetValues()
  dialog.Destroy()
  ...

Problem:

If I don't open any dialog everything works fine. But if there is a
dialog around the window opens, I can count to two and the whole
application crashes.

The error message is:
(gui.py:29768): Gtk-WARNING **: GtkEntry - did not receive
focus-out-event. If you
connect a handler to this signal, it must return
FALSE so the entry gets the event as well

Gtk-ERROR **: file gtkentry.c: line 4919 (blink_cb): assertion failed:
(GTK_WIDGET_HAS_FOCUS (entry))
aborting...

Reason of the problem:

I found a very good description for the reason:

> This is a lot easier to understand with a timeline:

> - focus into GtkEntry
> - GtkEntry installs timeout for cursor blinking
> - focus out of entry
> - GtkEntry emits focus-out-event
> - your handler runs **before the default handler**.
> - your handler traps exception and creates dialog box
> - dialog box runs nested event loop
> - event processing continues, focus goes to another widget
> - entry's cursor blink timeout is still installed, and runs again.
> entry does not have focus, but timeout has run, so the widget
> is in an invalid state and calls g_error() with a nastygram.
> - default handler runs, uninstalls cursor blink timeout

> The problem is that you're allowing the event loop to run in your handler for 
> focus-out.

Ok, if I use EVT_KILL_FOCUS the event has not finished completly, this
timeout is still around. That's ok with me but I thought this is what
event.Skip() is for, to call the standard handler.

Solution:

And there I am. event.Skip() doesn't help at all. And the other source
gives the following suggestion:

> a) use signal_connect_after to have your handler run *after* the default 
> handler for focus-out-event instead of before.
> b) leave the signal connected normally, but in your "catch" block, instead of 
> running the dialog right then, defer it with an idle, like this:

I couldn't find signal_connect_after anywhere in wxpython and I don't
know how to use idle in this case. And I have the problem more than
once (every time a have an error message in other EVT_KILL_FOCUS
routines).

There must be some solution to use EVT_KILL_FOCUS and a dialog without
killing the application.

Please help!

 Steffi

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


Re: generate HTML

2005-11-15 Thread Kent Johnson
Jim wrote:
> Perhaps you are trying to do this:
>   'text to go here: %s' % ('text',)
> ?  For that you need a double-quoted string:
>   "text to go here: %s" % ('text',)

Uh, no, not in Python:
 >>> 'text to go here: %s' % ('text',)
'text to go here: text'
 >>> "text to go here: %s" % ('text',)
'text to go here: text'

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


Re: generate HTML

2005-11-15 Thread Thomas Guettler
Am Tue, 15 Nov 2005 02:52:54 -0800 schrieb ss2003:

> alist = [ '
> ValueError: unsupported format character '"' (0x22) at index 14

Look at this:

===> python
Python 2.3.4 (#1, Feb  7 2005, 15:50:45) 
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "a%qb%sc"
'a%qb%sc'
>>> "a%qb%sc" % (1)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: unsupported format character 'q' (0x71) at index 2

If you don't have a '% (...)' behind the string, all percent signs are
ignored. But if you use it, %q will bring you an error because only %s, %d, ...
is supported.

If you create html, here the way I do it:

rows=[]
for i in range(...).
rows.append("")
rows=''.join(rows)

date=time.strftime()
html="""
 Today: %(date)s
 
 %(rows)s
 
 """ % locals()

outfile="out.html"
fd=open(outfile, "wt")
fd.write(html)
fd.close()
print "Created %s" % outfile

HTH,
 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Need advice on subclassing code

2005-11-15 Thread Rusty Shackleford
Hi --

We have some code that returns an object of a different class, depending
on some parameters.  For example:

if param x is 1 and y is 1, we make an object of class C_1_1.
if param x is 1 and y is 2, we make an object of class C_1_2.

C_1_1 and C_1_2 share a common C ancestor, and in practice may be
identical, but theoretically, could have the same function name with two
different implementations underneath.

We have a file where all the C_X_Y classes are defined.  It looks sort
of like this:

class C_1_1(C):
"""Creates a x=1 and y=1 class"""
def __init__(self):
C.__init__(self, 1, 1)

class C_1_2(C):
"""Creates a x=1 and y=2 class"""
def __init__(self):
C.__init__(self, 1, 2)

99% of the specific classes do the exact same thing.  For a tiny few,
the class definition looks like this:

class C_3_5(C):
"""Creates a x=3, y=5 class."""
def __init__(self):
C.__init__(self, 3, 5)

def foo(self):
"""Redefine the default C.foo() function."""
return 99

The reason for this is that we want to allow different classes to do
non-standard behavior.  In practice, however, it turns out that most of
the time, we don't need anything special.

Is this the best solution?  Is there some way of doing a default vs.
non-default deal, without having to manually hardcode all the different
possible subclasses?

Thanks for the help.

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python worth it??

2005-11-15 Thread bytecolor
http://www.norvig.com/21-days.html

-- 
bytecolor

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


Re: Background process for ssh port forwarding

2005-11-15 Thread Micah Elliott
On Nov 15, Jesse Rosenthal wrote:
> Whatever I do, though, I'll need to use pexpect to spawn the
> processes, since I'll need to log in to ssh servers with a password.

You might save yourself this effort by setting up ssh for
non-interactive use with keys instead of password authentication:

   $ cd ~/.ssh
   $ chmod 700 .
   $ ssh-keygen -t rsa  # just keep pressing 
   $ cp id_rsa.pub authorized_keys2

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need advice on subclassing code

2005-11-15 Thread [EMAIL PROTECTED]
Would the approach of using a switch to decide to instatite which class
good for you, like:

py> class C:
py. name = 'C'
py.
py> class D:
py. name = 'D'
py.
py> switch = { (1, 1): C, (1,2): D }
py> x = 1
py> y = 2
py> c = switch[(x,y)]()
py> print c.name
D
py>

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


Inheritance in nested classes

2005-11-15 Thread Martin Skou
I'm experimenting with using Python for a small web interface, using
Mark Hammond's nice win32 extensions.

I use a small class hierarchy which uses inheritance and nested classes.

Here are a small extract of the code:

class page:

def __init__(self):
self.head=[]

def __str__(self):
...

class simple_tag:
... 

class p(simple_tag):
...

class table:
...

class row:
...

class data:
...
...


Will this type of code perform noticable slower than unnested classes?

I'm using the Active Server Pages integration in the win32 extensions,
does anyone have good/bad experiences using this interface?

Thanks.

/Martin

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


Re: Default method arguments

2005-11-15 Thread Bill Mill
On 15 Nov 2005 08:03:26 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hello everybody!
> I have little problem:
>
> class A:
> def __init__(self, n):
> self.data = n
> def f(self, x = )
> print x
>
> All I want is to make self.data the default argument for self.f(). (I
> want to use 'A' class as following :
>
> myA = A(5)
> myA.f()
>
> and get printed '5' as a result.)
>

class A:
def __init__(self, n):
self.data = n

def f(self, x=None):
if not x:
x = self.data
print x

>>> myA = A(5)
>>> myA.f()
5

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default method arguments

2005-11-15 Thread Nicola Larosa
> I have little problem:
> 
> class A:
> def __init__(self, n):
> self.data = n
> def f(self, x = )
> print x
> 
> All I want is to make self.data the default argument for self.f(). (I
> want to use 'A' class as following :
> 
> myA = A(5)
> myA.f()
> 
> and get printed '5' as a result.)

# use new-style classes, if there's no cogent reason to do otherwise
class A(object):
def __init__(self, n):
self.data = n
def f(self, x = None)
# do NOT use "if not x" !
if x is None:
print self.data
else:
print x

-- 
Nicola Larosa - [EMAIL PROTECTED]

...Linux security has been better than many rivals. However, even
the best systems today are totally inadequate. Saying Linux is
more secure than Windows isn't really addressing the bigger issue
 - neither is good enough. -- Alan Cox, September 2005
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default method arguments

2005-11-15 Thread Nicola Larosa
> def f(self, x=None):
> if not x:

Ha! You fell for it! ;-D
(Hint: what about x being passed with a value of zero? :-) )

> x = self.data
> print x

-- 
Nicola Larosa - [EMAIL PROTECTED]

...Linux security has been better than many rivals. However, even
the best systems today are totally inadequate. Saying Linux is
more secure than Windows isn't really addressing the bigger issue
 - neither is good enough. -- Alan Cox, September 2005
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default method arguments

2005-11-15 Thread Duncan Booth
Nicola Larosa wrote:
> # use new-style classes, if there's no cogent reason to do otherwise
> class A(object):
> def __init__(self, n):
> self.data = n
> def f(self, x = None)
> # do NOT use "if not x" !
> if x is None:
> print self.data
> else:
> print x
> 

Using None might be problematic if None could be a valid argument. The 
safest way all round is to use a unique object created just for this 
purpose:

_marker = object()

class A(object):

def __init__(self, n):
self.data = n

def f(self, x=_marker)
if x is _marker:
x = self.data
print x
-- 
http://mail.python.org/mailman/listinfo/python-list


Default method arguments

2005-11-15 Thread gregory . petrosyan
Hello everybody!
I have little problem:

class A:
def __init__(self, n):
self.data = n
def f(self, x = )
print x

All I want is to make self.data the default argument for self.f(). (I
want to use 'A' class as following :

myA = A(5)
myA.f()

and get printed '5' as a result.)

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


Re: Default method arguments

2005-11-15 Thread Bill Mill
On 11/15/05, Nicola Larosa <[EMAIL PROTECTED]> wrote:
> > def f(self, x=None):
> > if not x:
>
> Ha! You fell for it! ;-D
> (Hint: what about x being passed with a value of zero? :-) )

I wasn't sure if you saw my post before you posted - good call. I just
tossed off an answer without thinking much, and we see the result. It
could have been a good debugging lesson for him if he'd tried to pass
0; I think I'll use that as my excuse.

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default method arguments

2005-11-15 Thread Gregory Petrosyan
I want to find REALLY NICE AND PYTHONIC solution (if any)

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


Re: Default method arguments

2005-11-15 Thread Nicola Larosa
> Using None might be problematic if None could be a valid argument.

That's like saying that NULL could be a significant value in SQL. In
Python, "None" *is* the empty, not significant value, and should always be
used as such. Specifically, never exchange "None" for "False".

-- 
Nicola Larosa - [EMAIL PROTECTED]

...Linux security has been better than many rivals. However, even
the best systems today are totally inadequate. Saying Linux is
more secure than Windows isn't really addressing the bigger issue
 - neither is good enough. -- Alan Cox, September 2005
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simulating #include in python

2005-11-15 Thread Nick Craig-Wood
Peter Otten <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood wrote:
> 
> > I'd really like to be able to run an __import__ in the context of the file
> > thats running the include() but I haven't figured that out. 
> 
>  execfile()?

Yes thats exactly what I was looking for - thank you very much!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need advice on subclassing code

2005-11-15 Thread bruno at modulix
Rusty Shackleford wrote:
> Hi --
> 
> We have some code that returns an object of a different class, depending
> on some parameters.  For example:
> 
> if param x is 1 and y is 1, we make an object of class C_1_1.
> if param x is 1 and y is 2, we make an object of class C_1_2.
> 
> C_1_1 and C_1_2 share a common C ancestor, and in practice may be
> identical, but theoretically, could have the same function name with two
> different implementations underneath.
> 
> We have a file where all the C_X_Y classes are defined.  It looks sort
> of like this:
> 
(snip)

> 99% of the specific classes do the exact same thing.  For a tiny few,
> the class definition looks like this:
> 
(snip same code with minor differences...)
>
> The reason for this is that we want to allow different classes to do
> non-standard behavior.  In practice, however, it turns out that most of
> the time, we don't need anything special.
> 
> Is this the best solution? 

No, of course - but I guess you knew it already !-)

> Is there some way of doing a default vs.
> non-default deal, without having to manually hardcode all the different
> possible subclasses?

Here are the pieces of the puzzle:
- A dict is usually the best choice for lookups.
- A tuple can serve as key for a dict.
- A (reference to) a class object can be stored in a dict (or the name
of the class, as a string).
- the get() method of a dict allow for an optional default value to be
use if the requested key is not found

And here's a first go:

def get_object(x, y):
  specials = {
(1, 2): C_1_2,
(33, 42): C_33_42,
  }
  # assume class C is the default class
  klass = specials.get((x, y), C)
  return klass()

Now if you store the class names as strings, ie :


  specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
  }

you can use a config file (ini, XML, Yaml, or even plain old python) to
store the 'specials' mapping and the default class name, and have
get_object() read from that config file. The trick is to get the class
from the class's name, which is solved with getattr():

def get_object(x, y):
  specials = {
(1, 2): "C_1_2",
(33, 42): "C_33_42",
  }
  # assume class 'C' is the default class
  class_name = specials.get((x, y), "C")

  # from class name to class:
  klass = getattr(module_where_classes_live, class_name)
  return klass()


I think you should be able to solve your problem with this.

A last thing: the name of the module storing the classes can also be
stored in a conf file. Use __import__() to get the module object from
it's name.


HTH
-- 
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: Need advice on subclassing code

2005-11-15 Thread Kent Johnson
Rusty Shackleford wrote:
> Hi --
> 
> We have some code that returns an object of a different class, depending
> on some parameters.  For example:
> 
> if param x is 1 and y is 1, we make an object of class C_1_1.
> if param x is 1 and y is 2, we make an object of class C_1_2.
> 
> C_1_1 and C_1_2 share a common C ancestor, and in practice may be
> identical, but theoretically, could have the same function name with two
> different implementations underneath.
> 
> We have a file where all the C_X_Y classes are defined.  
> Is this the best solution?  Is there some way of doing a default vs.
> non-default deal, without having to manually hardcode all the different
> possible subclasses?

How are you instantiating the correct class? You should be able to provide a 
default behaviour. For example if the classes are all defined in module C you 
could have a factory like this:

import C
def makeC(x, y):
  subtype = 'C_%d_%d' % (x, y)
  cls = getattr(C, subtype, C.C)
  return cls(x, y)

Then in module C just define the subtypes you need to specialize; all other 
values of x and y will get the base class C.C.

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


Re: Default method arguments

2005-11-15 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
> Hello everybody!
> I have little problem:
> 
> class A:
> def __init__(self, n):
> self.data = n
> def f(self, x = )
> print x
> 
> All I want is to make self.data the default argument for self.f(). (I
> want to use 'A' class as following :
> 
> myA = A(5)
> myA.f()
> 
> and get printed '5' as a result.)
> 

class A(object): # Stop using old-style classes, please
  def __init__(self, n):
self.data = n
  def f(self, x = None):
if x is None:
  x = self.data
print x



-- 
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: Is Python worth it??

2005-11-15 Thread Paul Watson
Simon Brunning wrote:
> On 14/11/05, john boy <[EMAIL PROTECTED]> wrote:
> 
>>I have started out trying to learn Python for my first programming language.
>> I am starting off with the book "how to think like a computer scientist."
>>I spend about 4-5 hrs a day trying to learn this stuff.  It is certainly no
>>easy task.  I've been at it for about 1-2 weeks now and have a very
>>elementary picture of how Python works.  I am teaching myself from home and
>>only recieve help from this forum.  Can anybody give me a timeframe as to
>>how long it usually takes to pick something like this up, so I can maybe
>>figure out a way to pace myself?  I can dedicate a good amount of time to it
>>everyday.  Any advice on what is the best way to learn Python?  I am a
>>fairly educated individual with a natural sciences degree (forestry), so I
>>also have a decent math background.  Are there any constraints
>>mathematically or logic "wise" that would prevent me from building a firm
>>grasp of this language?
> 
> 
> Keep at it.
> 
> Everyone is different, so don't worry about how long it takes you vs.
> how long others might take. If you have no programming background,
> there's a lot to learn. Using Python is a good choice, I think, 'cos
> it gets a lot of extranious crud that many other languages insist on
> out of your way, but there's still a lot to learn.
> 
> The best way to learn? Go through the tutorials - but if you get an
> idea for a mini-project of your own, don't be afraid to dive off and
> give it a go. Try to solve you own problems for a while, 'cos that's a
> valuable skill, but don't get to the point of frustration. Ask for
> help here or on the tutor mailing list[1].
> 
> And have fun.
> 
> [1] http://mail.python.org/mailman/listinfo/tutor
> 
> --
> Cheers,
> Simon B,
> [EMAIL PROTECTED],
> http://www.brunningonline.net/simon/blog/

Python is a great choice for a first language.  I agree with the 
tutorial recommendations of others.

I would suggest that you focus on getting out of it what you want out of 
it.  Get some data about rainfall and correlate it with regional fires, 
economic output, or religious practices.  That will get you reading 
data, calculating, and writing output.

Read more code than you write.  Download the Python sources and 
unpackage them on your machine.  You do not have to build the 
executable.  Lot's of the Python library functions are written in 
Python.  Try to explain what the code is doing.  If you do not yet 
understand (after applying due diligence and using Google), then ask 
questions.  Questions are good.  Questions are our friend.

Write as much code as you can.  Get comfortable with a debugger where 
you can watch the action happen.

There are many fundamental computer concepts such as memory, storage, 
persistence, threading, and all that.  Do not worry about understanding 
these in the first few weeks.  Focus on getting out of it something that 
you want.  Understanding the concepts will come to you as you are a 
practitioner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python worth it??

2005-11-15 Thread Luis M. Gonzalez
I was in you situation, and I'll tell you what worked for me:

Online tutorials:
I suggest starting out with Josh Cogliati's "Non-Programmers tutorial
for Python" (http://www.honors.montana.edu/~jjc/easytut/easytut/) .
It is an ideal introduction for a complete beginner, very easy to
follow and right to the point.

After that, I'd suggest:

- A byte of Python by Swaroop C. H. (http://www.byteofpython.info/)
This one is also a very easy and complete introduction.


This would be enough to get you going and comfortable with Python, but,
you may still need some good and simple introduction to object oriented
programing.
For that, I suggest Alan Gauld's "Learning to Program"
(http://www.freenetpages.co.uk/hp/alan.gauld/). Pay special attention
to the object oriented programming chapter. It has a simple "banking
accounts" example that was a real eye opener for me.

Of course, It won't hurt if you check regularly the official tutorial
by Guido Van Rossum, but I wouldn't use it as a step to step
introduction, because it seems more like an overview of the language.
More indicated for someone who's looking for something specific.

Good luck!
Luis

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


Re: Inheritance in nested classes

2005-11-15 Thread Diez B. Roggisch
Martin Skou wrote:
> I'm experimenting with using Python for a small web interface, using
> Mark Hammond's nice win32 extensions.
> 
> I use a small class hierarchy which uses inheritance and nested classes.
> 
> Here are a small extract of the code:
> 
> class page:
>   
>   def __init__(self):
>   self.head=[]
>   
>   def __str__(self):
>   ...
> 
>   class simple_tag:
>   ... 
>   
>   class p(simple_tag):
>   ...
>   
>   class table:
>   ...
> 
>   class row:
>   ...
>   
>   class data:
>   ...
>   ...
> 
> 
> Will this type of code perform noticable slower than unnested classes?

I'm not aware that there is much runtime penalty here - a quick test 
reveals that:

import time

class Foo:
 def __init__(self, baz):
self.baz = baz

def unnested():
 o = Foo(10)

def nested():
 class Foo:
def __init__(self, baz):
self.baz = baz



then = time.time()
for i in xrange(10):
 unnested()
print time.time() - then

then = time.time()
for i in xrange(10):
 nested()
print time.time() - then


Yields

0.839588165283
0.817638158798

for me.

But I hope you are aware that nested classes aren't quite the same as 
they are in java, are you?

Regards,

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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-15 Thread Alex Martelli
Neal  Norwitz <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> >
> > So, I thought I'd turn to the "wisdom of crowds"... how would YOU guys
> > go about adding to your automated regression tests one that checks that
> > a certain memory leak has not recurred, as cross-platform as feasible?
> > In particular, how would you code _memsize() "cross-platformly"?  (I can
> > easily use C rather than Python if needed, adding it as an auxiliary
> > function for testing purposes to my existing extension).
> 
> If you are doing Unix, can you use getrusage(2)?

On Unix, I could; on Linux, nope.  According to man getrusage on Linux,

"""
   The above struct was taken from BSD 4.3 Reno.  Not all fields are
meaningful under Linux.   Right  now  (Linux  2.4,  2.6)  only  the
fields ru_utime,  ru_stime, ru_minflt, ru_majflt, and ru_nswap are
maintained.
"""
and indeed the memory-usage parts are zero.


> >>> import resource
> >>> r = resource.getrusage(resource.RUSAGE_SELF)
> >>> print r[2:5]
> 
> I get zeroes on my gentoo amd64 box.  Not sure why.  I thought maybe it
> was Python, but C gives the same results.

Yep -- at least, on Linux, this misbehavior is clearly documented in the
manpage; on Darwin, aka MacOSX, you _also_ get zeros but there is no
indication in the manpage leading you to expect that.

Unfortunately I don't have any "real Unix" box around -- only Linux and
Darwin... I could try booting up OpenBSD again to check that it works
there, but given that I know it doesn't work under the most widespread
unixoid systems, it wouldn't be much use anyway, sigh.


> Another possibiity is to call sbrk(0) which should return the top of
> the heap.  You could then return this value and check it.  It requires
> a tiny C module, but should be easy and work on most unixes.  You can

As I said, I'm looking for leaks in a C-coded module, so it's no problem
to add some auxiliary C code to that module to help test it --
unfortunately, this approach doesn't work, see below...

> determine direction heap grows by comparing it with id(0) which should
> have been allocated early in the interpreters life.
> 
> I realize this isn't perfect as memory becomes fragmented, but might
> work.  Since 2.3 and beyond use pymalloc, fragmentation may not be much
> of an issue.  As memory is allocated in a big hunk, then doled out as
> necessary.

But exactly because of that, sbrk(0) doesn't mean much.  Consider the
tiny extension which I've just uploaded to
http://www.aleax.it/Python/memtry.c -- it essentially exposes a type
that does malloc when constructed and free when freed, and a function
sbrk0 which returns sbrk(0).  What I see on my MacOSX 10.4, Python
2.4.1, gcc 4.1, is (with a little auxiliary memi.py module that does
from memtry import *
import os
def memsiz():
return int(os.popen('ps -p %d -o vsz|tail -1' % os.getpid()).read())
)...:

Helen:~/memtry alex$ python -ic 'import memi'
>>> memi.memsiz()
35824
>>> memi.sbrk0()
16809984
>>> a=memi.mem(99)
>>> memi.sbrk0()
16809984
>>> memi.memsiz()
40900

See?  While the process's memory size grows as expected (by 500+ "units"
when allocating one meg, confirming the hypothesis that a unit is
2Kbyte), sbrk(0) just doesn't budge.

As the MacOSX "man sbrk" says,
"""
The brk and sbrk functions are historical curiosities left over from
earlier days before the advent of virtual memory management.
"""
and apparently it's now quite hard to make any USE of those quaint
oddities, in presence of any attempt, anywhere in any library linked
with the process, to do some "smart" memory allocation &c.

 
> These techniques could apply to Windows with some caveats.  If you are
> interested in Windows, see:
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/ht
> ml/UCMGch09.asp
> 
> Can't think of anything fool-proof though.

Fool-proof is way beyond what I'm looking for now -- I'd settle for
"reasonably clean, works in Linux, Mac and Windows over 90% of the time,
and I can detect somehow when it isn't working";-)


Since people DO need to keep an eye on their code's memory consumption,
I'm getting convinced that the major functional lack in today's Python
standard library is some minimal set of tools to help with that task.
PySizer appears to be a start in the right direction (although it may be
at too early a stage to make sense for the standard library of Python
2.5), but (unless I'm missing something about it) it won't help with
memory leaks not directly related to Python.  Maybe we SHOULD have some
function in sys to return the best guess at current memory consumption
of the whole process, implemented by appropriate techniques on each
platform -- right now, though, I'm trying to find out which these
appropriate techniques are on today's most widespread unixoid systems,
Linux and MacOSX.  (As I used to be a Win32 API guru in a previous life,
I'm confident that I can find out about _that_ platform by sweating
enough blood on MSDN -- problem here is I don't have any 

Re: best way to discover this process's current memory usage, cross-platform?

2005-11-15 Thread Alex Martelli
MrJean1 <[EMAIL PROTECTED]> wrote:

> My suggestion would also be to use sbrk() as it provides a high-water
> mark for the memory usage of the process.

That's definitely what I would have used in the '70s -- nowadays, alas,
it ain't that easy.

> Below is the function hiwm() I used on Linux (RedHat).  MacOS X and
> Unix versions are straigthforward.  Not sure about Windows.

The MacOSX version using sbrk is indeed straightforward, it just doesn't
work.  See my response to Neal's post and my little Python extension
module at http://www.aleax.it/Python/memtry.c -- on a Mac (OSX 10.4,
Python 2.4.1, gcc 4.1) sbrk(0) returns the same value as the process's
virtual memory consumption goes up and down (as revealed by ps).  As the
MacOSX's manpage says, "The brk and sbrk functions are historical
curiosities left over from earlier days before the advent of virtual
memory management."

Guess I'll now try the linux version you suggest, with mallinfo:

> #if _LINUX
> #include 
> 
> size_t hiwm (void) {
> /*  info.arena - number of bytes allocated
>  *  info.hblkhd - size of the mmap'ed space
>  *  info.uordblks - number of bytes used (?)
>  */
> struct mallinfo info = mallinfo();
> size_t s = (size_t) info.arena + (size_t) info.hblkhd;
> return (s);
> }

and see if and how it works.

I do wonder why both Linux and MacOSX "implemented" getrusage, which
would be the obviously right way to do it, as such a useless empty husk
(as far as memory consumption is concerned).  Ah well!-(


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


Re: Default method arguments

2005-11-15 Thread Gregory Petrosyan
Thanks a lot, but that's not what I do really want.
1) f() may have many arguments, not one
2) I don't whant only to _print_ x. I want to do many work with it, so
if I could simply write

def f(self, x = self.data)   (*)

it would be much better.

By the way, using

class A(object):
data = 0

def f(self, x = data)

solves this problem, but not nice at all

So I think (*) is the best variant, but it doesn't work :(

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


Re: Inheritance in nested classes

2005-11-15 Thread George Sakkis
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> But I hope you are aware that nested classes aren't quite the same as
> they are in java, are you?

Actually they are more like java's static inner classes. If you want to
simulate non-static inner classes in python, you may check the recipe
here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409366.

George

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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-15 Thread MrJean1
For some more details on Linux' mallinfo, see
 and maybe function mSTATs()
in glibc/malloc/malloc.c (RedHat).

/Jean Brouwers

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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-15 Thread MrJean1
For some more details on Linux' mallinfo, see
 and maybe function mSTATs()
in glibc/malloc/malloc.c (RedHat).

/Jean Brouwers

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


Re: Default method arguments

2005-11-15 Thread Alex Martelli
Gregory Petrosyan <[EMAIL PROTECTED]> wrote:
   ...
> def f(self, x = self.data)   (*)
   ...
> So I think (*) is the best variant, but it doesn't work :(

It DOES work -- it just does not work the way you _expect_ it to work,
but rather, it works the way it's _defined_ to work.

Specifically: all the evaluation of default arguments' values happens as
a part of the execution of the 'def' statement, and so, in particular,
happens at the TIME 'def' is executing.

A 'def' statement which is at the top level in a 'class' statement
evaluates as part of the evaluation of 'class'.

So, if, *while the 'class' statement is evaluating*, something known as
'self' exists, and has a 'data' attribute, this will give you the
default value for argument 'x'.  If the name 'self' is unknown, or
refers to an object which has no 'data' attribute, then of course
appropriate exceptions get raised (NameError or AttributeError) when
Python is TRYING to execute that 'def' statement.

Here's an example in which this works without exceptions:

class outer(object):
def __init__(self, data): self.data = data
def make_inner(self):
class inner(object):
def f(self, x=self.data):
print x
return inner()

Now, y = outer(23).make_inner() gives you an instance of an inner class,
such that y.f() is the same thing as y.f(23).  The 'self.data' in the
'def f', since it's the evaluation of a default value for an argument,
evaluates at the time 'def' evaluates -- and, at that time, 'self'
refers to the instance of class outer that's the only argument to method
make_inner of class outer.

While such "factories" (classes and functions making and returning other
classes and functions) are rarely used by beginners, they are an
extremely important idiom for advanced users of Python.  But the point
is that, by having extremely simple and universal rules, it takes no
exoteric knowledge to understand what the above Python code will do --
default argument values evaluate as 'def' executes, therefore there is
absolutely no ambiguity or difficulty to understand when this
'self.data' in particular evaluates.

If Python tried to guess at when to evaluate default argument values,
sometimes during the 'def', sometimes abstrusely storing "something"
(technically a 'thunk') for potential future evaluation, understanding
what's going on in any given situation would become extremely
complicated.  There are many languages which attempt to ``helpfully''
"do what the programmer meant in each single case" rather than follow
simple, clear and universal rules about what happens when; as a
consequence, programmers in such "helpful" languages spend substantial
energy fighting their compilers to try and work around the compilers'
attempted "helpfulness".

Which is why I use Python instead.  Simplicity is a GREAT virtue!


If it's crucial to you to have some default argument value evaluated at
time X, then, by Python's simple rules, you know that you must arrange
for the 'def' statement itself to execute at time X.  In this case, for
example, if being able to have self.data as the default argument value
is the crucial aspect of the program, you must ensure that the 'def'
runs AFTER self.data has the value you desire.

For example:

class A(object):
def __init__(self, n):
self.data = n
def f(self, x = self.data)
 print x
self.f = f

This way, of course, each instance a of class A will have a SEPARATE
callable attribute a.f which is the function you desire; this is
inevitable, since functions store their default argument values as part
of their per-function data.  Since you want a.f and b.f to have
different default values for the argument (respectively a.data and
b.data), therefore a.f and b.f just cannot be the SAME function object
-- this is another way to look at your issue, in terms of what's stored
where rather than of what evaluates when, but of course it leads to
exactly the same conclusion.

In practice, the solutions based on None or sentinels that everybody has
been suggesting to you are undoubtedly preferable.  However, you can, if
you wish, get as fancy as you desire -- the next level of complication
beyond the simple factory above is to turn f into a custom descriptor
and play similar tricks in the __get__ method of f (after which, one can
start considering custom metaclasses).  Exactly because Python's rules
and building blocks are simple, clean, and sharp, you're empowered to
construct as much complication as you like on top of them.

That doesn't mean you SHOULD prefer complication to simplicity, but it
does mean that the decision is up to you.


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


PyPy sprint announcement: Gothenburg 7th - 11th December 2005

2005-11-15 Thread Carl Friedrich Bolz
Gothenburg PyPy Sprint II: 7th - 11th December 2005
==
(NOTE: internal EU-only sprint starts on the 5th!)

The next PyPy sprint is scheduled to be in December 2005 in Gothenborg,
Sweden.  Its main focus is heading towards phase 2, which means JIT
work, alternate threading models and logic programming (but there are
also other possible topics).  We'll give newcomer-friendly
introductions.  To learn more about the new PyPy Python-in-Python
implementation look here:

 http://codespeak.net/pypy

Goals and topics of the sprint
--

We have released pypy-0.8.0_, which is officially a "research base" for
future work.  The goal of the Gothenburg sprint is to start exploring
new directions and continue in the directions started at the Paris
sprint.

The currently scheduled main topics are:

  - The L3 interpreter, a small fast interpreter for "assembler-level"
flow graphs.  This is heading towards JIT work.

  - Stackless: write an app-level interface, which might be either
Tasklets, as in "Stackless CPython", or the more limited Greenlets.

  - Porting C modules from CPython.  (_socket is not finished)

  - Optimization/debugging work in general.  In particular our thread
support is far from stable at the moment and unaccountably slow.

  - Experimentation: logic programming in Python.  A first step might be
to try to add logic variables to PyPy.


.. _`pypy-0.8.0`: http://codespeak.net/pypy/dist/pypy/doc/release-0.8.0.html

Location & Accomodation


The sprint will be held in the apartment of Laura Creighton and Jacob
Halen which is in Gotabergsgatan 22.  The location is central in
Gothenburg.  It is between the tram_ stops of Vasaplatsen and Valand,
where many lines call.

.. _tram: http://www.vasttrafik.se

Probably cheapest and not too far away is to book accomodation at `SGS
Veckobostader`_.  (You can have a 10% discount there; ask in the
pypy-sprint mailing list for details.  We also have some possibilites of
free accomodation.)

.. _`SGS Veckobostader`: http://www.sgsveckobostader.com

Exact times
---

The public PyPy sprint is held Wednesday 7th - Sunday 11th December
2005.  There is a sprint for people involved with the EU part of the
project on the two days before the "official" sprint.  Hours will be
from 10:00 until people have had enough.  It's a good idea to arrive a
day before the sprint starts and leave a day later.  In the middle of
the sprint there usually is a break day and it's usually ok to take
half-days off if you feel like it.


Network, Food, currency


Sweden is not part of the Euro zone. One SEK (krona in singular, kronor
in plural) is roughly 1/10th of a Euro (9.15 SEK to 1 Euro).

The venue is central in Gothenburg.  There is a large selection of
places to get food around, from edible-and-cheap to outstanding.

You normally need a wireless network card to access the network, but we
can provide a wireless/ethernet bridge.

Sweden uses the same kind of plugs as Germany. 230V AC.

Registration etc.pp.


Please subscribe to the `PyPy sprint mailing list`_, introduce yourself
and post a note that you want to come.  Feel free to ask any questions
there!  There also is a separate `Gothenburg people`_ page tracking who
is already thought to come.  If you have commit rights on codespeak then
you can modify yourself a checkout of

   http://codespeak.net/svn/pypy/extradoc/sprintinfo/gothenburg-2005/people.txt

.. _`PyPy sprint mailing list`: 
http://codespeak.net/mailman/listinfo/pypy-sprint
.. _`Gothenburg people`: 
http://codespeak.net/pypy/extradoc/sprintinfo/gothenburg-2005/people.html

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


Re: Need advice on subclassing code

2005-11-15 Thread Michael Spencer
Kent Johnson wrote:
> Rusty Shackleford wrote:
>> ...
>> C_1_1 and C_1_2 share a common C ancestor, and in practice may be
>> identical, but theoretically, could have the same function name with two
>> different implementations underneath.
>>
>> ...
> 
> How are you instantiating the correct class? You should be able to provide a 
> default behaviour. For example if the classes are all defined in module C you 
> could have a factory like this:
> 
> import C
> def makeC(x, y):
>   subtype = 'C_%d_%d' % (x, y)
>   cls = getattr(C, subtype, C.C)
>   return cls(x, y)
> 
> Then in module C just define the subtypes you need to specialize; all other 
> values of x and y will get the base class C.C.
> 
> Kent

Or, if you actually want different classes for each set of parameters (say for 
debugging or introspection), you could compose the default ones on the fly:


import C
def makeC(x, y):
   subtype = 'C_%d_%d' % (x, y)
   cls = getattr(C, subtype, None)
   if not cls:
 # No specialized class found, so compose a default
 # This requires C.C to be a new-style class
 cls = type(subtype, (C.C,), {"__autogenerated__": True})
   return cls(x, y)

Michael



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


Re: Default method arguments

2005-11-15 Thread bruno at modulix
Dennis Lee Bieber wrote:
> 
> 
(snip)
> but that may not be desirable if None is a valid value => myA.f(None),
> so...
> 
> class A(object):
> def __init__(self, n):
> self.data =n
> def f(self, *arg):
> if len(arg) == 0:
> x = self.data
> else:
> x = arg[0]
> print x

Another solution to this is the use of a 'marker' object and identity test:

_marker = []
class A(object):
def __init__(self, n):
self.data =n
def f(self, x = _marker):
if x is _marker:
x = self.data
print x


-- 
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: Addressing the last element of a list

2005-11-15 Thread Bengt Richter
On 15 Nov 2005 08:51:59 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:

>Op 2005-11-14, Bengt Richter schreef <[EMAIL PROTECTED]>:
[...]
>> You may be interested in reviewing
>>
>> 
>> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3
>>
>> before continuing this topic ;-)
>
>It is a rather long thread. You want to avoid this one becomes of
>comparable length?
Not necessarily. I just thought it might help in making new discussions
of previously discussed ideas clearer faster ;-)

Sometimes rehashing old topics seems just tedious, but sometimes someone
has a hunch that they are struggling to express, and they haven't yet succeeded
in communicating its essence. Then old discussions can sometimes serve
like first drafts of a speech, and revisions can prevent repeat of 
misunderstandings
that in the archived discussions one can see were inevitable.

If the nascent idea comes out viable, we all benefit, and the tedium will have 
been
worth it. If not, well, then at least some ideas will have clearer form, and
the whole process will have been a social event that some will have enjoyed 
anyway ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Needed class whose instances are many test cases

2005-11-15 Thread Sumit
Thanks for comments
.setup() is going the Run Before every testcase Run. But i need to
create resource for set of testcases , it is one time only . I can not
create at every instant before testcases Run . thats why
Unittest.testsuit is goingto help me out . There __init__() can be Run
One time and the resource can be create one time for set of tests.

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


Re: Default method arguments

2005-11-15 Thread Duncan Booth
Nicola Larosa wrote:

>> Using None might be problematic if None could be a valid argument.
> 
> That's like saying that NULL could be a significant value in SQL. In
> Python, "None" *is* the empty, not significant value, and should
> always be used as such. Specifically, never exchange "None" for
> "False". 
> 
You don't think there is a difference in SQL between a field explicitly set 
to NULL or a field initialised with a default value?

What you should be saying here is never use "None" when you actually mean 
"use the default non-None value for this parameter".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-based Document Management System?

2005-11-15 Thread Dieter Maurer
"W. Borgert" <[EMAIL PROTECTED]> writes on Thu, 10 Nov 2005 14:43:14 +0100:
> I'm looking for a Python-based DMS, but I don't know any.
> The following points are relevant:
> 
> - suitable for 10..100 users with more than 1 documents
> 
> - documents are mostly proprietary formats: MS Word, MS Excel,
>   MS PowerPoint, but maybe also: PDF, HTML, DocBook, ...
> 
> - typical DMS features: access control, archive older
>   versions, search/query, document hierarchy, web frontend

You may have a look at Plone, Silva and CPS (all Zope based).


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


Re: AJAX => APAX? Or: is there support for python in browsers?

2005-11-15 Thread [EMAIL PROTECTED]
Crackajax uses py2js to convert python code to client-side Javascript
(so you develop in python).

I've not used it, but am interested in hearing from anyone who has.

http://www.aminus.org/blogs/index.php/phunt/2005/10/06/subway_s_new_ajax_framework
http://www.aminus.org/blogs/index.php/phunt/2005/10/09/psst_crackajax_is_in_svn

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


python and VisualFox dbf

2005-11-15 Thread lux
Hi,
I've a dfb written in VisualFox,
I need to send a "pack" and "reindex"
but in odbc is not supported...

Anybody know how to do this?

TIA,
Luca

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


Re: best way to discover this process's current memory usage, cross-platform?

2005-11-15 Thread matt
Perhaps you could extend Valgrind (http://www.valgrind.org) so it works
with python C extensions?  (x86 only)

matt

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


Re: Background process for ssh port forwarding

2005-11-15 Thread mwilliams
Actually, an even better solution would be to set up public keys WITH a 
password, then 
simply use an "ssh-agent" to keep it in memory.  That way, you can leave the 
processes to do 
what deeds they will, and the keys are still protected with a password in the 
event they are 
stolen.


On Nov 15, Jesse Rosenthal wrote: 
> Whatever I do, though, I'll need to use pexpect to spawn the 
> processes, since I'll need to log in to ssh servers with a password. 

You might save yourself this effort by setting up ssh for 
non-interactive use with keys instead of password authentication: 

   $ cd ~/.ssh 
   $ chmod 700 . 
   $ ssh-keygen -t rsa  # just keep pressing  
   $ cp id_rsa.pub authorized_keys2 

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


is parameter an iterable?

2005-11-15 Thread py
I have function which takes an argument.  My code needs that argument
to be an iterable (something i can loop over)...so I dont care if its a
list, tuple, etc.  So I need a way to make sure that the argument is an
iterable before using it.  I know I could do...

def foo(inputVal):
if isinstance(inputVal, (list, tuple)):
for val in inputVal:
# do stuff

...however I want to cover any iterable since i just need to loop over
it.

any suggestions?

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


Re: Default method arguments

2005-11-15 Thread Martin Miller
Alex Martelli wrote, in part:
> If it's crucial to you to have some default argument value evaluated at
> time X, then, by Python's simple rules, you know that you must arrange
> for the 'def' statement itself to execute at time X.  In this case, for
> example, if being able to have self.data as the default argument value
> is the crucial aspect of the program, you must ensure that the 'def'
> runs AFTER self.data has the value you desire.
>
> For example:
>
> class A(object):
> def __init__(self, n):
> self.data = n
> def f(self, x = self.data)
>  print x
> self.f = f
>
> This way, of course, each instance a of class A will have a SEPARATE
> callable attribute a.f which is the function you desire; this is
> inevitable, since functions store their default argument values as part
> of their per-function data.  Since you want a.f and b.f to have
> different default values for the argument (respectively a.data and
> b.data), therefore a.f and b.f just cannot be the SAME function object
> -- this is another way to look at your issue, in terms of what's stored
> where rather than of what evaluates when, but of course it leads to
> exactly the same conclusion.

FWIT and ignoring the small typo on the inner def statement (the
missing ':'), the example didn't work as I (and possibily others) might
expect.  Namely it doesn't make function f() a bound method of
instances of class A, so calls to it don't receive an automatic 'self''
argument when called on instances of class A.

This is fairly easy to remedy use the standard new module thusly:

import new
class A(object):
def __init__(self, n):
self.data = n
def f(self, x = self.data):
print x
self.f = new.instancemethod(f, self, A)

This change underscores the fact that each instance of class A gets a
different independent f() method.  Despite this nit, I believe I
understand the points Alex makes about the subject (and would agree).

-Martin

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


Re: Default method arguments

2005-11-15 Thread Gregory Petrosyan
Great thanks, Alex!

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


  1   2   3   >