Re: What is different with Python ?

2005-06-12 Thread George Sakkis
"Andrea Griffini" wrote:

> I think that if you don't understand memory,
> addresses and allocation and deallocation, or
> (roughly) how an hard disk works and what's
> the difference between hard disks and RAM then
> you're going to be a horrible programmer.
>
> There's no way you will remember what is O(n),
> what O(1) and what is O(log(n)) among containers
> unless you roughly understand how it works.

There's a crucial distinction between these two scenarios though: the
first one has to do with today's hardware and software limitations
while the second one expresses fundamental, independent of  technology,
algorithmic properties. In the not-too-far-future, the difference
between RAM and hard disks may be less important than today; hard disks
may be fast enough for most purposes, or the storage policy may be
mainly decided by the OS, the compiler, the runtime system or a library
instead of the programmer (similarly to memory management being
increasingly based on garbage collection). As programmers today don't
have to know or care much about register allocation, future programmers
may not have to care about whether something is stored in memory or in
disk. OTOH, an algorithm or problem with exponential complexity will
always be intractable for sufficiently large input, no matter how fast
processors become. The bottom line is that there is both fundamental
and contemporary knowledge, and although one needs to be good at both
at any given time, it's useful to distinguish between them.

George

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


Re: What is different with Python ?

2005-06-12 Thread Steven D'Aprano
On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote:

> At some point, you need to draw a line in the sand (so to speak) and say, 
> "I understand everything down to *here* and can do cool stuff with that 
> knowledge.  Below that, I'm willing to take on faith".  I suspect you would 
> agree that's true, even if we don't agree just where the line should be 
> drawn.  You seem to feel that the level of abstraction exposed by a 
> language like C is the right level.  I'm not convinced you need to go that 
> far down.  I'm certainly not convinced you need to start there.

The important question is, what are the consequences of that faith when it
is mistaken?

As a Python developer, I probably won't write better code if I understand
how NAND gates work or the quantum mechanics of electrons in solid
crystals. But I will write better code if I understand how Python
implements string concatenation, implicit conversion from ints to longs,
floating point issues, etc.

It seems that hardly a day goes by without some newbie writing to the
newsgroup complaining that "Python has a bug" because they have discovered
that the floating point representation of 0.1 in decimal is actually more
like 0.10001. And let's not forget the number of bugs out
there because developers thought that they didn't need to concern
themselves with the implementation details of memory management.

It makes a difference whether your algorithm runs in constant time,
linear, quadratic, logarithmic or exponential time -- or something even
slower. The implementation details of the language can hide quadratic or
exponential algorithms in something that looks like a linear or constant
algorithm. Premature optimization is a sin... but so is unusably slow
code.



-- 
Steven.


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


Re: What is different with Python ?

2005-06-12 Thread Andrea Griffini
On Sun, 12 Jun 2005 21:52:12 -0400, Peter Hansen <[EMAIL PROTECTED]>
wrote:

>I'm curious how you learned to program.

An HP RPN calculator, later TI-57. Later Apple ][.
With Apple ][ after about one afternoon spent typing
in a basic program from a magazine I gave up with
basic and started with 6502 assembler ("call -151"
was always how I started my computer sessions).

>What path worked for you, and do you think it was
>a wrong approach, or the right one?

I was a fourteen with no instructor, when home
computers in my city could be counted on the fingers
of one hand. Having an instructor I suppose would
have made me going incredibly faster. Knowing better
the english language at that time would have made
my life also a lot easier.
I think that anyway it was the right approach in
terms of "path", not the (minimal energy) approach
in terms of method. Surely a lower energy one in
the long run comparing to those that started with
basic and never looked at lower levels.

>In my case, I started with BASIC.  Good old BASIC, with no memory 
>management to worry about, no pointers, no "concrete" details, just FOR 
>loops and variables and lots of PRINT statements.

That's good as an appetizer.

>A while (some months) later I stumbled across some assembly language and 
>-- typing it into the computer like a monkey, with no idea what I was 
>dealing with -- began learning about some of the more concrete aspects 
>of computers.

That is IMO a very good starting point. Basically it
was the same I used.

>This worked very well in my case, and I strongly doubt I would have 
>stayed interested in an approach that started with talk of memory 
>addressing, bits and bytes, registers and opcodes and such.

I think that getting interested in *programming* is
important... it's like building with LEGOs, but at a
logical level. However that is just to get interest...
and a few months with basic is IMO probably too much.
But after you've a target (making computers do what
you want) then you've to start placing solid bricks,
and that is IMO assembler. Note that I think that any
simple assembler is OK... even if you'll end up using
a different processor when working in C it will be
roughly ok. But I see a difference between those that
never (really) saw assembler and those that did.

>I won't say that I'm certain about any of this, but I have a very strong 
>suspicion that the *best* first step in learning programming is a 
>program very much like the following, which I'm pretty sure was mine:
>
>10 FOR A=1 TO 10: PRINT"Peter is great!": END

Just as a motivation. After that *FORGETTING* that
(for and the "next" you missed) is IMO perfectly ok.

>More importantly by far, *I made the computer do something*.

Yes, I agree. But starting from basic and never looking
lower is quit a different idea.

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


Re: What is different with Python ?

2005-06-12 Thread Claudio Grondi
> They're things that can be IMO genuinely accept
> as "obvious". Even "counting" is not the lowest
> level in mathematic... there is the mathematic
> philosohy direction.
I am personally highly interested in become
aware of the very bottom, the fundaments
all our knownledge is build on.
Trying to answer questions like:
What are the most basic ideas all other
are derived from in mathematics and
programming?
keeps me busy for hours, days, years ...

Any insights you can share with
me(and/or this group)?

Claudio



"Andrea Griffini" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith <[EMAIL PROTECTED]> wrote:
>
> >How far down do you have to go?  What makes bytes of memory, data busses,
> >and CPUs the right level of abstraction?
>
> They're things that can be IMO genuinely accept
> as "obvious". Even "counting" is not the lowest
> level in mathematic... there is the mathematic
> philosohy direction. From "counting" you can go
> "up" in the construction direction (rationals,
> reals, functions, continuity and the whole
> analysis area) building on the counting concept
> or you can go "down" asking yourself what it
> does really mean counting, what do you mean
> with a "proof", what really is a "set".
> However the "counting" is naturally considered
> obvious for our minds and you can build the
> whole life without the need to look at lower
> levels and without getting bitten too badly for
> that simplification.
>
> Also lower than memory and data bus there is
> of course more stuff (in our universe looks
> like there is *always* more stuff no mattere
> where you look :-) ), but I would say it's
> more about electronic than computer science.
>
> >Why shouldn't first-year CS students study "how a computer works" at the
> >level of individual logic gates?  After all, if you don't know how gates
> >work, things like address bus decoders, ALUs, register files, and the
like
> >are all just magic (which you claim there is no room for).
>
> It's magic if I'm curious but you can't answer
> my questions. It's magic if I've to memorize
> because I'm not *allowed* to understand.
> It's not magic if I can (and naturally do) just
> ignore it because I can accept it. It's not
> magic if I don't have questions because it's
> for me "obvious" enough.
>
> >> Also concrete->abstract shows a clear path; starting
> >> in the middle and looking both up (to higher
> >> abstractions) and down (to the implementation
> >> details) is IMO much more confusing.
> >
> >At some point, you need to draw a line in the sand (so to speak) and say,
> >"I understand everything down to *here* and can do cool stuff with that
> >knowledge.  Below that, I'm willing to take on faith".  I suspect you
would
> >agree that's true, even if we don't agree just where the line should be
> >drawn.  You seem to feel that the level of abstraction exposed by a
> >language like C is the right level.  I'm not convinced you need to go
that
> >far down.  I'm certainly not convinced you need to start there.
>
> I think that if you don't understand memory,
> addresses and allocation and deallocation, or
> (roughly) how an hard disk works and what's
> the difference between hard disks and RAM then
> you're going to be a horrible programmer.
>
> There's no way you will remember what is O(n),
> what O(1) and what is O(log(n)) among containers
> unless you roughly understand how it works.
> If those are magic formulas you'll just forget
> them and you'll end up writing code that is
> thousands times slower than necessary.
>
> If you don't understand *why* "C" needs malloc
> then you'll forget about allocating objects.
>
> Andrea


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


Re: What is different with Python ?

2005-06-12 Thread Andrea Griffini
On Sun, 12 Jun 2005 19:53:29 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Andrea Griffini <[EMAIL PROTECTED]> writes:
>> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen <[EMAIL PROTECTED]>
>> wrote:
>> Also concrete->abstract shows a clear path; starting
>> in the middle and looking both up (to higher
>> abstractions) and down (to the implementation
>> details) is IMO much more confusing.
>
>So you're arguing that a CS major should start by learning electronics
>fundamentals, how gates work, and how to design hardware(*)? Because
>that's what the concrete level *really* is. Start anywhere above that,
>and you wind up needing to look both ways.

Not really. Long ago I've drawn a line that starts at
software. I think you can be a reasonable programmer
even without the knowledge about how to design hardware.
I do not think you can be a reasonable programmer if
you never saw assembler.

>Admittedly, at some level the details simply stop mattering. But where
>that level is depends on what level you're working on. Writing Python,
>I really don't need to understand the behavior of hardware
>gates. Writing horizontal microcode, I'm totally f*cked if I don't
>understand the behavior of hardware gates.

But you better understand how, more or less, your
computer or language works, otherwise your code will
be needless thousand times slower and will require
thousand times more memory than is necessary.
Look a recent thread where someone was asking why
python was so slow (and the code contained stuff
like "if x in range(low, high):" in an inner loop
that was itself pointless).

>In short, you're going to start in the middle.

I've got "bad" news for you. You're always in the
middle :-D. Apparently it looks like this is a
constant in our universe. Even counting (i.e.
1, 2, 3, ...) is not the "start" of math (you
can go at "lower" levels).
Actually I think this is a "nice" property of our
universe, but discussing this would bring the
discussion a bit OT.

>Is it really justified to confuse them all
>by introducing what are really extraneous details early on?

I simply say that you will not able to avoid
introducing them. If they're going to write software
those are not "details" that you'll be able to hide
behind a nice and perfect virtual world (this is much
less true about bus cycles... at least for many
programmers).

But if you need to introduce them, then IMO is
way better doing it *first*, because that is the
way that our brain works.

You cannot build on loosely placed bricks.

>You've stated your opinion. Personally, I agree with Abelson, Sussman
>and Sussman, whose text "The Structure and Interpretation of Computer
>Programs" was the standard text at one of the premiere engineering
>schools in the world, and is widely regarded as a classic in the
>field: they decided to start with the abstract, and deal with concrete
>issues - like assignment(!) later.

Sure. I know that many think that starting from
higher levels is better. However no explanation is
given about *why* this should work better, and I
didn't even see objective studies about how this
approach pays off. This is of course not a field
that I've investigated a lot.

What I know is that every single competent programmer
I know (not many... just *EVERY SINGLE ONE*) started
by placing firmly concrete concepts first, and then
moved on higher abstractions (for example like
structured programming, OOP, functional languages ...).

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


Re: count string replace occurances

2005-06-12 Thread George Sakkis
"Jeff Epler" wrote:

> On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote:
> > if i have
> > mytext.replace(a,b)
> > how to find out many many occurances has been replaced?
>
> The count isn't returned by the replace method.  You'll have to count
> and then replace.
>
> def count_replace(a, b, c):
> count = a.count(b)
> return count, s.replace(b, c)
>
> >>> count_replace("a car and a carriage", "car", "bat")
> (2, 'a bat and a batriage')

I thought naively that scanning a long string twice would be almost
twice as slow compared to when counting was done along with replacing.
Although it can done with a single scan, it is almost 9-10 times
slower, mainly because of the function call overhead; the code is also
longer:

import re

def count_replace_slow(aString, old, new):
count = [0]
def counter(match):
count[0] += 1
return new
replaced = re.sub(old,counter,aString)
return count[0], replaced


A good example of trying to be smart and failing :)

George

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


Re: What is different with Python ?

2005-06-12 Thread Andrea Griffini
On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith <[EMAIL PROTECTED]> wrote:

>How far down do you have to go?  What makes bytes of memory, data busses, 
>and CPUs the right level of abstraction?

They're things that can be IMO genuinely accept
as "obvious". Even "counting" is not the lowest
level in mathematic... there is the mathematic
philosohy direction. From "counting" you can go
"up" in the construction direction (rationals,
reals, functions, continuity and the whole
analysis area) building on the counting concept
or you can go "down" asking yourself what it
does really mean counting, what do you mean
with a "proof", what really is a "set".
However the "counting" is naturally considered
obvious for our minds and you can build the
whole life without the need to look at lower
levels and without getting bitten too badly for
that simplification.

Also lower than memory and data bus there is
of course more stuff (in our universe looks
like there is *always* more stuff no mattere
where you look :-) ), but I would say it's
more about electronic than computer science.

>Why shouldn't first-year CS students study "how a computer works" at the 
>level of individual logic gates?  After all, if you don't know how gates 
>work, things like address bus decoders, ALUs, register files, and the like 
>are all just magic (which you claim there is no room for).

It's magic if I'm curious but you can't answer
my questions. It's magic if I've to memorize
because I'm not *allowed* to understand.
It's not magic if I can (and naturally do) just
ignore it because I can accept it. It's not
magic if I don't have questions because it's
for me "obvious" enough.

>> Also concrete->abstract shows a clear path; starting
>> in the middle and looking both up (to higher
>> abstractions) and down (to the implementation
>> details) is IMO much more confusing.
>
>At some point, you need to draw a line in the sand (so to speak) and say, 
>"I understand everything down to *here* and can do cool stuff with that 
>knowledge.  Below that, I'm willing to take on faith".  I suspect you would 
>agree that's true, even if we don't agree just where the line should be 
>drawn.  You seem to feel that the level of abstraction exposed by a 
>language like C is the right level.  I'm not convinced you need to go that 
>far down.  I'm certainly not convinced you need to start there.

I think that if you don't understand memory,
addresses and allocation and deallocation, or
(roughly) how an hard disk works and what's
the difference between hard disks and RAM then
you're going to be a horrible programmer.

There's no way you will remember what is O(n),
what O(1) and what is O(log(n)) among containers
unless you roughly understand how it works.
If those are magic formulas you'll just forget
them and you'll end up writing code that is
thousands times slower than necessary.

If you don't understand *why* "C" needs malloc
then you'll forget about allocating objects.

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


Re: searching for IDE

2005-06-12 Thread Chris Spencer
jean-marc wrote:
> if you are familiar with eclipse, you could use the PyDev python
> plugin.
> 
> jm

Thanks for that reference. I had been using SPE for my Python editing, 
but it's gone unmaintained as of late, so I've been looking for an 
alternative. Aside from an autocomplete bug (which I've reported) 
Pydev's been working great for me.

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


Re: How to use 8bit character sets?

2005-06-12 Thread =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=
copx wrote:
> For some reason Python (on Windows) doesn't use the system's default 
> character set and that's a serious problem for me.

I very much doubt this statement: Python does "use" the system's default
character set on Windows. What makes you think it doesn't?

> Is it possible to tell Python to use an 8bit charset (latin-1 in my case) 
> for textfile and string processing by default?

That is the default.

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Axel Straschil
Hello!

> You can 'hide' you getsetters using a property attribute[1]:

For me, the property attribute is a beast:

class A(object):
def getP(self): return 'A'
p = property(getP)
class A2(A):
def getP(self): return 'A2'
a = A()
a2 = A2()
print a.getP(), a2.getP()
print a.p, a2.p

So, property is instance-level super() tool ;-)

Lg,
AXEL.
-- 
Gentoo? Debian? RedHat? SuSE? *BSD? Stop the distri-war, make little user!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tree functions daily exercise: Range

2005-06-12 Thread lqf
thank
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use 8bit character sets?

2005-06-12 Thread John Machin
copx wrote:
> For some reason Python (on Windows) doesn't use the system's default 
> character set and that's a serious problem for me.
> I need to process German textfiles (containing umlauts and other > 7bit 
> ASCII characters) and generally work with strings which need to be processed 
> using the local encoding (I need to display the text using a Tk-based GUI 
> for example). The only solution I managed to find was converting between 
> unicode and latin-1 all the time (the textfiles aren't unicode, the output 
> of the program isn't supposed to be unicode either). Everything worked fine 
> until I tried to run the program on a Windows 9x machine.. It seems that 
> Python on Win9x doesn't really support unicode (IIRC Win9x doesn't have real 
> unicode support so that's not suprising).
> Is it possible to tell Python to use an 8bit charset (latin-1 in my case) 
> for textfile and string processing by default?
> 
> copx


1. Your description of your problem is extremely vague. If you were to 
supply a minimal script that "works" [on what platform?? what version of 
Python??], with a description of what you understand by "works", and 
what happens differently when you run that script on a Win9x box [for 
what value(s) of x?? what version of Python??], we might be able to help 
you. N.B. somewhere near the top of the script you should have something 
like:

import sys
print "Python version:", sys.version
print "platform:", sys.platform
print "default encoding:", sys.getdefaultencoding()
try:
 print "Windows version:", sys.getwindowsversion()
except AttributeError:
 print "sys.getwindowsversion not available"

2. You should read this:

http://www.catb.org/~esr/faqs/smart-questions.html

3. You should not rely on a crutch like a default encoding, especially 
one obtained by a kludge like sitecustomize.py. If your app expects to 
receive data in encoding x and send data in encoding y, these facts are 
properties of the application and the data, NOT the box you are running 
on. If you had a requirement to read MacCyrillic from a Classic Mac and 
write KOI8 for consumption on a Windows PC, you should be able to do it 
on a SPARC Solaris box in Timbuktu or Walla Walla, Wa., without having 
to fiddle with site-wide configuration.

4. AFAIK, support for Unicode is provided by Python with no assistance 
from the operating system. The multitudinous deficiencies in Win9x 
should have no bearing on the problem. Have you tried to run your 
program on a Win2K or WinXP box?

HTH,

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


Re: how to startup the default web browser to open a url?

2005-06-12 Thread erinhouston


flyaflya wrote:
> I want to startup the default web browser(ie...) to open a url, "execl"
> can open a process, but when the process exit, the other process will
> exit too, has any why to deal this problem?

You can do this with the win32aip module found in win32all
Home page
http://starship.python.net/crew/mhammond/win32/Downloads.html
files
http://sourceforge.net/project/showfiles.php?group_id=78018
example:
import win32api
a = win32api.ShellExecute(0,None,"www.ishpeck.net",None,None,1)

Hope that is of help

Erin

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


Re: How to use 8bit character sets?

2005-06-12 Thread copx

"Chris Curvey" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Check out sitecustomize.py.
>
> http://diveintopython.org/xml_processing/unicode.html

Thanks but I'm looking for a way to do this on application level (i.e. I
want my app to run in an unmodified interpreter enviroment).

copx



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


Re: Annoying behaviour of the != operator

2005-06-12 Thread pmaupin
If a behavior change is possible at all, I think a more reasonable
behavior would be:

if any rich comparison methods are defined, always use rich comparisons
(and throw an exception if the required rich comparison method is not
available).

This would at least have the benefit of letting users know what code it
had broken when they try to run it :)

Regards,
Pat

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


Re: What is different with Python ?

2005-06-12 Thread George Sakkis
"Mike Meyer" wrote:

> Andrea Griffini <[EMAIL PROTECTED]> writes:
> > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen <[EMAIL PROTECTED]>
> > wrote:
> > Also concrete->abstract shows a clear path; starting
> > in the middle and looking both up (to higher
> > abstractions) and down (to the implementation
> > details) is IMO much more confusing.
>
> So you're arguing that a CS major should start by learning electronics
> fundamentals, how gates work, and how to design hardware(*)? Because
> that's what the concrete level *really* is. Start anywhere above that,
> and you wind up needing to look both ways.

This may sound as a rhetorical question, but in fact as an Informatics
undergrad I had to take courses in electronics, logic design, signals
and systems and other obscure courses as far CS is concerned
(http://www2.di.uoa.gr/en/lessons.php). Although these are certainly
useful if one is interested in hardware, architecture, realtime and
embedded systems, etc., I hardly find them relevant (or even more,
necessary) for most CS/IT careers. Separation of concerns works pretty
well for most practical purposes.

George

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


Re: searching for IDE

2005-06-12 Thread Grumman
alexrait1 wrote:
> I need an IDE for python that has the ability to show the filds of a
> class when I write "."
> Just the way it works in eclipse/JBuilder with java or visual studio
> with c++
> For now I treid eric3 and IDLE they don't do this...
> 

The ActiveState python editor (pythonwin?) does this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BBC R&D White Paper on Kamaelia Published (Essentially a framework using communicating python generators)

2005-06-12 Thread pmaupin

> I'm posting a link to this since I hope it's of interest to people here :)
>
> I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework,
> and it's been published as a BBC R&D White Paper and is available here:
>
>* http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml

I enjoyed the paper.  I don't have time to play with the code right
now, but it sounds like fun.  I do have one question -- in practice,
how difficult have you found it that Python generators don't maintain
separate stacks?

Regards,
Pat

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


RE: inactive Spambayes w/ Outlook

2005-06-12 Thread Tony Meyer
> I had installed spambayes with outlook 2003 a while ago and 
> it worked great. Then I did who know what it stopped working. 

If Peter's link doesn't help, I suggest you try the spambayes mailing list:



=Tony.Meyer

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


Re: case/switch statement?

2005-06-12 Thread Peter Hansen
Chinook wrote:
> On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote:
>>Case statements are actually more suitable in many cases even when 
>>performance is not a goal for reasons of *readability*.
>>
>>When reading an if statement, you have to scan down through effective 
>>each statement attempting to find the case in which you are interested. 
>>  Some cases can be compound.  The nested ifs can get confused with the 
>>surrounding ones (in Python or a language with explicit block 
>>delimiters).  The cases are often not written in any particular order, 
>>or they are ordered *for* performance reasons, but in ways that make it 
>>harder to "scan".
> 
> The problem I do see is your apples and oranges argument.  You are equating 
> at the extreme, "compound" if conditions with "_simple_" case statement 
> conditionals.  Yet you are leaving out of your argument the transition from 
> the former to the latter.  If mapping one to the other is simple then the 
> readability is no harder with if statements.  

I dispute that, and believe you've misunderstood my core point.  It's 
not anything to do with "equivalence" between the two approaches.  It's 
that if you see a set of if/else statements, you have to look at all of 
them to understand completely what's happening.  (I mean the structure 
of the if/else... the conditionals, not the contents of the blocks.) 
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.

So it's not a comparison between two ways of writing the same thing, 
it's about the fact that with a case statement there are many things you 
*cannot* write, so reading one is much easier than reading a similarly 
sized compound if/else.

This is much like saying that a short function is easier to read than a 
long one.  The long one can obviously do much more, so it's an apples 
and oranges comparison in that sense.  But clearly if the short one fits 
all on one screen and the long one does not, the short one is basically 
much easier to grok.

That's all I'm saying.

> In my experience I've also seen where case statements promote overly long and 
> partially repetitive code blocks, which would be better constructed in a 
> top-down fashion.  Admittedly, if statements could be used in a similar way 
> but I've not seen the same level of abuse with such.  

That's true.

> So arguably, if the translation is pretty much one to one then the argument 
> is mute :~)  
   "moot"

Sort of, except my point here would be that a case statement is then the 
better choice in many cases because it communicates to the reader that 
the entire thing *is* simple, while the if/else/if/else does not.

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


Re: case/switch statement?

2005-06-12 Thread Raymond Hettinger
[Joe Stevenson]
> > I skimmed through the docs for Python, and I did not find anything like
> > a case or switch statement.  I assume there is one and that I just
> > missed it.

[deelan]
> topic already beated to death

It's not dead yet.  It has excellent use cases and an open PEP,
http://www.python.org/peps/pep-0275.html .

It needs advocacy, TLC, a clear proposal, an implementer, and a little
luck.


Raymond Hettinger

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


Re: Get drives and partitions list (Linux)

2005-06-12 Thread Peter Hansen
cantabile wrote:
> Hi, I'd like to get drives and partitions (and their size too) with
> python under Linux. So far, I thought of reading /proc/partitions but
> maybe i could use fdsik also ?
> How would I do that in python ?

Somebody else posted a very similar question quite recently.  A Google 
Groups search would probably lead you to the answers pretty quickly. 
(Try "partition proc sfdisk" or something like that.)

My previous answer was to call sfdisk, using os.popen().  Others 
suggested reading /proc/partitions.  I doubt fdisk (if that's what you 
meant) is a good idea.

There is no pure Python solution, so far as I know, probably because 
there may not be any standardized way of finding this information.

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


Re: how to operate the excel by python?

2005-06-12 Thread Tim Roberts
John Machin <[EMAIL PROTECTED]> wrote:

>Rune Strand wrote:
>> The key is Python for Windows :
>> http://starship.python.net/crew/mhammond/win32/
>> 
>> See here for an Excel dispatch example:
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325735
>> 
>> When doing such operations, I generally save all the Excel files to CSV
>> files and do the operations on them using the csv module.
>> 
>
>Problems with that approach:
>
>1. Unfortunately, "save as CSV" is very much a WYSIWYG operation. If the 
>"number formats" are not sensible, loss of information can result.

This is a real problem.  US postal codes are a particular nasty issue.  The
value "01234", for example, will be imported into Excel as "1234".
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-12 Thread Peter Hansen
Andrea Griffini wrote:
> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen <[EMAIL PROTECTED]>
> wrote:
>>I think new CS students have more than enough to learn with their 
>>*first* language without having to discover the trials and tribulations 
>>of memory management (or those other things that Python hides so well).
> 
> I'm not sure that postponing learning what memory
> is, what a pointer is and others "bare metal"
> problems is a good idea. ...
> I think that for a programmer skipping the
> understanding of the implementation is just
> impossible: if you don't understand how a
> computer works you're going to write pretty
> silly programs. 

I'm curious how you learned to program.  What path worked for you, and 
do you think it was a wrong approach, or the right one?

In my case, I started with BASIC.  Good old BASIC, with no memory 
management to worry about, no pointers, no "concrete" details, just FOR 
loops and variables and lots of PRINT statements.

A while (some months) later I stumbled across some assembly language and 
-- typing it into the computer like a monkey, with no idea what I was 
dealing with -- began learning about some of the more concrete aspects 
of computers.

This worked very well in my case, and I strongly doubt I would have 
stayed interested in an approach that started with talk of memory 
addressing, bits and bytes, registers and opcodes and such.

I won't say that I'm certain about any of this, but I have a very strong 
suspicion that the *best* first step in learning programming is a 
program very much like the following, which I'm pretty sure was mine:

10 FOR A=1 TO 10: PRINT"Peter is great!": END

And no, I don't recall enough BASIC syntax to be sure that's even 
correct, but I'm sure you get my point.  In one line I learned 
(implicitly at first) about variables, control structures and iteration, 
  output, and probably a few other things.

More importantly by far, *I made the computer do something*.  This 
should be everyone's first step in a programming course, and it doesn't 
take the slightest understanding of what you call "concrete" things... 
(though I'd call these things very concrete, and memory management 
"esoteric" or something).

If I had been stuck in a course that made me learn about memory 
management before I could write a program, I'm pretty sure I'd be doing 
something fascinating like selling jeans in a Levis store...

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


Re: Get drives and partitions list (Linux)

2005-06-12 Thread Jeff Epler
Using /proc/partitions is probably preferable because any user can read
it, not just people who can be trusted with read access to drives, and
because the format of /proc/partitions is probably simpler and more
stable over time.

That said, what you do is
import commands
fdisk_output = commands.getoutput("fdisk -l %s" % partition)
followed by some specialized code to parse the output of 'fdisk -l'
The following code is not at all tested, but might do the trick.

# python parse_fdisk.py
/dev/hda4 blocks=1060290 bootable=False partition_id_string='Linux swap' 
partition_id=130 start=8451 end=8582
/dev/hda1 blocks=15634048 bootable=True partition_id_string='HPFS/NTFS' 
partition_id=7 start=1 end=1947
/dev/hda3 blocks=9213277 bootable=False partition_id_string='W95 FAT32 (LBA)' 
partition_id=12 start=8583 end=9729
/dev/hda2 blocks=52235347 bootable=False partition_id_string='Linux' 
partition_id=131 start=1948 end=8450

# This source code is placed in the public domain
def parse_fdisk(fdisk_output):
result = {}
for line in fdisk_output.split("\n"):
if not line.startswith("/"): continue
parts = line.split()

inf = {}
if parts[1] == "*":
inf['bootable'] = True
del parts[1]
else:
inf['bootable'] = False

inf['start'] = int(parts[1])
inf['end'] = int(parts[2])
inf['blocks'] = int(parts[3].rstrip("+"))
inf['partition_id'] = int(parts[4], 16)
inf['partition_id_string'] = " ".join(parts[5:])

result[parts[0]] = inf
return result

def main():
import commands
fdisk_output = commands.getoutput("fdisk -l /dev/hda")
for disk, info in parse_fdisk(fdisk_output).items():
print disk, " ".join(["%s=%r" % i for i in info.items()])

if __name__ == '__main__': main()


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

Re: What is different with Python ?

2005-06-12 Thread Peter Hansen
Mike Meyer wrote:
> Andrea Griffini <[EMAIL PROTECTED]> writes:
>>Also concrete->abstract shows a clear path; starting
>>in the middle and looking both up (to higher
>>abstractions) and down (to the implementation
>>details) is IMO much more confusing.
> 
> So you're arguing that a CS major should start by learning electronics
> fundamentals, how gates work, and how to design hardware(*)? 

No, Andrea means you need to learn physics, starting perhaps with basic 
quantum mechanics and perhaps with some chemistry thrown in (since you 
can't really understand semiconductors without understanding how they're 
built, right?).  Oh, and manufacturing.  And a fundamental understanding 
of scanning electron microscopes (for inspection) would be helpful as 
well.  I think probably a Ph.D. level training in mathematics might be a 
good start also, since after all this is the foundation of much of 
computing.  A while later comes the electronics, and then memory management.

Things like while loops and if statements, and *how to actually write a 
program* are, of course, only the eventual outcome of all that good 
grounding in "the basics" that you need first.



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


Re: Learning more about "The Python Way"

2005-06-12 Thread Robert Kern
Kalle Anke wrote:

> So, I'm looking for advice/information on:
> 
> + How to write "proper" python code instead of 
>   Java/Perl/C/C++/Pascal/Modula-2/etc inspired code

Read other people's Python code especially that from the standard 
library. Extend the functionality of those projects to fit your needs.

As someone else mentioned, get a copy of the 2nd edition of the Python 
Cookbook. It's full of gold.

> + The more advanced parts/uses of Python

It depends on your viewpoint what is advanced. Metaclasses are probably 
the most notorious examples of "advanced Python." You can also find 
plenty of "advanced Python" in the guts of the numerous framework-type 
packages (Zope, Twisted, PEAK and the like).

> + Discussions about the ideas behind different Python
>   constructs

The best place to search is probably Google Groups for c.l.py and GMane 
for gmane.comp.python.devel for the python-dev list. If you have a more 
specific question in mind, you can also ask here.

> + What's going to happen with v3

Python 3.0 (also sometimes referred to as Python 3000) is when Guido is 
going to allow backwards-incompatible changes. Some duplicated 
functionality, warts, and redundancies will be cleaned up. Old-style 
classes will disappear, etc. There are no concrete plans at this time; 
Python 3.0 is still a long ways off. In short, talk of Python 3.0 
shouldn't worry you until Guido writes a post entitled "Some rich fool 
is paying me to work fulltime on Python 3.0 for a year. What's on *your* 
wishlist?"

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: count string replace occurances

2005-06-12 Thread Jeff Epler
On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote:
> if i have
> mytext.replace(a,b)
> how to find out many many occurances has been replaced?

The count isn't returned by the replace method.  You'll have to count
and then replace.

def count_replace(a, b, c):
count = a.count(b)
return count, s.replace(b, c)

>>> count_replace("a car and a carriage", "car", "bat")
(2, 'a bat and a batriage')



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

Re: Following the white rabbit (was "The Python Way")

2005-06-12 Thread Christopher Subich
Claudio Grondi wrote:

 >> Just follow the white rabbit.
 >
 >
 > This triggers in me the temptation to start
 > a thread asking:
 >
 > What (in your opinion) can a good programmer
 > learn from watching all of the Matrix movies?
 > Which part, one, two or three deals most with
 > the philosophy of programming?


IMO, in my opinion almost certainly the first.

The first can be summed up in the words, "free your mind." From my very 
limited experience, that captures 90% of the Zen right there.

The second... uh... "dancing rave orgies are fun?"  Doesn't quite work.

The third is entirely inappropriate, since it's rather hard to program 
in Python after one has gouged one's eyes out with a rusty spoon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending mail from 'current user' in Python

2005-06-12 Thread Mike Meyer
Marcus Alanen <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>>>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.

On reflection, you're right. It was the way I described when I started
working with Unix, and I still configure all my Unix systems that
way. But recently there's been move to have no servers configured by
default. I've been bit by this, now having to enable TCP on Postgres
by every time I upgrade the server. So most modern Unix systems
probably come out of the box without a local SMTP listener.

> Rather, sendmail is configured to transport the message to
> company/university mailserver(s).

Sendmail? Don't you mean qmail/postfix/exim?

> If that happens to fail,
> the mail is put on the queue at localhost, and transported later
> (e.g. via a cronjob) to the server. At no point is there a server on
> localhost involved. Of course, not everybody's computer is on such a
> network and a sendmail server may indeed be running on localhost, but
> that's not a very informed guess. Let the sendmail program take care
> of those details.

Well, maybe you do mean sendmail. The other MTAs typically aren't that
configurable. qmail, for instance, always queues messages to the local
disk if they are bound for another host.

In lieue of the current discussion, this stuff doesn't matter. All of
these MTAs come with a "sendmail" program designed specifically so
that programs that invoke sendmail to arrange delivery of a message
will continue work if you replace the system sendmail with their
version. On FreeBSD, this has been carried a step further: the system
sendmail is a wrapper that reads /etc/mail/mailer.conf to figure out
what sendmail binary to invoke, so that users don't have to deal with
replacing the system sendmail, or worry about accidently overwriting
the replaced system sendmail if they upgrade their system.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning more about "The Python Way"

2005-06-12 Thread George Sakkis
"Kalle Anke" wrote:

> [snipped]
>
> So, I'm looking for advice/information on:
>
> + How to write "proper" python code instead of
>   Java/Perl/C/C++/Pascal/Modula-2/etc inspired code
>
> + The more advanced parts/uses of Python
>
> + Discussions about the ideas behind different Python
>   constructs

For all these, do yourself a favor and buy/borrow/steal a copy of the
python cookbook, 2nd edition. You'll get over 300 recipes, ranging from
simple one-liners to full working programs, packed with pythonic idioms
and extensive discussion for every single recipe.

> + What's going to happen with v3
>

Google is your friend; search for "python 3000" (interestingly,
searching for "python 3" returns something completely different :-)).

George

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


Re: changing how instances are "created"

2005-06-12 Thread John Roth

"newseater" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> > class Creator
>> > def createInstance(cls, *args, **kwargs):
>> > anewinstance = cls.__new__(cls, *args, **kwargs)
>> > anewinstance.__init__(*args, **kwargs)
>> >
>> > return anewinstance
>> > createInstance = staticmethod(createInstance)
>> >
>> >
>> > can anyone help??
>>
>> __new__ is the proper way to do this, but making it work
>> is a bit tricky. If you could post the code you tried to
>> get to work for __new__(), we could critique it.
>>
>> The current documentation is in 3.3.1 of the Python
>> Reference Manual (Python 2.4 version). In earlier
>> versions, there were a couple of other documents
>> that did a better (IMO) job of explaining things.
>>
>> The trick is that __new__ must return an instance.
>> It can be a newly created instance (and the doc shows
>> how to do this) or an existing instance of any new style
>> class.
>
> from the documentation it was very hard to guess what the "..." was
> supposed to be. also i wasn't able to find out how to control if
> __init__() would be called on an instance (if i reused that instance..
> and that instance could be of a completely different type).

I believe that __init__() is not called if the instance is not of
the same type as the class with the __new__() method.

There was a thread on that not too long ago, and I believe
that was the resolution: the docs were wrong, __init__ is
only called if the returned instance is for the class with the
__new__ method. The 2.4 docs seem to say it properly.

> eg. i didn't get much out of
> http://docs.python.org/ref/customization.html
>
> from http://gnosis.cx/publish/programming/metaclass_1.html

This has nothing to do with metaclasses. Wandering into
that will fry your brain.

...

>
> but that way of creating objects is just plain silly!

Yep. If you don't need a metaclass, don't use one. Metaclasses
are a special purpose construct. If you need it, you'll know that
you need it. Othewise you don't, and you certainly don't here.

> I tried looking at the __new__ buildin but this seems to be addressing
> old-style objects (which i'm not interested in using).

__new__ is only invoked for new style classes; it is not invoked
for old style classes.f

The following may be helpful: it's a relatively extended article
on new style classes that was left out of the 2.4 references
because the content had supposedly been absorbed into the
mainline documentation.

http://www.python.org/2.2.3/descrintro.html


>> By the way - when you post code, please use spaces
>> for indentation. There are a number of popular mail
>> clients that don't play fair with tabs, and people using
>> these clients will frequently ignore code that isn't
>> properly indented.
>
> sorry. maybe people should complain to those lousy newsreader authors
> instead of everyone having to comply to the lowest standards? I guess
> the readers are actually un*x readers although your comment typically
> is found in the w*ndows world where everyone is forced into using word
> :-)

This dead horse has been beaten into a pulp many times. People
with newsreaders and mail clients that don't play fair with tabs are
not going to change; snide remarks will only reflect on the person
making the remark.

The major problem is IE, although I've seen other newsreaders
and mail clients do the same thing. Also, I don't even have Word
on my Windows system; I use Open Office. Being "forced" to
use Word is a choice.

John Roth
>
>
>> John Roth
> 

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


Re: What is different with Python ?

2005-06-12 Thread Mike Meyer
Andrea Griffini <[EMAIL PROTECTED]> writes:
> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen <[EMAIL PROTECTED]>
> wrote:
> Also concrete->abstract shows a clear path; starting
> in the middle and looking both up (to higher
> abstractions) and down (to the implementation
> details) is IMO much more confusing.

So you're arguing that a CS major should start by learning electronics
fundamentals, how gates work, and how to design hardware(*)? Because
that's what the concrete level *really* is. Start anywhere above that,
and you wind up needing to look both ways.

Admittedly, at some level the details simply stop mattering. But where
that level is depends on what level you're working on. Writing Python,
I really don't need to understand the behavior of hardware
gates. Writing horizontal microcode, I'm totally f*cked if I don't
understand the behavior of hardware gates.

In short, you're going to start in the middle. You can avoid looking
down if you avoid certain classes of problems - but not everyone will
be able to do that. Since you can only protect some of the students
from this extra confusion, is it really justified to confuse them all
by introducing what are really extraneous details early on?

You've stated your opinion. Personally, I agree with Abelson, Sussman
and Sussman, whose text "The Structure and Interpretation of Computer
Programs" was the standard text at one of the premiere engineering
schools in the world, and is widely regarded as a classic in the
field: they decided to start with the abstract, and deal with concrete
issues - like assignment(!) later.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Chinook
On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote
(in article <[EMAIL PROTECTED]>):

> Steven D'Aprano wrote:
>> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:
>>> If the case values are constants known to the compiler, it can generate 
>>> O(1)
>>> code to take the correct branch.
>>> It is precisely this behavior that is desired in many situations.  
>> 
>> Agreed. I certainly don't object to sensible optimizations! But the number
>> of if...elif statements which can be optimised are a vanishingly small
>> subset of the number of possible if...elif statements.
>> 
>> And you can bet your last dollar that many people will use case statements
>> even when doing so gives no advantage, in a mistaken opinion that it will
>> be somehow magically faster.
> 
> Case statements are actually more suitable in many cases even when 
> performance is not a goal for reasons of *readability*.
> 
> When reading an if statement, you have to scan down through effective 
> each statement attempting to find the case in which you are interested. 
>   Some cases can be compound.  The nested ifs can get confused with the 
> surrounding ones (in Python or a language with explicit block 
> delimiters).  The cases are often not written in any particular order, 
> or they are ordered *for* performance reasons, but in ways that make it 
> harder to "scan".
> 
> A case statement, on the other hand, can be a message from the 
> programmer, saying in effect "here's code that represents a series of 
> _simple_ conditionals, ordered (usually) in a sensible way (e.g. 
> ascending numerical order), so just jump to the case you want and carry 
> on maintaining this nice code."
> 
> 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.
> 
> -Peter
> 

I'm new to Python, but I'm retired from a software engineering career that 
began in the early 60s.  I'm not against case statements in the simplest 
syntactical context, but over the years I've seen so many abuses of such 
(i.e. difficult to follow code) that neither am I against their exclusion 
from Python.  The thought being (in my mind) that such might force the 
programmer to rethink their approach to something more intuitively structured 
(whether module/function wise or OO wise or some combination), though I admit 
it is an idealistic view.  

The problem I do see is your apples and oranges argument.  You are equating 
at the extreme, "compound" if conditions with "_simple_" case statement 
conditionals.  Yet you are leaving out of your argument the transition from 
the former to the latter.  If mapping one to the other is simple then the 
readability is no harder with if statements.  An example might be in dealing 
with variably formated records where each record contains a record type flag. 
 On the other hand if you were to map compound conditions to "_simple_" case 
statement conditionals, you need an intermediate translation that must be 
studied to understand the "_simple_" conditionals anyway.  Such translations 
also promote an overabundance of status/flag variables to understand and 
follow which does not increase the readability of code.  

In my experience I've also seen where case statements promote overly long and 
partially repetitive code blocks, which would be better constructed in a 
top-down fashion.  Admittedly, if statements could be used in a similar way 
but I've not seen the same level of abuse with such.  

So arguably, if the translation is pretty much one to one then the argument 
is mute :~)  If on the other hand the translation is many to one, then one's 
skill in developing well structured readable code is really the issue, and 
again case statements are a mute point.  

Lee C


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


Re: What is different with Python ?

2005-06-12 Thread Roy Smith
Andrea Griffini <[EMAIL PROTECTED]> wrote:
> I think that for a programmer skipping the
> understanding of the implementation is just
> impossible: if you don't understand how a
> computer works you're going to write pretty
> silly programs. Note that I'm not saying that
> one should understand every possible implementation
> down to the bit (that's of course nonsense), but
> there should be no room for "magic" in a computer
> for a professional programmer.

How far down do you have to go?  What makes bytes of memory, data busses, 
and CPUs the right level of abstraction?

Why shouldn't first-year CS students study "how a computer works" at the 
level of individual logic gates?  After all, if you don't know how gates 
work, things like address bus decoders, ALUs, register files, and the like 
are all just magic (which you claim there is no room for).

Digging down a little deeper, a NAND gate is magic if you don't know how a 
transistor works or can't do basic circuit analysis.  And transistors are 
magic until you dig down to the truly magical stuff that's going on with 
charge carriers and electric fields inside a semiconductor junction.  
That's about where my brain starts to hurt, but it's also where the quantum 
mechanics are just getting warmed up.
 
> Also concrete->abstract shows a clear path; starting
> in the middle and looking both up (to higher
> abstractions) and down (to the implementation
> details) is IMO much more confusing.

At some point, you need to draw a line in the sand (so to speak) and say, 
"I understand everything down to *here* and can do cool stuff with that 
knowledge.  Below that, I'm willing to take on faith".  I suspect you would 
agree that's true, even if we don't agree just where the line should be 
drawn.  You seem to feel that the level of abstraction exposed by a 
language like C is the right level.  I'm not convinced you need to go that 
far down.  I'm certainly not convinced you need to start there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to receive events (eg. user mouse clicks) from IE

2005-06-12 Thread Roger Upole
Each frame acts as a separate document.
You should be able catch document events
from a frame using something like
win32com.client.DispatchWithEvents(ie.Document.frames().document, 
)

  Roger


<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Resurrecting an old thread..
> It seems that this solution does not return events on objects within
> frames in webpages eg . if you go to www.andersondirect.com - the page
> is composed of three frames called as topFrame main and address. Now
> when I click on say 'Select a Vehicle' which is within main - I do not
> get any Onclick event. I also do not get an OnMousemove event if I move
> the mouse. However, I do get on Mousemove event on a tag called as
> frameset (which is part of the top page).
> How does one get events from the frames then?
> As always thanks a lot.
>
> Roger Upole wrote:
>> <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> ...
>> > The problem is that msdn documentation says that in order to identify
>> > the element that was clicked - one has to query on IHTMLWindow2::event
>> > property on iHTMLWindow2 interface to get IEventOBj interface and then
>> > from there - use query interfce to get to the id of the element.
>> >
>> > How do I do this in python? ie. I have this code
>> > class Doc_Events(doc_mod.HTMLDocumentEvents):
>> >def Ononclick(self):
>> >print 'onClick fired '
>> > and I see onClick being trapped.
>> > Now I need to go and get a reference to the iHTMLWindow2 interface. For
>> > this I need to get a reference to doc_mod (as far as I can see). How do
>> > I get that in the OnonClick method above.
>>
>> To get the IHTMLWindow2, you can just use self.parentWindow
>> inside the event hander, and then get the event from it.  And then
>> the event's srcElement should be what you need.
>>
>> class Doc_Events(doc_mod.HTMLDocumentEvents):
>> def Ononclick(self):
>> print 'onclick'
>> ev=self.parentWindow.event
>> src=ev.srcElement
>> print 'tagName:',src.tagName,'name:',src.getAttribute('name')
>>
>> For clicking on google's input field, this yields
>> tagName: INPUT name: q
>>
>> >
>> > b) You had mentioned PumpWaitingMessages in the previous posting. I
>> > first encountered this on newsgroup postings. None of the standard
>> > books (python on win32 / python developer) seem to explain this in
>> > detail although this seems to be commonly used. Though I understand
>> > this now - my problem is that there seems to be a lack of cohesive
>> > explanation on how python ties up with COM (despite a good chapter 12
>>
>> PumpWaitingMessages is just a way to ensure that normal message processing
>> (window messages, events, dde, etc) happens while python code is running.
>> Normally you don't need it, but every once in a while you hit a situation
>> where
>> blocking occurs.
>>
>> For how exactly python interacts with COM, the source is your best bet.
>>
>> Roger
>>
>>
>>
>>
>>
>> == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet 
>> News==
>> http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
>> Newsgroups
>> ---= East/West-Coast Server Farms - Total Privacy via Encryption =---
> 




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


OSCON: Volunteer for Python?

2005-06-12 Thread Aahz
I'm trying to organize a group of people to run a Python booth at OSCON
so that people will see an alternative to Perl.  ;-)  I'd like at least
ten or twelve volunteers so that nobody has to pull a long shift.  If
you're interested, please subscribe to the OSCON mailing list:

http://mail.python.org/mailman/listinfo/oscon
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Get drives and partitions list (Linux)

2005-06-12 Thread cantabile
Hi, I'd like to get drives and partitions (and their size too) with
python under Linux. So far, I thought of reading /proc/partitions but
maybe i could use fdsik also ?
How would I do that in python ?

Thanks for your help (newbie here :) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use 8bit character sets?

2005-06-12 Thread Chris Curvey
Check out sitecustomize.py.

http://diveintopython.org/xml_processing/unicode.html

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


Re: changing how instances are "created"

2005-06-12 Thread newseater
>
> A staticmethod does not take a cls argument. It is essentially just a
> function that is attached to a class.

yes i know of that difference... but one cannot easily override a class
method in a supclass.. as calling super then make the cls variable
point to the super class class rather than the subclass! very
confusing! So i decided to skip that one...

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


Re: changing how instances are "created"

2005-06-12 Thread newseater
> > class Creator
> > def createInstance(cls, *args, **kwargs):
> > anewinstance = cls.__new__(cls, *args, **kwargs)
> > anewinstance.__init__(*args, **kwargs)
> >
> > return anewinstance
> > createInstance = staticmethod(createInstance)
> >
> >
> > can anyone help??
>
> __new__ is the proper way to do this, but making it work
> is a bit tricky. If you could post the code you tried to
> get to work for __new__(), we could critique it.
>
> The current documentation is in 3.3.1 of the Python
> Reference Manual (Python 2.4 version). In earlier
> versions, there were a couple of other documents
> that did a better (IMO) job of explaining things.
>
> The trick is that __new__ must return an instance.
> It can be a newly created instance (and the doc shows
> how to do this) or an existing instance of any new style
> class.

from the documentation it was very hard to guess what the "..." was
supposed to be. also i wasn't able to find out how to control if
__init__() would be called on an instance (if i reused that instance..
and that instance could be of a completely different type).

eg. i didn't get much out of
http://docs.python.org/ref/customization.html

from http://gnosis.cx/publish/programming/metaclass_1.html

i get

>>> class ChattyType(type):
... def __new__(cls, name, bases, dct):
... print "Allocating memory for class", name
... return type.__new__(cls, name, bases, dct)
... def __init__(cls, name, bases, dct):
... print "Init'ing (configuring) class", name
... super(ChattyType, cls).__init__(name, bases, dct)
...
>>> X = ChattyType('X',(),{'foo':lambda self:'foo'})
Allocating memory for class X
Init'ing (configuring) class X
>>> X, X().foo()
(, 'foo')


but that way of creating objects is just plain silly!
(the X = Chattype('X'.)
and where are the arguments to __init__() passed?? maybe i want to
change those as well this is partly why i wanted to use an external
class for the creation.

I tried looking at the __new__ buildin but this seems to be addressing
old-style objects (which i'm not interested in using)



>
> By the way - when you post code, please use spaces
> for indentation. There are a number of popular mail
> clients that don't play fair with tabs, and people using
> these clients will frequently ignore code that isn't
> properly indented.

sorry. maybe people should complain to those lousy newsreader authors
instead of everyone having to comply to the lowest standards? I guess
the readers are actually un*x readers although your comment typically
is found in the w*ndows world where everyone is forced into using word
:-)


> John Roth

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


count string replace occurances

2005-06-12 Thread Xah Lee
if i have
mytext.replace(a,b)
how to find out many many occurances has been replaced?

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

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

Re: changing how instances are "created"

2005-06-12 Thread Robert Kern
newseater wrote:
> 
> Robert Kern wrote:
> 
>>newseater wrote:
>>
>>>Hello. I need to be able to control how objects are created. Sometimes
>>>when creating an object, i want to reuse another object instead. I've
>>>searched for factory method implementations and singleton
>>>implementations. They were too much of a hack!
>>>
>>>My first attempt of doing this was to play around with the __new__()
>>>method. But i didn't quite succed. Then i came up with making a static
>>>method which can create my instances or re-use other instances.
>>>However, the below code I cannot get to work :(
>>>
>>>class Creator
>>> def createInstance(cls, *args, **kwargs):
>>> anewinstance = cls.__new__(cls, *args, **kwargs)
>>> anewinstance.__init__(*args, **kwargs)
>>>
>>> return anewinstance
>>> createInstance = staticmethod(createInstance)
>>
>>You want a classmethod, not a staticmethod.
> 
> why do i want that? how should the code look like? currently the
> objects fail to get initialized etc...

A staticmethod does not take a cls argument. It is essentially just a 
function that is attached to a class.

class Something(object):
 def foo(x, y, z):
 print x, y, z
 foo = staticmethod(foo)

A classmethod does that a cls argument.

class Creator(object):
 def createInstance(cls, *args, **kwds):
 pass
 createInstance = classmethod(createInstance)

As for the desired content of the classmethod, I don't care to 
speculate. I usually just use the Borg pattern or a factory or any one 
of the Singleton implementations floating around. They are no more hacky 
than this, but they have the added benefit of working.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: changing how instances are "created"

2005-06-12 Thread John Roth
"newseater" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello. I need to be able to control how objects are created. Sometimes
> when creating an object, i want to reuse another object instead. I've
> searched for factory method implementations and singleton
> implementations. They were too much of a hack!
>
> My first attempt of doing this was to play around with the __new__()
> method. But i didn't quite succed. Then i came up with making a static
> method which can create my instances or re-use other instances.
> However, the below code I cannot get to work :(
>
> class Creator
> def createInstance(cls, *args, **kwargs):
> anewinstance = cls.__new__(cls, *args, **kwargs)
> anewinstance.__init__(*args, **kwargs)
>
> return anewinstance
> createInstance = staticmethod(createInstance)
>
>
> can anyone help??

__new__ is the proper way to do this, but making it work
is a bit tricky. If you could post the code you tried to
get to work for __new__(), we could critique it.

The current documentation is in 3.3.1 of the Python
Reference Manual (Python 2.4 version). In earlier
versions, there were a couple of other documents
that did a better (IMO) job of explaining things.

The trick is that __new__ must return an instance.
It can be a newly created instance (and the doc shows
how to do this) or an existing instance of any new style
class.

By the way - when you post code, please use spaces
for indentation. There are a number of popular mail
clients that don't play fair with tabs, and people using
these clients will frequently ignore code that isn't
properly indented.

John Roth

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


Re: changing how instances are "created"

2005-06-12 Thread newseater


Robert Kern wrote:
> newseater wrote:
> > Hello. I need to be able to control how objects are created. Sometimes
> > when creating an object, i want to reuse another object instead. I've
> > searched for factory method implementations and singleton
> > implementations. They were too much of a hack!
> >
> > My first attempt of doing this was to play around with the __new__()
> > method. But i didn't quite succed. Then i came up with making a static
> > method which can create my instances or re-use other instances.
> > However, the below code I cannot get to work :(
> >
> > class Creator
> > def createInstance(cls, *args, **kwargs):
> > anewinstance = cls.__new__(cls, *args, **kwargs)
> > anewinstance.__init__(*args, **kwargs)
> >
> > return anewinstance
> > createInstance = staticmethod(createInstance)
>
> You want a classmethod, not a staticmethod.

why do i want that? how should the code look like? currently the
objects fail to get initialized etc...

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


RE: Controlling a generator the pythonic way

2005-06-12 Thread Delaney, Timothy C (Timothy)
Thomas Lotze wrote:

> call. The picture might fit better (IMO) if it didn't look so much
> like working around the fact that the next() call can't take
> parameters for some technical reason. 

You might want to take a look at PEP 342
. Doesn't help you now, but it
will in the future.

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Chris Spencer
Peter Dembinski wrote:
> Chris Spencer <[EMAIL PROTECTED]> writes:
> 
> 
>>Peter Dembinski wrote:
>>
>>Of course, in that Python is dynamically typed as opposed to the
>>static typing of Java or C++. Please excuse my previous mis-wording :)
> 
> 
> Mis-wording?

I previously said Python was "untyped", when it's more accurate to say 
"dynamically typed".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing how instances are "created"

2005-06-12 Thread Robert Kern
newseater wrote:
> Hello. I need to be able to control how objects are created. Sometimes
> when creating an object, i want to reuse another object instead. I've
> searched for factory method implementations and singleton
> implementations. They were too much of a hack!
> 
> My first attempt of doing this was to play around with the __new__()
> method. But i didn't quite succed. Then i came up with making a static
> method which can create my instances or re-use other instances.
> However, the below code I cannot get to work :(
> 
> class Creator
>   def createInstance(cls, *args, **kwargs):
>   anewinstance = cls.__new__(cls, *args, **kwargs)
>   anewinstance.__init__(*args, **kwargs)
> 
>   return anewinstance
>   createInstance = staticmethod(createInstance)

You want a classmethod, not a staticmethod.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


changing how instances are "created"

2005-06-12 Thread newseater
Hello. I need to be able to control how objects are created. Sometimes
when creating an object, i want to reuse another object instead. I've
searched for factory method implementations and singleton
implementations. They were too much of a hack!

My first attempt of doing this was to play around with the __new__()
method. But i didn't quite succed. Then i came up with making a static
method which can create my instances or re-use other instances.
However, the below code I cannot get to work :(

class Creator
def createInstance(cls, *args, **kwargs):
anewinstance = cls.__new__(cls, *args, **kwargs)
anewinstance.__init__(*args, **kwargs)

return anewinstance
createInstance = staticmethod(createInstance)


can anyone help??

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


Re: What is different with Python ?

2005-06-12 Thread Andrea Griffini
On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen <[EMAIL PROTECTED]>
wrote:

>I think new CS students have more than enough to learn with their 
>*first* language without having to discover the trials and tribulations 
>of memory management (or those other things that Python hides so well).

I'm not sure that postponing learning what memory
is, what a pointer is and others "bare metal"
problems is a good idea. Those concept are not
"more complex" at all, they're just more *concrete*
than the abstract concept of "variable".
Human mind work best moving from the concrete to
the abstract, we first learn counting, and only
later we learn rings (or even set theory).
Unless you think a programmer may live happy
without understanding concrete issues then IMO
the best is to learn concrete facts first, and
only later abstractions.
I think that for a programmer skipping the
understanding of the implementation is just
impossible: if you don't understand how a
computer works you're going to write pretty
silly programs. Note that I'm not saying that
one should understand every possible implementation
down to the bit (that's of course nonsense), but
there should be no room for "magic" in a computer
for a professional programmer.

Also concrete->abstract shows a clear path; starting
in the middle and looking both up (to higher
abstractions) and down (to the implementation
details) is IMO much more confusing.

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


Re: tree functions daily exercise: Table

2005-06-12 Thread Xah Lee
Here's the next tree functions exercise in Python, Perl, Java. Other
language solutions welcome.
http://xahlee.org/tree/tree.html
-

 Table('exprString', [iMax]) generates a list of iMax copies of value
of
eval('exprString'), and returns the refence to the list. i.e.
[eval('exprString'),eval('exprString'),...]

Table('exprString', ['i', iMax]) generates a list of the values by
evaluating 'exprString' when 'i' in the string runs from 1 to iMax.

Table('exprString', ['i', iMin, iMax]) starts with 'i' = iMin.

Table('exprString', ['i', iMin, iMax, iStep]) uses steps iStep. If
iStep
is negative, then the role of iMin and iMax are reversed. Inputs
such as
[1, -3 , 1] returns bad result.

Table('exprString', ['i', iMin, iMax, iStep], ['j', jMin, jMax,
iStep],
... ) gives a array by iterating 'i', 'j' in 'exprString'. For
example,
Table('f(i,j)', ['i',1,3], ['j',5,6]) returns [[f(1, 5), f(1, 6)],
[f(2,
5), f(2, 6)], [f(3, 5), f(3, 6)]].

In general, Table has the form Table('expressionString', iterator1,
iterator2, ...) where 'expressionString' is a string that will be
evaluated by eval. iterator have one of the following forms [iMax],
['dummyVarString',iMax], ['dummyVarString',iMin, iMax], or
['dummyVarString',iMin, iMax, iStep].

If Table fails, 0 is returned. Table can fail, for example, when
the
argument are not appropriate references or the iterator range is
bad
such as ['i',5,1].

Example:

 Table('q(s)' ,[3]); # returns ['s','s','s']

 Table( 'i**2' , ['i', 4]); # returns [1, 4, 9, 16]

 Table('[i,j,k]',['i',2],['j',100,200,100],['k',5,6])
 # returns 1,100,5],[1,100,6]],[[1,200,5],[1,200,6]]],
 #  [[[2,100,5],[2,100,6]],[[2,200,5],[2,200,6


Wolfram Research's Table function documentation is at:
http://documents.wolfram.com/mathematica/functions/Table
(this post is not affliated with Wolfram Research Incorporated and has
not been approved by Wolfram Research Incorporated.)

The first argument of Table function in Mathematica (mma) is a
expression. Most other languages cannot have such symbolic expressions.
In Perl, a string is choosen instead as the experssion, and it is being
evalutade later as code. This may not be a practical choice but anyway
it's just a exercise. Each other language should choose appropriate
design for this emulation...

Perl, Python, Java solutions will be posted by me in the coming days.

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

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

Re: Scaling down (was Re: Dealing with marketing types...)

2005-06-12 Thread Aahz
In article <[EMAIL PROTECTED]>,
Paul Rubin   wrote:
>[EMAIL PROTECTED] (Aahz) writes:
>>
>> So what?  I think you're missing the real point of the article: using
>> LAMP scales *DOWN* in a way that enterprise systems don't.  Getting your
>> first prototype up and running is far more important than sheer
>> scalability,
>
>There comes a day when your first prototype can no longer handle the
>traffic.  The question then is how do you deal with that.

Then you scale with hardware or do profiling and rewrite chunks,
whichever costs less FOR THE BUSINESS.

>> and LAMP does have many mechanisms to obtain scalability when it's
>> needed.
>
>LAMP seems to have no solution other than scaling (i.e. blowing more
>money on hardware and colo space).  One really gets the impression
>that a more thoughtful design could handle the traffic without needing
>to scale the hardware.

Is there some reason you keep repeating yourself without actually paying
attention to other people?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Following the white rabbit (was "The Python Way")

2005-06-12 Thread Claudio Grondi
> Just follow the white rabbit.
This triggers in me the temptation to start
a thread asking:

What (in your opinion) can a good programmer
learn from watching all of the Matrix movies?
Which part, one, two or three deals most with
the philosophy of programming?

Claudio

"Jarek Zgoda" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Kalle Anke napisa³(a):
>
> > So, I'm looking for advice/information on:
> >
> > + How to write "proper" python code instead of
> >   Java/Perl/C/C++/Pascal/Modula-2/etc inspired code
>
> Just follow the white rabbit.
>
> Rewrite your code in Python, then optimize.
>
> -- 
> Jarek Zgoda
> http://jpa.berlios.de/ | http://www.zgodowie.org/


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

Re: How to test if an object IS another object?

2005-06-12 Thread Roose
This isn't a good example to test with, since 3 is an immutable object, as 
is 300 and all ints.

It's more meaningful if the objects are mutable.  Why do you want to test 
identity in the first place?

Roose


<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Sorry about removing my message, I posted with the wrong google
> account, I don't really want my email where those irritating spam bots
> can find it.
>
>>The most obvious way (as usual ?):
>>
>>if obj1 is obj2:
>>  // your code here
>
> I immediately thought of is, and tested it in the console, but it
> didn't work quite like I expected:
>
>>foo = 3
>>bar = 3
>>zoo = foo
>>foo is zoo
> True
>>foo is bar
> True
>>zoo is bar
> True
>
> clearly foo and bar have the same value but they are different objects
> aren't they? Yet applying the is operator yields True.
>
> Thanks,
> -Dan
> 


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


tree functions daily exercise: Range

2005-06-12 Thread Xah Lee
Here's the belated Java solution.

import java.util.List;
import java.util.ArrayList;
import java.lang.Math;

class math {
public static List range(double n) {
return range(1,n,1);
}

public static List range(double n, double m) {
return range(n,m,1);
}

public static List range(double iMin, double iMax, double iStep) {
List ll = new ArrayList();
if (iMin <= iMax && iStep > 0) {
for (int i=0; i <= Math.floor((iMax-iMin)/iStep); i++) {
ll.add(new Double(iMin+i*iStep));
}
return ll;
}
if (iMin >= iMax && iStep < 0) {
for (int i=0; i <= Math.floor((iMin-iMax)/-iStep); i++) {
ll.add(new Double(iMin+i*iStep));
}
return ll;
}
// need to raise exception here
return ll;
}
}

class Range {
public static void main(String[] arg) {
System.out.println(math.range(5));
System.out.println(math.range(5,10));
System.out.println(math.range(5,7, 0.3));
System.out.println(math.range(5,-4, -2));
}
}

Perl & Python versions archived here:
http://xahlee.org/tree/tree.html

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


Dear functional programers,

i run services called a-python-a-day and a-java-a-day, where each day i

 give a tip or snippet of code in these languages, also as a way for me

 to learn these languages.

I've been running this perl-python a-day mailing list for several
 months, and have accumulated a sizable tutorial here:
http://xahlee.org/perl-python/python.html

In the coming days, i'll be starting to translate a complete set of
 tree processing functions. These functions, always takes a tree as
 input (arbitrary nested list) and always returns a list of a definite
 structure. Together, they form a particular functional programing
 paradigm. See this page for the complete documentation as it exists
 now:
http://xahlee.org/PerlMathemat ica_dir/Matica.html

As usuall, each day we will be spending about 20 minutes enjoying these

 little exercises. If past experience is a good indication, then i
 presume that in a month or two we will have built a complete set of
 functions that manipulates tress, in languages Python and Java and
 Perl. (the Perl set is already written)

I'm always interested in LISP and Haskell languages, but never
 seriously learned them. I'm hoping that you functional programers in
 these languages or learners, join me in these 15 minutes daily
 exercises as a fun routine to learn languages or functional
programing.

I'm in particular very interested in the daily discussions of these
 topics by functional programers, as well seeing such set of complete
 code in scsh and Haskell. (Common Lisp or other functional languages
 are always welcome of course)

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

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

Re: python bytecode grammar

2005-06-12 Thread Peter Dembinski
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> "Peter Dembinski" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> "Terry Reedy" <[EMAIL PROTECTED]> writes:
>>> I believe the top-level production is something like
>>> BYTECODE := (OPCODE ARGS)*
>>
>> ROTFL :)
>
> Glad to make your day ;-)

You are welcome.

"Asking stupid questions is the best way to get quick answers" :>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dealing with marketing types...

2005-06-12 Thread Andrew Dalke
Paul Rubin wrote:
> Andrew Dalke <[EMAIL PROTECTED]> writes:
  ...
>> I found more details at
>> http://jeremy.zawodny.com/blog/archives/001866.html
>> 
>> It's a bunch of things - Perl, C, MySQL-InnoDB, MyISAM, Akamai,
>> memcached.  The linked slides say "lots of MySQL usage." 60 servers.
> 
> LM uses MySQL extensively but what I don't know is whether it serves
> up individual pages by the obvious bunch of queries like a smaller BBS
> might.  I have the impression that it's more carefully tuned than that.

The linked page links to a PDF describing the architecture.
The careful tuning comes in part from a high-performance caching
system - memcached.

>> I don't see that example as validating your statement that
>> LAMP doesn't scale for mega-numbers of hits any better than
>> whatever you might call "printing press" systems.
> 
> What example?  Slashdot?

Livejournal.  You gave it as a counter example to the LAMP
architecture used by /.

]  It seems to me that by using implementation methods that
] map more directly onto the hardware, a site with Slashdot's
] traffic levels could run on a single modest PC (maybe a laptop).
] I believe LiveJournal (which has something more like a million
] users) uses methods like that, as does ezboard. 

Since LJ uses a (highly hand-tuned) LAMP architecture, it isn't
an effective counterexample.

>  It uses way more hardware than it needs to,
> at least ten servers and I think a lot more.  If LJ is using 6x as
> many servers and taking 20x (?) as much traffic as Slashdot, then LJ
> is doing something more efficiently than Slashdot.  

I don't know where the 20x comes from.  Registered users?  I
read /. but haven't logged into it in 5+ years.  I know I
hit a lot /. more often than I do LJ (there's only one diary
I follow there).  The use is different as well; all people
hit one story / comments page, and the comments are ranked
based on reader-defined evaluations.  LJ has no one journal
that gets anywhere as many hits and there is no ranking scheme.

>> I'ld say that few sites have >100k users, much less
>> daily users with personalized information. As a totally made-up
>> number, only few dozens of sites (maybe a couple hundred?) would
>> need to worry about those issues.
> 
> Yes, but for those of us interested in how big sites are put together,
> those are the types of sites we have to think about ;-).

My apologies since I know this sounds snide, but then why didn't
you (re)read the LJ architecture overview I linked to above?
That sounds like something you would have been interested in
reading and would have directly provided information that
counters what you said in your followup.

The "ibm-poop-heads" article by Ryan Tomayko gives pointers to 
several other large-scale LAMP-based web sites.  You didn't
like the Google one.  I checked a couple of the others:

  IMDB -
  http://www.findarticles.com/p/articles/mi_zdpcm/is_200408/ai_ziff130634
  As you might expect, the site is now co-located with other Amazon.com
  sites, served up from machines running Linux and Apache, but ironically,
  most of the IMDb does not use a traditional database back end. Its
  message boards are built on PostgreSQL, and certain parts of IMDb
  Pro-including its advanced search-use MySQL, but most of the site is
  built with good old Perl script.

  del.icio.us
  Took some digging but I found
  http://lists.del.icio.us/pipermail/discuss/2004-November/001421.html
  "The database gets corrupted because the machine gets power-cycled,
  not through any fault of MySQL's."

The point is that LAMP systems do scale, both down and up.  It's
a polemic against "architecture astronauts" who believe the only
way to handle large sites (and /., LJ, IMDB, and del.icio.us are
larger than all but a few sites) is with some spiffy "enterprise"
architecture framework.

> I'd say
> there's more than a few hundred of them, but it's not like there's
> millions.  And some of them really can't afford to waste so much
> hardware--look at the constant Wikipedia fundraising pitches for more
> server iron because the Wikimedia software (PHP/MySQL, natch) can't
> handle the load.

Could that have, for example, bought EnterpriseWeb-O-Rama and done
any better/cheaper?  Could they have even started the project
had they gone that route?

> Yes, of course there is [exprience in large-scale web apps]. 
> Look at the mainframe transaction systems of the 60's-70's-80's, for
> example. Look at Google.

For the mainframe apps you'll have to toss anything processed
in batch mode, like payrolls.  What had the customization level
and scale comparable to 100K+ sites of today?  ATMs?  Stock trading?

Google is a one-off system.  At present there's no other system
I know of - especially one with that many users - where a single
user request can trigger searches from hundreds of machines.
That's all custom software.  Or should most servers implement
what is in essence a new distributed operating system just to
run a web site?

>  Then th

Re: slicing a bsddb table, eg. for rec in bsddb["AArdvark":"zebra"]: print rec

2005-06-12 Thread Skip Montanaro

Neville> # I was expecting a slice of an index file to yield a
Neville> # generator so not all the records need to be read from disk

Slicing is a feature of sequence types, not mapping types.

>>> import string
>>> d = dict(zip(string.lowercase, string.uppercase))
>>> d
{'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...}
>>> d["a":"z"]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unhashable type
>>> import UserDict
>>> d2 = UserDict.UserDict(d)
>>> d2
{'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...}
>>> d2["a":"z"]
Traceback (most recent call last):
  File "", line 1, in ?
  File "/Users/skip/local/lib/python2.5/UserDict.py", line 17, in 
__getitem__
def __getitem__(self, key): return self.data[key]
TypeError: unhashable type

The unhashable type it's referring to is the slice object generated by the
"a":"z" notation:

>>> hash(slice("a", "z"))
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unhashable type

If you look at help on the slice type, you'll see that it takes three args:

class slice(object)
 |  slice([start,] stop[, step])
 |  
 | Create a slice object.  This is used for extended slicing
 | (e.g. a[0:10:2]).
 |  

Step sizes really only make sense for sequence indices.

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Peter Dembinski
Chris Spencer <[EMAIL PROTECTED]> writes:

> Peter Dembinski wrote:
>> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>>
>>> Nope. Python *is* typed. But it doesnt confuse implementation with
>>> semantic.
>> Python is typed.  And its type system may look strange for anyone
>> who did only Java or C++ programming before :>
>
> Of course, in that Python is dynamically typed as opposed to the
> static typing of Java or C++. Please excuse my previous mis-wording :)

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


How to use 8bit character sets?

2005-06-12 Thread copx
For some reason Python (on Windows) doesn't use the system's default 
character set and that's a serious problem for me.
I need to process German textfiles (containing umlauts and other > 7bit 
ASCII characters) and generally work with strings which need to be processed 
using the local encoding (I need to display the text using a Tk-based GUI 
for example). The only solution I managed to find was converting between 
unicode and latin-1 all the time (the textfiles aren't unicode, the output 
of the program isn't supposed to be unicode either). Everything worked fine 
until I tried to run the program on a Windows 9x machine.. It seems that 
Python on Win9x doesn't really support unicode (IIRC Win9x doesn't have real 
unicode support so that's not suprising).
Is it possible to tell Python to use an 8bit charset (latin-1 in my case) 
for textfile and string processing by default?

copx


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


Re: Learning more about "The Python Way"

2005-06-12 Thread Jarek Zgoda
Kalle Anke napisał(a):

> So, I'm looking for advice/information on:
> 
> + How to write "proper" python code instead of 
>   Java/Perl/C/C++/Pascal/Modula-2/etc inspired code

Just follow the white rabbit.

Rewrite your code in Python, then optimize.

-- 
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if an object IS another object?

2005-06-12 Thread Grant Edwards
On 2005-06-12, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Fascinating. With small strings, it uses the same object, and with
> small numbers like 3. With 300 they were different objects (why,

It's purely an implimentation detail.  The small integers get
used a lot, so Python keeps a pre-created set of small integers
handy.  It would be a bit, uh, wasteful to pre-create all of
possible integer objects, so "large" integers get created on
the fly without checking to see if there are any existing ones
with the right value.  Large integers could get cached and
re-used, but that would be extra overhead with little chance
for benefit.

> shouldn't they both be ints still?)

They are.

-- 
Grant Edwards   grante Yow!  .. over in west
  at   Philadelphia a puppy is
   visi.comvomiting...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if an object IS another object?

2005-06-12 Thread Grant Edwards
On 2005-06-12, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

>>The most obvious way (as usual ?):
>>
>>if obj1 is obj2:
>>  // your code here
>
> I immediately thought of is, and tested it in the console, but it
> didn't work quite like I expected:
>
>>foo = 3
>>bar = 3
>>zoo = foo
>>foo is zoo
> True
>>foo is bar
> True
>>zoo is bar
> True
>
> clearly foo and bar have the same value but they are different objects
> aren't they?

Nope.

> Yet applying the is operator yields True.

They're the same object.  Why did you expect them not to be?

-- 
Grant Edwards   grante Yow!  Am I elected yet?
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-12 Thread Peter Hansen
Steven D'Aprano wrote:
> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote:
>>If the case values are constants known to the compiler, it can generate O(1)
>>code to take the correct branch.
>>It is precisely this behavior that is desired in many situations.  
> 
> Agreed. I certainly don't object to sensible optimizations! But the number
> of if...elif statements which can be optimised are a vanishingly small
> subset of the number of possible if...elif statements.
> 
> And you can bet your last dollar that many people will use case statements
> even when doing so gives no advantage, in a mistaken opinion that it will
> be somehow magically faster.

Case statements are actually more suitable in many cases even when 
performance is not a goal for reasons of *readability*.

When reading an if statement, you have to scan down through effective 
each statement attempting to find the case in which you are interested. 
  Some cases can be compound.  The nested ifs can get confused with the 
surrounding ones (in Python or a language with explicit block 
delimiters).  The cases are often not written in any particular order, 
or they are ordered *for* performance reasons, but in ways that make it 
harder to "scan".

A case statement, on the other hand, can be a message from the 
programmer, saying in effect "here's code that represents a series of 
_simple_ conditionals, ordered (usually) in a sensible way (e.g. 
ascending numerical order), so just jump to the case you want and carry 
on maintaining this nice code."

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.

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


Post-EuroPython 2005 PyPy Sprint 1st - 7th July 2005

2005-06-12 Thread Armin Rigo
Post-EuroPython 2005 PyPy Sprint 1st - 7th July 2005 
==

The next PyPy sprint is scheduled right after EuroPython 2005
in Gothenborg, Sweden.  Its main focus is translation to 
lower level backends but there are also other possible topics. 
We'll give newcomer-friendly introductions.  To learn more
about the new PyPy Python-in-Python implementation look here: 

http://codespeak.net/pypy 

On a side note, there are a number of sub projects that may be
interesting for participating in google's summer-of-code event
(deadline June 14th!).  The PyPy group is willing to mentor
projects that have some link with PyPy, so if you are accepted
in such a project, the sprint could also serve as a good
meeting and kick-off point.  Further down you'll find some
examples, but there are certainly more and bigger ones :-)

Goals and topics of the sprint 
--

The main, though not the only, focus of the sprint will be on
the "translation" aspect of PyPy.   The goal here is to
progress towards a completely translated PyPy.  How much will
already have been done before EuroPython is unknown; as a
guess, we will be left with:
 
- completing the "rtyper", the piece of code that assigns low-level
  C-like types to high-level RPython objects (lists, dicts, instances,
  etc.) and low-level control flow graphs to high-level ones;
   
- polish off the GenC and GenLLVM back-ends, responsible for turning
  the low-level C-like flow graphs into real C or LLVM source code.

See http://codespeak.net/pipermail/pypy-dev/2005q2/002136.html for more
information (10th of June status).
 
Non-translation-related topics are welcome too.  Here are some suggestions
from the issue tracker (https://codespeak.net/issue/pypy-dev/):
   
- integrate the parser module, possibly making it RPython
  conformant;
 
- rewrite in Python a C module you are familiar with
  (partial list of missing/incomplete modules: os, math, array,
  regular expressions, binascii...)

- implement Python 2.3's import hook extensions (zip-imports etc.)

- fix Windows-related issues, '%'-formatting rounding errors,
  add missing docstrings on app-level built-in types and functions,
  etc.

- weakrefs (but this requires discussion and planning on pypy-dev
  before the sprint! feel free to start such a discussion, though.)


Location & Accomodation  
 

The sprint will be held in the former Math Center building
near the crossing of Gibraltargatan and Eklandagatan. Entrance
is on the middle of the side facing Gibraltargatan. The doors
to the building are normally locked, so you need the phone number
of somebody inside to get in. Instructions on whom to call will be
posted on the door.

The sprint will be co-located with several other sprints. See the 
`EuroPython Wiki`_, to find out what other sprints will be running.

Nearest, and probably cheapest is to book accomodation at SGS Veckobostäder
through the Europython website. This option will be available until about
20 June.

.. _`EuroPython special accomodation`: 
http://www.europython.org/sections/accomodation/special_accomodation
.. _`EuroPython Wiki`: http://www.europython.org/sections/sprints_and_wiki

Exact times 
---

The public Pypy sprint is held Friday 1st July - Thursday 7 July 2005.
Hours will be from 09:00 until people have had enough. It's a good 
idea to arrive a day before the sprint starts.   

(There is a sprint for people who are familiar with the Pypy codebase
before Europython as well. This will be held at Jacob & Laura's home
on Götabergsgatan 22.)


Network, Food, currency 
 

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

There are some pizzerias, kebab places and the like close to the venue.
Their food is edible and cheap, but not very good. For good food, you need to
go downtown.

You need a wireless network card to access the network. You will be 
issued a login to the Chalmers NOMAD network. This will allow you to 
use access points all over Chalmers.  However, we can likely provide 
a wireless/ethernet bridge.  

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

Registration etc.pp. 
 

Please subscribe to the `PyPy sprint mailing list`_, introduce
yourself and post a note that you want to come.  Feel free
to ask any questions there! 

.. _`PyPy sprint mailing list`: 
http://codespeak.net/mailman/listinfo/pypy-sprint


-- 
Armin Rigo & the PyPy team

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

Re: Code documentation tool similar to what Ruby (on Rails?) uses

2005-06-12 Thread Andrew Dalke
Ksenia Marasanova responsded to Michele Simionato
>> >>> print "%s" % inspect.getsource(os.makedirs)
> 
> That's easy, thanks! I guess I'll submit a patch for Epydoc with the
> functionality I've mentioned :)

Before doing that, add a "cgi.escape()" to the text.  Otherwise
embedded [<>&] characters will be interpreted as HTML.

Andrew
[EMAIL PROTECTED]

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


Learning more about "The Python Way"

2005-06-12 Thread Kalle Anke
Those who have read my posts today have probably understood that I'm 
not a "true" Python programmer ... but I want to learn more (I think 
that Python is rather fun).

I've read "Learning Python" pretty thoroughly, I've looked at some of 
the tutorials, some of online documentation, etc. But I still miss a 
lot of pieces for writing good python code, idioms, advanced 
usage/features, etc.

I've also seen a lot of references to v3, but I haven't found any 
real documentation of what's planned for that version.

So, I'm looking for advice/information on:

+ How to write "proper" python code instead of 
  Java/Perl/C/C++/Pascal/Modula-2/etc inspired code

+ The more advanced parts/uses of Python

+ Discussions about the ideas behind different Python
  constructs

+ What's going to happen with v3

I would really appriciate some pointers to where I can find info 
about this. Web sites (I've looked at python.org but haven't manage 
to find the stuff of what I'm looking for ... but perhaps I've missed 
all the interesting parts) ? Books (I've got 'Learning Python' and 
'Programming Python')? Other things?

 jem


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


Re: How to get/set class attributes in Python

2005-06-12 Thread Chris Spencer
Peter Dembinski wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> 
>>Nope. Python *is* typed. But it doesnt confuse implementation 
>>with semantic.
> 
> 
> Python is typed.  And its type system may look strange for anyone who
> did only Java or C++ programming before :>

Of course, in that Python is dynamically typed as opposed to the static 
typing of Java or C++. Please excuse my previous mis-wording :)

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Chris Spencer
Bruno Desthuilliers wrote:
> Chris Spencer a écrit :
> 
>> I was providing the original poster with a simple way to ensure 
>> appropriate type.
> 
> 
> s/appropriate type/specific implementation/
> 
> Hint : the appropriate type for print >> XXX is "whatever has a 
> 'write(anything_that_can_be_coerced_to_a_string)' method".

Certainly, although now I think you're splitting hairs over my 
terminology. Let's synchronize our wording with a point made in the 
Python docs. Section 2.1 of the Library Reference recommends that the 
builtin function isinstance() be used for testing the object type. Does 
this then mean that "type" refers to the class of an object? In which 
case, wouldn't "interface" refer to a collection of methods, that when 
present in a class create an implementation?

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


Re: How to test if an object IS another object?

2005-06-12 Thread eloff777
Fascinating. With small strings, it uses the same object, and with
small numbers like 3. With 300 they were different objects (why,
shouldn't they both be ints still?)

Mutable objects functioned differently as you suggested:

>>>foo = []
>>>bar = []
>>>foo == bar
True
>>>foo is bar
False

Tuples (which are immutable) also appear to be reused

>>>foo = ()
>>>bar = ()
>>>foo is bar
True

Thanks for your help, I know how to solve the problem now.
-Dan

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


Re: How to overcome automatic cyrillic-to-/hex convert

2005-06-12 Thread Florian Diesch
<[EMAIL PROTECTED]> <[EMAIL PROTECTED]> wrote:
> But when I enter some Bulgarian (actually cyrillic) text as a string,
> it
> seems that Python automatically converts it to '\x00..\x00 ' and once
> converted that way I can't get it back into its original look. The only
> way to get it right is using print :
>
 a = 'ÌÀÌÀ' # 'Mam' in Bulgarian
 print a
> 'ÌÀÌÀ'
>
> but
>
 a
> '\xcc\xe0\xec\xe0'


Did you try the locale module?


   Florian
-- 
begin  signature_virus
 Hi! I'm a signature virus. Please copy me to your signature to help me spread.
end
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if an object IS another object?

2005-06-12 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Sorry about removing my message, I posted with the wrong google
> account, I don't really want my email where those irritating spam bots
> can find it.
> 
> 
>>The most obvious way (as usual ?):
>>
>>if obj1 is obj2:
>> // your code here
> 
> 
> I immediately thought of is, and tested it in the console, but it
> didn't work quite like I expected:
> 
> 
>>foo = 3
>>bar = 3
>>zoo = foo
>>foo is zoo
> 
> True
> 
>>foo is bar
> 
> True
> 
>>zoo is bar
> 
> True
> 
> clearly foo and bar have the same value but they are different objects
> aren't they? 

Nope. They are two different names bound to the same integer object. You 
may have similar situation with strings:

 >>> s1 = "toto"
 >>> s2 = "toto"
 >>> s1 is s2
True

This is an application of the lightweight pattern. The Python 
interpreter reuse the same "value object" to avoid memory clutter. Since 
ints and strings are immutable, this is perfectly safe (but yet 
confusing when you're not aware of this).


> Yet applying the is operator yields True.

Yes. But now you know why !-)

And don't worry, this is quite unlikely that it will cause you any 
trouble in real code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if an object IS another object?

2005-06-12 Thread [EMAIL PROTECTED]
You can use the id() function to test equality of objects:

[EMAIL PROTECTED]:~$ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3
>>> b = 3
>>> id(a)
135585176
>>> id(b)
135585176
>>>

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


Re: How to test if an object IS another object?

2005-06-12 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> >foo = 3
> >bar = 3

> clearly foo and bar have the same value but they are different objects
> aren't they? 

No, they're the same object.  Now try it with 300 instead of 3 ;-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if an object IS another object?

2005-06-12 Thread eloff777
Sorry about removing my message, I posted with the wrong google
account, I don't really want my email where those irritating spam bots
can find it.

>The most obvious way (as usual ?):
>
>if obj1 is obj2:
>  // your code here

I immediately thought of is, and tested it in the console, but it
didn't work quite like I expected:

>foo = 3
>bar = 3
>zoo = foo
>foo is zoo
True
>foo is bar
True
>zoo is bar
True

clearly foo and bar have the same value but they are different objects
aren't they? Yet applying the is operator yields True.

Thanks,
-Dan

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


Re: python bytecode grammar

2005-06-12 Thread Terry Reedy

"Peter Dembinski" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Terry Reedy" <[EMAIL PROTECTED]> writes:
>> I believe the top-level production is something like
>> BYTECODE := (OPCODE ARGS)*
>
> ROTFL :)

Glad to make your day ;-)

I am aware that since ARGS depends on OPCODE, the above would lead to 
context-dependent productions for ARGS.  Upon thoroughly perusing
http://docs.python.org/lib/bytecodes.html
18.10.1 Python Byte Code Instructions

I discovered that there is at most one (non-stack) argument in the byte 
stream (contrary to the possibly plural implication of "All of the 
following opcodes expect arguments").  So the above could be written 
context-freely as
BYTECODE := (NO_ARG_CODE | ARG_CODE TWO_BYTE_ARG)*

where the symbolic expansions of NO_ARG_CODE  and ARG_CODE, with semantic 
explanations, constitute the contents of the doc above.

Terry J. Reedy



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


Re: How to get/set class attributes in Python

2005-06-12 Thread Bruno Desthuilliers
Chris Spencer a écrit :
> Bruno Desthuilliers wrote:
> 
>> And *this* is highly unpythonic. And un-OO too, since it makes foo() 
>> dependant on *class* Bar, when it should most probably be enough that 
>> it only depends on (probably part of) the *interface* of class Bar. 
> 
> I was providing the original poster with a simple way to ensure 
> appropriate type.

s/appropriate type/specific implementation/

Hint : the appropriate type for print >> XXX is "whatever has a 
'write(anything_that_can_be_coerced_to_a_string)' method".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-12 Thread Peter Dembinski
Steven D'Aprano <[EMAIL PROTECTED]> writes:

[snap]

> new_text = ""
> for word in text:
> new_text = new_text + process(word)

new_text = "".join(map(process, text))

(I couldn't resist)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What language to manipulate text files

2005-06-12 Thread Dan Christensen
ross <[EMAIL PROTECTED]> writes:

> What are the ideal languages for the following examples?
>
> 1. Starting from a certain folder, look in the subfolders for all
> filenames matching *FOOD*.txt Any files matching in each folder should
> be copied to a new subfolder within the current folder called EATING
> with a new name of *FOOD*COPY.txt

Bash?  

  for f in *FOOD*.txt; do cp ${f} EATING/${f}COPY.txt; done

Or "mmv", a linux utility:

  mmv '*FOOD*.txt' 'EATING/#1FOOD#2COPY.txt'

For the rest, I personally for choose python.

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


Re: How to test if an object IS another object?

2005-06-12 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> If two objects are of equal value you can compare them with ==. What I
> want to do is find out if two objects are actually just references to
> the same object, how can I do this in Python?

The most obvious way (as usual ?):

if obj1 is obj2:
   // your code here


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


How to test if an object IS another object?

2005-06-12 Thread dan . eloff
If two objects are of equal value you can compare them with ==. What I
want to do is find out if two objects are actually just references to
the same object, how can I do this in Python?

Thanks

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


Re: searching for IDE

2005-06-12 Thread Rob
Try ActiveState Komodo.  It costs $30 for a personal license, and is well 
worth it.  If you like visual studio you will like it.

Like many other people, I have looked far and wide for a Python IDE and this 
is what I've found.  The free solutions don't cut it, at least without 
spending many many hours of work, more than $30 worth.


R


"alexrait1" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I need an IDE for python that has the ability to show the filds of a
> class when I write "."
> Just the way it works in eclipse/JBuilder with java or visual studio
> with c++
> For now I treid eric3 and IDLE they don't do this...
> 


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


Re: searching for IDE

2005-06-12 Thread jean-marc
if you are familiar with eclipse, you could use the PyDev python
plugin.

jm

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Peter Dembinski
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

[snap]

>> Being an untyped language, Python does not require you to enforce
>> types.
>
> Nope. Python *is* typed. But it doesnt confuse implementation 
> with semantic.

Python is typed.  And its type system may look strange for anyone who
did only Java or C++ programming before :>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-12 Thread Philippe C. Martin
Taking stuff for granted in unrelated to progress.

I agree that the "trade" of software engineering evolves and that, thanks to
hardware advances, we _usually_ can now "object orient" our software, add
billions of abstraction layers, and consume memory without a second
thought. But the trade evolves in the sense "sub"-trades are created, one
person becomes a database experts while another will html all of his/her
life (I personally find that sad). I'm being redundant here: The reason we
can use Python and take many issues for granted is because some very
skilled people handle the issues we find cumbersome.



Roy Smith wrote:

> The point I was trying to make was that as computer science progresses,
> stuff that was really important to know a lot about becomes more and more
> taken for granted.  This is how we make progress.

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


searching for IDE

2005-06-12 Thread alexrait1
I need an IDE for python that has the ability to show the filds of a
class when I write "."
Just the way it works in eclipse/JBuilder with java or visual studio
with c++
For now I treid eric3 and IDLE they don't do this...

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


Re: ElementTree Namespace Prefixes

2005-06-12 Thread Jarek Zgoda
Chris Spencer napisał(a):

> Given xml with no namespaces, Elementtree works perfectly. However, if 
> you give the root tag an xmlns attribute, Elementtree relabels all child 
> nodes with it's own prefix, completely defeating the purpose of the 
> default namespace. In my opinion, this is unacceptable behavior.

There is no functional difference between default namespace and "normal" 
namespace. Replacing "default" with "normal" has no effect for document 
processing (namespace doesn't change, only prefix), although it looks 
differently for humans. Anyway, XML is for machines, not for humans.

> If an XML parser reads in and then writes out a document without having 
> altered it, then the new document should be the same as the original. 
> With Elementtree this isn't so. Lundh apparently believes he knows 
> better than you and I on how our namespaces should be represented.

No, this is perfectly valid behaviour. Go, see spec.

> It's a shame the default ns behavior in Elementtree is in such a poort 
> staten. I'm surprised no one's forked Elementtree solely to fix this issue.

There is at least one ElementTree API implementation that retains 
prefixes, lxml.ETree. Go google for it.

-- 
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Developers Handbook - Mistake done and corrected.

2005-06-12 Thread wooks
Arsenal v Spurs in baseball that translates to Red Sox v Yankees.

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


Re: checking for when a file or folder exists, typing

2005-06-12 Thread Bryan Rasmussen
>Hi Bryan,

>Here's a potential idea.  Try converting the variable to a string by
>using the following syntax:


>   thePath = str(thePathArg)


Actually it was a stupid thing, what happened was I was looping through the
commandline to build a file path in cases where there was more than one
commandline argument, such as when one passes c:/Documents and Settings/ 

only I was adding the space in the wrong place so I never had a proper
location.

Thanks though, it got me back to the problem and solved it.  

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


slicing a bsddb table, eg. for rec in bsddb["AArdvark":"zebra"]: print rec

2005-06-12 Thread Neville C. Dempsey
#!/bin/env python
import bsddb

test=bsddb.btopen("test.tbl")
for m in "JFMATQPHSOND": 
  test[m]="Profit for month "+m+" $1B"

def subyear_report(record_selection):
  for data in record_selection.iteritems(): print data

# I was expecting a slice of an index file to yield a
# generator so not all the records need to be read from disk
subyear_report(test["Apr":"Sep"])

"""
I have tried a few ideas but is there a simple way to convert this
["Apr":"Sep"] slice of a file into a generator of the requested records?

(I tried UserDict and got a bit further...)

Any hints?

ThanX
NevilleDNZ
"""

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


Re: Capture close window button in Tkinter

2005-06-12 Thread William Gill
Jonathan Ellis wrote:
> William Gill wrote:
> 
>>I am trying to make a simple data editor in Tkinter where each data
>>element has a corresponding Entry widget.   I have tried to use the
>>FocusIn/FocusOut events to set a 'hasChanged' flag  (if a record has not
>>changed, the db doesn't need updating).  This seems to work fine except
>>that when the user finishes and clicks a 'done' button or the close
>>window button (in the root widget) no FocusOut event is triggered.  I
>>can trigger a FocusOut event if the 'done' button opens another window
>>(i.e. a messagebox) that takes focus.  Enter and Leave follow the mouse,
>>but don't trigger when the user tabs between fields.
>>
>>Is there a better way to monitor 'hasChanged'?
> 
> 
> I'd go with monitoring keypresses in the Entry widget.

Well, It doesn't seem logical to do a before and after test of the Entry 
values after each keypress, but I suppose I could monitor keypresses, 
test event.key for Tab (in case the user tabbed out of the widget w/o 
making any changes.

Is that along the lines of what you are suggesting?

> 
> 
>>Also, how do I capture
>>the root window close button?
> 
> 
> root = Tk()
> root.protocol("WM_DELETE_WINDOW", onexit)
I had seen something like this somewhere, but couldn't remember where. 
Thanks to your reminder I found an example of "Capturing destroy 
events."  Since that will allow me to route the exit process through a 
tkMessageBox, it may be just as good to continue using FocusIn/FocusOut 
events.






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


Re: Scaling down (was Re: Dealing with marketing types...)

2005-06-12 Thread Paul Rubin
[EMAIL PROTECTED] (Aahz) writes:
> So what?  I think you're missing the real point of the article: using
> LAMP scales *DOWN* in a way that enterprise systems don't.  Getting your
> first prototype up and running is far more important than sheer
> scalability,

There comes a day when your first prototype can no longer handle the
traffic.  The question then is how do you deal with that.

> and LAMP does have many mechanisms to obtain scalability when it's
> needed.

LAMP seems to have no solution other than scaling (i.e. blowing more
money on hardware and colo space).  One really gets the impression
that a more thoughtful design could handle the traffic without needing
to scale the hardware.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get/set class attributes in Python

2005-06-12 Thread Chris Spencer
Bruno Desthuilliers wrote:

> And *this* is highly unpythonic. And un-OO too, since it makes foo() 
> dependant on *class* Bar, when it should most probably be enough that it 
> only depends on (probably part of) the *interface* of class Bar.

I was providing the original poster with a simple way to ensure 
appropriate type. You can assert whatever aspect you wish. If you want 
to ensure compatibility with some other property simply use "assert 
blah" subsituting blah for whatever test you wish to perform (e.g. 
assert MyInterface.implementedBy(bar) to test for interface implementation).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Controlling a generator the pythonic way

2005-06-12 Thread Terry Reedy

"news:[EMAIL PROTECTED]
> Thomas Lotze <[EMAIL PROTECTED]> writes:
>> A related problem is skipping whitespace. Sometimes you don't care about
>> whitespace tokens, sometimes you do. Using generators, you can either 
>> set
>> a state variable, say on the object the generator is an attribute of,
>> before each call that requires a deviation from the default, or you can
>> have a second generator for filtering the output of the first. Again, 
>> both
>> solutions are ugly (the second more so than the first).

Given an application that *only* wanted non-white tokens, or tokens meeting 
any other condition, filtering is, to me, exactly the right thing to do and 
not ugly at all.  See itertools or roll your own.

Given an application that intermittently wanted to skip over non-white 
tokens, I would use a *function*, not a second generator, that filtered the 
first when, and only when, that was wanted.  Given next_tok, the next 
method of a token generator, this is simply

def next_nonwhite():
   ret = next_tok()
   while not iswhte(ret):
  ret = next_tok()
   return ret

A generic method of sending data to a generator on the fly, without making 
it an attribute of a class, is to give the generator function a mutable 
parameter, a list, dict, or instance, which you mutate from outside as 
desired to change the operation of the generator.

The pair of statements
  
  val = gen.next()
can, of course, be wrapped in various possible gennext(args) functions at 
the cost of an additional function call.

Terry J. Reedy







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


RE: Dealing with marketing types...

2005-06-12 Thread bruce
just out of curiosity.. where'd you read the 150,000-200,000 servers...

i've never seen guesses that high.. i've seen somewhere as high as possible
100K... but the author stated that he was purely guessing...

-bruce


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Terry Reedy
Sent: Sunday, June 12, 2005 9:48 AM
To: python-list@python.org
Subject: Re: Dealing with marketing types...



"Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message
news:[EMAIL PROTECTED]
> Andrew Dalke <[EMAIL PROTECTED]> writes:
>> If that's indeed the case then I'll also argue that each of
>> them is going to have app-specific choke points which are best
>> hand-optimized and not framework optimized.  Is there enough
>> real-world experience to design a EnterpriseWeb-o-Rama (your
>> "printing press") which can handle those examples you gave
>> any better than starting off with a LAMP system and hand-caching
>> the parts that need it?
>
> Yes, of course there is.  Look at the mainframe transaction systems of
> the 60's-70's-80's, for example.  Look at Google.

Based on what I've read, if we could look at Google, we would see 150,000
to 200,000 servers (about half bought with IPO money).  We would see a
highly customized dynamic cluster computing infrastructure that can be
utilized with high-level (Python-like) commands.  The need to throw
hundreds of machines at each web request strikes me as rather specialized,
though definitely not limited to search.  So while not LAMP, I don't see it
as generic EWeboRama either.

Terry J. Reedy



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

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


Re: ElementTree Namespace Prefixes

2005-06-12 Thread Chris Spencer
Andrew Dalke wrote:
> On Sun, 12 Jun 2005 15:06:18 +, Chris Spencer wrote:
> 
> 
>>Does anyone know how to make ElementTree preserve namespace prefixes in 
>>parsed xml files?
> 
> 
> See the recent c.l.python thread titled "ElemenTree and namespaces"
> and started "May 16 2:03pm".  One archive is at
> 
> http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/31b2e9f4a8f7338c/363f46513fb8de04?&rnum=3&hl=en

Thanks, although that thread didn't seem to resolve the issue. All the 
first few links talk about is how to hack your own parser to make sense 
of the Clark notation.

The problem at hand is with how Elementtree outputs namespaces and 
represents the tag name in memory.

Given xml with no namespaces, Elementtree works perfectly. However, if 
you give the root tag an xmlns attribute, Elementtree relabels all child 
nodes with it's own prefix, completely defeating the purpose of the 
default namespace. In my opinion, this is unacceptable behavior.

If an XML parser reads in and then writes out a document without having 
altered it, then the new document should be the same as the original. 
With Elementtree this isn't so. Lundh apparently believes he knows 
better than you and I on how our namespaces should be represented.

It's a shame the default ns behavior in Elementtree is in such a poort 
staten. I'm surprised no one's forked Elementtree solely to fix this issue.

Anyways, Python's native minidom works as expected, so I'll probably use 
that instead, even if the api is slightly less intuitive.

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


Re: What is different with Python ?

2005-06-12 Thread Steven D'Aprano
On Sun, 12 Jun 2005 08:11:47 -0400, Roy Smith wrote:

> The point I was trying to make was that as computer science progresses, 
> stuff that was really important to know a lot about becomes more and more 
> taken for granted.  This is how we make progress.
> 
> I used to worry about memory busses at the milivolt and microsecond level.  
> I knew about termination impedances and wired-OR logic, and power budgets 
> and all that good stuff.  Today all I know about memory is you go to 
> www.crucial.com, type in your Visa card number, and the nice UPS guy shows 
> up with some SIMMs in a few days.

Yes. But (to a first approximation) memory either works or it doesn't. And
we never need to worry about it scaling, because you don't get to assemble
your own SIMMs -- you buy them pre-made. Software is nothing like that.

[snip]
> Just like you can't even begin to think about building today's
> GUI-driven desktop applications if you're still worrying about
> individual logic gates, you can't begin to think about solving some of
> these really hard problems (and others we haven't even imagined) if
> you're still worrying about memory buffer reference counting and garbage
> collection. Yesterday's research projects are today's utilities and
> tomorrow's historical footnotes.

Nice in theory, but frequently breaks down in practice. Let's take a nice,
real, Python example:

I write an text-handling application in Python. I've taken your advice,
and don't worry about messy details about the language implementation,
and concentrated on the application logic. Consequently, I've used the
idiom:

new_text = ""
for word in text:
new_text = new_text + process(word)

I test it against text containing a few thousand words, and performance is
good. Then my customers use my application in the real world, using texts
of a few hundreds of millions of words, and performance slows to a painful
crawl.

Python does a good job of insulating the developer from the implementation
details, but even in Python those details can sometimes turn around and
bite you on the behind. And your users will discover those bum-biting
situations long before your testing will.

Joel of "Joel On Software" discusses this issue here:

http://www.joelonsoftware.com/articles/fog000319.html

Of course, we should not prematurely optimise. But we should also be aware
of the characteristics of the libraries we call, so we can choose the
right library. 

Fortunately, a high-level language like Python makes it comparatively easy
to refactor a bunch of slow string concatenations into the list-append
plus string-join idiom.


-- 
Steven.



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


Re: Custom type: PyObject_IS_GC access violation

2005-06-12 Thread =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=
Bue Krogh Vedel-Larsen wrote:

> But if I call
> 
> SA_PyVector_Type.tp_new = PyType_GenericNew;
> PyType_Ready( &SA_PyVector_Type );
> 
> then, when Py_Finalize is called, PyObject_IS_GC(op) in visit_decref() in 
> gcmodule.c causes an access violation. If I don't call PyType_Ready, then 
> the access violation doesn't occure, but then the type can't be used...
> 
> So, the question is, does anyone have any idea about what could be 
> causing this?

Most likely some code that you haven't shown. Here is the expansion
of PyObject_IS_GC(op)

#define PyObject_IS_GC(o) (PyType_IS_GC((o)->ob_type) && \
((o)->ob_type->tp_is_gc == NULL || (o)->ob_type->tp_is_gc(o)))

so it becomes

PyType_IS_GC(op->type) && (op->ob_type->tp_is_gc==NULL ||
op->ob_type->tp_is_gc(op))

Then, PyType_IS_GC(op->type) becomes

PyType_HasFeature((op->type), Py_TPFLAGS_HAVE_GC)

which in turn becomes

(op->tp_flags & Py_TPFLAGS_HAVE_GC) != 0

So typically, PyObject_IS_GC goes to the type of the object,
which should never crash, and then looks into the flags of
the type, which cannot crash - unless somebody messed with
ob_type of the object, and unless this isn't a Python
object in the first place.

You did not say what kind of object op was in the crash - this
is something you should investigate further. Does it point to
a Python object? If so, what is the type of the Python object?

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


Re: How to get/set class attributes in Python

2005-06-12 Thread Bruno Desthuilliers
Chris Spencer a écrit :
> Kalle Anke wrote:
> 
>> On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote
>> (in article <[EMAIL PROTECTED]>):
>>
>> void doSomething( data : SomeClass ){ ... }
>>
>> and I would be sure at compile time that I would only get SomeClass 
>> objects as parameters into the method.
> 
> 
> Being an untyped language,  Python does not require you to enforce types.

Nope. Python *is* typed. But it doesnt confuse implementation with semantic.

> However, for those that require such functionality, you can get away 
> with using the "assert" statement. For example, if I wanted to make sure 
> my function foo was only given instances of class Bar, I'd write 
> something like:
> 
>  >>> class Bar: pass
>  >>> def foo(bar):
> ... assert isinstance(bar, Bar), "argument is not of type Bar"
> ... print "argument must be of type Bar"
  ...
>  >>> bar = Bar()
>  >>> foo(bar)
> argument must be of type Bar
>  >>> foo(123)
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 2, in foo
> AssertionError: argument is not of type Bar
>  >>>

And *this* is highly unpythonic. And un-OO too, since it makes foo() 
dependant on *class* Bar, when it should most probably be enough that it 
only depends on (probably part of) the *interface* of class Bar.

Suppose I want to adapt my own class Baaz so it's compatible with Bar. 
Now I *must* make the adapter a subclass of Bar (and then depends on 
Bar's *implementation*) when it only needs to expose the same (probably 
subset of) interface.

Except for exceptions (please pardon the pun), one most usually don't 
have to worry about the real class of an object. In 5 years programming 
Python, I only had to check for the type of an object a couple of times, 
and each time only for more genericity (I mostly needed to dispatch on 
some 'generic types' like string-like, sequence-like, map-like, 
numeric-like, callable, and others), and this was never used as a way to 
restrict the possible types (exceptions are good enough for this).

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


Re: Code documentation tool similar to what Ruby (on Rails?) uses

2005-06-12 Thread Ksenia Marasanova
12 Jun 2005 08:12:14 -0700, Michele Simionato <[EMAIL PROTECTED]>:
> What about doing it yourself?
> 
> >>> import inspect, os
> >>> print "%s" % inspect.getsource(os.makedirs)

That's easy, thanks! I guess I'll submit a patch for Epydoc with the
functionality I've mentioned :)


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


  1   2   >