Re: "also" to balance "else" ?

2005-06-13 Thread Donn Cave
Quoth Ron Adam <[EMAIL PROTECTED]>:
| ... The current for-else 
| is IMHO is reversed to how the else is used in an if statement.

Is that all?  As a matter of opinion, this one is fairly simply
an arbitrary choice to assign a positive sense to completion of
the loop predicate.  For search loops, for example, it's clearly
a failure - the loop predicate is there to put a bound on the search,
and to reach that bound is to fail.

Whatever, I don't care if you find this compelling.  My point
is that rather than a case of intuition driven by subconscious
forces beyond our control, the choice between two ways to take
the boolean sense of a loop control is really based on some
logical premises, which we can reconsider if it's productive
to do so.  I prefer this to fantasies about changing the language,
your mileage may vary.

Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regarding cgi

2005-06-13 Thread Fredrik Lundh
"praba kar" wrote:

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

if you expect the HTML contents to appear as HTML, it's wrong.

(some web browsers may display it as HTML even if it's tagged
as something else, but you shouldn't rely on this)





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


Re: Tiff Image Reader/writer

2005-06-13 Thread Fredrik Lundh
"PyPK" wrote:

> nothing fancy. I just want to be able to read a tiff image, get pixel
> values, write back to a tiff file.

so why doesn't PIL or ImageMagick work for you?

here's a minimal PIL version:

from PIL import Image

im = Image.open("myfile.tiff")
value = im.getpixel((12, 34))
im.save("other.tiff")





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


regarding cgi

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




___
Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for 
FREE! http://in.mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: \r\n or \n notepad editor end line ???

2005-06-13 Thread Fredrik Lundh
John Machin wrote:

> Many people don't appear to want to know why; they only want a solution
> to what they perceive to be their current problem.

and many people can identify a short HOWTO when they see it, and look
things up in the documentation when they want the full story.  reposting
the documentation in response to every question is, in most cases, a
waste of time and bandwidth...





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


stuck in cgi-image mess

2005-06-13 Thread nephish
i have an html form with a drop-down list that lists a bunch of images.
how can i get my cgi script to load the image ?
i have imported cgi and os
text entered from a form and read from a file do ok, but i cant seem to
get it to load an image.

the form writes all of the entries as lines in a .txt file
this file is selected later,
all the lines are read,
and based on the first line of the text file determines the name of the
.gif image to load.

is there a way to do this, i think i am getting all the ' and '' stuff
confused.

thanks.

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


Re: ElementTree Namespace Prefixes

2005-06-13 Thread Fredrik Lundh
Oren Tirosh wrote:

> It all boils down to how you define "the same". Which parts of the XML
> document are meaningful content that needs to be preserved and which
> ones are mere encoding variations that may be omitted from the internal
> representation?
>
> Some relevant references which may be used as guidelines:
>
> * http://www.w3.org/TR/xml-infoset
> The XML infoset defines 11 types of information items including
> document type declaration, notations and other features. It does not
> appear to be suitable for a lightweight API like ElementTree.
>
> * http://www.w3.org/TR/xpath-datamodel
> The XPath data model uses a subset of the XML infoset with "only" seven
> node types.
>
> http://www.w3.org/TR/xml-c14n
> The canonical XML recommendation is meant to describe a process but it
> also effectively defines a data model: anything preserved by the
> canonicalization process is part of the model. Anything not preserved
> is not part of the model.

you forgot

http://effbot.org/zone/element-infoset.htm

which describes the 3-node XML infoset subset used by ElementTree.





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


Re: "also" to balance "else" ?

2005-06-13 Thread Ron Adam
Terry Hancock wrote:

> On Monday 13 June 2005 11:09 pm, Ron Adam wrote:

>>My suggestion is to use, also as the keyword to mean "on normal exit" 
>>'also' do this.
> 
> 
> Unfortunately, "also" is also a bad keyword to use for this, IMHO.
> I don't find it any more intuitive than "else".  (And since your idea
> would break if-else code, I don't think it would be allowed, anyway).

Hi Terry,

How would it break the current if-else?

> I can't think of what would be a better keyword, though.  :-/

Well there's 'not-else' or 'nelse'  Ack!  Just kidding of course.

Yes, I can't think of anything that has the same meaning that would 
work.  'And' would be the English language alternative to "else", but 
it's already used of course.


Regards, Ron

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


Re: "also" to balance "else" ?

2005-06-13 Thread Ron Adam
Andrew Dalke wrote:

> Ron Adam wrote:
> 
>>It occurred to me (a few weeks ago while trying to find the best way to 
>>form a if-elif-else block, that on a very general level, an 'also' 
>>statement might be useful.  So I was wondering what others would think 
>>of it.
> 
> 
>>for x in :
>>BLOCK1
>>if : break   # do else block
>>also:
>>BLOCK2
>>else:
>>BLOCK3
> 
> 
> 
> For this specific case you could rewrite the code in
> current Python as
> 
> for x in :
>   BLOCK1
>   if :
> BLOCK3
> break
> else:
>   BLOCK2

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


> In order for your proposal to be useful you would need an
> example more like the following in current Python
> 
> for x in :
>   ...
>   if :
> BLOCK3
> break
>   ...
>   if :
> BLOCK3
> break
> else:
>   BLOCK2
> 
> That is, where "BLOCK3;break" occurs multiple times in
> the loop.  My intuition is that that doesn't occur often
> enough to need a new syntax to simplify it.

I think you have BLOCK 2 and 3 confused here.  BLOCK2 is the 'also' 
block above.  The current for-else already does the 'also' behavior. I'm 
asking if changing the current 'else' in a for statement to 'also' would 
make it's current behavior clearer.  It's been stated before here that 
current behavior is confusing.

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

> Can you point to some existing code that would be improved
> with your also/else?
> 
> 
>>while :
>> BLOCK1
>> if : break# jump to else
>>also:
>> BLOCK2
>>else:
>> BLOCK3
>>
>>Here if the while loop ends at the while , the BLOCK2 
>>executes,  or if the break is executed, BLOCK3 executes.
> 
> 
> which is the same (in current Python) as
> 
> 
> while :
>   BLOCK1
>   if :
> BLOCK3
> break
> else:
>   BLOCK2

Actually, my example above has a problem, it conflicts with the current 
while else.  Probably the while-also-else should behave the same as an 
if-also-else.  Maybe more thinking on how the break behaves in relation 
to these is needed.


>>In and if statement...
>>
>>if :
>> BLOCK1
>>elif :
>> BLOCK2
>>elif :
>> BLOCK3
>>also:
>> BLOCK4
>>else:
>> BLOCK5
>>
>>Here, the also block would execute if any previous condition is true, 
>>else the else block would execute.
> 
> 
> That is ... funky.  When is it useful?

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

> One perhaps hackish solution I've done for the rare cases when
> I think your proposal is useful is
> 
> while 1:
>   if :
> BLOCK1
>   elif :
> BLOCK2
>   elif :
> BLOCK3
>   else:
> # couldn't do anything
> break
>   BLOCK4
>   break
> 

The type of thing I would try to avoid. ;-)


>>I think this gives Pythons general flow control some nice symmetrical 
>>and consistent characteristics that seem very appealing to me.  Anyone 
>>agree?
> 
> 
> No.  Having more ways to do control flow doesn't make for code that's
> easy to read.

I agree that having more ways isn't a reason by it self.

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

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

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


> My usual next step after thinking (or hearing) about a new Python
> language change is to look at existing code and see if there's
> existing code which would be easier to read/understand and get an
> idea if it's a common or rare problem.  Perhaps you could point
> out a few examples along those lines?
> 
>   Andrew
>   [EMAIL PROTECTED]

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

Which Python Wiki engine?

2005-06-13 Thread Kenneth McDonald
I'm looking for a Wiki engine to set up for my company, so that we  
can incrementally add user documentation for a fairly complex  
program, plus allow users to add their own comments for the benefit  
of others. I'd strongly prefer a Python-based Wiki, since that allows  
me the chance to add plugins with minimal effort (being a python  
enthusiast and programmer).

However, I'd also like something that can provide a little more  
structure than MoinMoin seems able to provide (correct me if I'm  
wrong.) Though there would be cross-references amongst various  
sections, the idea is that the structure of the wiki would be very  
much that of an outline, with topics divided into sub topics and then  
into sub sub topics, etc. A person at our company would be the  
"editor"; responsible for setting up the original structure, putting  
in the documentation we currently have, and periodically editing  
contributions from users.

Here are some of the features I'd greatly like to have that I haven't  
seen provided by the (relatively few) wiki engines I've looked at.  
Mind you, I don't claim to have looked at even these few  
exhaustively. (No time!) MoinMoin is the one I've looked at the most.

1) Automatically generated table of contents, based on the outline  
structure. This would be regenerated periodically (probably nightly)
2) Ability for users to add new subsections, but not to change that  
part of the document structure which has been locked by the editor.
3) Clear visual distinction between material added by the users, and  
material added or approved by the editor.
4) Legal-style numbering of sections, subsections, etc.
5) Ability to have single pages containing both locked text (which  
users cannot edit or delete) and unlocked text. Such a page would  
consist of one or more locked blocks of text, interspersed with  
comments put in by users. Users could put comments anywhere except  
side a locked text block.

Ideally, this would also be something that doesn't depend on a  
backend database or other things besides the web server and python  
packages. This is not likely to be a wiki where huge amounts of  
interactivity must be supported; there will probably be a moderate  
amount of reading, and a small amount of writing.

If you know of any Python wiki engines which can satisfy (even  
partially) this list, please let me know. I'd strongly prefer to have  
a Python engine. On the other hand, if you know of another type of  
wiki that matches well with these requirements, I won't complain if  
you mention it :-)

Thanks,
Ken McDonald
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-13 Thread Terry Hancock
On Monday 13 June 2005 11:09 pm, Ron Adam wrote:
> John Roth wrote:
> > "Ron Adam" <[EMAIL PROTECTED]> wrote in message 
> > news:[EMAIL PROTECTED]
> > The difficulty you're having with this is that else
> > is a very bad keyword for this particular construct.
> > I'd prefer something like "on normal exit" as
> > a keyword.
> 
> It's not a difficulty.  This is the point I was making.  :)
> 
> My suggestion is to use, also as the keyword to mean "on normal exit" 
> 'also' do this.

Unfortunately, "also" is also a bad keyword to use for this, IMHO.
I don't find it any more intuitive than "else".  (And since your idea
would break if-else code, I don't think it would be allowed, anyway).

I can't think of what would be a better keyword, though.  :-/

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

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


Re: implicit variable declaration and access

2005-06-13 Thread Christopher Subich
Cameron Laird wrote:
> cleaner algorithm somewhere in the neighborhood.  In general,
> "application-level" programming doesn't need exec() and such.
> 
> PyPy and debugger writers and you other "systems" programmers 
> already know who you are.

Out of curiosity, where would you classify interpreters for secondary 
app-specific programming languages? Specifically, mud-client stored 
procedures (triggers, timed events) seem to correspond very naturally to 
generating the python code required to execute them in advance, then 
compile()ing and storing the compiled code for repeated execution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Steven D'Aprano
D H wrote:

> But what you are getting at is more akin to our mental model of what the 
> computer is doing when we write and run a program.  Without a 
> fundamental understanding of memory and addresses, a programmer can make 
> certain mistakes that reveal this lack of understanding.  But that 
> doesn't mean they have to learn about memory management at the very 
> beginning of their instruction.

Finally somebody who gets it :-)

Every home handyman needs to know the difference 
between a claw hammer and a tack hammer and rubber 
hammer, and why you shouldn't use a claw hammer to 
knock dints out of steel sheeting, but they don't need 
to learn them all on the first time they look at a nail.

I'm reminded about the concept "lies for children", 
used by Ian Stewart and Jack Cohen (mathematician and 
biologist respectively) in some of their books. The 
point they make is that much of what we teach each 
other -- even adults -- is "lies for children". The 
Earth is not a sphere, even though we can often get 
away with pretending it is. High and low tides aren't 
caused by the moon. Testosterone doesn't cause 
aggression. DNA is not a blueprint. And adding two 
strings together is not a simple operation, despite 
appearances.

"Lies for children" in this sense are not *bad*, they 
are a necessary step towards a more sophisticated 
understanding. Imagine trying to learn about projectile 
motion if you needed to understand general relativity 
and friction just to get started. Now imagine you are a 
ballistic missile scientist, and you assume that the 
problem of firing a missile from here to there is 
independent of the shape of the Earth's gravitional 
field, air resistance and relativity. You've just 
missed your target by a kilometre. Ooops.

Learning when you can ignore implementation details is 
just as important a skill as learning how to use 
variables. Just as you wouldn't try teaching closures 
to people who haven't yet learnt what a function is, 
you don't want to bog people down with implementation 
details too early -- but if you don't teach them *at 
all*, you are creating second-class programmers who 
will write slow, buggy, hard-to-maintain code.

-- 
Steven.

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


Re: How to get/set class attributes in Python

2005-06-13 Thread Terry Hancock
On Monday 13 June 2005 03:50 pm, Kalle Anke wrote:
> On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
> (in article <[EMAIL PROTECTED]>):
> 
> > 1) Assume the variables are of a sensible type (not 
> > necessarily the one you expected, though), and provide
> > exception handling to catch the case where their interface
> > does not match what you expect.
> 
> The problem I have with this is that I might discover an error at runtime 
> instead of compile time, this means that I need to really exercise all 
> possible test cases to make sure that I've covered everything (which of 
> course is a good thing) but it would be easier to discover this at "compile 
> time".

The Python solution to this problem is called "unittest". It is
at least as easy to do unit testing in Python as it is to properly
handle type-checking in C or Java.

> > Let's face it -- should it matter if you "are a programmer" 
> > or only if you "can program"?  This is the difference in
> > philosophy behind a dynamically-typed language like
> > Python and a statically typed one like Java.
> 
> I don't really understand what you're meaning (English isn't my native 
> language as you probably already have discovered)

(Actually no, you're quite fluent, AFAICT).  I was making
an analogy:

Requiring a variable to be, say, a "float" is like insisting that
only people with the job title "Programmer" be allowed to
see the language documentation.

In both situations, real life will confront you with situations
where you will wish that you had been more tolerant.  Lots
of us are not "Programmers", but we do quite a bit of programming.

Likewise, you'll be happier to discover that ints or complex
numbers work with your code too, without having to jump
through hoops to make it happen.

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

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

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


Re: What is different with Python ?

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

Philosophically I disagree.  Biology and physics depends on
models of how the world works.  The success of a model depends
on how well it describes and predicts what's observed.

Programming too has its model of how things work; you've mentioned
algorithmic complexity and there are models of how humans
interact with computers.  The success depends in part on how
well it fits with those models.

In biology there's an extremely well developed body of evidence
to show the general validity of evolution.  That doesn't mean
that a biological theory of predator-prey cycles must be based
in an evolutionary model.  Physics too has its share of useful
models which aren't based on QCD or gravity; weather modeling
is one and the general term is "phenomenology."

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

Science also has its purely observational domains.  A
biologist friend of mine talked about one of his conferences
where the conversations range from the highly theoretical
to the "look at this sucker we caught!"

My feeling is that most scientists do not develop new fundamental
theories.  They instead explore and explain things within
existing theory.  I think programming is similar.  Both fields
may build new worlds, but success is measured by its impact
in this world.

Andrew
[EMAIL PROTECTED]

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


Re: ANN: pyparsing-1.3.1 released

2005-06-13 Thread Christopher Subich
Paul McGuire wrote:
> (sorry if this is a double-post - I tried posting this last night but I
> think GoogleGroups ate it)
> 
> Pyparsing is a pure-Python class library for quickly and easily
> constructing recursive-descent parsers.  Pyparsing takes a
> "building-block" approach to parser construction, as opposed to code
> generation methods (such as lex/yacc) or pattern definition strings
> (such as regular expressions).

Funnily enough, I've been thinking about something exactly like this. 
I've realized that my desired scripting language for the mud client I'm 
writing is very much a CFG, so simple regexes aren't going to cut it.

The biggest issue for me is command syntax -- commands can have one of a 
number of parameter formats (number and type of parameters can vary). 
With a special command-marker at the beginning of the expression, I know 
unambiguously what is a command and what is not, but I'd need to look up 
in a dictionary (indexed by command name) the types.  Is the pyparsing 
tokenizer flexible enough to let me do this sort of thing easily?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-13 Thread Ron Adam
John Roth wrote:
> 
> "Ron Adam" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>> Currently the else block in a for loop gets executed if the loop is 
>> completed, which seems backwards to me.  I would expect the else to 
>> complete if the loop was broken out of.  That seems more constant with 
>> if's else block executing when if's condition is false.
> 
> 
> Actually, it makes sense if you look at it correctly.
> 
> In an unadorned loop, exits via break and via the
> loop condition becoming false go to the same place.
> To distinguish requires some kind of a switch.
> 
> In a loop with an else, exits via break skip the else
> clause, while an exit via the loop condition takes
> the else clause. You don't need a special exit on
> break since you can put any amount of logic after
> the if and in front of the break. Where you need it
> is on exit via the loop condition.
> 
> The difficulty you're having with this is that else
> is a very bad keyword for this particular construct.
> I'd prefer something like "on normal exit" as
> a keyword.

It's not a difficulty.  This is the point I was making.  :)

My suggestion is to use, also as the keyword to mean "on normal exit" 
'also' do this.

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


Re: circular import Module

2005-06-13 Thread Greg Ewing
Magnus Lycka wrote:
> Due to the cycle, you can never use file1 without
> file2 or vice versa. Why do you then want it to be
> two different modules instead of one?

Perhaps because it would then be too big and
unwieldy to maintain?

Sometimes there are legitimate reasons for
mutually-dependent modules.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Terry Reedy

"Roy Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Andrea Griffini <[EMAIL PROTECTED]> wrote:
>> Hehehe... a large python string is a nice idea for modelling
>> memory.
>
> Actually, a Python string is only good for modelling ROM.  If you want to
> model read-write memory, you need a Python list.

or array from the array module. 



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


RE: Controlling a generator the pythonic way

2005-06-13 Thread Delaney, Timothy C (Timothy)
FWIW, PEP 342 is now titled "Coroutines via Enhanced Iterators" :)

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


Re: What is different with Python ?

2005-06-13 Thread D H
Andrea Griffini wrote:
> On Mon, 13 Jun 2005 22:23:39 +0200, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
> 
> 
>>Being familiar with 
>>fondamental *programming* concepts like vars, branching, looping and 
>>functions proved to be helpful when learning C, since I only had then to 
>>focus on pointers and memory management.
> 
> 
> If you're a good programmer (no idea, I don't know
> you and you avoided the issue) then I think you
> wasted a lot of energy and neurons learning that way.
> Even high-level scripting languages are quite far
> from a perfect virtualization, and either the code
> you wrote in them was terrible *OR* you were able
> to memorize an impressive quantity of black magic
> details (or you were just incredibly lucky ;-) ).

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

If you want to understand what engineers like programmers, and 
scientists approach their work, look up the structure-behavior-function 
framework.  Engineers work from function (the effect something has on 
its environment, in this case the desired effect), to structure - how to 
consistently constrain behavior to achieve that desired function. 
Scientists, on the other hand, primarily work from structure and 
behavior to function.  Here is an unknown plant - why does it have this 
particular structure or behavior?  What is its function, or what in its 
environment contributed to its evolution?  See descriptions of SBF by 
Cindy Hmelo and others.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread D H
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. 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, 

You're exactly right that people learn better going from concrete to 
abstract, but you're examples (pointers and memory management) are not 
what is typically meant by concrete in learning contexts.

Starting concretely would mean using programming to solve real problems 
and develop useful tools.  In programming it is often good to start with 
examples - some common ones I've seen in informal learning of 
programming include a calculator, an RSS viewer or aggregator, a video 
game, etc.

But what you are getting at is more akin to our mental model of what the 
computer is doing when we write and run a program.  Without a 
fundamental understanding of memory and addresses, a programmer can make 
certain mistakes that reveal this lack of understanding.  But that 
doesn't mean they have to learn about memory management at the very 
beginning of their instruction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "also" to balance "else" ?

2005-06-13 Thread John Roth

"Ron Adam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> Currently the else block in a for loop gets executed if the loop is 
> completed, which seems backwards to me.  I would expect the else to 
> complete if the loop was broken out of.  That seems more constant with 
> if's else block executing when if's condition is false.

Actually, it makes sense if you look at it correctly.

In an unadorned loop, exits via break and via the
loop condition becoming false go to the same place.
To distinguish requires some kind of a switch.

In a loop with an else, exits via break skip the else
clause, while an exit via the loop condition takes
the else clause. You don't need a special exit on
break since you can put any amount of logic after
the if and in front of the break. Where you need it
is on exit via the loop condition.

The difficulty you're having with this is that else
is a very bad keyword for this particular construct.
I'd prefer something like "on normal exit" as
a keyword.

John Roth 

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


Re: recursive import list

2005-06-13 Thread Mike Meyer
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
>> I have a fairly large project going on and would like to figure out
>> automatically from the source which files are being imported.
> If you use your own import function, like below, you could create a
> list of all imported modules.

Why not use sys.modules? To answer the question actually asked, check
for a __file__ attributes on each module in sys.modules, and print
that if it exists.

That won't list builtin modules that are imported - but they don't
have files to be imported, so I assume that the OP doesn't want them
listed.

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


Re: "also" to balance "else" ?

2005-06-13 Thread Ron Adam
Eloff wrote:
> My first reaction was that this is terrible, else clauses on loops are
> confusing enough. But if I think about it more, I'm warming up to the
> idea. Also/Else for loops is clear, symmetrical, and would be useful.
 >
> Reversing the meanign of else will break code, but it's not used that
> frequently, and it was a confusing thing to begin with, nothing wrong
> in breaking something (slowly!) if it was 'broken' to begin with.
> 
> Alifs look evil, I couldn't deduce the control flow very easily, but
> then they are a new idea. I'll keep an open mind on that one.

Yes, it's probably because it's new.  Alifs would be used where you want 
to test for multiple possible values, and need to respond differently 
depending on the values.  They probably wouldn't be used as often as elifs.

alifs is a way to string if's together as a group.  The following would 
be equivalent to if-alif-also-else.

didif = False
if val == condition1:
 didif = True
 BLOCK1
if val == condition2:
 didif = True
 BLOCK2
if val == condition3:
 didif = True
if didif:
 BLOCK3
else:
 BLOCK4


The if-alif-also-else version doesn't need the extra name to mark if any 
of the conditions were true.

if val == condition1:
 BLOCK1
alif val == condition2:
 BLOCK2
alif val == condition3:
 BLOCK3
also:
 BLOCK4
else:
 BLOCK5

But I think we will need to find some real use case's to make it 
convincing.


> I think the best thing would be to compare the also/else syntax to what
> identical functionality looks like in python now [hint to someone with
> more time than me right now ;)]. I'd vote for whichever is the more
> concise and readable of the two.
> 
> -Dan
> 

In cases of if-also,  the equivalent code needs an extra local variable 
and an additional if statement.

iftest = False
if :
 iftest = True
 BLOCK1
elif :
 iftest = True
 BLOCK2
if iftest:
 BLOCK3

This is the pattern that caused me to think of having an also.  I was 
parsing and formatting doc strings at the time, and also would allow it 
to become.

if :
 BLOCK1
elif :
 BLOCK2
also:
 BLOCK3

Which is much easier to read.


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


Re: What is different with Python ?

2005-06-13 Thread D H
Philippe C. Martin wrote:
> Yet for the first time I get (most) of my questions answered by a language I
> did not know 1 year ago.
^^
You're in the Python honeymoon stage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get/set class attributes in Python

2005-06-13 Thread Mike Meyer
Kalle Anke <[EMAIL PROTECTED]> writes:

> On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
> (in article <[EMAIL PROTECTED]>):
>
>> 1) Assume the variables are of a sensible type (not 
>> necessarily the one you expected, though), and provide
>> exception handling to catch the case where their interface
>> does not match what you expect.
>
> The problem I have with this is that I might discover an error at runtime 
> instead of compile time, this means that I need to really exercise all 
> possible test cases to make sure that I've covered everything (which of 
> course is a good thing) but it would be easier to discover this at "compile 
> time".

But static typing only catches *some* of the errors that might
occur. Other errors will occur at run time even with static typing -
so you need to really exercise all possible test cases to make sure
you've covered everything in any case.

> (note: I'm not trying to change Python, only that to me statically typing has 
> it advantages also)

Static typing saves you some time by catching a small subset of
programming errors at compile time. On the other hand, it costs you
time by forcing you to declare a type for - well, everything that
you're going to catch errors for.

It's not clear which cost is larger.

   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: The need to put "self" in every method

2005-06-13 Thread D H
Steve Holden wrote:
> Fernando M. wrote:
> 
>> Hi,
>>
>> i was just wondering about the need to put "self" as the first
>> parameter in every method a class has because, if it's always needed,
>> why the obligation to write it? couldn't it be implicit?
>>
>> Or is it a special reason for this being this way?
>>
>> Thanks.

One reason is because of the dynamic nature of Python classes.  You can 
attach new methods to a class after it is instantiated, or remove 
methods.  The language boo (http://boo.codehaus.org/) has classes 
defined at compile time, and there "self" is not needed at all.  If you 
want to use the duck typing features in boo, however, and re-implement 
python-like dynamic classes that can have methods removed or added at 
any time, then your methods need some kind of "self" parameter so they 
can access the context of their class instance, because really there is 
no special relationship between the methods and the class unless you 
explicitly specify it.

> The reason can be found in the output from the python statement "import 
> this". Explicit is better than implicit.

Like those invisible yet explicit scope indicators, tabs and spaces.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread D H
Peter Hansen wrote:
> With a case statement, on the other hand, you *know* that it must be 
> just simple conditionals (a series of x == some_constant tests), so you 
> don't need to look at all the cases, just the one that interests you.

Since you and Steve Holden agree that a case statement is useful, why 
don't you propose it for python, or add it to the wiki page for Python 3000.

Here is the syntax the developers of your favorite language boo ( 
http://boo.codehaus.org/ ) are using:

given x:
 when 1:
 ...
 when 2:
 ...
 otherwise:
 ...


must-stop-hyphenating-ly y'rs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Mike Meyer
Andrea Griffini <[EMAIL PROTECTED]> writes:
> On Mon, 13 Jun 2005 01:54:53 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:
>>Andrea Griffini <[EMAIL PROTECTED]> writes:
>>I disagree. If you're going to make competent programmers of them,
>>they need to know the *cost* of those details, but not necessarily the
>>actual details themselves. It's enough to know that malloc may lead to
>>a context switch; you don't need to know how malloc actually works.
>
> Unless those words have a real meaning for you then
> you'll forget them... I've seen this a jillion times
> with C++. Unless you really understand how an
> std::vector is implemented you'll end up doing stupid
> things like looping erasing the first element.

But this same logic applies to why you want to teach abstract things
before concrete things. Since you like concrete examples, let's look
at a simple one:

   a = b + c

Now, in a modern OO language (like Python) this can invoke arbitrary
bits of code. In a 70s-era structured language (like C), this will
mean one of a fixed set of things, but you still don't know enough to
say how many abstract operations this statement involves. In a very
few languages (BCPL being one), this means exactly one thing. But
until you know the underlying architecture, you still can't say how
many operations it is.

All of which is so much noise to someone who's just starting
programming. Anything beyond the abstract statement "a gets the result
of adding b to c" is wasted on them. Learning about programming at
that level is complicated enough. After they've mastered that, you can
teach them the concrete details that determine what actually happens,
and how much it costs: things like method lookup (Python), namespace
lookups (Python), operator overloading (C), implicit type conversions
(C and Python), integer overflow (BCPL and C), and floating point
behavior in general (C and Python), register vs. stack architectures,
RISC vs. CISC, caching, and other such things.


> Actually I cannot blame someone for forgetting that
> insert at the beginning is O(n) and at the end is
> amortized O(1) if s/he never understood how a vector
> is implemented and was told to just learn those two
> little facts. Those little facts are obvious and
> can easily be remembered only if you've a conceptual
> model where they fit. If they're just random notions
> then the very day after the C++ exam you'll forget
> everything.

It's true that in some cases, it's easier to remember the
implementation details and work out the cost than to remember the cost
directly. That's also true for abstract things as well.

>>That's the way *your* brain works. I'd not agree that mine works that
>>way. Then again, proving either statement is an interesting
>>proposition.
>
> Are you genuinely saying that abelian groups are
> easier to understand than relative integers ?

Yup. Then again, my formal training is as a mathematician. I *like*
working in the problem space - with the abstact. I tend to design
top-down.

>>The explanation has been stated a number of times: because you're
>>letting them worry about learning how to program, before they worry
>>about learning how to evaluate the cost of a particular
>>construct. Especially since the latter depends on implementation
>>details, which are liable to have to be relearned for every different
>>platform.
>
> You'll get programmers that do not understand how
> their programs work. This unavoidably will be a show
> stopper when their programs will not work (and it's
> when, not if...).
  
The same is true of programmers who started with concrete details on a
different platform - unless they relearn those details for that
platform. The critical things a good programmer knows about those
concrete details is which ones are platform specific and which aren't,
and how to go about learning those details when they go to a new
platform.

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

>>I don't normally ask how people learned to program, but I will observe
>>that most of the CS courses I've been involved with put aside concrete
>>issues - like memory management - until later in the course, when it
>>was taught as part of an OS internals course. The exception would be
>>those who were learning programming as part of an engineering (but not
>>software engineering) curriculum. The least readable code examples
>>almost uniformly came from the latter group.
>
> I suppose that over there who is caught reading
> TAOCP is slammed in jail ...

Those taught the concrete method would never have been exposed to
anything so abstract.

> Placing memory allocation in the "OS internals" course
> is very funny. Let's hope you're just joking.

Actually, it's a natural place to teach the details of that kind of
thing. An

Re: just learning eric ide

2005-06-13 Thread McBooCzech
Try this:
http://www.pycs.net/lateral/stories/16.html
HTH

Petr

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


Re: "also" to balance "else" ?

2005-06-13 Thread Andrew Dalke
Ron Adam wrote:
> It occurred to me (a few weeks ago while trying to find the best way to 
> form a if-elif-else block, that on a very general level, an 'also' 
> statement might be useful.  So I was wondering what others would think 
> of it.

> for x in :
> BLOCK1
> if : break   # do else block
> also:
> BLOCK2
> else:
> BLOCK3


For this specific case you could rewrite the code in
current Python as

for x in :
  BLOCK1
  if :
BLOCK3
break
else:
  BLOCK2

In order for your proposal to be useful you would need an
example more like the following in current Python

for x in :
  ...
  if :
BLOCK3
break
  ...
  if :
BLOCK3
break
else:
  BLOCK2

That is, where "BLOCK3;break" occurs multiple times in
the loop.  My intuition is that that doesn't occur often
enough to need a new syntax to simplify it.

Can you point to some existing code that would be improved
with your also/else?

> while :
>  BLOCK1
>  if : break# jump to else
> also:
>  BLOCK2
> else:
>  BLOCK3
> 
> Here if the while loop ends at the while , the BLOCK2 
> executes,  or if the break is executed, BLOCK3 executes.

which is the same (in current Python) as


while :
  BLOCK1
  if :
BLOCK3
break
else:
  BLOCK2

> In and if statement...
> 
> if :
>  BLOCK1
> elif :
>  BLOCK2
> elif :
>  BLOCK3
> also:
>  BLOCK4
> else:
>  BLOCK5
> 
> Here, the also block would execute if any previous condition is true, 
> else the else block would execute.

That is ... funky.  When is it useful?

One perhaps hackish solution I've done for the rare cases when
I think your proposal is useful is

while 1:
  if :
BLOCK1
  elif :
BLOCK2
  elif :
BLOCK3
  else:
# couldn't do anything
break
  BLOCK4
  break

> I think this gives Pythons general flow control some nice symmetrical 
> and consistent characteristics that seem very appealing to me.  Anyone 
> agree?

No.  Having more ways to do control flow doesn't make for code that's
easy to read.

My usual next step after thinking (or hearing) about a new Python
language change is to look at existing code and see if there's
existing code which would be easier to read/understand and get an
idea if it's a common or rare problem.  Perhaps you could point
out a few examples along those lines?

Andrew
[EMAIL PROTECTED]

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


Re: Is Python Suitable for Large Find & Replace Operations?

2005-06-13 Thread Brian
Hi Rbt,

To give an example of processing a lot of data, I used Python to read 
and process every word in a single text file that contained the entire 
King James Bible version.  It processed it within about one second -- 
split the words, etc.  Worked quite well.

Hope this helps,

Brian
---


rbt wrote:
> Here's the scenario:
> 
> You have many hundred gigabytes of data... possible even a terabyte or 
> two. Within this data, you have private, sensitive information (US 
> social security numbers) about your company's clients. Your company has 
> generated its own unique ID numbers to replace the social security numbers.
> 
> Now, management would like the IT guys to go thru the old data and 
> replace as many SSNs with the new ID numbers as possible. You have a tab 
> delimited txt file that maps the SSNs to the new ID numbers. There are 
> 500,000 of these number pairs. What is the most efficient way  to 
> approach this? I have done small-scale find and replace programs before, 
> but the scale of this is larger than what I'm accustomed to.
> 
> Any suggestions on how to approach this are much appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching for IDE

2005-06-13 Thread Steve Holden
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...
> 
Wing IDE gives you a completion drop-down whenever it can. You can try 
the tool out with a free download from www.wingware.com if you want, and 
both personal and full licenses are available.

regards
  Steve
-- 
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/

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


Re: Is Python Suitable for Large Find & Replace Operations?

2005-06-13 Thread John Machin
rbt wrote:
> Here's the scenario:
> 
> You have many hundred gigabytes of data... possible even a terabyte or 
> two. Within this data, you have private, sensitive information (US 
> social security numbers) about your company's clients. Your company has 
> generated its own unique ID numbers to replace the social security numbers.
> 
> Now, management would like the IT guys to go thru the old data and 
> replace as many SSNs with the new ID numbers as possible.

This question is grossly OT; it's nothing at all to do with Python. 
However 

(0) Is this homework?

(1) What to do with an SSN that's not in the map?

(2) How will a user of the system tell the difference between "new ID 
numbers" and SSNs?

(3) Has the company really been using the SSN as a customer ID instead 
of an account number, or have they been merely recording the SSN as a 
data item? Will the "new ID numbers" be used in communication with the 
clients? Will they be advised of the new numbers? How will you handle 
the inevitable cases where the advice doesn't get through?

(4) Under what circumstances will it not be possible to replace *ALL* 
the SSNs?

(5) For how long can the data be off-line while it's being transformed?


> You have a tab 
> delimited txt file that maps the SSNs to the new ID numbers. There are 
> 500,000 of these number pairs.

And what is the source of the SSNs in this file??? Have they been 
extracted from the data? How?

> What is the most efficient way  to 
> approach this? I have done small-scale find and replace programs before, 
> but the scale of this is larger than what I'm accustomed to.
> 
> Any suggestions on how to approach this are much appreciated.

A sensible answer will depend on how the data is structured:

1. If it's in a database with tables some of which have a column for 
SSN, then there's a solution involving SQL.

2. If it's in semi-free-text files where the SSNs are marked somehow:

---client header---
surname: Doe first: John initial: Q SSN:123456789 blah blah
or
123456789

then there's another solution which involves finding the markers ...

3. If it's really free text, like
"""
File note: Today John Q. Doe telephoned to advise that his Social 
Security # is 123456789  not 987654321 (which is his wife's) and the soc 
sec numbers of his kids Bob & Carol are 
"""
then you might be in some difficulty ... google("TREC")


AND however you do it, you need to be very aware of the possibility 
(especially with really free text) of changing some string of digits 
that's NOT an SSN.

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


Re: Going crazy...

2005-06-13 Thread Irmen de Jong
Jan Danielsson wrote:
> Hello all,
> 
>I'm 100% sure that I saw an example which looked something like this
> recently:
> 
> 
a=(1, 2, 3, 4, 5, 6)
b=(2, 3, 6)
a - b
> 
> (1, 4, 5)
> 
>The only new language I have been involved in lately is Python. Is my
> memory failing me, or have I seen such an Python-example somewhere? If
> so: Where; or more importantly: How does it work?
> 
>I just tried typing the above in Python, and it - obviously - doesn't
> work, so it must be some other syntax.

Try sets:

 >>> a=set([1,2,3,4,5,6])
 >>> b=set([2,3,6])
 >>> a-b
set([1, 4, 5])
 >>>

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


Re: Going crazy...

2005-06-13 Thread Chinook
On Mon, 13 Jun 2005 20:52:43 -0400, Gary Herron wrote
(in article <[EMAIL PROTECTED]>):

> Jan Danielsson wrote:
> 
>> Hello all,
>> 
>> I'm 100% sure that I saw an example which looked something like this
>> recently:
>> 
>> 
>> 
> a=(1, 2, 3, 4, 5, 6)
> b=(2, 3, 6)
> a - b
> 
> 
>> (1, 4, 5)
>> 
>> The only new language I have been involved in lately is Python. Is my
>> memory failing me, or have I seen such an Python-example somewhere? If
>> so: Where; or more importantly: How does it work?
>> 
>> I just tried typing the above in Python, and it - obviously - doesn't
>> work, so it must be some other syntax.
>> 
>> 
>  Not with tuples, lists or dictionaries.  However a more recent addition 
> to the language is Sets, and they support set differences:
> 
>  >>> from sets import Set
>  >>> Set([1,2,3,4,5,6]) - Set([2,3,6])
> Set([1, 4, 5])
> 
> 
> Gary Herron
> 
> 

Looks like something that might be part of an example of class operator 
overloading???  But I'm not far enough along to quickly show a sample if such 
is possible.  

Lee C


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


Re: implicit variable declaration and access

2005-06-13 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Ali Razavi  <[EMAIL PROTECTED]> wrote:
>Tom Anderson wrote:
>> On Mon, 13 Jun 2005, Ali Razavi wrote:
>> 
>>> Is there any reflective facility in python that I can use to define a 
>>> variable with a name stored in another variable ?
.
.
.
>> Are you absolutely sure you want to do this?
>> 
>> tom
>> 
>Have you ever heard of meta programming ?
>I guess if you had, it wouldn't seem this odd to you.

Mr. Razavi, Python has explicit idioms for metaprogramming that
most experienced Pythoneers favor over name-reflection.  http://blog.ianbicking.org/python-metaprogramming-and-macros.html?version=1 >
is only one of several useful write-ups on the subject.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32evtlog

2005-06-13 Thread J Correia

<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Doh! I didn't think to look in the demo directory. Silly me.
>


http://www.win32com.de/index.php?option=com_content&task=view&id=163&Itemid=189


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


Re: Controlling a generator the pythonic way

2005-06-13 Thread Thomas Lotze
Thomas Lotze wrote:

> I'm trying to figure out what is the most pythonic way to interact with a
> generator.

JFTR, so you don't think I'd suddenly lost interest: I won't be able to
respond for a couple of days because I've just incurred a nice little
hospital session... will be back next week.

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


Re: What is different with Python ?

2005-06-13 Thread Andrea Griffini
On Mon, 13 Jun 2005 22:23:39 +0200, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

>Being familiar with 
>fondamental *programming* concepts like vars, branching, looping and 
>functions proved to be helpful when learning C, since I only had then to 
>focus on pointers and memory management.

If you're a good programmer (no idea, I don't know
you and you avoided the issue) then I think you
wasted a lot of energy and neurons learning that way.
Even high-level scripting languages are quite far
from a perfect virtualization, and either the code
you wrote in them was terrible *OR* you were able
to memorize an impressive quantity of black magic
details (or you were just incredibly lucky ;-) ).

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


Re: What is different with Python ?

2005-06-13 Thread Andrea Griffini
On Mon, 13 Jun 2005 01:54:53 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Andrea Griffini <[EMAIL PROTECTED]> writes:
>>>In short, you're going to start in the middle.
>>
>> I've got "bad" news for you. You're always in the
>> middle :-D.
>
>That's what I just said.

Yeah. I should stop replying before breakfast.

>I disagree. If you're going to make competent programmers of them,
>they need to know the *cost* of those details, but not necessarily the
>actual details themselves. It's enough to know that malloc may lead to
>a context switch; you don't need to know how malloc actually works.

Unless those words have a real meaning for you then
you'll forget them... I've seen this a jillion times
with C++. Unless you really understand how an
std::vector is implemented you'll end up doing stupid
things like looping erasing the first element.

Actually I cannot blame someone for forgetting that
insert at the beginning is O(n) and at the end is
amortized O(1) if s/he never understood how a vector
is implemented and was told to just learn those two
little facts. Those little facts are obvious and
can easily be remembered only if you've a conceptual
model where they fit. If they're just random notions
then the very day after the C++ exam you'll forget
everything.

>That's the way *your* brain works. I'd not agree that mine works that
>way. Then again, proving either statement is an interesting
>proposition.

Are you genuinely saying that abelian groups are
easier to understand than relative integers ?

>The explanation has been stated a number of times: because you're
>letting them worry about learning how to program, before they worry
>about learning how to evaluate the cost of a particular
>construct. Especially since the latter depends on implementation
>details, which are liable to have to be relearned for every different
>platform.

You'll get programmers that do not understand how
their programs work. This unavoidably will be a show
stopper when their programs will not work (and it's
when, not if...).

>I don't normally ask how people learned to program, but I will observe
>that most of the CS courses I've been involved with put aside concrete
>issues - like memory management - until later in the course, when it
>was taught as part of an OS internals course. The exception would be
>those who were learning programming as part of an engineering (but not
>software engineering) curriculum. The least readable code examples
>almost uniformly came from the latter group.

I suppose that over there who is caught reading
TAOCP is slammed in jail ...

Placing memory allocation in the "OS internals" course
is very funny. Let's hope you're just joking.

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


Re: Going crazy...

2005-06-13 Thread Gary Herron
Jan Danielsson wrote:

>Hello all,
>
>   I'm 100% sure that I saw an example which looked something like this
>recently:
>
>  
>
a=(1, 2, 3, 4, 5, 6)
b=(2, 3, 6)
a - b


>(1, 4, 5)
>
>   The only new language I have been involved in lately is Python. Is my
>memory failing me, or have I seen such an Python-example somewhere? If
>so: Where; or more importantly: How does it work?
>
>   I just tried typing the above in Python, and it - obviously - doesn't
>work, so it must be some other syntax.
>  
>
 Not with tuples, lists or dictionaries.  However a more recent addition 
to the language is Sets, and they support set differences:

 >>> from sets import Set
 >>> Set([1,2,3,4,5,6]) - Set([2,3,6])
Set([1, 4, 5])


Gary Herron

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


Re: win32evtlog

2005-06-13 Thread sigzero
Doh! I didn't think to look in the demo directory. Silly me.

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


Going crazy...

2005-06-13 Thread Jan Danielsson
Hello all,

   I'm 100% sure that I saw an example which looked something like this
recently:

>>> a=(1, 2, 3, 4, 5, 6)
>>> b=(2, 3, 6)
>>> a - b
(1, 4, 5)

   The only new language I have been involved in lately is Python. Is my
memory failing me, or have I seen such an Python-example somewhere? If
so: Where; or more importantly: How does it work?

   I just tried typing the above in Python, and it - obviously - doesn't
work, so it must be some other syntax.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32evtlog

2005-06-13 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> Is anyone versed in pulling out information from the Windows (2000)
> event log? I have looked at the docs and I am in the dark as to how to
> do it. Do what? I am looking to pull out all events with "error" as the
> type.

Generally there are a few things you can do to help yourself with such 
things.  There are some samples of win32 stuff in the win32all package, 
in the "Demos" directories.  It's possible there is some support for 
that already.

Google can also help you search the list archives to find whether others 
have asked this question in the past, as is almost always the case. 
Usually it helps to know the name of either the relevant module from the 
win32all package, or the relevant Win32 API which you can often get from 
the msdn.com site if you don't already know it.

Finally, Googling the web instead of the newsgroup will often work very 
nicely.  The best approach is to start with the subject line you are 
about to use for your posting plus the word Python (e.g. "python 
win32evtlog").  Let us know what you find out!

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


Re: "also" to balance "else" ?

2005-06-13 Thread Eloff
My first reaction was that this is terrible, else clauses on loops are
confusing enough. But if I think about it more, I'm warming up to the
idea. Also/Else for loops is clear, symmetrical, and would be useful.

Reversing the meanign of else will break code, but it's not used that
frequently, and it was a confusing thing to begin with, nothing wrong
in breaking something (slowly!) if it was 'broken' to begin with.

Alifs look evil, I couldn't deduce the control flow very easily, but
then they are a new idea. I'll keep an open mind on that one.

I think the best thing would be to compare the also/else syntax to what
identical functionality looks like in python now [hint to someone with
more time than me right now ;)]. I'd vote for whichever is the more
concise and readable of the two.

-Dan

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


Re: \r\n or \n notepad editor end line ???

2005-06-13 Thread Peter Hansen
Steven D'Aprano wrote:
> So going back to the original question... if I open in "r" mode a text
> file which was created under Windows, I will get \r characters in the
> text and have to deal with them regardless of what platform I am running
> Python under. Correct?

Almost, but the way you phrased that makes it incorrect in at least one 
case.  I suspect you are clear on the actual situation now, but just to 
correct your wording: you will get \r characters and have to deal with 
them on any platform which does *not* use \r\n for its line endings. 
(Under Windows, of course, you won't have to deal with them at all.)

> If I use "rU" mode Python suppress the \r characters. When I write a
> string back, I'm responsible for making sure the EOL markers are correct
> for whatever platform I expect the file to be read under. Unless Python
> can somehow magically read my mind and know that even though I'm writing
> the file under Linux it will be read later under Windows. Am I close?

Python can't magically read your mind, although if you manage to steal 
the time machine (in the future) you could always just come back and fix 
the files as they are written, and you (in present time) would *think* 
that Python had magically read your mind...

A few more trinkets: some programs on Windows will work just fine even 
if they encounter files with only \n line endings.  Decent text editors 
will either adapt or let you specify what line ending should be 
expected.  Trying always to work with only \n line endings in files you 
write will help us move towards the day when we can obliterate the 
abomination that is \r\n so try it out and use "rU" to read, "w" to 
write on Linux if that works in your case.

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


Re: What is different with Python ?

2005-06-13 Thread Andrea Griffini
On Mon, 13 Jun 2005 13:35:00 +0200, Peter Maas <[EMAIL PROTECTED]>
wrote:

>I think Peter is right. Proceeding top-down is the natural way of
>learning.

Depends if you wanna build or investigate.

To build top down is the wrong approach (basically because
there's no top). Top down is however great for *explaining*
what you already built or know.

>(first learn about plants, then proceed to cells, molecules,
>atoms and elementary particles).

This is investigating. Programming is more similar to building
instead (with a very few exceptions). CS is not like physics or
chemistry or biology where you're given a result (the world)
and you're looking for the unknown laws. In programming *we*
are building the world. This is a huge fundamental difference!

>If you learn a computer language you have to know about variables,
>of course.

There are no user defined variables in assembler.
Registers of a CPU or of a programmable calculator
are easier to understand because they're objectively
simpler concepts. Even things like locality of scope
will be appreciated and understood better once you
try to live with just a global scope for a while.

>The concepts of memory, data and addresses can easily be demonstrated
>in high level languages including python e.g. by using a large string
>as a memory model. Proceeding to bare metal will follow driven by
>curiosity.

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

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


Re: What is different with Python ?

2005-06-13 Thread Roy Smith
Andrea Griffini <[EMAIL PROTECTED]> wrote:
> Hehehe... a large python string is a nice idea for modelling
> memory.

Actually, a Python string is only good for modelling ROM.  If you want to 
model read-write memory, you need a Python list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: \r\n or \n notepad editor end line ???

2005-06-13 Thread John Machin
Steven D'Aprano wrote:
> On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote:
> 
> 
>><[EMAIL PROTECTED]> wrote:
>>
>>
>>>It means in windows we should use 'wb' to write and 'rb' to read ?
>>>Am I right?
>>
>>no.
>>
>>you should use "wb" to write *binary* files, and "rb" to read *binary*
>>files.
>>
>>if you're working with *text* files (that is, files that contain lines of text
>>separated by line separators), you should use "w" and "r" instead, and
>>treat a single "\n" as the line separator.
> 
> 
> I get nervous when I read instructions like this. It sounds too much like
> voodoo: "Do this, because it works, never mind how or under what
> circumstances, just obey or the Things From The Dungeon Dimensions will
> suck out your brain!!!"
> 
> Sorry Fredrik :-)
> 

Many people don't appear to want to know why; they only want a solution 
to what they perceive to be their current problem.

> When you read a Windows text file using "r" mode, what happens to the \r
> immediately before the newline?

The thing to which you refer is not a "newline". It is an ASCII LF 
character. The CR and the LF together are the physical representation 
(in a Windows text file) of the logical "newline" concept.

Internally, LF is used (irrespective of platform) to represent that concept.

> Do you have to handle it yourself? 

No.

> Or will
> Python cleverly suppress it so you don't have to worry about it?

Suppressed: no, it's a transformation from a physical line termination 
representation to a logical one. Cleverly: matter of opinion. By Python: 
In general, no -- the transformation is handled by the underlying C 
run-time library.

> 
> And when you write a text file under Python using "w" mode, will the
> people who come along afterwards to edit the file in Notepad curse your
> name?

If they do, it will not be because other than CRLF has been written as a 
line terminator.

> Notepad expects \r\n EOL characters, and gets cranky if the \r is
> missing.

AFAIR, it performs well enough for a text editor presented with a file 
consisting of one long unterminated line with occasional embedded 
meaningless-to-the-editor control characters. You can scroll it, edit 
it, write it out again ... any crankiness is likely to be between the 
keyboard and the chair :-)

> 
> How does this behaviour differ from "universal newlines"?
> 

Ordinary behaviour in text mode:

Win: \r\n -> newline -> \r\n
Mac OS X < 10: \r -> newline -> \r
other box: \n -> newline -> \n

Note : TFM does appear a little light on in this area. I suppose not all 
users of Python have aquired this knowledge by osmosis through decades 
of usage of C on multiple platforms :-)

"Universal newlines":
On *any* box: \r\n or \n or \r (even a mixture) -> \n on reading
On writing, behaviour is "ordinary" i.e. the line terminator is what is 
expected by the current platform

"Universal newlines" (if used) solves problems like where an other-boxer 
FTPs a Windows text file in binary mode and then posts laments about all 
those ^M things on the vi screen and :1,$s/^M//g doesn't work :-)

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


Re: Get drives and partitions list (Linux)

2005-06-13 Thread Peter Hansen
cantabile wrote:
> Hi, Peter
> Thanks for the reply. I'll check popen().
> But you said I should not rely on fdisk... Why ? And should I prefer
> sfdisk ? Why ?

I was under the impression that fdisk was older and more primitive, but 
a quick check shows I'm probably not only wrong, but had it backwards! 
(The man page for fdisk says "try parted, then fdisk, then sfdisk" 
basically...)

Also, as you saw in Jeff's reply, there's a commands.getoutput() 
function that does basically what popen() would do, so just use whatever 
seems simplest.

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


just learning eric ide

2005-06-13 Thread David Bear
Eric is the first IDE I have used since the borland c++ ide for dos many
many years ago. Aside from the docs that come in the help system, I'm
looking for a quick tutorial that gives me an overview of the test, debug
cycle that is considered -- for beginners.

any pointers or books. This seems like a terrific environment.
-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: implicit variable declaration and access

2005-06-13 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Peter Dembinski  <[EMAIL PROTECTED]> wrote:
>Benji York <[EMAIL PROTECTED]> writes:
>
>[snap]
>
>>> code = x + '= 0'
>>> exec(code)
>>
>> You should generally stay away from exec for lots of reasons.
>
>Code 'refactorizability' is one of them.

There's an affirmative way to express this that I can't now make
the time to generate.  Yes, you're both right that, as popular as
some make out such coding is in Lisp (and Perl and PHP), the per-
ception that there's a need for it generally indicates there's a
cleaner algorithm somewhere in the neighborhood.  In general,
"application-level" programming doesn't need exec() and such.

PyPy and debugger writers and you other "systems" programmers 
already know who you are.

My own view is that refactorizability is one of the secondary
arguments in this regard.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Andrea Griffini
On Mon, 13 Jun 2005 09:22:55 +0200, Andreas Kostyrka
<[EMAIL PROTECTED]> wrote:

>Yep. Probably. Without a basic understanding of hardware design, one cannot
>many of todays artifacts: Like longer pipelines and what does this
>mean to the relative performance of different solutions.

I think that pipeline stalls, CPU/FPU parallel computations
and cache access optimization is the lowest level I ever
had to swim in (it was when I was working in the videogame
industry, on software 3D rendering with early pentiums).
Something simpler but somewhat similar was writing on
floppy disks on the Apple ][ where there was no timer
at all in the computer excluding the CPU clock and the
code for writing was required to output a new nibble for
the writing latch exactly every 40 CPU cycles (on the
Apple ][ the CPU was doing everything, including
controlling the stepper motor for disk seek).

However I do not think that going this low (that's is still
IMO just a bit below assembler and still quite higher than
HW design) is very common for programmers.

>Or how does one explain that a "stupid and slow" algorithm can be in
>effect faster than a "clever and fast" algorithm, without explaining
>how a cache works. And what kinds of caches there are. (I've seen
>documented cases where a stupid search was faster because all hot data
>fit into the L1 cache of the CPU, while more clever algorithms where
>slower).

Caching is indeed very important, and sometimes the difference
is huge. I think anyway that it's probably something confined
in a few cases (processing big quantity of data with simple
algorithms, e.g. pixel processing).
It's also a field where if you care about the details the
specific architecture plays an important role, and anything
you learned about say the Pentium III could be completely
pointless on the Pentium 4.

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

>Or you get perfect abstract designs, that are horrible when
>implemented.

Current trend is that you don't even need to do a
clear design. Just draw some bubbles and arrows on
a white board with a marker, throw in some buzzword
and presto! you basically completed the new killing app.
Real design and implementation are minutiae for bozos.

Even the mighty python is incredibly less productive
than powerpoint ;-)

>Yes. But for example to understand the memory behaviour of Python
>understanding C + malloc + OS APIs involved is helpful.

This is a key issue. If you've the basis firmly placed
most of what follows will be obvious. If someone tells
you that inserting an element at the beginning of an array
is O(n) in the number of elements then you think "uh... ok,
sounds reasonable", if they say that it's amortized O(1)
instead then you say "wow..." and after some thinking
"ok, i think i understand how it could be done" and in
both cases you'll remember it. It's a clear *concrete* fact
that I think just cannot be forgot.

If O(1) and O(n) and how dynamic arrays could be possibly
be implemented is just black magic and a few words in a
text for you then IMO you'll never be able to remember
what that implies, and you'll do soon or late something
really really stupid about it in your programs.

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


"also" to balance "else" ?

2005-06-13 Thread Ron Adam

There seems to be a fair amount of discussion concerning flow control 
enhancements lately.  with, do and dowhile, case,  etc...  So here's my 
flow control suggestion.  ;-)


It occurred to me (a few weeks ago while trying to find the best way to 
form a if-elif-else block, that on a very general level, an 'also' 
statement might be useful.  So I was wondering what others would think 
of it.

'also' would be the opposite of 'else' in meaning.  And in the case of a 
for-else...  would correct what I believe to be an inconsistency. 
Currently the else block in a for loop gets executed if the loop is 
completed, which seems backwards to me.  I would expect the else to 
complete if the loop was broken out of.  That seems more constant with 
if's else block executing when if's condition is false.


'also' would work like this.

for x in :
BLOCK1
if : break   # do else block
also:
BLOCK2
else:
BLOCK3

where the also block is executed if the loop completes (as the current 
else does), and the else block is executed if it doesn't.


while :
 BLOCK1
 if : break# jump to else
also:
 BLOCK2
else:
 BLOCK3

Here if the while loop ends at the while , the BLOCK2 
executes,  or if the break is executed, BLOCK3 executes.


In and if statement...

if :
 BLOCK1
elif :
 BLOCK2
elif :
 BLOCK3
also:
 BLOCK4
else:
 BLOCK5

Here, the also block would execute if any previous condition is true, 
else the else block would execute.


And 'tentatively', there is the possible 'alif', (also-if), to be 
used this way.

if :
 BLOCK1
alif :
 BLOCK2
 break # skip to also block
alif :
 BLOCK3
alif :
 BLOCK4
also: # at lease one condition was true
 BLOCK5
else: # no conditions evaluated as true
 BLOCK6

Where only one elif will ever evaluate as true, any or all 'alif's could 
evaluate as true.  This works similar to some case statements except all 
alif conditions may be evaluated.  Not a true case statement, but a good 
replacement where speed isn't the main concern?

I'm not sure if 'elif's and 'alif's could or should be used together? 
Maybe a precedence rule would be needed.  Or simple that all also's and 
alif's must precede any elif's.  Then again maybe alif's between elif's 
could be useful?  For example the alif  could be and 'elif' 
instead, so the break above would't be needed.

'also' can be used without the else in the above examples, and of course 
the 'else' doesn't need an 'also'.

I think this gives Pythons general flow control some nice symmetrical 
and consistent characteristics that seem very appealing to me.  Anyone 
agree?

Any reason why this would be a bad idea?  Is there an equivalent to an 
also in any other language?  (I haven't seen it before.)

Changing the for-else is probably a problem...  This might be a 3.0 wish 
list item because of that.

Is alif too simular to elif?

On the plus side, I think this contributes to the pseudocode character 
of Python very well.

Cheers, Ron

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


reading a python file object in c extension crashes python

2005-06-13 Thread travis ray
Hi,

I have an extension in which a file object is created in python and
passed down to a c extension which attempts to read from it or write
to it.  Writing to the file pointer seems to work okay, but reading
from it results in EBADF.  It also causes python to crash on exit.

I've attached the minimal (I think) c code, python code, build script,
build log, and run log.  Any and all help is greatly appreciated.

Thanks.

System: Win-XP Professional
Compiler: Vc7 (MSVS 2003)
Python: Python 2.4.1
Builder: SCons 0.96.1

P.S. Sorry for including everything in one message.  I keep getting
bounced when I attach them.


###  file:my_module.c -

#include 
#define MAXLEN 128

int 
my_read(char *buffer, int max, FILE *fp)
{   
int n = 0;
fprintf (stdout, "[c] pre-read: errno=%d, fp=%x\n", errno, fp);
n = fread(buffer, 1, max, fp);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d,
data='%s'\n", errno, fp, n, buffer);
return n;
}

int 
my_write(const char *buffer, FILE *fp)
{   
int n = 0;
fprintf (stdout, "[c] pre-write: errno=%d, fp=%x, data='%s'\n", 
errno, fp, buffer);
n = fprintf(fp, "%s", buffer);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d\n", 
errno, fp, n);
return n;
}

static PyObject *
my_module_my_read(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int  count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;

memset((void*)&(buffer),0,sizeof(char)*MAXLEN);

if (!PyArg_ParseTuple(args, "O", &py_file))
return NULL;

if (PyFile_Check(py_file))
{

count = my_read((char*)&(buffer), MAXLEN, PyFile_AsFile(py_file));
return Py_BuildValue("(is)", count, (char*)buffer);
}
return NULL;
}

static PyObject *
my_module_my_write(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int  count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;
const char* py_string;

memset((void*)&(buffer),0,sizeof(char)*MAXLEN);

if (!PyArg_ParseTuple(args, "sO", &py_string, &py_file))
return NULL;

if ((PyFile_Check(py_file)) && (py_string != NULL))
{
count = my_write(py_string, PyFile_AsFile(py_file));
return Py_BuildValue("i", count);
}
return NULL;
}

static PyMethodDef MyModuleMethods[] = {
{"my_read",  my_module_my_read,  METH_VARARGS, 
"read at most 128 bytes from a file"},
{"my_write", my_module_my_write, METH_VARARGS, 
"write a string to a file"},
{NULL,NULL,0,NULL}
};

PyMODINIT_FUNC
initmy_module(void)
{
PyObject *m;
m = Py_InitModule("my_module", MyModuleMethods);
}


### file: my_module.py 

import my_module

filename = "hello.txt"
fp1 = open(filename, "wb")
print "[py] pre-write: fp=%s" % (fp1)
result1 = my_module.my_write("Hello, World!", fp1)
print "[py] result=", result1
fp1.close()

fp2 = open(filename, "rb")
print "[py] pre-read: fp=%s" % (fp2)
result2 = my_module.my_read(fp2)
print "[py] result=", result2
#fp2.close() 
# crashes python here EBADF when fp2.close() is called
print "done"
# crashes python here when fp2.close() is commented out



### file: Sconstruct --
env = Environment()
import os

python_include_path = os.path.join(os.path.sep,'Python24','include')
python_lib_path = os.path.join(os.path.sep,'Python24','libs')
python_libs = 'python24'
my_module_name = 'my_module'
my_module_sources = 'my_module.c'

library = env.SharedLibrary(my_module_name,
my_module_sources,
CPPPATH=[python_include_path],
LIBPATH=[python_lib_path],
LIBS=[python_libs])


### file: build.log ---
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
cl /nologo /I\Python24\include /c my_module.c /Fomy_module.obj
my_module.c
link /nologo /dll /out:my_module.dll /implib:my_module.lib
/LIBPATH:\Python24\libs python24.lib my_module.obj
   Creating library my_module.lib and object my_module.exp
scons: done building targets.


### file: run.log -
[py] pre-write: fp=
[c] pre-write: errno=0, fp=7c38b548, data='Hello, World!'
[c] post-write: errno=0, fp=7c38b548, count=13
[py] result= 13
[py] pre-read: fp=
[c] pre-read: errno=0, fp=7c38b548
[c] post-write: errno=9, fp=7c38b548, count=0, data=''
[py] result= (0, '')
done
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Andrew Dalke
Peter Maas wrote:
> I think Peter is right. Proceeding top-down is the natural way of
> learning (first learn about plants, then proceed to cells, molecules,
> atoms and elementary particles).

Why in the world is that way "natural"?  I could see how biology
could start from molecular biology - how hereditary and self-regulating
systems work at the simplest level - and using that as the scaffolding
to describe how cells and multi-cellular systems work.

Plant biology was my least favorite part of my biology classes.  In
general I didn't like the "learn the names of all these parts" approach
of biology.  Physics, with its more directly predictive view of the world,
was much more interesting.  It wasn't until college when I read some
Stephen J. Gould books that I began to understand that biology was
different than "'the mitochondria is the powerhouse of the cell', here's
the gall bladder, that plant's a dicot, this is a fossilized trilobite."

Similarly, programming is about developing algorithmic thought.
A beginner oriented programming language should focus on that, and
minimize the other details.

Restating my belief in a homologous line: proceeding from simple to
detailed is the most appropriate way of learning.  Of course in some
fields even the simplest form takes a long time to understand, but
programming isn't string theory.

Andrew
[EMAIL PROTECTED]

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


win32evtlog

2005-06-13 Thread sigzero
Is anyone versed in pulling out information from the Windows (2000)
event log? I have looked at the docs and I am in the dark as to how to
do it. Do what? I am looking to pull out all events with "error" as the
type.

Robert

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


reading a python file object in c extension crashes python

2005-06-13 Thread travis ray
Hi,

I have an extension in which a file object is created in python and
passed down to a c extension which attempts to read from it or write
to it.  Writing to the file pointer seems to work okay, but reading
from it results in EBADF and causes python to crash on exit.

I've attached the minimal (I think) c code, python code, build script,
build log, and run log.  Any and all help is greatly appreciated.

Thanks.

System: Win-XP Professional
Compiler: Vc7 (MSVS 2003)
Python: Python 2.4.1
Builder: SCons 0.96.1

#include 
#define MAXLEN 128

int 
my_read(char *buffer, int max, FILE *fp)
{   
int n = 0;
fprintf (stdout, "[c] pre-read: errno=%d, fp=%x\n", errno, fp);
n = fread(buffer, 1, max, fp);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d, data='%s'\n", 
errno, fp, n, buffer);
return n;
}

int 
my_write(const char *buffer, FILE *fp)
{   
int n = 0;
fprintf (stdout, "[c] pre-write: errno=%d, fp=%x, data='%s'\n", errno, fp, 
buffer);
n = fprintf(fp, "%s", buffer);
fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d\n", errno, fp, 
n);
return n;
}

static PyObject *
my_module_my_read(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int  count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;

memset((void*)&(buffer),0,sizeof(char)*MAXLEN);

if (!PyArg_ParseTuple(args, "O", &py_file))
return NULL;

if (PyFile_Check(py_file))
{

/*count = my_read((char*)&(buffer), MAXLEN, PyFile_AsFile(py_file));*/
count = my_read((char*)&(buffer), MAXLEN, ((PyFileObject 
*)py_file)->f_fp);
return Py_BuildValue("(is)", count, (char*)buffer);
}
return NULL;
}

static PyObject *
my_module_my_write(PyObject *self, PyObject *args)
{
char buffer[MAXLEN];
int  count = 0;
FILE *fp = NULL;
PyObject* py_file = NULL;
const char* py_string;

memset((void*)&(buffer),0,sizeof(char)*MAXLEN);

if (!PyArg_ParseTuple(args, "sO", &py_string, &py_file))
return NULL;

if ((PyFile_Check(py_file)) && (py_string != NULL))
{
count = my_write(py_string, PyFile_AsFile(py_file));
return Py_BuildValue("i", count);
}
return NULL;
}

static PyMethodDef MyModuleMethods[] = {
{"my_read",  my_module_my_read,  METH_VARARGS, "read at most 128 bytes from 
a file"},
{"my_write", my_module_my_write, METH_VARARGS, "write a string to a file"},
{NULL,NULL,0,NULL}
};

PyMODINIT_FUNC
initmy_module(void)
{
PyObject *m;
m = Py_InitModule("my_module", MyModuleMethods);
}

import my_module

filename = "hello.txt"
fp1 = open(filename, "wb")
print "[py] pre-write: fp=%s" % (fp1)
result1 = my_module.my_write("Hello, World!", fp1)
print "[py] result=", result1
fp1.close()

fp2 = open(filename, "rb")
print "[py] pre-read: fp=%s" % (fp2)
result2 = my_module.my_read(fp2)
print "[py] result=", result2
#fp2.close() # <- crashes python here (probably because of EBADF)
print "done"
# <- crashes python here when fp2.close() is commented out

SConstruct
Description: Binary data


build.log
Description: Binary data


run.log
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: \r\n or \n notepad editor end line ???

2005-06-13 Thread Steven D'Aprano
On Mon, 13 Jun 2005 10:52:52 -0400, Peter Hansen wrote:

> Steven D'Aprano wrote:
>> When you read a Windows text file using "r" mode, what happens to the \r
>> immediately before the newline? Do you have to handle it yourself? Or will
>> Python cleverly suppress it so you don't have to worry about it?
>> 
>> And when you write a text file under Python using "w" mode, will the
>> people who come along afterwards to edit the file in Notepad curse your
>> name? Notepad expects \r\n EOL characters, and gets cranky if the \r is
>> missing.
> 
> This is Python.  Fire up the interactive interpreter and try it out!  It 
> will take all of two or three minutes...

Which I would have done, except see comment below:

>> How does this behaviour differ from "universal newlines"?
> 
> If you open a text file created with a different line-ending convention 
> than that used on your own platform, you may get "interesting" results. 

I'm using Linux, not Windows. Of course I *could* try to fake reading and
writing Windows files from Linux, but that would require me actually
understanding how Python deals with line endings across the platforms in
order to generate them in the first place. But if I understood it, I
wouldn't have needed to ask the question.

And I would still be none the wiser about Python's behaviour when running
under Windows -- that's hard to fake on a Linux box.

>   If you use "rU" instead, you will receive only \n line endings and not
> have anything to worry about.  (For example, reading a Windows text file
> on Linux will give you lines that have \r\n endings in them... not what
> you really want.  Using "rU" will give you just \n line endings whether
> you are on Linux or Windows.)

So going back to the original question... if I open in "r" mode a text
file which was created under Windows, I will get \r characters in the
text and have to deal with them regardless of what platform I am running
Python under. Correct?

If I use "rU" mode Python suppress the \r characters. When I write a
string back, I'm responsible for making sure the EOL markers are correct
for whatever platform I expect the file to be read under. Unless Python
can somehow magically read my mind and know that even though I'm writing
the file under Linux it will be read later under Windows. Am I close?


(Ew, I hate cross-platform issues. They make my head hurt.)


-- 
Steve.

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


Re: \r\n or \n notepad editor end line ???

2005-06-13 Thread Terry Hancock
On Monday 13 June 2005 09:34 am, Steven D'Aprano wrote:
> On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote:
> > <[EMAIL PROTECTED]> wrote:
> >> It means in windows we should use 'wb' to write and 'rb' to read ?
> >> Am I right?
> > no.
> > you should use "wb" to write *binary* files, and "rb" to read *binary*
> > files.
> > 
> > if you're working with *text* files (that is, files that contain lines of 
> > text
> > separated by line separators), you should use "w" and "r" instead, and
> > treat a single "\n" as the line separator.
> 
> I get nervous when I read instructions like this. It sounds too much like
> voodoo: "Do this, because it works, never mind how or under what
> circumstances, just obey or the Things From The Dungeon Dimensions will
> suck out your brain!!!"

Actually, it's very simple. It just means that '\n' in memory maps to '\r\n' on
disk, and vice-versa.  So long as you remain on Windows (or MS-DOS for
that matter).

> When you read a Windows text file using "r" mode, what happens to the \r
> immediately before the newline? Do you have to handle it yourself? Or will
> Python cleverly suppress it so you don't have to worry about it?

'\n' in memory, '\r\n' on disk.

Do the same thing on a Linux or Unix system, and it's

'\n' in memory, '\n' on disk

and on the Mac:

'\n' in memory, '\r' on disk

> And when you write a text file under Python using "w" mode, will the
> people who come along afterwards to edit the file in Notepad curse your
> name? Notepad expects \r\n EOL characters, and gets cranky if the \r is
> missing.

No, all will be well.  So long as you use 'r' (or 'rt' to be explicit) and 'w'
(or 'wt').

Only use 'rb' and 'wb' if you want to make sure that what is on disk is
literally the same as what is in memory.  If you write text files this way
in Python, you will get '\n' line endings.

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

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


Re: implicit variable declaration and access

2005-06-13 Thread Steven D'Aprano
On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote:

> Is there any reflective facility in python
> that I can use to define a variable with a
> name stored in another variable ?
> like I have :
> x = "myVarName"
> 
> what can I do to declare a new variable with the name of the string
> stored in x. And how can I access that implicitly later ?

Any time you find yourself wanting to indirectly define variables like
this, the chances are you would get better results (faster, less security
risks, easier to maintain, easier to re-factor and optimise, more
readable) if you change the algorithm.

Instead of:

x = "myVarName"
create_real_variable(x, some_value)
print myVarName

why not do something like this:

data = {"myVarName": some_value}
print data["myVarName"]

It is fast, clean, easy to read, easy to maintain, no security risks from
using exec, and other Python programmers won't laugh at you behind your
back 


-- 
Steven

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


Re: implicit variable declaration and access

2005-06-13 Thread Tom Anderson
On Mon, 13 Jun 2005, Peter Dembinski wrote:

> Tom Anderson <[EMAIL PROTECTED]> writes:
>
> [snap]
>
>> The MAtrix had evarything in it: guns, a juimping off teh walls, flying 
>> guns, a bullet tiem, evil computar machenes, numbers that flew, flying 
>> gun bullets in slowar motian, juimping into a gun, dead police men, 
>> computar hackeing, Kevin Mitnick, oven trailers, a old womans kitchen, 
>> stairs, mature women in clotheing, head spark plugs, mechaanical 
>> squids, Japaneseses assasins, tiem traval, volcanos, a monstar, slow 
>> time at fastar speed, magic, wizzards, some dirty place, Kung Few, 
>> fighting, a lot of mess explodsians EVARYWHERE, and just about anything 
>> else yuo can names!
>
> ...with greetings to Carnivore ;)

Ah, poor old Carnivore. I sort of feel sorry for it, trying to find 
terrsts in the midst of an internet populated by a hojillion people 
jabbering about, well, everything, really. Maybe the FBI should hook up 
with the [EMAIL PROTECTED] guys. After all, if they can find intelligence in 
outer 
space, surely they can find it on the internet?

Actually, on second thoughts ...

tom

-- 
When I see a man on a bicycle I have hope for the human race. -- H. G. Wells
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: implicit variable declaration and access

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


Re: Request for help on naming conventions

2005-06-13 Thread Terry Hancock
On Monday 13 June 2005 03:59 am, Steven D'Aprano wrote:
> Are there any useful naming conventions for modules, classes and functions?
> 
> For instance, should I name functions as verbs and classes as nouns?

Hmm. Okay, here's a few I use:

Classes are generally: Capitalized  or CapWords  and I use nouns.
Unless it's a "mix-in" in which case, I use adjectives.  This mirrors
usage in the Zope sources, BTW.

Method names are either: funkyCaps (Zope uses this) or
lower_case_with_underscores.

I use verb names for methods and functions with very few exceptions.

I use nouns or occasionally adjectives for attributes.

Constants or enumeration values are ALLCAPS or ALL_CAPS, and
usually I define them within a namespace with a descriptive, all lower
case name (a trivial class).  The enumeration is usually abbreviated,
but would be an adjective, e.g.:

color.RED

I use *plural* names for lists and tuples, but singular names for
mappings.  This is so that I can use the singular in the loop:

for book in books:
pass

But I use single character variables in list comprehensions (and
generators, except I haven't used them yet):

late_books = [b for b in books if b.duedate < datetime.now()]

I also use single-character names in highly mathematical code:

def dot_product(a,b):
return a.x*b.x + a.y*b.y + a.z*b.z

But if a variable is going to be used more than about 20 lines
away from where it is defined, I use a descriptive word instead.

I like to use Capital or CapWords for modules, too, although I'm
beginning to wonder about that practice.

I really hate redundancy like this:

Topic.create_topic()

and usually prefer:

Topic.create()

which of course means, I have to qualify things a lot in my code.
This has never been an issue, but if it did, I would just introduce
an intermediary like this ("_" for "."):

Topic_create = Topic.create


After that, it's kind of case-by-case.  Do read PEP 8, too, of
course.

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

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


Re: How to use 8bit character sets?

2005-06-13 Thread John Roth
""Martin v. Löwis"" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> John Roth wrote:
>>> That is the default.
>>
>>
>> As far as I can tell, there are actually two defaults, which tends
>> to confuse things.
>
> Notice that there are two defaults already in the operating system:
> Windows has the notion of the "ANSI code page" and the "OEM code
> page", which are used in different contexts.
>
>> One is used whenever a unicode to 8-bit
>> conversion is needed on output to stdout, stderr or similar;
>> that's usually Latin-1 (or whatever the installation has set up.)
>
> You mean, in Python? No, this is not how it works. On output
> of 8-bit strings to stdout, no conversion is ever performed:
> the byte strings are written to stdout as-is.

That's true, but I was talking about outputing unicode strings,
not 8-bit strings. As  you say below, the OP may not have
been talking about that.

>> The other is used whenever the unicode to 8-bit conversion
>> doesn't have a context - that's usually Ascii-7.
>
> Again, you seem to be talking about Unicode conversions -
> it's not clear that the OP is actually interested in
> Unicode conversion in the first place.
>
> Regards,
> Martin

John Roth 

-- 
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-13 Thread pmaupin
Yes, the question was about the lack of full coroutine support in
Python, and whether in practice that was a problem or not.  It's
interesting that you think it may actually be a strength -- I'll have
to mull that over.

Thanks!
Pat

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


RE: Controlling a generator the pythonic way

2005-06-13 Thread Delaney, Timothy C (Timothy)
Steve Holden wrote:

> Sigh indeed. But if you allow next() calls to take arguments you are
> effectively arguing for the introduction of full coroutines into the
> language, and I suspect there would be pretty limited support for
> that. 

You mean `PEP 342`_ which I posted earlier and is considered pretty
non-controversial?

I think I may suggest that the name of the PEP be changed to "Coroutines
using advanced iterators".

.. _`PEP 342`: http://www.python.org/peps/pep-0342.html

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


Re: Get drives and partitions list (Linux)

2005-06-13 Thread cantabile
Hi, Peter
Thanks for the reply. I'll check popen().
But you said I should not rely on fdisk... Why ? And should I prefer
sfdisk ? Why ?


Peter Hansen wrote:
> 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: BBC R&D White Paper on Kamaelia Published (Essentially a framework using communicating python generators)

2005-06-13 Thread Michael Sparks
[EMAIL PROTECTED] wrote:

> 
>> 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'm pleased to hear that and I hope the ideas are useful at some point in
time! (directly or indirectly :)

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

I'm not sure I understand the question! (I think you're either coming from a
false assumption or mean something different) I can see 3 possible
answers...

How difficult is it to build systems using them? Well, we managed to get a
novice programmer up to speed and happy with python and using the core
ideas in Kamaelia in a 2 week period. And over the 3 month period he was
with us he implemented a small system essentially demoing previewing
streamed content from a PVR on a Series 60 mobile (and on a desktop/laptop
PC). (Of course that could be because he was a natural, *or* because it can
be fairly easy - or both)

Regarding the idea that python generators stacks "collide" aren't separate.
If you mean an implementation detail I'm not aware of, it doesn't cause any
problems at all. If you are coming from the assumption that they share the
same state/stack frame...

Consider the example generator function:

>>> def fib():
...a,b = 0,1
...while 1:
...   yield b
...   a,b = b, a+b
... 

Then call this twice yielding two different generator objects:
>>> G = fib()
>>> G

>>> H = fib()
>>> H


If they shared the same stack (by which I assume you mean stack frame), then
advancing one of these should advance both. Since in practice they run
independently you get the following behaviour:
>>> G.next()
1
>>> G.next()
1
>>> G.next()
2
>>> G.next()
3
>>> G.next()
5
>>> H.next()
1
>>> H.next()
1
>>> H.next()
2
>>> G.next()
8

ie both generators "run" independently with different local values for a,b
since they *don't* share stack frames. (Also as I understand it the stack
frame associated with each generator is effectively put aside between
invocations)

As a result from that interpretation of your question (that it's based on
the mistaken assumption that state is shared between generators), we
haven't found it a problem at all because it's a false assumption - the
generators naturally don't share stacks.


The alternative is that you're talking about the fact that if you put
"yield" in a def statement that it forces that definition to define a
generator function. (ie you can't nest a yield)

For example in some TCP client code we have:
   def runClient(self,sock=None):
  try:
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 1
 try:
sock.setblocking(0); yield 2
try:
   while not self.safeConnect(sock,(self.host, self.port)):
  yield 1
... snip ...

It would be a lot more natural (especially with full co-routines) to have:

   def runClient(self,sock=None):
  try:
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 1
 try:
sock.setblocking(0); yield 2
try:
   self.safeConnect(sock,(self.host, self.port)):
... snip ...

And to still have runClient be the generator, but have safeConnect doing the
yielding. (You can do this using Greenlets and/or Stackless for example)

However in practice it seems that this limitation is in fact more of a
strength - it encourages smaller simpler generators whose logic is more
exposed. Furthermore we very rarely have to nest calls to generators because
the way we deal with multiple generators is to set them running
independently and wait for communications between them.

These small generators also seem to lend themselves better to composition.
For example:

clientServerTestPort=1500
pipeline(TCPClient("127.0.0.1",clientServerTestPort),
 VorbisDecode(),
 AOAudioPlaybackAdaptor()
).run()

If you allow nested calls, it's perhaps natural to couple the last two
together as one component - but that is ultimately limiting - because each
component would then be trying to do too much.

Finally, in practice, it's pretty easy to write new components - we tend to
focus on the functionality we want, find it's main loop, add in yields in
key locations to effectively time slice it to turn it into a generator. 

That then becomes the core of the component, and we then remove code that
deals with direct input/output (eg from files) and recv/send to/from
in/out-boxes.

It leads to a fairly natural process for creating generator based
components. (And can also lead to a fast assimilation process for
existing python based code, when needed) There's a walk through the
creation of multicast handling components here:
   
http://kamaelia.sourcefo

Re: Get drives and partitions list (Linux)

2005-06-13 Thread cantabile
Hi, Jeff

Great help : this works like a charm. I think I can customize it to read
from sfdisk. Do you agree with Peter Hansen (post below) about fdisk ?

Jeff Epler wrote:
> 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()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Show current ip on Linux

2005-06-13 Thread David Van Mosselbeen
Lee Harr wrote:

> On 2005-06-13, David Van Mosselbeen <[EMAIL PROTECTED]>
> wrote:
>> Hi,
>> Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine
>> man :-)
>>
>> My question is : How can i rwite a script that show my current ip. If i
>> have more than one network card, the script must then show all used ip.
>>
>> It's important that this will work on a linux. i Have rwite some piece of
>> code that realy work under Windows XP, but the same script wil not work
>> on Linux.
>>
>> Verry thanks to all vulunteers.
>>
> 
> This comes up at least once a month. Google. Is. Your. Friend.
> 
> http://mail.python.org/pipermail/python-list/2005-January/258883.html

Thanks for support.
I have read the refered page you show above. I try some piece of code that
im have copy and paste it into a blank file that i give the name
"ip_adress.py" to test it.


THE SOURCE CODE :
-

import commands

ifconfig = '/sbin/ifconfig'
# name of ethernet interface
iface = 'eth0'
# text just before inet address in ifconfig output
telltale = 'inet addr:'

def my_addr():
cmd = '%s %s' % (ifconfig, iface)
output = commands.getoutput(cmd)

inet = output.find(telltale)
if inet >= 0:
start = inet + len(telltale)
end = output.find(' ', start)
addr = output[start:end]
else:
addr = ''

return addr
# End python code

But now, it's fine to have some piece of code but this wil not work on my
computer. I'm sure that y do somethings bad.
To run the python script on a Linux machine. How to proceed it ?

1) I have open a terminal
2) then i type "python ip_adress.py" (to run the script)

But nothings, i not view the current ip of my computer.
What happend ?

-- 
David Van Mosselbeen - DVM
http://dvm.zapto.org:
---
Fedora Core 3 User
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tiff Image Reader/writer

2005-06-13 Thread PyPK
When i try this i get this error:

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

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


Re: Tiff Image Reader/writer

2005-06-13 Thread Robert Kern
PyPK wrote:
> One reason why I don't want to use PIL is it seems very slow for tiff
> images of very large sizes(2400x4800). So I am looking for a better
> tool than does the right job faster.

This isn't fast enough?

In [8]: %time img2 = Image.open('foo.tiff')
CPU times: user 0.00 s, sys: 0.01 s, total: 0.01 s
Wall time: 0.03

In [9]: img2.size
Out[9]: (2400, 4800)

-- 
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: Tiff Image Reader/writer

2005-06-13 Thread PyPK
One reason why I don't want to use PIL is it seems very slow for tiff
images of very large sizes(2400x4800). So I am looking for a better
tool than does the right job faster.

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


Re: Show current ip on Linux

2005-06-13 Thread Lee Harr
On 2005-06-13, David Van Mosselbeen <[EMAIL PROTECTED]> wrote:
> Hi,
> Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine
> man :-)
>
> My question is : How can i rwite a script that show my current ip. If i have
> more than one network card, the script must then show all used ip.
>
> It's important that this will work on a linux. i Have rwite some piece of
> code that realy work under Windows XP, but the same script wil not work on
> Linux. 
>
> Verry thanks to all vulunteers.
>

This comes up at least once a month. Google. Is. Your. Friend.

http://mail.python.org/pipermail/python-list/2005-January/258883.html

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


wxpython wxlistctrl with combo

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

F.P.


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


Re: How to get/set class attributes in Python

2005-06-13 Thread Kalle Anke
On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote
(in article <[EMAIL PROTECTED]>):

> 1) Assume the variables are of a sensible type (not 
> necessarily the one you expected, though), and provide
> exception handling to catch the case where their interface
> does not match what you expect.

The problem I have with this is that I might discover an error at runtime 
instead of compile time, this means that I need to really exercise all 
possible test cases to make sure that I've covered everything (which of 
course is a good thing) but it would be easier to discover this at "compile 
time".

(note: I'm not trying to change Python, only that to me statically typing has 
it advantages also)

> Let's face it -- should it matter if you "are a programmer" 
> or only if you "can program"?  This is the difference in
> philosophy behind a dynamically-typed language like
> Python and a statically typed one like Java.

I don't really understand what you're meaning (English isn't my native 
language as you probably already have discovered)

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


Re: How to use 8bit character sets?

2005-06-13 Thread =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=
John Roth wrote:
>> That is the default.
> 
> 
> As far as I can tell, there are actually two defaults, which tends
> to confuse things.

Notice that there are two defaults already in the operating system:
Windows has the notion of the "ANSI code page" and the "OEM code
page", which are used in different contexts.

> One is used whenever a unicode to 8-bit
> conversion is needed on output to stdout, stderr or similar;
> that's usually Latin-1 (or whatever the installation has set up.)

You mean, in Python? No, this is not how it works. On output
of 8-bit strings to stdout, no conversion is ever performed:
the byte strings are written to stdout as-is.

> The other is used whenever the unicode to 8-bit conversion
> doesn't have a context - that's usually Ascii-7.

Again, you seem to be talking about Unicode conversions -
it's not clear that the OP is actually interested in
Unicode conversion in the first place.

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


Re: Tiff Image Reader/writer

2005-06-13 Thread Robert Kern
PyPK wrote:
> nothing fancy. I just want to be able to read a tiff image, get pixel
> values, write back to a tiff file.

[An aside: please quote the message you are replying to.]

Why doesn't the PIL satisfy this need? Or are you just collecting a list 
of packages with this capability?

-- 
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: Controlling assignation

2005-06-13 Thread Bruno Desthuilliers
Xavier Décoret a écrit :
(snip)
> What I wanted to do is something like this:
> 
> def change(x,v):
> x = v
> 
> class A(object):
> def __init__(self,v):
> self.x = v
> 
> a = A(3)
> print a.x  # displays 3
> change(a.x,4)
> print a.x  # still displays 3
> 
> 
> It may seem weird, 

It does

> but I ensure there is a reason for doing this. 

I really wonder what it can be ???

>  In C++ 
> (the language I am mot familiar with), I could define f to take a 
> pointer to member function of a class, a pointer and a value and achieve 
> what I want. In python, I cannot that way becauswe when change(a.x,4) is 
> executed, a.x is "replaced" by ist value (returned by __getattribute__).
> 
> Finally, here is how I hold the situation:
> 
> 
> class Handle:
> def __init__(self,v):
> self.__v = v
> def __call__(self):
> x = self.__v
> while callable(x): x=x()
> return x
> def set(self,v):
> self.__v = v
> 
> class HandledProperty(object):
> def __init__(self,name=""):
> self.name = name
> def __get__(self,o,t):
> return o.__dict__[self]
> def __set__(self,o,v):
> o.__dict__[self] = Handle(v)
> 
> class A(object):
> x = HandledProperty("x")
> def __init__(self,v):
> self.x = v
> 
> def change(x,v):
> x.set(v)
> 
> 
> a = A(3)
> print a.x()  # displays 3 (notice the () in the call)
> change(a.x,4)
> print a.x()  # still displays 4

You could achieve the same effect with:

class A( object):
   def __init__(self, value):
 self.value = value

a = A(3)
a.value = 4
a.value
=> 4

And it's *much* more simple/readable/efficient.

Ever googled for "evolution of a programmer" ?-)


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


Re: What is different with Python ?

2005-06-13 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
Philippe C. Martin <[EMAIL PROTECTED]> wrote:
>> 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.
>
>Some very good schools still believe that

Historically, CS departments either grew out of EE departments or Math
departments.  That happened back in the 60's and 70's, but I suspect
they still tend to show their roots in how they teach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tiff Image Reader/writer

2005-06-13 Thread PyPK
nothing fancy. I just want to be able to read a tiff image, get pixel
values, write back to a tiff file.

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


Re: Is Python Suitable for Large Find & Replace Operations?

2005-06-13 Thread Bruno Desthuilliers
rbt a écrit :
> Here's the scenario:
> 
> You have many hundred gigabytes of data... possible even a terabyte or 
> two. Within this data, you have private, sensitive information (US 
> social security numbers) about your company's clients. Your company has 
> generated its own unique ID numbers to replace the social security numbers.
> 
> Now, management would like the IT guys to go thru the old data and 
> replace as many SSNs with the new ID numbers as possible. You have a tab 
> delimited txt file that maps the SSNs to the new ID numbers. There are 
> 500,000 of these number pairs. What is the most efficient way  to 
> approach this? I have done small-scale find and replace programs before, 
> but the scale of this is larger than what I'm accustomed to.
> 
> Any suggestions on how to approach this are much appreciated.

I may say something stupid (that would not be the first time), but why 
don't you just put it all in a good RDBMS and go with a few SQL queries?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive import list

2005-06-13 Thread [EMAIL PROTECTED]
If you use your own import function, like below, you could create a
list of all imported modules.

#!/usr/bin/env python

mod_list = []

def my_import(name, globals = None, locals = None, fromlist = None):
mod_list.append(name)
mod = __import__(name, globals, locals, fromlist)
return mod

os = my_import('os')
print os.name

print mod_list

sys = my_import('sys')
print sys.version

print mod_list

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


Re: Tiff Image Reader/writer

2005-06-13 Thread James Carroll
What sort of things do you want to do with the TIFFs?  How
heavy-weight or light-weight are you interested in?  For heavy-weight
there are:

- wxPython will do a bunch of tiff reading, and some image processing
http://www.wxpython.org

- GDAL
>(quoting Khalid Zuberi:)
>GDAL supports GeoTIFF and includes python bindings:
>
>http://www.remotesensing.org/gdal/

- ITK  Insight Toolkit from Kitware (wicked heavy-weight)
http://www.itk.org

-Jim

On 13 Jun 2005 12:50:48 -0700, PyPK <[EMAIL PROTECTED]> wrote:
> Is there any package out there which handles Tiff Images other than PIL
> or ImageMagic .
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: case/switch statement?

2005-06-13 Thread Philippe C. Martin
Any speed issue ?


[EMAIL PROTECTED] wrote:

> Philippe C. Martin wrote:
>> Leif K-Brooks wrote:
>>
>> > Joe Stevenson wrote:
>> >> 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.  Can someone please point me to the appropriate document,
>> >> or
>> >> post an example?  I don't relish the idea especially long if-else
>> >> statements.
>> >
>> > If you really want one, you could use
>> > .
>>
>> I _love_ Python!
> 
> 
> Well, if you loved that, here's something even more evil.  This was
> Bengt Richter's original idea that Cliff Wells and I improved upon.
> First define some functions and classes:
> 
> . _cache = {}
> .
> . class _BaseCaseException(Exception):
> . pass
> .
> . def switch(v):
> . if v not in _cache:
> . class _CaseException(_BaseCaseException):
> . pass
> . _cache[v] = _CaseException
> . raise _cache[v]
> .
> . def case(v):
> . if v not in _cache:
> . class _CaseException(_BaseCaseException):
> . pass
> . _cache[v] = _CaseException
> . return _cache[v]
> .
> . default = _BaseCaseException
> 
> 
> Then you can define a switch statement like this:
> 
> . x = 2
> .
> . try: switch(x)
> .
> . except case(1):
> . print "Case 1"
> .
> . except case(2):
> . print "Case 2"
> .
> . except case(3):
> . print "Case 3"
> .
> . except default:
> . print "Default"
> .
> . except NameError:
> . print "You can still catch regular exceptions like NameError"
> 
> 
> 
> I-love-Python-too-but-this-isn't-why-ly yr's,
> 

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


Re: searching for IDE

2005-06-13 Thread Philippe C. Martin
pydev for eclipse ?

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

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


Re: implicit variable declaration and access

2005-06-13 Thread Peter Dembinski
Tom Anderson <[EMAIL PROTECTED]> writes:

[snap]

> The MAtrix had evarything in it: guns, a juimping off teh walls,
> flying guns, a bullet tiem, evil computar machenes, numbers that
> flew, flying gun bullets in slowar motian, juimping into a gun, dead
> police men, computar hackeing, Kevin Mitnick, oven trailers, a old
> womans kitchen, stairs, mature women in clotheing, head spark plugs,
> mechaanical squids, Japaneseses assasins, tiem traval, volcanos, 
> a monstar, slow time at fastar speed, magic, wizzards, some dirty
> place, Kung Few, fighting, a lot of mess explodsians EVARYWHERE, 
> and just about anything else yuo can names!

...with greetings to Carnivore ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is different with Python ?

2005-06-13 Thread Bruno Desthuilliers
Andrea Griffini a écrit :
(snip)

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

I don't know if I qualify as a "competent programmer" (you'd have to ask 
my co-workers), but I started with hi-level scripting languages, 
event-driven programming, and OO. Only then did I learn lower-level 
languages (C, Pascal, and bits of 68k assembly). Being familiar with 
fondamental *programming* concepts like vars, branching, looping and 
functions proved to be helpful when learning C, since I only had then to 
focus on pointers and memory management.
-- 
http://mail.python.org/mailman/listinfo/python-list


Access Database Using Python

2005-06-13 Thread Karthish

I'm writing a script to look through DNA sequences in a database and
select sequences I require. So far, my code looks like this for
authentication:

import os
import Bio.Clustalw
from Bio.Alphabet import IUPAC
import pdb
import sys
import os
import urllib
import urllib2

import urllib
userid = 'something'
password = 'something2'
location = 'index.html'
params = urllib.urlencode({'user': userid, 'password': password,
'request_uri': location})
f = urllib2.urlopen("http://www.gene-regulation.com/login?%s"; % params)
print f.read()

When I run the program, I see the following:
__



  Redirect
  
  
  
  
Please stand by, you will be redirected
toindex.html...


The code works as it is. How would I modify this script to display the
page
"http://www.gene-regulation.com/cgi-bin/pub/databases/transfac/getTF.cgi?AC=R00077";?
I can't figure out how to authenticate and then load a page, since the
page requires cookies for authentication.

Thanks.

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


Re: Slicing an IXMLDOMNodeList

2005-06-13 Thread marcel . vandendungen
For future reference:

The solution to this problem is a simple one.
rgelem = list(xmldoc.selectNodes('/root/elem'))
returns a real list of IXMLDOMElements that can be sliced.

-- Marcel

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


Re: Tiff Image Reader/writer

2005-06-13 Thread PyPK
Is there any package out there which handles Tiff Images other than PIL
or ImageMagic .

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


Access Database Using Python

2005-06-13 Thread Karthish
I'm writing a script to look through DNA sequences in a database and
select sequences I require. So far, my code looks like this for
authentication:

import os
import Bio.Clustalw
from Bio.Alphabet import IUPAC
import pdb
import sys
import os
import urllib
import urllib2


import urllib
userid = 'kmdawg'
password = 'kmdawgyeah'
location = 'index.html'
params = urllib.urlencode({'user': userid, 'password': password,
'request_uri': location})
f = urllib2.urlopen("http://www.gene-regulation.com/login?%s"; % params)
print f.read()

When I run the program, I see the following:
__



  Redirect
  
  
  
  
Please stand by, you will be redirected
toindex.html...


The code works as it is. How would I modify this script to display the
page
"http://www.gene-regulation.com/cgi-bin/pub/databases/transfac/getTF.cgi?AC=R00077";?
I can't figure out how to authenticate and then load a page, since the
page requires cookies for authentication. 

Thanks.

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


Re: Dealing with marketing types...

2005-06-13 Thread Thomas Bartkus
"fuzzylollipop" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> man this is the worst advice I have ever heard, you can't "walk away
> with code" someone else paid you to write. Regardless of what your
> perceived slight is.
>
> NEVER take code you were paid to write unless you have it in writing
> that you can, you will lose that one everytime.

I'll agree here.  If you were hired as an employee for salary or an hourly
wage, you will have no standing whatsover as "owner" of the work you
produced.  If your ex employer charges you with theft, it will be a slam
dunk in court. You don't own what you produced for your employer.  Even if
you were fool enough to do much if it on your own unpaid off hours.  Even if
they reneged on some verbal promises to you in order to con you into doing
so.  It sucks but that's the way it is.

However - I certainly sympathize with the desire to fight thievery with
thievery.
Unfortunately, you can't win that way. Unless, of course, you can do it
without being caught :-)

But that only gets you revenge - not payment.
Thomas Barkus


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


Re: Adding to Exception.args

2005-06-13 Thread Scott David Daniels
Andreas Beyer wrote:
> I came up with the following code:
>inp = file(file_name)
>for n, line in enumerate(inp):
>try:
># parse line ...
>except Exception, e:
>inp.close() # Is this necessary for 'r' files?
>args = list(e.args)
>args.insert(0, 'line: %d'%(n+1))
>e.args = tuple(args)
>raise
 inp = open(file_name)   # GvR prefers this style, not file
 try:
 for n, line in enumerate(inp):
 try:
 # parse line ...
 except Exception, e:
 e.args = e.args + ('line: %d' % (n + 1),) # tuple add
 raise
 finally:
 inp.close() # it is certainly more portable, and more readable


> Is there any specific order to the arguments in e.args? 
 > Should my 'user argument' be at the beginning or at the end of e.args?

If you are going to play with it, it is more likely that indices
are used (so making e.args[0] refer to the same thing may help).
The __str__ method of the Exception is responsible for formatting.
If you "wrap" an exception that has its own __str__ method, it
may well expect the args tuple to hold a precise number of
elements (and therefore fail to convert to a string).

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


Re: What is different with Python ?

2005-06-13 Thread Philippe C. Martin
> I don't buy that. I think there's a world of difference between knowing
> what something does and how it does it; a black-box view of the memory
> system (allocation + GC) is perfectly sufficient as a basis for
> programming using it. That black-box view should include some idea of how
> long the various operations take, but it's not necessary to understand how
> it works, or even how pointers work, to have this.


Maybe you should say programming at the application level. Also if you will
notice from this newsgroup that people are sometimes trying to figure out
how to optimize the speed of their application; you will also notice that
the answers they get usually involve how Python is implemeted in their
specific environment.


I like analogies: twice in my career in and two different companies in two
different industries, it was decided that the application should be
prototyped on workstations and then ported to the embedded environment.
Both times, the speed/size of the "ported" code was so bad that it was
virtually unsusable. It was then decided to spend some time (it took years)
optimizing the system(s) to make it feasible.

I am conviced that if some of the target constraints had been taken into
consideration from the beginning:
1) much less time would have been spent in the optimization process.
2) the architecture of the final piece of code would have been cleaner.

Assuming I am correct, this implies that the folks working on the initial
prototypes should fully understand the constraints of a realtime embedded
environment (and that includes memory management)

Regards,

Philippe






Tom Anderson wrote:

> On Mon, 13 Jun 2005, Andrea Griffini wrote:
> 
>> On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith <[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.
>>>
>>> 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 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.
> 
> I don't buy that. I think there's a world of difference between knowing
> what something does and how it does it; a black-box view of the memory
> system (allocation + GC) is perfectly sufficient as a basis for
> programming using it. That black-box view should include some idea of how
> long the various operations take, but it's not necessary to understand how
> it works, or even how pointers work, to have this.
> 
> tom
> 

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


Re: What is different with Python ?

2005-06-13 Thread Philippe C. Martin
> 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.

Some very good schools still believe that


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.
> 
> 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.
> 
> 
> *) "My favorite programming langauge is solder." - Bob Pease
> 

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


recursive import list

2005-06-13 Thread Philippe C. Martin
Hi,

I have a fairly large project going on and would like to figure out
automatically from the source which files are being imported.

ex: find_out mymain.py


Is there an easy way to achieve that ?

Regards,

Philippe

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


  1   2   3   >