Re: What is different with Python ?

2005-06-14 Thread Andrea Griffini
On Mon, 13 Jun 2005 21:33:50 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

>But this same logic applies to why you want to teach abstract things
>before concrete things. Since you like concrete examples, let's look
>at a simple one:
>
>   a = b + c
>
...
>In a very
>few languages (BCPL being one), this means exactly one thing. But
>until you know the underlying architecture, you still can't say how
>many operations it is.

That's exactly why

 mov eax, a
 add eax, b
 mov c, eax

or, even more concrete and like what I learned first

 lda $300
 clc
 adc $301
 sta $302

is simpler to understand. Yes... for some time I even
worked with the computer in machine language without
using a symbolic assembler; I unfortunately paid a
price to it and now I've a few neurons burnt for
memorizing irrelevant details like that the above
code is (IIRC) AD 00 03 18 6D 01 03 8D 02 03... but
I think it wasn't a complete waste of energy.

Writing programs in assembler takes longer exactly beacuse
the language is *simpler*. Assembler has less implicit
semantic because it's closer to the limited brain of our
stupid silicon friend.
Programming in assembler also really teaches (deeply
to your soul) who is the terrible "undefined behaviour"
monster you'll meet when programming in C.

>Anything beyond the abstract statement "a gets the result
>of adding b to c" is wasted on them.

But saying for example that

 del v[0]

just "removes the first element from v" you will end up
with programs that do that in a stupid way, actually you
can easily get unusable programs, and programmers that
go around saying "python is slow" for that reason.

>It's true that in some cases, it's easier to remember the
>implementation details and work out the cost than to
>remember the cost directly.

I'm saying something different i.e. that unless you
understand (you have a least a rough picture, you
don't really need all the details... but there must
be no "magic" in it) how the standard C++ library is
implemented there is no way at all you have any
chance to remember all the quite important implications
for your program. It's just IMO impossible to memorize
such a big quantity of unrelated quirks.
Things like for example big O, but also undefined
behaviours risks like having iterators invalidated
when you add an element to a vector.

>> Are you genuinely saying that abelian groups are
>> easier to understand than relative integers ?
>
>Yup. Then again, my formal training is as a mathematician. I *like*
>working in the problem space - with the abstact. I tend to design
>top-down.

The problem with designing top down is that when
building (for example applications) there is no top.
I found this very simple and very powerful rationalization
about my gut feeling on building complex systems in
Meyer's "Object Oriented Software Construction" and
it's one to which I completely agree. Top down is a
nice way for *explaining* what you already know, or
for *RE*-writing, not for creating or for learning.

IMO no one can really think that teaching abelian
groups to kids first and only later introducing
them to relative numbers is the correct path.
Human brain simply doesn't work like that.

You are saying this, but I think here it's more your
love for discussion than really what you think.

>The same is true of programmers who started with concrete details on a
>different platform - unless they relearn those details for that
>platform.

No. This is another very important key point.
Humans are quite smart at finding general rules
from details, you don't have to burn your hand on
every possible fire. Unfortunately sometimes there
is the OPPOSITE problem... we infer general rules
that do not apply from just too few observations.

>The critical things a good programmer knows about those
>concrete details is which ones are platform specific and which aren't,
>and how to go about learning those details when they go to a new
>platform.

I never observed this problem. You really did ?

That is such not a problem that Knuth for example
decided to use an assembler language for a processor
that doesn't even exist (!).

>If you confuse the issue by teaching the concrete details at the same
>time as you're teaching programming, you get people who can't make
>that distinction. Such people regularly show up with horrid Python
>code because they were used to the details for C, or Java, or
>whatever.

Writing C code with python is indeed a problem that
is present. But I think this is a minor price to pay.
Also it's something that with time and experience
it will be fixed.

>> I suppose that over there who is caught reading
>> TAOCP is slammed in jail ...
>
>Those taught the concrete method would never have been exposed to
>anything so abstract.

Hmmm; TACOP is The Art Of Computer Programming, what
is the abstract part of it ? The code presented is
only MIX assembler. There are math prerequisites for
a few parts, but I think no one could call it "abstract"

Re: What is different with Python ?

2005-06-14 Thread Andrea Griffini
On Mon, 13 Jun 2005 22:19:19 -0500, D H <[EMAIL PROTECTED]> wrote:

>The best race driver doesn't necessarily know the most about their car's 
>engine.  The best baseball pitcher isn't the one who should be teaching 
>a class in physics and aerodynamics.  Yes, both can improve their 
>abilities by learning about the fundamentals of engines, aerodynamics, 
>etc., but they aren't "bad" at what they do if they do not know the 
>underlying principles operating.

And when you've a problem writing your software who is
your mechanic ? Who are you calling on the phone for help ?

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


Re: regarding cgi

2005-06-14 Thread db
I think you should give another header:
Content-type: text/html

regards Arjen



On Tue, 14 Jun 2005 07:00:09 +0100, praba kar wrote:

> Dear All,
>  
>  I have doubt regarding headers in cgi
> programming. If I gives "Content-Type:text/plain"
> then  I try to print html contents.  Is right or wrong
>  after  giving content-type: text/plain?
>  
> regards
> Prabahar
> 
> 
> 
>   
> ___
> Too much spam in your inbox? Yahoo! Mail gives you the best spam protection 
> for FREE! http://in.mail.yahoo.com

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


Re: "also" to balance "else" ?

2005-06-14 Thread Terry Hancock
On Tuesday 14 June 2005 12:07 am, Ron Adam wrote:
> Terry Hancock wrote:
> > On Monday 13 June 2005 11:09 pm, Ron Adam wrote:
> >>My suggestion is to use, also as the keyword to mean "on normal exit" 
> >>'also' do this.
> > Unfortunately, "also" is also a bad keyword to use for this, IMHO.
> > I don't find it any more intuitive than "else".  (And since your idea
> > would break if-else code, I don't think it would be allowed, anyway).
> 
> How would it break the current if-else?

I meant "for-else".  Typo, sorry.  The point is though, that there
is a fairly strict rule against breaking old code, AFAICT.  Which
makes the issue academic, "for-else" will continue to mean what
it currently does.

> > I can't think of what would be a better keyword, though.  :-/
> 
> Well there's 'not-else' or 'nelse'  Ack!  Just kidding of course.

No, I know what it should be.  It should be "finally".   It's already
a keyword, and it has a similar meaning w.r.t. "try".

ISTM, that it would have to be a synonym for "else" though to
be accepted on the backwards-compatibility criterion, and
then it would be "more than one way to do it" which breaks
the Zen. ;-)

Personally, though, "for-finally" would make a lot more sense
to me than "for-else" (and I don't have enough "for-else" code
to worry about it breaking).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: What is different with Python ?

2005-06-14 Thread Andrea Griffini
On Tue, 14 Jun 2005 04:18:06 GMT, Andrew Dalke
<[EMAIL PROTECTED]> wrote:

>In programming you're often given a result ("an inventory
>management system") and you're looking for a solution which
>combines models of how people, computers, and the given domain work.

Yes, at this higher level I agree. But not on how
a computer works. One thing is applied math, another
thing is math itself. When you're trying to find a solution
of a problem it's often the fine art of compromise.

>Science also has its purely observational domains.

I agree that "applied CS" is one of them (I mean the
art of helping people by using computers). But not
about the language or explaining how computers work.
I know that looking at the art of installing (or
uninstalling!) windows applications seems that
this is a completely irrational world where no rule
indeed exists... but this is just an illusion; there
are clear rules behind it and, believe it or not, we
know *all* of them.

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


Re: "also" to balance "else" ?

2005-06-14 Thread Andrew Dalke
Ron Adam wrote:
> True, but I think this is considerably less clear.  The current for-else 
> is IMHO is reversed to how the else is used in an if statement.

As someone else pointed out, that problem could be resolved in
some Python variant by using a different name, like "at end".
Too late for anything before P3K.

> I'm asking if changing the current 'else' in a for statement to 'also'
> would make it's current behavior clearer.  It's been stated before here
> that current behavior is confusing.

"It's been stated" is the passive tense.  You are one, and I
saw a couple others.  But it isn't the same as "many people say
that the current behavior is confusing."  If memory serves, I
don't even recall an FAQ on this, while there is a FAQ regarding
the case statement.

> You are correct that the 'else' behavior could be nested in the if:break
> statement.  I think the logical non-nested grouping of code in the
> for-also-else form is easier to read.  The block in the if statement
> before the break isn't part of the loop, IMO,  being able to move it to
> after the loop makes it clear it evaluates after the loop is done.

There is a tension with code coherency.  In my version the code
that occurs a result of the condition is only in one place while
in yours its in two spots.

If all (>1) break statements in the loop have the same post-branch
code then it might make some sense.  But as I said, I don't think
it occurs all that often.

Given the Python maxim of
  There should be one-- and preferably only one --obvious way to do it.

which of these is the preferred and obvious way?

while f():
  print "Hello!"
  if g():
break
else:
  print "this is a test"
also:
  print "this is not a pipe"

 -or-

while f():
  print "Hello!"
  if g():
print "this is a test"
break
else:
  print "this is not a pipe"


I prefer the second over the first.

Which of these is preferred?

while f():
  print "Hello"
  if g():
a = 10
print "world", a
break
  if h():
a = 12
print "world",a
break

  -or-

while f():
  print "Hello"
  if g():
a = 10
break
  if h():
a = 12
break
else:  # your else, not std. python's
  print "world", a

The latter is fragile, in some sense.  Suppose I added

  if hg():
a = 14
print "there"
break

Then I have to change all of the existing code to put the
"else:" block back into the loop.

That for me makes it a big no.

>> That is ... funky.  When is it useful?
> 
> Any time you've writen code that repeats a section of code at the end of
> all the if/elif statements or sets a variable to check so you can
> conditionally execute a block of code after the if for the same purpose.

Let me clarify.  When is it useful in real code?  Most cases
I can think of have corner cases which treat some paths different
than others.


> My thinking is that this would be the type of thing that would be used
> to argue against more specialized suggestions.  ie...   No a  new suggested keyword here> isn't needed because the also-else form
> already does that.  ;-)

An argument for 'X' because it prevents people from asking for
some theoretical 'Y' isn't that strong.  Otherwise Python would
have had a goto years ago.

> An example of this might be the case statement suggestions which have
> some support and even a PEP.  The if-alif-also-else works near enough to
> a case statement to fulfill that need.  'alif' (also-if) could  be
> spelled 'case' and maybe that would be clearer as many people are
> already familiar with case statements from other languages.

Assuming you are talking about PEP 275 ("Switching on Multiple
Values"), how does this fulfill that need any better than the
existing if/elif/else chain?

> Vetoing a suggestion on grounds of it can be done in another way, is
> also not sufficient either as by that reasoning we would still be using
> assembly language.  So the question I'm asking here is can an inverse to
>   the 'else' be useful enough to be considered?

I disagree.  Given the "one -- and preferably only one -- obvious
way to do it" there is already a strong bias against language
features which exist only to do something another way but not
a notably better way.

> I'll try to find some use case examples tomorrow, it shouldn't be too
> hard.  It probably isn't the type of thing that going to make huge
> differences.  But I think it's a fairly common code pattern so shouldn't
> be too difficult to find example uses from pythons library.

My guess is that it will be be hard.  There's no easy pattern
to grep for and I don't think the use case you mention comes up
often, much less often enough to need another control mechanism.

Andrew
[EMAIL PROTECTED]

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


Re: Controlling assignation

2005-06-14 Thread =?ISO-8859-1?Q?Xavier_D=E9coret?=
Bruno Desthuilliers a écrit :
> Xavier Décoret a écrit :
> (snip)
> 
>> What I wanted to do is something like this:
>>
>> def change(x,v):
>> x = v
>>
>> class A(object):
>> def __init__(self,v):
>> self.x = v
>>
>> a = A(3)
>> print a.x  # displays 3
>> change(a.x,4)
>> print a.x  # still displays 3
>>
>>
>> It may seem weird, 
> 
> 
> It does
> 
>> but I ensure there is a reason for doing this. 
> 
> 
> I really wonder what it can be ???

It's the ability to develop the equivalent of GeoNext (and much more) in 
  Python with a very nice syntax.

> 
> You could achieve the same effect with:
> 
> class A( object):
>   def __init__(self, value):
> self.value = value
> 
> a = A(3)
> a.value = 4
> a.value
> => 4
> 

Of course, and even simpler ;-)
print "4"

More seriously, try to do this with your simpler approach.

a = A(4)
b = A(lambda : a.x+5)
a.x = 2

print b.x # I want this to be 7, not 9


> And it's *much* more simple/readable/efficient.
> 
> Ever googled for "evolution of a programmer" ?-)
> 
> 
Not to brag, but I think I know what programming is.  Google for my 
name. C'est bien un commentaire de francais ca ;-)

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


Re: extending Python base class in C

2005-06-14 Thread Grigoris Tsolakidis
There was good article of how to do this on DDJ home page www.ddj.com
"harold fellermann" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hi all,

I once read that it is possible to use a python base class for a C
extension class. To be precise, I want to achieve the following
behavior:

class PythonClass :
pass

class CClass(PythonClass) :
"this class should be implemented as C extension"
pass


Unfortunately, google could not find me the right reference. Does
anyone know how to do it, or where I can find relevant information?

Thanks,

- harold -


--
Je me suis enfermé dans mon amour -- je rève.
-- Paul Eluard 


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

Re: How to get/set class attributes in Python

2005-06-14 Thread Kalle Anke
On Tue, 14 Jun 2005 06:40:51 +0200, Terry Hancock wrote
(in article <[EMAIL PROTECTED]>):

> I find the biggest problem coming to Python from a language
> like C, C++, or Java is that you overthink things and try to
> do them the hard way.  A lot of times, you find out that the
> "Python way" to do the thing is so blindingly obvious that
> it just didn't occur to you that it could be that simple.

It's very possible that this is the case, I'm not experienced enough in 
Python yet to have a opinion on this yet. I tend to think in terms of larger 
systems with several programmers ... instead of what I'm actually doing 
writing code for my own pleasure.

But I'm learning new stuff every day ... so in 6 months I'll probably have an 
opinion.


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


windows directory

2005-06-14 Thread Austin
I would like to write a program which creates the folders in specific
directory.
For example, I want to create folder in Program Files. How do I know which
is in C:\ or D:\
Is there any function to get the active path?

Thanks in advance.


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


Regarding Content-type headers

2005-06-14 Thread praba kar

Dear All,

I have doubt regarding headers in cgi
programming. If I gives "Content-Type:text/plain" then
I try to print html contents.  Is right or wrong after
giving content-type: text/plain?

regards
Prabahar




__
How much free photo storage do you get? Store your friends 'n family snaps for 
FREE with Yahoo! Photos http://in.photos.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Reg cgi header

2005-06-14 Thread praba kar
Dear All,
 
 I have doubt regarding headers in cgi
programming. If I gives "Content-Type:text/plain"
then  I try to print html contents.  Is right or wrong
 after  giving content-type: text/plain?
 
regards
Prabahar





__
How much free photo storage do you get? Store your friends 'n family snaps for 
FREE with Yahoo! Photos http://in.photos.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-14 Thread Michele Simionato
Andrea Griffini wrote:
>This is investigating. Programming is more similar to building
>instead (with a very few exceptions). CS is not like physics or
>chemistry or biology where you're given a result (the world)
>and you're looking for the unknown laws. In programming *we*
>are building the world. This is a huge fundamental difference!

It looks like you do not have a background in Physics research.
We *do* build the world! ;)

   Michele Simionato

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


Re: wxpython wxlistctrl with combo

2005-06-14 Thread Franz Steinhaeusler
On Mon, 13 Jun 2005 21:05:09 GMT, "Fabio Pliger" <[EMAIL PROTECTED]>
wrote:

>Hi all,
>i'm working on a very large project using wx 2.5... On one frame i have a
>wx.lib.mixins.listctrl widget, wich is a listctrl extended with the
>possibility to edit the columns text entrys Anyone know if it's possible
>(or if there's a widget...) to have also the possbility to have a comboBox
>in the list (with the text edit entry)? The final result i need is a list
>with 2 columns, one with the text entry editable, and the other with a
>comboBox in it... Anyone know to do it?
>TNX a lot...
>
>F.P.
>

Hm, I'm no expert, and it is probably better to ask in the wxpython-user
mailing list.

For what I saw:
I think, you use TextEditMixin class.
How about making a new class, (copying the TextEditMixin code), change 
the PreTextCtrl to a PreComboBox and maybe the navigation keys (TAB,
...)?
-- 
Franz Steinhaeusler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-14 Thread Andrew Dalke
Terry Hancock wrote:
> No, I know what it should be.  It should be "finally".   It's already
> a keyword, and it has a similar meaning w.r.t. "try".

Except that a finally block is executed with normal and exceptional
exit, while in this case you would have 'finally' only called
when the loop exited without a break.

Andrew
[EMAIL PROTECTED]

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


Re: "also" to balance "else" ?

2005-06-14 Thread Fredrik Lundh
Ron Adam wrote:

> True, but I think this is considerably less clear.  The current for-else
> is IMHO is reversed to how the else is used in an if statement.

nope.  else works in exactly the same way for all statements that
support it: if the controlling expression is false, run the else suite
and leave the statement.





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


Re: What is different with Python ?

2005-06-14 Thread Andreas Kostyrka
On Tue, Jun 14, 2005 at 12:02:29AM +, Andrea Griffini wrote:
> However I do not think that going this low (that's is still
> IMO just a bit below assembler and still quite higher than
> HW design) is very common for programmers.
Well, at least one University (Technical University Vienna) does it
this way. Or did it at least when I passed the courses ;)

> 
> >Or how does one explain that a "stupid and slow" algorithm can be in
> >effect faster than a "clever and fast" algorithm, without explaining
> >how a cache works. And what kinds of caches there are. (I've seen
> >documented cases where a stupid search was faster because all hot data
> >fit into the L1 cache of the CPU, while more clever algorithms where
> >slower).
> 
> Caching is indeed very important, and sometimes the difference
> is huge. I think anyway that it's probably something confined
> in a few cases (processing big quantity of data with simple
> algorithms, e.g. pixel processing).
> It's also a field where if you care about the details the
> specific architecture plays an important role, and anything
> you learned about say the Pentium III could be completely
> pointless on the Pentium 4.

Nope. While it's certainly true that it's different from architecture
to architecture, you need to learn the different types of caches,
etc. so that one can quickly crasp the architecture currently in use.

> Except by general locality rules I would say that everything
> else should be checked only if necessary and on a case-by-case
> approach. I'm way a too timid investor to throw in neurons
> on such a volatile knowledge.

It's not volatile knowledge. Knowledge what CPU uses what cache
organisation is volatile and wasted knowledge. Knowledge what kinds
of caches are common is quite useful ;)

Easy Question:
You've got 2 programs that are running in parallel.
Without basic knowledge about caches, the naive answer would be that
the programs will probably run double time. The reality is different.


> >Or you get perfect abstract designs, that are horrible when
> >implemented.
> 
> Current trend is that you don't even need to do a
> clear design. Just draw some bubbles and arrows on
> a white board with a marker, throw in some buzzword
> and presto! you basically completed the new killing app.

Well, somehow I'm happy that it is this way. That ensures enough work
for me, because with this approach somebody will call in the fire
department when it doesn't work anymore ;)
Or the startup goes belly up. 

> Real design and implementation are minutiae for bozos.
> 
> Even the mighty python is incredibly less productive
> than powerpoint ;-)
> 
> >Yes. But for example to understand the memory behaviour of Python
> >understanding C + malloc + OS APIs involved is helpful.
> 
> This is a key issue. If you've the basis firmly placed
> most of what follows will be obvious. If someone tells
> you that inserting an element at the beginning of an array
> is O(n) in the number of elements then you think "uh... ok,
> sounds reasonable", if they say that it's amortized O(1)
> instead then you say "wow..." and after some thinking
> "ok, i think i understand how it could be done" and in
> both cases you'll remember it. It's a clear *concrete* fact
> that I think just cannot be forgot.

Believe it can ;)
But that's the idea why certain courses forced us to implement at
least the most important data structures by ourselves.

Because looking at it in a book is so much less intensive than doing
it ;)

Andreas

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


Re: Regarding Content-type headers

2005-06-14 Thread Ola Natvig
praba kar wrote:
> Dear All,
> 
> I have doubt regarding headers in cgi
> programming. If I gives "Content-Type:text/plain" then
> I try to print html contents.  Is right or wrong after
> giving content-type: text/plain?
> 
> regards
> Prabahar

It's not wrong, but you won't get the results you want. If you want to 
display HTML your should send the content-type: text/html.

regards Ola Natvig
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-14 Thread Fredrik Lundh
Terry Hancock wrote:

> Personally, though, "for-finally" would make a lot more sense
> to me than "for-else" (and I don't have enough "for-else" code
> to worry about it breaking).

"finally" means "run this piece of code no matter what happens in
the previous block".  that's not how "else" works in today's Python.





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


RE: windows directory

2005-06-14 Thread Tim Golden
[Austin]
| I would like to write a program which creates the folders in specific
| directory.
| For example, I want to create folder in Program Files. How do 
| I know which
| is in C:\ or D:\
| Is there any function to get the active path?

It's not quite clear what you mean. You seem to be asking three
possibly distinct questions:

1) How do I create folders in a particular directory.

A. Look at os.mkdir or os.makedirs


2) How do I know where the "Program Files" folder is?

A. Look at the shell module of the pywin32 extensions.
   Specifically, you're looking for the shell.SHGetPathFromIDList
   and shell.SHGetSpecialFolderLocation functions.


3) How do I know what the active path is?

A. Look at os.getcwd


I know I haven't been too detailed in my answers, but I didn't
want to spend lots of time explaining in case I'd actually
missed the point of the question.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: windows directory

2005-06-14 Thread Richard Lewis
On Tue, 14 Jun 2005 15:32:02 +0800, "Austin" <[EMAIL PROTECTED]>
said:
> I would like to write a program which creates the folders in specific
> directory.
> For example, I want to create folder in Program Files. How do I know
> which
> is in C:\ or D:\
> Is there any function to get the active path?
> 

You can find the current working directory with
os.getcwd()

If you want to know where a particular directory is (on a Windows
'drive') you could use:

for drive_label in ["C", "D"]:
if "Program Files" in os.listdir(drive_label + ":/"): return
drive_label

Or something similar.

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


Re: Access Database Using Python

2005-06-14 Thread Piet van Oostrum
> "Karthish" <[EMAIL PROTECTED]> (K) wrote:

>K> I can't figure out how to authenticate and then load a page, since the
>K> page requires cookies for authentication.

http://www.voidspace.org.uk/python/articles/cookielib.shtml
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


gobal var inside class without notice???

2005-06-14 Thread [EMAIL PROTECTED]
I have code like this:

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

  def something(self):
print self.j
print i  # PROBLEM is here there is no var i in class A but it
works ???

if __name__ == '__main__':
  i = 10
  a = A(5)
  a.something()

I don't define global i but it will takes var i from outside of class
A.

Can somebody explain this ???

pujo

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


Re: Which Python Wiki engine?

2005-06-14 Thread garabik-news-2005-05
Kenneth McDonald <[EMAIL PROTECTED]> wrote:
> 
> Here are some of the features I'd greatly like to have that I haven't  
> seen provided by the (relatively few) wiki engines I've looked at.  
> Mind you, I don't claim to have looked at even these few  
> exhaustively. (No time!) MoinMoin is the one I've looked at the most.
> 

I do not like to write about vapourware, but anyway I am writing a
new simple wiki/forum in python (using Karrigell framework), the main
reason being that it needs some specialties not present in any other
wiki. Anyway, I am going to put some notes about what my wiki _will_ have.

> 1) Automatically generated table of contents, based on the outline  
> structure. This would be regenerated periodically (probably nightly)

easily done


> 2) Ability for users to add new subsections, but not to change that  
> part of the document structure which has been locked by the editor.

I have not considered this, but it could be doable

> 3) Clear visual distinction between material added by the users, and  
> material added or approved by the editor.

easily done

> 4) Legal-style numbering of sections, subsections, etc.

by section you mean section in text, or section as "a group of wiki
pages" ?
The first one is easily done, due to pluggable formatters.

> 5) Ability to have single pages containing both locked text (which  
> users cannot edit or delete) and unlocked text. Such a page would  
> consist of one or more locked blocks of text, interspersed with  
> comments put in by users. Users could put comments anywhere except  
> side a locked text block.

possible, with some limitations (internaly, the sections are 
represented as separate pages, each with separate set of access rights,
they are just rendered as one document)

> 
> Ideally, this would also be something that doesn't depend on a  
> backend database or other things besides the web server and python  
> packages. This is not likely to be a wiki where huge amounts of  

more or less - storage is directly on filesystem, only if you need a
full-text search you need a database (e.g. sqlite).

You need Karrigell, though.


-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: gobal var inside class without notice???

2005-06-14 Thread Michael Smith
[EMAIL PROTECTED] wrote:

>I have code like this:
>
>class A:
>  def __init__(self,j):
>self.j = j
>
>  def something(self):
>print self.j
>print i  # PROBLEM is here there is no var i in class A but it
>works ???
>
>if __name__ == '__main__':
>  i = 10
>  a = A(5)
>  a.something()
>
>I don't define global i but it will takes var i from outside of class
>A.
>
>Can somebody explain this ???
>
>pujo
>
>  
>
Actually you *have* defined a global variable called 'i' - when you run 
code at file scope, as you have where you wrote i = 10, all variables 
are global. This means that they can be referred to anywhere in the 
module, as you found.

It also means that variable accesses are slower, since accessing globals 
is slower than accessing local variables. This is why many people 
suggest that you define a function called main() and have the main 
script simply call that.

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


Re: What is different with Python ?

2005-06-14 Thread Andrew Dalke
Andreas Kostyrka wrote:
> On Tue, Jun 14, 2005 at 12:02:29AM +, Andrea Griffini wrote:
>> Caching is indeed very important, and sometimes the difference
>> is huge.
 ...
> Easy Question:
> You've got 2 programs that are running in parallel.
> Without basic knowledge about caches, the naive answer would be that
> the programs will probably run double time. The reality is different.

Okay, I admit I'm making a comment almost solely to have
Andrea, Andreas and Andrew in the same thread.

I've seen superlinear and sublinear performance for this.
Superlinear when the problem fits into 2x cache size but not
1x cache size and is nicely decomposable, and sublinear when
the data doesn't have good processor affinity.

Do I get an A for Andre.*?  :)
 
Andrew
[EMAIL PROTECTED]

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


Re: gobal var inside class without notice???

2005-06-14 Thread [EMAIL PROTECTED]
Thanks a lot.
pujo

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


Re: Sending mail from 'current user' in Python

2005-06-14 Thread Leo Breebaart
Marcus Alanen <[EMAIL PROTECTED]> writes:

> >>I've also tried opening a pipe to sendmail, and feeding the
> >>message to that instead. This too works great [but] doesn't
> >>seem like much of an improvement, portability-wise.
>
> No, but at least it can be expected to do the right thing
> w.r.t. sending the mail.

Good point.

> >>Finally, if at all possible I'd also like to get this working on
> >>Windows, so I'd rather stick with the standard smtplib if I can.
> > smtplib needs an SMTP server to connect to. For unix systems, this is
> > typically localhost. What do you use for Windows systems? Or are you
> > connecting to your machine to deliver the mail?
> 
> I'd be very surprised if the typical SMTP server is localhost
> on unix-like computers. [...] Let the sendmail program take
> care of those details.
> 
> The Unix Programming Frequently Asked Questions "Q5.2 What's the best 
> way to send mail from a program?" is worth reading.

Thanks to you and everyone else who contributed to this thread.

I've now decided to accept the inherent non-portabilitiness of
the whole concept of 'sending mail from within a program', and
will be going with a Unix-only see-if-you-can-find-sendmail
approach.

-- 
Leo Breebaart  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Resume after exception

2005-06-14 Thread Richard Lewis
Hi there,

Is it possible to have an 'except' case which passes control back to the
point after the exception occurred?

e.g.

# a function to open the file
# raises FileLockedException is file contains 'locked' information
def open_file(file_name):
f = file(file_name, 'r')
{read first line for file lock info}
if first_line == "FILE LOCKED":
raise FileLockedException(lock_user, lock_timestamp)
{read remainder of file}
return True

# elsewhere in a user interface module
def open_command():
try:
open_file("foo.bar")
except FileLockException, X:
ans = tkMessageBox.askyesno(title="File Locked", message="File
locked by '" + X.user + "' on " + X.time_stamp + "\nContinue
anyway?")
if ans == tkMessageBox.YES:
# return control to the remainder of the open_file function.
How?
else:
return False

Any ideas?

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


Re: translating C++ exceptions to python

2005-06-14 Thread Denis S. Otkidach
On 13 Jun 2005 04:23:03 -0700
[EMAIL PROTECTED] wrote:

> Hi all,
> 
> I have a C++ library I call from python. The problem is I have c++
> exceptions that i want to be translated to python. I want to be able to
> do stuff like:
> try:
> my_cpp_function()
> except cpp_exception_1:
> do_stuff
> except cpp_exception_2:
> do_other_stuff
> 
> any ideas how can i do the translation?

1. Create Python class for your exception.  For simple case the code
will be:

static PyObject *YouExceptionClass;

# and in module initialization function:
YouExceptionClass =  PyErr_NewException("YourModule.YourException", 0, 0);

2. Add it to module dictionary.

3. In wrapper for my_cpp_function use something like the following 
code:

try {
my_cpp_function_impl();
} catch (YouException &exc) {
PyErr_SetString(YouExceptionClass, exc.what());
return 0;
}

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


sudo open() ? (python newbee question)

2005-06-14 Thread slava
hello,

i am writing a python script that will be run by a non root user
the script needs to open a file in write mode that is owned by root

file = open('/etc/apt/sources.list', 'r+')

returns permission error

how can i call sudo on open()?

thanks alot
slava
-- 
http://mail.python.org/mailman/listinfo/python-list


collect data using threads

2005-06-14 Thread Qiangning Hong
A class Collector, it spawns several threads to read from serial port.
Collector.get_data() will get all the data they have read since last
call.  Who can tell me whether my implementation correct?

class Collector(object):
def __init__(self):
self.data = []
spawn_work_bees(callback=self.on_received)

def on_received(self, a_piece_of_data):
"""This callback is executed in work bee threads!"""
self.data.append(a_piece_of_data)

def get_data(self):
x = self.data
self.data = []
return x

I am not very sure about the get_data() method.  Will it cause data lose
if there is a thread is appending data to self.data at the same time?

Is there a more pythonic/standard recipe to collect thread data?

-- 
Qiangning Hong

 ___
< Those who can, do; those who can't, simulate. >
 ---
\  ___---___
 \ _-~~ ~~-_
  \ _-~/~-_
 /^\__/^\ /~  \   /\
   /|  O|| O|/  \___/\
  | |___||__|  /   /\  \
  |  \/  /\  \
  |   (___) /__/\_ \
  | / / \  /\
   \ \^\\ \  /   \ /
 \ ||   \__/  _-_   //\__//
   \   ||--_-~~-_ - \ --/~   ~\|| __/
 ~-||/~ |==|   |/~
  (_(__/  ./ /\_\  \.
 (_(___/ \_)_)
-- 
http://mail.python.org/mailman/listinfo/python-list


Where is Word?

2005-06-14 Thread Guy Lateur
Hi all,

I need a way to get the path where MS Word/Office has been installed. I need 
to start Word from a script (see earlier post), but it doesn't work if I 
don't know its path. So "os.system("winword.exe %s" % fileName)" doesn't 
always work; I need to say "os.system("C:\Program Files\Microsoft 
Office\Office10\winword.exe %s" % fileName)".

Any ideas?

TIA,
g 


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


RE: Where is Word?

2005-06-14 Thread Tim Golden
[Guy Lateur]
| I need a way to get the path where MS Word/Office has been 
| installed. I need 
| to start Word from a script (see earlier post), but it 
| doesn't work if I 
| don't know its path. So "os.system("winword.exe %s" % 
| fileName)" doesn't 
| always work; I need to say "os.system("C:\Program Files\Microsoft 
| Office\Office10\winword.exe %s" % fileName)".

While this doesn't answer the question you're asking, I
believe it does solve the problem you're facing. Relying
on the fact that the Microsoft Office products will
have associated themselves as the default (Open) action
with files of the appropriate extensions, you can use
os.startfile:


import os

os.startfile ("c:/temp/blah.doc")


HTH
TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: sudo open() ? (python newbee question)

2005-06-14 Thread Denis WERNERT
The script could be SUID Root, and you could use os.setuid immediately after
having performed the task to switch to a non-priviledged user. May be a big
security risk, if someone can alter the script, he gains root access to the
system...

[EMAIL PROTECTED] wrote:

> hello,
> 
> i am writing a python script that will be run by a non root user
> the script needs to open a file in write mode that is owned by root
> 
> file = open('/etc/apt/sources.list', 'r+')
> 
> returns permission error
> 
> how can i call sudo on open()?
> 
> thanks alot
> slava
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module and blocking

2005-06-14 Thread Robin Becker
Dieter Maurer wrote:
.
> 
> You just found out that this is not the case.

thanks I suppose I was being a moron.

> 
> The warning attached to "communicate"s docstring might have
> you averted: "Note: the data read is buffered in memory...
> do not use for large size".
> 
> If subprocess would do what you expect, it would need to
> buffer the output (to make room in the pipes again).
> But, for large data, this could have dramatic consequences.
> 
> Thus, you should use "select" on the pipes to find out
> when to read data.
> 

Unfortunately select isn't an option for windows (I think that's only for 
sockets). I guess I need to read repeatedly from the stdout etc to get the 
output. Clearly the poll call can't return a status until we've finished
reading.

> 
> Dieter


-- 
Robin Becker

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


Re: circular import Module

2005-06-14 Thread Magnus Lycka
Greg Ewing wrote:
> Magnus Lycka wrote:
> 
>> Due to the cycle, you can never use file1 without
>> file2 or vice versa. Why do you then want it to be
>> two different modules instead of one?
> 
> Perhaps because it would then be too big and
> unwieldy to maintain?
> 
> Sometimes there are legitimate reasons for
> mutually-dependent modules.

Agreed, but I think it's important to think about
the design if a chunk of code gets that big. Most
of the time, things can be organized differently,
and there will be maintenance gains from this. If
you have mutual dependenices between two modules,
they still have to be maintained as a unit. You
can't disregard one when you modify the other. To
achieve looser (and prefereably not mutual)
dependencies between separate modules both makes
it easier to maintain the modules and more likely
that we will be able to reuse them in other contexts.

Sure, there simple are tricks you can use to get away
with mutual import dependencies, but if I ran into a
mutual dependency between two Python modules, I would
first think about their design and try to resolve this
dependency issue. I probably wouldn't use a trick such
as import in a local scope unless I was in a hurry and
needed a quick fix while I was considering a proper
design. (I might then be lazy and not resolve the
design problem, but it would continue to disturb me...)

Composition and inheritance might be used to break
out parts of code that doesn't have dependencies to
the rest of the code. There are all sorts of design
pattern that can resolve mutual dependencies. I often
use callbacks to get away from mutual dependencies.

E.g.

class Adder:
 def __init__(self, x, y, callback):
 self.x = x
 self.y = y
 self.callback = callback

 def calc(self):
 result = self.x + self.y
 self.callback(result)

class Manager:
 def add(self, x, y):
 b = B(x, y, self.show)
 b.calc()

 def show(self, value):
 print value

This is a silly example of course. Adder.calc could simply
have returned the result, but I don't have time to construct
anything elaborate now. The point I want to show is that
by passing in a callable from Manager to Adder, Adder
instances can call certain methods in particular Manager
instanes without any dependencies to the module where Manager
lives. It just needs to know what kind of parameters it should
supply to the callable it was passed.

Martin Fowler's book Refactoring shows a lot of examples
that are useful when code grows and needs to be divided
into smaller chunks. His examples and ideas revolve around
Java and C++ though, and it's often much simpler in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


ZCatalog for standalone Zodb?

2005-06-14 Thread Almad
Hello, 

is ZCatalog available for standalone zodb? As far as I read tutorial, the
relation to zope is obvious. 

I knew there is IndexedCatalog, but its not developed any more...and without
indexing, oodbms are unusable for cms, imo. 

Thank You, 
-- 
Lukas "Almad" Linhart
[:: http://www.almad.net/ ::]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is Word?

2005-06-14 Thread Guy Lateur
Unfortunately, I need to open/edit a (temporary) text file with Word, and 
those are opened by default with UltraEdit (or Notepad or..). Thanks for the 
tip, though.

Anything else? Do I need to read the registry?

g




While this doesn't answer the question you're asking, I
believe it does solve the problem you're facing. Relying
on the fact that the Microsoft Office products will
have associated themselves as the default (Open) action
with files of the appropriate extensions, you can use
os.startfile:


import os

os.startfile ("c:/temp/blah.doc")


HTH
TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
 


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


Re: Where is Word?

2005-06-14 Thread Tomasz Lisowski
> Unfortunately, I need to open/edit a (temporary) text file with Word, and 
> those are opened by default with UltraEdit (or Notepad or..). Thanks for the 
> tip, though.
> 
> Anything else? Do I need to read the registry?
> 
> g

You may try to launch Word as a COM object and control it directly from 
Python using the COM object methods. This does not require you to know 
the application's path, only the COM object identifier.

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


RE: Where is Word?

2005-06-14 Thread Tim Golden
[Guy Lateur]
| Unfortunately, I need to open/edit a (temporary) text file 
| with Word, and 
| those are opened by default with UltraEdit (or Notepad or..). 
| Thanks for the 
| tip, though.
| 
| Anything else? Do I need to read the registry?
| 
| g

OK, you have a couple of options (at least). Easiest, probably
is to read the app paths from the registry.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

You're looking for winword.exe.

An alternative is to use WMI to interrogate the Win32_Product
classes and then to pick out the Software Elements etc. It's
a bit messy, so I'd stick to the the AppPath approach if I were you.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


RE: Where is Word?

2005-06-14 Thread Tim Golden
[Guy Lateur]
| Sent: 14 June 2005 11:02
| To: python-list@python.org
| Subject: Re: Where is Word?
| 
| 
| Unfortunately, I need to open/edit a (temporary) text file 
| with Word, and 
| those are opened by default with UltraEdit (or Notepad or..). 
| Thanks for the 
| tip, though.
| 
| Anything else? Do I need to read the registry?
| 
| g

OK, a slightly more intelligent idea in place of my previous
one. You can use win32api.ShellExecute (from the pywin32 extensions)
which is like a beefed-up os.startfile. In particular, it allows
you to pass parameters to the command. So...


import win32api
win32api.ShellExecute (
  0, # hwnd
  "open", # action; could be "print" etc.
  "winword.exe", # application
  "c:/temp/temp.txt", #params
  ".", # working directory
  1 # show/don't show
)


TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Where is Word?

2005-06-14 Thread Guy Lateur
Thanks, but could you pretty please post some code that does this? I'm new 
to Python, let alone COM..

TIA,
g



"Tomasz Lisowski" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> You may try to launch Word as a COM object and control it directly from 
> Python using the COM object methods. This does not require you to know the 
> application's path, only the COM object identifier.
>
> TLis 


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


Re: Where is Word?

2005-06-14 Thread Guy Lateur
Thank you very much; I'll check that out shortly.

g




"Tim Golden" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
OK, a slightly more intelligent idea in place of my previous
one. You can use win32api.ShellExecute (from the pywin32 extensions)
which is like a beefed-up os.startfile. In particular, it allows
you to pass parameters to the command. So...


import win32api
win32api.ShellExecute (
  0, # hwnd
  "open", # action; could be "print" etc.
  "winword.exe", # application
  "c:/temp/temp.txt", #params
  ".", # working directory
  1 # show/don't show
)


TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
 


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


Re: implicit variable declaration and access

2005-06-14 Thread Tom Anderson
On Mon, 13 Jun 2005, Ali Razavi wrote:

> Tom Anderson wrote:
>> On Mon, 13 Jun 2005, Ali Razavi wrote:
>> 
>>> Is there any reflective facility in python that I can use to define a 
>>> variable with a name stored in another variable ?
>>> 
>>> like I have :
>>> x = "myVarName"
>>> 
>>> what can I do to declare a new variable with the name of the string stored 
>>> in x. And how can I access that implicitly later ?
>> 
>> Are you absolutely sure you want to do this?
>
> Have you ever heard of meta programming ? I guess if you had, it 
> wouldn't seem this odd to you.

Oh, i have. It's just that i've also seen about a billion posts from 
novice programmers asking exactly that question, when it turns out what 
they really want is a dictionary, or sometimes a list. If that was the 
case, answering your question would not be solving your problem, an i'd 
rather solve your problem.

If it's not, try:

x = "myVarName"
y = "myVarValue"
locals()[x] = y

What did you mean by "And how can I access that implicitly later?"?

tom

-- 
I content myself with the Speculative part [...], I care not for the Practick. 
I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. 
-- Sir Nicholas Gimcrack
-- 
http://mail.python.org/mailman/listinfo/python-list


multi-CPU, GIL, threading on linux

2005-06-14 Thread gabor
hi,

as i understand, on linux, python uses the operating systems threads
(so python is not simulating threads by himself).

that means that on a multi-CPU computer, the different threads may get 
executed on different CPUs.

i am working with zope, and i was referenced to this page:
http://www.zope.org/Members/glpb/solaris/report_ps

it's rather old (2002), but it claims the following:


 > I do *not* recommend running Zope on multiprocessor machines without an
 > ability to restrict Zope to execution on a single CPU.
 >
 > The reason for this is that the Python Global Interpreter Lock is shared
 > inside a Zope process.  However, threads in Python are backed by
 > underlying OS threads.  Thus, Zope will create multiple threads, and
 > each thread is likely to be assigned to a different CPU by the OS
 > scheduler.  However, all CPUs but one which are dispatching any given
 > Zope process will have to then wait and attempt to acquire the GIL; this
 > process introduces significant latency into Python and thus into Zope.

now, i know about tools that allow me to bind a python process to a 
specific cpu, but i wonder..


is the performance soo bad when i am running a python process, and the 
threads are running on different cpus?

i understand that because of the GIL i cannot make my application 
faster. but slower?

thanks,
gabor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-14 Thread Peter Maas
Andrea Griffini schrieb:
 > On Mon, 13 Jun 2005 13:35:00 +0200, Peter Maas <[EMAIL PROTECTED]>
 > wrote:
 >
 >
 >>I think Peter is right. Proceeding top-down is the natural way of
 >>learning.
 >
 >
 > Depends if you wanna build or investigate.

Learning is investigating. By top-down I mean high level (cat,
dog, table sun, sky) to low level (molecules, atoms, fields ...).
And to know the lowest levels is not strictly necessary for
programming. I have seen good programmers who didn't know about
logic gates.

> Hehehe... a large python string is a nice idea for modelling
> memory. This shows clearly what I mean with that without firm
> understanding of the basis you can do pretty huge and stupid
> mistakes (hint: strings are immutable in python... ever
> wondered what does that fancy word mean ?)

Don't nail me down on that stupid string, I know it's immutable but
didn't think about it when answering your post. Take  instead.

-- 
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree Namespace Prefixes

2005-06-14 Thread Oren Tirosh
> you forgot
>
>http://effbot.org/zone/element-infoset.htm
>
> which describes the 3-node XML infoset subset used by ElementTree.

No, I did not forget your infoset subset. I was comparing it with other
infoset subsets described in various XML specifications.

I agree 100% that prefixes were not *supposed* to be part of the
document's meaning back when the XML namespace specification was
written, but later specifications broke that.

Please take a look at http://www.w3.org/TR/xml-c14n#NoNSPrefixRewriting

"... there now exist a number of contexts in which namespace prefixes
can impart information value in an XML document..."

"...Moreover, it is possible to prove that namespace rewriting is
harmful, rather than simply ineffective."

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


Re: translating C++ exceptions to python

2005-06-14 Thread harold fellermann

On 13.06.2005, at 13:23, [EMAIL PROTECTED] wrote:

> Hi all,
>
> I have a C++ library I call from python. The problem is I have c++
> exceptions that i want to be translated to python. I want to be able to
> do stuff like:
> try:
> my_cpp_function()
> except cpp_exception_1:
> do_stuff
> except cpp_exception_2:
> do_other_stuff
>
> any ideas how can i do the translation?

If you do not already use it, have a look at
http://www.boost.org/libs/python/ a C++ -- library to wrap the
Python C API, i.e. it helps you to extend Python in C++.
AFAIK it has fascilities to transform exceptions from one type
into the other.

- harold -

---
Everybody lies. but it does not matter, as no one listens.
---

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


Re: python bytecode grammar

2005-06-14 Thread Magnus Lycka
M1st0 wrote:
> Ops yes is BNF :P Bacus Normal Form if I am not wrong...

Backus Naur Form.

John Backus and Peter Naur first used it to describe ALGOL around 1960.
See e.g. 
http://cui.unige.ch/db-research/Enseignement/analyseinfo/AboutBNF.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating HTML from python

2005-06-14 Thread Magnus Lycka
Philippe C. Martin wrote:
> I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have
> a title followed by lines of text that do not look too ugly. If possible I
> would like to use an existing module.

How to do this really depends on what your data looks like, and how you
get it. E.g. if you just want uniform pages with paragraphs of plain
texts with headings in between, you can just make a template HTML file
with the main block of text replaced with %s, and then do something like:

text = []

for heading, paragraph in data_source:
 text.append('%s' % heading)
 text.append(paragraph)

templ = open('template.html').read()
print templ % '\n'.join(text)


If your data has more structure, you might find a tool like Fredrik
Lundh's elementtree useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Hopefully simple regular expression question

2005-06-14 Thread [EMAIL PROTECTED]
I want to match a word against a string such that 'peter' is found in
"peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or
"hey peterbe," because the word has to stand on its own. The following
code works for a single word:

def createStandaloneWordRegex(word):
""" return a regular expression that can find 'peter' only if it's
written
alone (next to space, start of string, end of string, comma, etc)
but
not if inside another word like peterbe """
return re.compile(r"""
  (
  ^ %s
  (?=\W | $)
  |
  (?<=\W)
  %s
  (?=\W | $)
  )
  """% (word, word), re.I|re.L|re.M|re.X)


def test_createStandaloneWordRegex():
def T(word, text):
print createStandaloneWordRegex(word).findall(text)

T("peter", "So Peter Bengtsson wrote this")
T("peter", "peter")
T("peter bengtsson", "So Peter Bengtsson wrote this")

The result of running this is::

 ['Peter']
 ['peter']
 []   <--- this is the problem!!


It works if the parameter is just one word (eg. 'peter') but stops
working when it's an expression (eg. 'peter bengtsson')

How do I modify my regular expression to match on expressions as well
as just single words??

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


Re: Get drives and partitions list (Linux)

2005-06-14 Thread cantabile
Thanks for the answer and help.
Cheers  :)

Peter Hansen wrote:
> cantabile wrote:
> 
>> Hi, Peter
>> Thanks for the reply. I'll check popen().
>> But you said I should not rely on fdisk... Why ? And should I prefer
>> sfdisk ? Why ?
> 
> 
> I was under the impression that fdisk was older and more primitive, but
> a quick check shows I'm probably not only wrong, but had it backwards!
> (The man page for fdisk says "try parted, then fdisk, then sfdisk"
> basically...)
> 
> Also, as you saw in Jeff's reply, there's a commands.getoutput()
> function that does basically what popen() would do, so just use whatever
> seems simplest.
> 
> -Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: collect data using threads

2005-06-14 Thread Jeremy Jones
Qiangning Hong wrote:

>A class Collector, it spawns several threads to read from serial port.
>Collector.get_data() will get all the data they have read since last
>call.  Who can tell me whether my implementation correct?
>
>class Collector(object):
>def __init__(self):
>self.data = []
>spawn_work_bees(callback=self.on_received)
>
>def on_received(self, a_piece_of_data):
>"""This callback is executed in work bee threads!"""
>self.data.append(a_piece_of_data)
>
>def get_data(self):
>x = self.data
>self.data = []
>return x
>
>I am not very sure about the get_data() method.  Will it cause data lose
>if there is a thread is appending data to self.data at the same time?
>
>Is there a more pythonic/standard recipe to collect thread data?
>
>  
>
This looks a little scary.  If a thread is putting something in 
self.data (in the on_received() method) when someone else is getting 
something out (in the get_data() method), the data that is put into 
self.data could conceivably be lost because you are pointing self.data 
to an empty list each time get_data() is called and the list that 
self.data was pointing to when on_received() was called may just be 
dangling.  Why not use the Queue from the Queue module?  You can push 
stuff in from one side and (have as many threads pushing stuff onto it 
as you like) and pull stuff off from the other side (again, you can have 
as many consumers as you'd like as well) in a thread safe manner.

HTH,

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


Re: Learning more about "The Python Way"

2005-06-14 Thread Jim
Have you seen the Zen of Python
  http://www.python.org/peps/pep-0020.html
?  Like a lot of humor, it has a lot of truth in it. 

Jim

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


Re: "also" to balance "else" ?

2005-06-14 Thread Sion Arrowsmith
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>Ron Adam wrote:
>> True, but I think this is considerably less clear.  The current for-else
>> is IMHO is reversed to how the else is used in an if statement.
>nope.  else works in exactly the same way for all statements that
>support it: if the controlling expression is false, run the else suite
>and leave the statement.

For example, consider the behaviour of:

condition = False
if condition:
print "true"
else:
print "false"

and

condition = False
while condition:
print "true"
break
else:
print "false"

>From this, it's clear that while/else gets its semantics from if/else.
Then:

i = 0
while i < 10:
print i
i += 1
else:
print "Done!"

for i in range(10):
print i
else:
print "Done!"

So for/else behaves while/else, hence for/else really is the same way
round as if/else. It may not be "intuitive", but it's consistent, and
personally I'd rather have that.

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

Re: case/switch statement?

2005-06-14 Thread Peter Hansen
D H wrote:
> Peter Hansen wrote:
>> With a case statement, on the other hand, you *know* that it must be 
>> just simple conditionals (a series of x == some_constant tests), so 
>> you don't need to look at all the cases, just the one that interests you.
> 
> Since you and Steve Holden agree that a case statement is useful, why 
> don't you propose it for python, or add it to the wiki page for Python 
> 3000.

Two simple reasons.

1. You forgot my previous comment that "in current Python the equivalent 
approach is, of course, a dictionary of some kind, though it's arguable 
whether this is as clean in many cases as a case statement would be."

2. Just because something is "useful" doesn't mean it should be added to 
Python.  The bar should be set much higher, and should include at least 
"and significantly better than any existing alternative way of doing the 
same thing."  Now go read point 1 again... ;-)

My point was not to suggest that I want a case statement in Python, nor 
even that a case statement is a good thing to have in a language (though 
it might be... it's not my place to say).  My point was simply to point 
out that performance is not the only reason to use a case statement.

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


Re: ANN: pyparsing-1.3.1 released

2005-06-14 Thread Peter Hansen
Christopher Subich wrote:
> Is the pyparsing 
> tokenizer flexible enough to let me do this sort of thing easily?

I can't say that for sure, but I can say that it is certainly easy 
enough to try it out (and well enough documented) that downloading it, 
installing it, and doing a quick proof-of-concept experiment would 
probably take less time than waiting for a reply to that question. ;-)

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


Re: Resume after exception

2005-06-14 Thread Dan Sommers
On Tue, 14 Jun 2005 10:09:30 +0100,
"Richard Lewis" <[EMAIL PROTECTED]> wrote:

> Hi there,
> Is it possible to have an 'except' case which passes control back to the
> point after the exception occurred?

Not that I can think of.

[ example of "interrupting" a file-reading function in order to ask the
user if they really want to read a locked file ]

I would rewrite that this way (untested, and without error checking):

def open_file(file_name, read_if_locked=False):
f = file(file_name)
[read first line]
if first_line == "FILE LOCKED" and read_if_locked == FALSE:
return False
[read the rest]
return True

def open_command():
if open_file("foo.bar") == False:
[ask the user what to do]
if ans == tkMessageBox.YES:
open_file("foo.bar", True )

Regards,
Dan

-- 
Dan Sommers

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


Re: Resume after exception

2005-06-14 Thread [EMAIL PROTECTED]
Why does the first function return True? Shouldn't it return the file
content? That's at least what the function name implies.
You call the second function open_command() which returns a boolean.
Feels wrong.

Where you have written "How?" I suggest that you replace that by:
return open_file("foo.bar", 1)

and change open_file() to look something like this:
 def open_file(file_name, ignore_lock=False):
f = file(file_name, 'r')
{read first line for file lock info}
if first_line == "FILE LOCKED" and not ignore_lock:
raise FileLockedException(lock_user, lock_timestamp)
{read remainder of file}
return True

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


Re: windows directory

2005-06-14 Thread Peter Hansen
Richard Lewis wrote:
> If you want to know where a particular directory is (on a Windows
> 'drive') you could use:
> 
> for drive_label in ["C", "D"]:
> if "Program Files" in os.listdir(drive_label + ":/"): return
> drive_label

This would cause trouble in at least two cases that I've seen.  One was 
a multiboot machine that had Windows 2000 on D: and Windows XP on C:. 
The other was a machine that had the Program Files folder copied, for 
reasons I don't recall (and perhaps only temporarily), to the D: drive.

Use one of the defined APIs for getting this information, not a hack 
like this please.

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


Re: Reg cgi header

2005-06-14 Thread Peter Hansen
praba kar wrote:
>  I have doubt regarding headers in cgi
> programming. If I gives "Content-Type:text/plain"
> then  I try to print html contents.  Is right or wrong
>  after  giving content-type: text/plain?

Since you didn't like the other two replies you've already received in 
response to your previous two postings of the same question, I'll 
provide another and you can see if you like it any better:

It is wrong.  Don't do it.

:-)

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


Geometry library

2005-06-14 Thread Cyril BAZIN
Hello,

I am looking for a geometry library for Python. 
I want to make some computations like: 
 -distance between vertex and polygon, vertex and polyline, vertex and segment, etc
 -if a point is inside a polygon, if a polyline intersect a polygon, etc

Thanks for your help,

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

Re: Resume after exception

2005-06-14 Thread Peter Hansen
Richard Lewis wrote:
> Is it possible to have an 'except' case which passes control back to the
> point after the exception occurred?

Basically no, although I could imagine some gross hack with the frame 
info and some bytecode hacks that effect a "goto".  Basically the stack 
frame gets unwound to the point where the exception is caught.  If you 
need recoverability, write your open_file function to be resumable in 
some way.

Note that you could easily (perhaps) implement this as a callable 
object, with the required state stored internally, and make the result 
almost indistinguishable from what you are asking for:

I could imagine an API allowing something like this:

open_file = RecoverableOpenFileThingy()

while not open_file.completed:
 try:
 open_file("foo.bar")
 except FileLockException, ex:
 # blah blah
 if ans != tkMessageBox.YES:
 open_file.completed = True

But since your open_file() doesn't seem likely to be doing anything 
particularly complicated, I really doubt you need the complexity of a 
special class here.  Just stick the relevant code inside a loop, much 
like that above, and break out of the loop when things succeed.

(What internal state do you think the open_file procedure would have to 
maintain, which you would be trying to resume?  If you are just going to 
go back to the beginning of it and try again, you don't need anything 
like what you asked for, just a regular loop.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sudo open() ? (python newbee question)

2005-06-14 Thread Dan Sommers
On Tue, 14 Jun 2005 11:52:13 +0200,
Denis WERNERT <[EMAIL PROTECTED]> wrote:

> The script could be SUID Root, and you could use os.setuid immediately
> after having performed the task to switch to a non-priviledged
> user. May be a big security risk, if someone can alter the script, he
> gains root access to the system...

I am *not* advocating suid scripts, and *ESPECIALLY NOT* suid Python
programs, but if a user can modify an unwriteable suid script owned by
root in a an unwriteable directory, then they already have root access
to the system (unless there's' a kernel or filesystem bug, in which case
all bets are off anyway).

Regards,
Dan

-- 
Dan Sommers

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


Re: Hopefully simple regular expression question

2005-06-14 Thread John Machin
[EMAIL PROTECTED] wrote:
> I want to match a word against a string such that 'peter' is found in
> "peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or
> "hey peterbe," because the word has to stand on its own. The following
> code works for a single word:
> 
> def createStandaloneWordRegex(word):
> """ return a regular expression that can find 'peter' only if it's
> written
> alone (next to space, start of string, end of string, comma, etc)
> but
> not if inside another word like peterbe """
> return re.compile(r"""
>   (
>   ^ %s
>   (?=\W | $)
>   |
>   (?<=\W)
>   %s
>   (?=\W | $)
>   )
>   """% (word, word), re.I|re.L|re.M|re.X)
> 
> 
> def test_createStandaloneWordRegex():
> def T(word, text):
> print createStandaloneWordRegex(word).findall(text)
> 
> T("peter", "So Peter Bengtsson wrote this")
> T("peter", "peter")
> T("peter bengtsson", "So Peter Bengtsson wrote this")
> 
> The result of running this is::
> 
>  ['Peter']
>  ['peter']
>  []   <--- this is the problem!!
> 
> 
> It works if the parameter is just one word (eg. 'peter') but stops
> working when it's an expression (eg. 'peter bengtsson')

No, not when it's an "expression" (whatever that means), but when the 
parameter contains whitespace, which is ignored in verbose mode.

> 
> How do I modify my regular expression to match on expressions as well
> as just single words??
> 

If you must stick with re.X, you must escape any whitespace characters 
in your "word" -- see re.escape().

Alternatively (1), drop re.X but this is ugly:

regex_text_no_X = r"(^%s(?=\W|$)|(?<=\W)%s(?=\W|$))" % (word, word)

Alternatively (2), consider using the \b gadget; this appears to give 
the same answers as the baroque method:

regex_text_no_flab = r"\b%s\b" % word


HTH,
John



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


Re: Where is Word?

2005-06-14 Thread Tomasz Lisowski
> Thanks, but could you pretty please post some code that does this? I'm new 
> to Python, let alone COM..
> 
> TIA,
> g

import win32com.client
wordCOMID = "Word.Application"

word = win32com.client.Dispatch(wordCOMID)

Then you can use the methods of the word object, provided by the COM 
object definition. Unfortunately I don't know them - you may do a 
research by making a reference to the Microsoft Word type library in 
Visual Basic, declaring the variable of type Word.Application, and then 
watching the code assistant showing the available methods and 
properties. You may also use the object browser.

Tomasz Lisowski

> 
> "Tomasz Lisowski" <[EMAIL PROTECTED]> schreef in bericht 
> news:[EMAIL PROTECTED]
> 
>>You may try to launch Word as a COM object and control it directly from 
>>Python using the COM object methods. This does not require you to know the 
>>application's path, only the COM object identifier.
>>
>>TLis 
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: collect data using threads

2005-06-14 Thread Peter Hansen
Qiangning Hong wrote:
> A class Collector, it spawns several threads to read from serial port.
> Collector.get_data() will get all the data they have read since last
> call.  Who can tell me whether my implementation correct?
[snip sample with a list]
> I am not very sure about the get_data() method.  Will it cause data lose
> if there is a thread is appending data to self.data at the same time?

That will not work, and you will get data loss, as Jeremy points out.

Normally Python lists are safe, but your key problem (in this code) is 
that you are rebinding self.data to a new list!  If another thread calls 
on_received() just after the line "x = self.data" executes, then the new 
data will never be seen.

One option that would work safely** is to change get_data() to look like 
this:

def get_data(self):
 count = len(self.data)
 result = self.data[:count]
 del self.data[count:]
 return result

This does what yours was trying to do, but safely.  Not that it doesn't 
reassign self.data, but rather uses a single operation (del) to remove 
all the "preserved" elements at once.  It's possible that after the 
first or second line a call to on_received() will add data, but it 
simply won't be seen until the next call to get_data(), rather than 
being lost.

** I'm showing you this to help you understand why your own approach was 
wrong, not to give you code that you should use.  The key problem with 
even my approach is that it *assumes things about the implementation*. 
Specifically, there are no guarantees in Python the Language (as opposed 
to CPython, the implementation) about the thread-safety of working with 
lists like this.  In fact, in Jython (and possibly other Python 
implementations) this would definitely have problems.  Unless you are 
certain your code will run only under CPython, and you're willing to put 
comments in the code about potential thread safety issues, you should 
probably just follow Jeremy's advice and use Queue.  As a side benefit, 
Queues are much easier to work with!

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


Re: Where is Word?

2005-06-14 Thread Peter Hansen
Guy Lateur wrote:
> I need a way to get the path where MS Word/Office has been installed. I need 
> to start Word from a script (see earlier post), 

(Asking us to refer to some earlier post that may or may not even be 
available on our news servers isn't the best way to get us the info.  A 
sentence or two summarizing would work best, I think.)

Can you describe what the user is going to do after Word pops open with 
this file in it?  Maybe there are simpler ways to do what you are trying 
to accomplish, aside from the specific issue of how to open Word itself.

For example, maybe the work you plan to have the user accomplish can be 
done automatically by controlling Word with COM.

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


Re: Tiff Image Reader/writer

2005-06-14 Thread PyPK
I get a decoder error when i do a get pixel on the Image

>>> im.getpixel((12,34))

Traceback (most recent call last):
  File "", line 1, in ?
  File "Image.py", line 858, in getpixel
self.load()
  File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line
180, in load
d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
  File "Image.py", line 328, in _getdecoder
raise IOError("decoder %s not available" % decoder_name)
IOError: decoder group4 not available

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


Re: recursive import list

2005-06-14 Thread Philippe C. Martin
Mike Meyer wrote:

> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
>>> I have a fairly large project going on and would like to figure out
>>> automatically from the source which files are being imported.
>> If you use your own import function, like below, you could create a
>> list of all imported modules.
> 
> Why not use sys.modules? To answer the question actually asked, check
> for a __file__ attributes on each module in sys.modules, and print
> that if it exists.
> 
> That won't list builtin modules that are imported - but they don't
> have files to be imported, so I assume that the OP doesn't want them
> listed.
> 
> http://mail.python.org/mailman/listinfo/python-list


Re: Resume after exception

2005-06-14 Thread Skip Montanaro

>> Is it possible to have an 'except' case which passes control back to
>> the point after the exception occurred?

Peter> Basically no, although I could imagine some gross hack with the
Peter> frame info and some bytecode hacks that effect a "goto".

Someone (I forget who) posted an autoload module (appended) awhile ago for
Python that does a reasonable job of recovery in the case of
use-before-import.  I modified it slightly and use it on my laptop.
Examples:

% python
Python 2.5a0 (#77, May 14 2005, 14:47:06) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> time.time()
found time in xmlrpclib module
1118752288.5277729
>>> datetime.datetime.now()
found datetime in xmlrpclib module
datetime.datetime(2005, 6, 14, 7, 31, 43, 136432)
>>> math.sin(7)
autoloading math
0.65698659871878906

Note that it's far from perfect (to wit: the weird fact that "time" and
"datetime" are found in the xmlrpclib module).

Skip



bint2TmtDAgpX.bin
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Hopefully simple regular expression question

2005-06-14 Thread Kalle Anke
On Tue, 14 Jun 2005 13:01:58 +0200, [EMAIL PROTECTED] wrote
(in article <[EMAIL PROTECTED]>):

> How do I modify my regular expression to match on expressions as well
> as just single words??

import re

def createStandaloneWordRegex(word):
""" return a regular expression that can find 'peter' only if it's
written alone (next to space, start of string, end of string,
comma, etc) but not if inside another word like peterbe """

return re.compile(r'\b' + word + r'\b', re.I)


def test_createStandaloneWordRegex():
def T(word, text):
print createStandaloneWordRegex(word).findall(text)

T("peter", "So Peter Bengtsson wrote this")
T("peter", "peter")
T("peter bengtsson", "So Peter Bengtsson wrote this")
test_createStandaloneWordRegex()

Works?

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


Re: What is different with Python ?

2005-06-14 Thread Roy Smith
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> High and low tides aren't caused by the moon.

They're not???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hopefully simple regular expression question

2005-06-14 Thread TZOTZIOY
On 14 Jun 2005 04:01:58 -0700, rumours say that "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> might have written:

>I want to match a word against a string such that 'peter' is found in
>"peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or
>"hey peterbe," because the word has to stand on its own. The following
>code works for a single word:

[snip]

use \b before and after the word you search, for example:

rePeter= re.compile("\bpeter\b", re.I)

In the documentation for the re module, Subsection 4.2.1 is Regular
Expression Syntax; it'll help a lot if you read it.

Cheers.
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-14 Thread John Roth

"Andrew Dalke" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Ron Adam wrote:
>> True, but I think this is considerably less clear.  The current for-else
>> is IMHO is reversed to how the else is used in an if statement.
>
> As someone else pointed out, that problem could be resolved in
> some Python variant by using a different name, like "at end".
> Too late for anything before P3K.

I don't think it has to wait. There seems to be a movement toward
putting new things in the next couple of releases, and then waiting until
3.0 to remove the old way of doing things.

So "at end" or "on normal exit" could be put in any time;
the use of "else" in that context wouldn't go away until 3.0.
The real question is whether it's worth doing at all. I consider
it a fairly minor issue, all told.

John Roth


>
>
> Andrew
> [EMAIL PROTECTED]
> 

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


Re: Going crazy...

2005-06-14 Thread Jan Danielsson
Gary Herron wrote:
[---]
>>   I just tried typing the above in Python, and it - obviously - doesn't
>> work, so it must be some other syntax.
>>  
>>
> Not with tuples, lists or dictionaries.  However a more recent addition
> to the language is Sets, and they support set differences:
> 
 from sets import Set
 Set([1,2,3,4,5,6]) - Set([2,3,6])
> Set([1, 4, 5])

   That's it! Thanks; I knew I had seen it. That's a pretty cool
feature; which I have use for in a library I'm writing.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Urwid 0.8.8 with web_display

2005-06-14 Thread Ian Ward
Announcing Urwid 0.8.8
--

Urwid home page:
  http://excess.org/urwid/

Tarball:
  http://excess.org/urwid/urwid-0.8.8.tar.gz
or:
  https://excess.org/urwid/urwid-0.8.8.tar.gz


Summary:


This release adds a new web_display module that can emulate a console
display within a web browser window, as well as other enhancements.  

Live demo of the web_display module:
  http://live.excess.org/


New in this release:


  - New web_display module that emulates a console display within a web 
browser window.  Application must be run as a CGI script under Apache.

Supports font/window resizing, keepalive for long-lived connections,
limiting maximum concurrent connections, polling and connected update
methods.

Tested with Mozilla Firefox and Internet Explorer.

  - New BoxAdapter class for using box widgets in places that usually expect
flow widgets.

  - New curses_display input handling with better ESC key detection and 
broader escape code support.
  
  - Shortened resize timeout on gradual resize to improve responsiveness.
  

About Urwid
===

Urwid is a curses-based UI library for Python. It features fluid 
interface resizing, CJK support, multiple text layouts, simple 
attribute markup, powerful scrolling list boxes, flexible edit boxes
and HTML screen shots.

Urwid is released under the GNU LGPL.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resume after exception

2005-06-14 Thread [EMAIL PROTECTED]
Richard Lewis schreef:
> Is it possible to have an 'except' case which passes control back to the
> point after the exception occurred?

No, not in Python. The concept has however been discussed, under the
name "resumable exceptions".

http://www.google.com/search?num=100&q=%22resumable+exceptions%22+site%3Apython.org

An excellent article about the concept was written by Kent Pitman:

"Condition Handling in the Lisp Language Family"
http://www.nhplace.com/kent/Papers/Condition-Handling-2001.html

Common Lisp is a language that does have the feature. Your code would
be written in Lisp like below. When the function notices the file is
locked, it will raise an exception. Now imagine there are two ways to
solve the problem: 1) read the file anyway, despite the lock; 2) clear
the lock and read the file. Or reading the file could be cancelled.
These three possible ways to continue the execution are set up by
"restart-case". (So this is actually a generalization of your request,
in that instead of "just continueing", you can direct the way of
continuing)

(defun read-unlocked-file (file-name)
  (with-open-file (f file-name)

(when (string= (read-line f) "FILE LOCKED")
  (let ((user "lock-user")
(timestamp 123))
(restart-case (error 'file-locked :name file-name
 :user user :timestamp timestamp)
  (continue () :report "Continue reading the locked file.")
  (clear-lock () :report "Clear the lock and continue reading"
(warn "clearing lock..."))
  (abort () :report "Abort reading the file."
(return-from read-unlocked-file)

(warn "reading remainder of file...")
t))

When reading a locked file, you end up with this message:

CL-USER(31): (read-unlocked-file "file.txt")
Error: File file.txt was locked by lock-user at time 123.
  [condition type: FILE-LOCKED]

Restart actions (select using :continue):
 0: Continue reading the locked file.
 1: Clear the lock and continue reading
 2: Abort reading the file.
 3: Return to Top Level (an "abort" restart).
 4: Abort entirely from this process.

Note the three first "restart actions" are the ones we just defined
inside "read-unlocked-file". Let's continue execution by clearing the
lock (restart number 1):

[1] CL-USER(32): :continue 1
Warning: clearing lock...
Warning: reading remainder of file...
T

If Python had restarts, in your example you would set up code that,
depending on whether the user clicked "abort" or "continue" in the
dialog, automatically invokes the corresponding restart to either
continue or abort the calculation.

Restarts are pretty cool. Maybe Stackless Python could support it
fairly easily, restarts basically being named continuations?


- Willem

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


Re: Where is Word?

2005-06-14 Thread Guy Lateur
My original post is called "Start application & continue after app exits". 
Is there a better way to refer to past posts, btw?

I want to make a temporary file (directory listing), open it in Word to let 
the user edit, layout and print it, and then delete the temp file 
afterwards. I don't think we'll be able to fully automate it, though. The 
user should be able to set her own fonts and stuff.

g



"Peter Hansen" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> Guy Lateur wrote:
>> I need a way to get the path where MS Word/Office has been installed. I 
>> need to start Word from a script (see earlier post),
>
> (Asking us to refer to some earlier post that may or may not even be 
> available on our news servers isn't the best way to get us the info.  A 
> sentence or two summarizing would work best, I think.)
>
> Can you describe what the user is going to do after Word pops open with 
> this file in it?  Maybe there are simpler ways to do what you are trying 
> to accomplish, aside from the specific issue of how to open Word itself.
>
> For example, maybe the work you plan to have the user accomplish can be 
> done automatically by controlling Word with COM.
>
> -Peter 


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


Re: sudo open() ? (python newbee question)

2005-06-14 Thread TZOTZIOY
On 14 Jun 2005 08:12:17 -0400, rumours say that Dan Sommers
<[EMAIL PROTECTED]> might have written:

>On Tue, 14 Jun 2005 11:52:13 +0200,
>Denis WERNERT <[EMAIL PROTECTED]> wrote:
>
>> The script could be SUID Root, and you could use os.setuid immediately
>> after having performed the task to switch to a non-priviledged
>> user. May be a big security risk, if someone can alter the script, he
>> gains root access to the system...

>I am *not* advocating suid scripts, and *ESPECIALLY NOT* suid Python
>programs, but if a user can modify an unwriteable suid script owned by
>root in a an unwriteable directory, then they already have root access
>to the system (unless there's' a kernel or filesystem bug, in which case
>all bets are off anyway).

I believe that the suid bit on scripts (either *sh or python) is
completely ignored on most *nix systems.

Try this in a shell (bash or ksh) as a sudo-capable user:

echo hello >/tmp/tmp
sudo chown root /tmp/tmp
sudo chmod 600 /tmp/tmp
cat >/tmp/ax.py <<@
#!/usr/bin/env python
x = open("/tmp/tmp", "w")
x.write("there")
x.close()
@
sudo chown root /tmp/ax.py
sudo chmod a=rx,u+s /tmp/ax.py
ls -l /tmp/ax.py /tmp/tmp
/tmp/ax.py

I get:

-r-sr-xr-x  1 root users 75 2005-06-14 16:15 /tmp/ax.py
-rw---  1 root users  6 2005-06-14 16:15 /tmp/tmp
Traceback (most recent call last):
  File "/tmp/ax.py", line 2, in ?
x = open("/tmp/tmp", "w")
IOError: [Errno 13] Permission denied: '/tmp/tmp'

-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Show current ip on Linux

2005-06-14 Thread Sibylle Koczian
David Van Mosselbeen schrieb:
> 
> Thanks for support.
> I have read the refered page you show above. I try some piece of code that
> im have copy and paste it into a blank file that i give the name
> "ip_adress.py" to test it.
> 
> 
> THE SOURCE CODE :
> -
> 
> import commands
> 
> ifconfig = '/sbin/ifconfig'
> # name of ethernet interface
> iface = 'eth0'
> # text just before inet address in ifconfig output
> telltale = 'inet addr:'
> 
> def my_addr():
> cmd = '%s %s' % (ifconfig, iface)
> output = commands.getoutput(cmd)
> 
> inet = output.find(telltale)
> if inet >= 0:
> start = inet + len(telltale)
> end = output.find(' ', start)
> addr = output[start:end]
> else:
> addr = ''
> 
> return addr
> # End python code
> 
> But now, it's fine to have some piece of code but this wil not work on my
> computer. I'm sure that y do somethings bad.
> To run the python script on a Linux machine. How to proceed it ?
> 
> 1) I have open a terminal
> 2) then i type "python ip_adress.py" (to run the script)
> 
> But nothings, i not view the current ip of my computer.
> What happend ?
> 

You have defined a function, but you never call this function. Running a 
script won't do anything, if this script consists only of function (or 
class) definitions.

You can either

- open the interactive python interpreter and type:
import ip_adress
ip_adress.my_addr()

or, probably simpler,

- add the following two lines to your script, after the definition of 
your function:

if __name__ == '__main__':
 print my_addr()

Then run your script just as you did before. Now you are calling the 
function and printing the value it returns.

-- 
Dr. Sibylle Koczian
Universitaetsbibliothek, Abt. Naturwiss.
D-86135 Augsburg
e-mail : [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-14 Thread Peter Hansen
Roy Smith wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>>High and low tides aren't caused by the moon.
> 
> They're not???

Probably he's referring to something like this, from Wikipedia, which 
emphasizes that while tides are caused primarily by the moon, the height 
of the high and low tides involves the sun as well:

"The height of the high and low tides (relative to mean sea level) also 
varies. Around new and full Moon, the tidal forces due to the Sun 
reinforce those of the Moon, due to the syzygy found at those times - 
both the Sun and the Moon are 'pulling the water in the same direction.'"

(If I'm right about this, then the statement is still wrong, since even 
without the sun there would be high and low tides, just not of the 
magnitude we have now.)

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


AIX 4.3, Python 2.4.1 fails in test_exceptions with a core dump

2005-06-14 Thread mkent
I'm attempting to switch from 2.3.2 to 2.4.1 on our AIX 4.3
development system.  I have no problems building Python 2.3.2.  I
build Python 2.4.1 using 'configure --without-threads; gmake;
gmake test', and always get a coredump during the tests on
'test_exceptions'.  I've searched for any reports of this problem on
the Sourceforge bug list and here, with no success.  Has anyone seen
this problem?

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


Re: Resume after exception

2005-06-14 Thread Richard Lewis

On Tue, 14 Jun 2005 10:09:30 +0100, "Richard Lewis"
<[EMAIL PROTECTED]> said:
> Hi there,
> 
> Is it possible to have an 'except' case which passes control back to the
> point after the exception occurred?
> 
> e.g.
> 
> # a function to open the file
> # raises FileLockedException is file contains 'locked' information
> def open_file(file_name):
> f = file(file_name, 'r')
> {read first line for file lock info}
> if first_line == "FILE LOCKED":
> raise FileLockedException(lock_user, lock_timestamp)
> {read remainder of file}
> return True
> 
> # elsewhere in a user interface module
> def open_command():
> try:
> open_file("foo.bar")
> except FileLockException, X:
> ans = tkMessageBox.askyesno(title="File Locked", message="File
> locked by '" + X.user + "' on " + X.time_stamp + "\nContinue
> anyway?")
> if ans == tkMessageBox.YES:
> # return control to the remainder of the open_file function.
> How?
> else:
> return False
> 
Thanks for your suggestions.

I've gone with the passing an 'ignore_lock' option to the open_file
function:

def open_file(self, ignore_lock=False):
"Retrieves content file from FTP server and parses it into local DOM
tree."
ftp = ftplib.FTP(self.host)
ftp.login(self.login, self.passwd)

content_file = file(self.local_content_file_name, 'w+b')
ftp.retrbinary("RETR " + self.path, content_file.write)
ftp.quit()
content_file.close()

self.document = parse(self.local_content_file_name)

root = self.document.documentElement
if not(ignore_lock) and root.getAttribute("locked") == "1":
raise ContentLocked(root.getAttribute("user"),
root.getAttribute("time-stamp"))

self.set_file_lock()

self.opened = True

return True

#. elsewhere .

def open_command(self):
"Command to handle 'open' actions."
try:

self.site.load_from_server('user','host.name','login','passwd','path/to/content.xml',
False)
except ContentLocked, e:
ans = QMessageBox.question("Content Locked", "The content file
is locked!\n\nIt seems that the user '" + e.user + "' is already
working on the website. They left the time stamp:\n" +
e.time_stamp + "\n\nChoose 'Yes' to carry on working on the
website and risk losing another user's changes, or 'No' to
quit.", "Yes", "No", "Cancel")
if ans == "Yes":

self.site.load_from_server('user','host.name','login','passwd','path/to/content.xml',
True)
else:
qApp.quit()
except Exception, e:
#...

I don't know why I put return False in my original open_command
function, it was supposed to be a quit call.

This solution allows me to keep my exception mechanism (which passes the
lock information [user and timestamp] out of the open_file function)
because it is dependent on ignore_lock being false.

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


Re: Where is Word?

2005-06-14 Thread Peter Hansen
Guy Lateur wrote:
> My original post is called "Start application & continue after app exits". 
> Is there a better way to refer to past posts, btw?

No, the subject is a good way to refer to past posts.  I just meant 
forcing us to dig back, when the post may no longer even be on our 
servers, is not helpful.

> I want to make a temporary file (directory listing), open it in Word to let 
> the user edit, layout and print it, and then delete the temp file 
> afterwards. I don't think we'll be able to fully automate it, though. The 
> user should be able to set her own fonts and stuff.

I understand now.  Definitely if you are doing this to allow customizing 
fonts and such, at the user's whim, you can't automate it, by definition...

(Perhaps I should ask why anyone would want to waste time putting 
arbitrary fonts and colours and such around a simple directory listing, 
but I won't. )

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


Re: Python as CGI on IIS and Windows 2003 Server

2005-06-14 Thread jean-marc


[EMAIL PROTECTED] wrote:
> jean-marc schrieb:
> > Some bits are coming back to me: the problems stemmed from adresses -
> > getting the root of IIS was different so accessing files didn't work
> > the same way.
>
> thanks for that.
> you are right, IIS versions are different.
> Wich kind of adresses do you mean, http-adresses or paths in file
> systems to root of IIS or to pythonscripts below IIS' root?
>
> Unfortunately I couldn't find a way to solve the problem.
>
>
> regards
> Lothar

I think it was due to the way of getting a reference to the IIS's root
- I think that all adresses in html (wheter from static documents or
those generated by python) need to use relative adresses (double dot
slash, or dot slash type of adresses).

If it still doesn't work maybe posting some culprit code could help
figure it out...!

Jean-Marc

May

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


Re: [OT ?] (Pythonic) detection word protected files

2005-06-14 Thread Gilles Lenfant
Tim Golden a écrit :
> [Gilles Lenfant]
> | I'm building an utility that makes a catalog of M$ word files 
> | in a giant 
> | directory tree. The password protected files must be marked, and I 
> | didn't find how to guess which files are password protected and which 
> | ones are not.
> | 
> | I can't use the COM interface for this because the utility 
> | must run on a 
> | Linux Samba server.
> | 
> | I didn't find anything satisfying in M$ related sites (like msdn) or 
> | forums or google.
> 
> This page looks like it might be useful:
> 
> http://wvware.sourceforge.net/wvInfo.html

Wow ! What a great starter ! I got to much information now :o)

Many thanks.

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


Re: "also" to balance "else" ?

2005-06-14 Thread TZOTZIOY
On Tue, 14 Jun 2005 07:20:06 GMT, rumours say that Andrew Dalke
<[EMAIL PROTECTED]> might have written:

>Given the Python maxim of
>  There should be one-- and preferably only one --obvious way to do it.
>
>which of these is the preferred and obvious way?
>
>while f():
>  print "Hello!"
>  if g():
>break
>else:
>  print "this is a test"
>also:
>  print "this is not a pipe"
>
> -or-
>
>while f():
>  print "Hello!"
>  if g():
>print "this is a test"
>break
>else:
>  print "this is not a pipe"

>I prefer the second over the first.

I am not advocating for either side AFA python 2 is concerned (however I
would substitute "then" for "also"), however the second way does not
handle /elegantly/ multiple break points.

I'm +1 for making "else" the target for break in Py3K though, given an
elegant "also"/"then" keyword.
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT ?] (Pythonic) detection word protected files

2005-06-14 Thread Gilles Lenfant
Gerald Klix a écrit :
> Perhaps you can use OpenOffice and it's python UNO Bindings?
> I only know about their existence, but perhaps this will be a starting 
> point: http://udk.openoffice.org/

Thanks, I already considered this but didn't find the way to get the 
encryption information (protected or not) in the UNO API.

Anyway UNO is somehow overkill to get something like a pair of bytes at 
some position in the file (4 or 5 python lines with the standard packages).

Many thanks

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


RE: Where is Word?

2005-06-14 Thread Tim Golden
[Guy Lateur]
| I want to make a temporary file (directory listing), open it 
| in Word to let 
| the user edit, layout and print it, and then delete the temp file 
| afterwards. I don't think we'll be able to fully automate it, 
| though. The 
| user should be able to set her own fonts and stuff.

Haven't tried the technique myself, but this post

http://groups-beta.google.com/group/comp.lang.python/msg/4ea1a92c2c3a4664

looks like it might do what you're after. In essence,
you use CreateProcess to run Word (which is a bit messier
than the other techniques described, but gives you a
bit more control), and then you use the handle that passes
back to determine when it's finished.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Tiff Image Reader/writer

2005-06-14 Thread James Carroll
Hmm... that's unfortunate.

What platform are you on?  If Windows, then I believe that PIL is
statically linked against LibTIFF and that particular libtiff wasn't
compiled with certain options (CCITT formats or something.)  (in 1999
that was true, I found a post from Fred here:
http://mail.python.org/pipermail/image-sig/1999-June/000755.html)

If it's a one-time thing, there are ways of converting the TIFF to a
different encoding.  I use the libtiff tifftools  command tiffcp:

tiffcp -c none  infile.tif out file.tif

which will decode into a non-compressed tiff.

Otherwise, you might be out of luck (or have to change some of the
libtiff options.)

If you put your tiff file somewhere where I can download it, I'll try
reading it with the alternatives that I have on my system and let you
know what works...

-Jim



On 14 Jun 2005 05:25:46 -0700, PyPK <[EMAIL PROTECTED]> wrote:
> I get a decoder error when i do a get pixel on the Image
> 
> >>> im.getpixel((12,34))
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "Image.py", line 858, in getpixel
> self.load()
>   File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line
> 180, in load
> d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
>   File "Image.py", line 328, in _getdecoder
> raise IOError("decoder %s not available" % decoder_name)
> IOError: decoder group4 not available
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Single Application Instance Example

2005-06-14 Thread Chris Lambacher
Does anyone know of an example of how to make a Python program only
run a single instance.  I am specifically looking for examples for
win32.

I think I should be able to do this with win32all but the method is
not obvious.  Preferably I would like to be able to get a handle to
the already running instance so that I can push it to the foreground
as well.

Thanks
-Chris
-- 
Christopher Lambacher
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windows directory

2005-06-14 Thread Rune Strand
On XP at least you have the environment variable "ProgramFiles".

You can fetch the path it holds through os.environ

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


RE: Single Application Instance Example

2005-06-14 Thread Tim Golden
[Chris Lambacher]
| Does anyone know of an example of how to make a Python program only
| run a single instance.  I am specifically looking for examples for
| win32.
| 
| I think I should be able to do this with win32all but the method is
| not obvious.  Preferably I would like to be able to get a handle to
| the already running instance so that I can push it to the foreground
| as well.

You could Google around through the archives of this group and
find some previous discussions, for greater detail, but the
standard approach (within the Python world and without) seems 
to be to use the Mutexes exposed by the win32event module.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Single Application Instance Example

2005-06-14 Thread Paul McNett
Chris Lambacher wrote:
> Does anyone know of an example of how to make a Python program only
> run a single instance.  I am specifically looking for examples for
> win32.

The Python Cookbook, Second Edition, page 380, recipe 9.9: Determining 
Whether Another Instance of a Script is Already Running in Windows, 
suggests using a mutex kernel object to be safe from race conditions:

from win32event import CreateMutex
from win32api import GetLastError
from winerror import ERROR_ALREADY_EXISTS
from sys import exit
handle = CreateMutex(None, 1, 'A unique mutex name')
if GetLastError() == ERROR_ALREADY_EXISTS:
print "I exist already"
exit(1)
else:
print "I don't exist already"


> I think I should be able to do this with win32all but the method is
> not obvious.  Preferably I would like to be able to get a handle to
> the already running instance so that I can push it to the foreground
> as well.

There are ways using win32 to get the handle to the existing process, 
but I'm too rusty with win32 to offer that part of the solution.


-- 
Paul McNett
http://paulmcnett.com

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


Re: What is different with Python ?

2005-06-14 Thread Peter Maas
Andrew Dalke schrieb:
> Peter Maas wrote:
> 
>>I think Peter is right. Proceeding top-down is the natural way of
>>learning (first learn about plants, then proceed to cells, molecules,
>>atoms and elementary particles).
> 
> 
> Why in the world is that way "natural"?  I could see how biology
> could start from molecular biology - how hereditary and self-regulating
> systems work at the simplest level - and using that as the scaffolding
> to describe how cells and multi-cellular systems work.

Yes, but what did you notice first when you were a child - plants
or molecules? I imagine little Andrew in the kindergarten fascinated
by molecules and suddenly shouting "Hey, we can make plants out of
these little thingies!" ;)

-- 
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-14 Thread Claudio Grondi
> > High and low tides aren't caused by the moon.
> They're not???

I suppose, that the trick here is to state,
that not the moon, but the earth rotation relative
to the moon causes it, so putting the moon at
cause is considered wrong, because its existance
alone were not the cause for high and low tides
in case both rotations were at synch. It is probably
a much more complicated thingy where also the
sun and maybe even the planets must be
considered if going into the details, but this is
another chapter.

I experienced once a girl who pointing me to the
visible straight beams from earth to sky one can see
as result of sunlight coming through the clouds
said: "look, along this visible beams the water from
the lake wents upwards and builds the clouds".
She was very convinced it's true, because she
learned it at school, so I had no chance to go the
details explaining, that there is no need for the
visible straight light beams coming through the
holes in the clouds for it.

I can imagine, that many believe that the
moon is orbiting each day around the earth
even if they know, that earth rotates around
its own axle and around the sun. Its not that
important for them to ask for details, so that
is the mechanism how the "lies" are born -
caused by lack of the necessity or the laziness
to achieve deeper understanding.

Claudio

"Roy Smith" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> > High and low tides aren't caused by the moon.
>
> They're not???


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


Re: What is different with Python ? (OT I guess)

2005-06-14 Thread Magnus Lycka
Andrew Dalke wrote:
> Andrea Griffini wrote:
> 
>>This is investigating. Programming is more similar to building
>>instead (with a very few exceptions). CS is not like physics or
>>chemistry or biology where you're given a result (the world)
>>and you're looking for the unknown laws. In programming *we*
>>are building the world. This is a huge fundamental difference!
> 
> Philosophically I disagree.  Biology and physics depends on
> models of how the world works.  The success of a model depends
> on how well it describes and predicts what's observed.
> 
> Programming too has its model of how things work; you've mentioned
> algorithmic complexity and there are models of how humans
> interact with computers.  The success depends in part on how
> well it fits with those models.

And this is different from building? I don't disagree with the
other things you say, but I think Andrea is right here, although
I might have said construction or engineering rather than building.

To program is to build. While scientists do build and create things,
the ultimate goal of science is understanding. Scientists build
so that they can learn. Programmers and engineers learn so that
they can build.

There is a big overlap between science and engineering. I hope we
can embrace each other's perspectives and see common goals, but
I also think the distinction is useful.

It seems to me that a lot of so called science is really more
focused on achieving a certain goal than to understand the
world. I think Richard Feynman said something like "disciplines
with the word 'science' in their names aren't", and I feel that
he had a point.

I find the idea of computer science a bit odd. Fields like civil
engineering or electronics rely solidly on science and the laws
of nature. We must, or else our gadgets fail. We work closely
with field such as physics and chemistry, but we're not scientists,
because we learn to build, not vice versa. Our goal is problem
solving and solutions, not knowledge and understanding.

As you said:
"The success of a model depends on how well it describes and
predicts what's observed."
It's quite obvious that this is as true when we build houses,
airplanes or bridges, and when we build programs. Right?

It seems to me that *real* computer scientists are very rare. I
suspect that the label computer scientist comes from a lack of
a better word. Erh, computer engineering without engineering?
What do we call this? I don't mean to offend anyone. I have all
respect for both the education and the students of the discipline
called computer science, and I think it's vital that there is a
foundation of science and mathematics in this field, but most
practitioners aren't scientists any more than engineers are
scientists. Ok, my degree is "Master of Science" in English,
but my academic discipline is electronic engineering, not
electronic science--because the goal with the education is to
be able to use scientific knowledge to solve practical problems,
which is, by definition, what engineers do.

Oh well, I guess it's a bit late to try to rename the Computer
Science discipline now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: implicit variable declaration and access

2005-06-14 Thread Scott David Daniels
Tom Anderson wrote:
> ... If it's not, try:
> x = "myVarName"
> y = "myVarValue"
> locals()[x] = y

Sorry, this works with globals(), but not with locals().
There isn't a simple way to fiddle the locals (the number
is determined when the function is built).

I do, however, agree with you about what to use.  I use:
   class Data(object):
  def __init__(self, **kwargs):
 for name, value in kwargs.iteritems():
 setattr(self, name, value)
  def __repr__(self):
 return '%s(%s)' % (type(self).__name__, ', '.join(
['%s=%r' % (name, getattr(self, name))
 for name in dir(self) if name[0] != '_']))

When I want to fiddle with named values.
 el = Data(a=5, b='3')
 el.c = el.a + float(el.b)
 setattr(el, 'other', getattr(el, 'a') + getattr(el, 'c'))
 el

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


  1   2   >