Re: Partial classes

2006-07-18 Thread Kay Schluehr

Sanjay wrote:
> Hi All,
>
> Not being able to figure out how are partial classes coded in Python.
>
> Example: Suppose I have a code generator which generates part of a
> business class, where as the custome part is to be written by me. In
> ruby (or C#), I divide the code into two source files. Like this:
>
> GeneratedPerson.rb
> Class Person
>   .
>   .
>   .
>
> End Class
>
> HandcraftedPerson.rb
> Class Person
>  .
>  .
>  .
> End Class
>
> The intrepretor adds the code in both to compose the class Person.
>
> What is the equivalent in Python? Inheriting is a way, but is not
> working in all scenerios.
>
> Thanks
> Sanjay

Python has no notion of a partial class because it is a pure compile
time construct. You might merge different class definitions by means of
a meta class that puts everything together but whether or not certain
methods in the merged class are available depends on which modules are
imported. This might give rise to a "virtual" or runtime module. It is
not a module that refers to a physical file on the disc but is a pure
runtime construct. When creating this module all physical modules that
define class fragments might be put together by means of the metaclass
mechanism.  I indeed used this construction to unify different access
points before I reimplemented it using partial classes in C# which are
very fine IMO.

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


Re: Python : Event-Driven Paradigm

2006-07-18 Thread Kusanagi



Were you looking for more specific 
features?
 
Parallel Processing. 
 
Grant, 
    
        It looks like 
I have a lot more studying to do, all of the information that I have seems to be 
screwed up. I will look at event
loops in Python to see if that answers my question. 
I was just looking at the event-driven programming page on wikipedia and it 
mentioned that TCL had event driven programming built in, go figure and it did 
not mention python at all. I have made a lot of assumptions, and you know the 
old saying that assumptions are the mother of all fu**ups. Well I am going to 
get back to it, interest thing just occurred though. I have a program that 
actually runs faster with the more user-defined functions called than with 
less, I am trying to track down the reason why. I am ecstatic! I am getting into 
parallel processing because of a graphics project that I am researching and I 
have to stay with Python, because I don't want to spend a year recoding what 
others have already completed and tweaked to max efficiency. What a vicious 
circle I am caught up in. 
 
As always thanks for the response E-mail. I have 
not even checked out the Google groups yet, but I will very soon. 
 
        
        - Steven. 

  - Original Message - 
  From: 
  Grant Olson 
  
  To: 'Kusanagi' 
  Sent: Tuesday, July 18, 2006 4:34 
PM
  Subject: RE: Python : Event-Driven 
  Paradigm
  
  
  This is weird, but 
  your post didn’t show up on Google Groups; looks like it did on python 
  list.  I was going to let you know that you can just post to python list, 
  and if I have anything worthwhile to say I’ll put it up there, but I always 
  check through google groups.
   
  Anyway, I don’t 
  really have much worthwhile to say on this question, but I think the general 
  response on python-list would be that it isn’t too hard to write a basic event 
  loop with stock python; were you looking for more specific 
  features?
   
  -Grant
   
  
  
  
  
  
  From: 
  Kusanagi [mailto:[EMAIL PROTECTED] Sent: Tuesday, July 18, 2006 5:03 
  AMTo: Python Mailing List; 
  Grant Olson; Bob IppolitoSubject: Python : Event-Driven 
  Paradigm
   
  
  Hi All, 
  
  
   
  
      I have been 
  looking through wikipedia at the Event-Driven Page http://en.wikipedia.org/wiki/Event-driven_programming
  
  and I noticed that it mentions 
  that TCL has event driven programming built in. I also looked over the Python 
  3000 proposals and I did not notice any mention of future versions of python 
  that are going to be changed to include this awesome feature. 
  
  
   
  
      I currently use 
  the Twisted framework in various ways and I was just curious to know if the 
  event-driven paradigm is going to be implemented without the use 
  of 3rd party frameworks. i.e. Twisted. in the future. 
  
   
  
      If this 
  question has already been asked and answered then please accept my apology. 
  
  
   
  
   
  
      - Steven. 
  
  
   
  
   
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Partial classes

2006-07-18 Thread alex23
Sanjay wrote:
> Not being able to figure out how are partial classes coded in Python.

Hi Sanjay,

To the best of my knowledge, Python currently has no support for
partial classes.

However, BOO (http://boo.codehaus.org/) - which is a Python-like
language for the .NET CLI)- _does_ support partial classes
(http://jira.codehaus.org/browse/BOO-224). While it _isn't_ Python,
there could be enough similarities to make this worthwhile for you if
you absolutely have to have partial classes.

(Disclaimer: I've never used BOO)

Hope this helps.

-alex23

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


Re: Dispatch with multiple inheritance

2006-07-18 Thread looping
Michael J. Fromberger wrote:
>
> Is there a better (i.e., more elegant) way to handle the case marked
> (**) above?
>

You have to call super in each method __init__, if you don't, the call
chain break before the end:

class A (object):
def __init__(self):
super(A, self).__init__()
print "cons A"

class B (object):
def __init__(self):
super(B, self).__init__()
print "cons B"

class C (A):
def __init__(self):
super(C, self).__init__()
print "cons C"

class D (B):
def __init__(self):
super(D, self).__init__()
print "cons D"

class E (C, D):
def __init__(self):
super(E, self).__init__()  # calls C constructor
print "cons E"

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


Re: What is a type error?

2006-07-18 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
> > Chris Smith wrote:
> >> Joachim Durchholz <[EMAIL PROTECTED]> wrote:
> >> I *think* I understand Marshall here.  When you are saying "assignment",
> >> you mean assignment to values of attributes within tuples of the cell.
> >> When Marshall is saying "assignment", he seems to mean assigning a
> >> completely new *table* value to a relation; i.e., wiping out the entire
> >> contents of the relation and replacing it with a whole new set of
> >> tuples.  Your assignment is indeed less powerful than DML, whereas
> >> Marshall's assignment is more powerful than DML.
> >
> > Exactly.
>
> Ah well. I never meant that kind of assignment.

Sorry for the confusion.


Marshall

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


Partial classes

2006-07-18 Thread Sanjay
Hi All,

Not being able to figure out how are partial classes coded in Python.

Example: Suppose I have a code generator which generates part of a
business class, where as the custome part is to be written by me. In
ruby (or C#), I divide the code into two source files. Like this:

GeneratedPerson.rb
Class Person
  .
  .
  .

End Class

HandcraftedPerson.rb
Class Person
 .
 .
 .
End Class

The intrepretor adds the code in both to compose the class Person.

What is the equivalent in Python? Inheriting is a way, but is not
working in all scenerios.

Thanks
Sanjay

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


Re: Object Persistence Using a File System

2006-07-18 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Chris Spencer wrote:

> I've been looking for a method of transparent, scalable, and
> human-readable object persistence...

Don't do object persistence. What is an object? It's a combination of code
and data. Code structure is internal to your program--it has no business
being reflected in external data that may be saved to a persistent medium,
transmitted over an external channel or whatever. Otherwise when you
refactor your code, that external data no longer becomes readable without
major backward-compatibility hacks.

Use data abstraction instead: define a high-level data structure that is
independent of implementation details of your code. When you look at the
major data-interchange formats in use today--such as XML, ODF, MPEG,
WAV--there's a reason why none of them are built on object persistence.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Authentication

2006-07-18 Thread Nick Vatamaniuc
Matheus,
There is libgmail @ http://libgmail.sourceforge.net/
Here is the excerpt from their page.
"""
The following code logs into an account, retrieves a list of threads,
displays information about them and displays the source of the
individual messages.
"""
import libgmail
ga = libgmail.GmailAccount("[EMAIL PROTECTED]", "mymailismypass")
ga.login()
folder = ga.getMessagesByFolder('inbox')
for thread in folder:
  print thread.id, len(thread), thread.subject
  for msg in thread:
print "  ", msg.id, msg.number, msg.subject
print msg.source

I tried it before and it didn't work, it said login failed. Perhaps it
will work for you. Looking at the source is always a GoodThing
(especially if you give your password to a program you just downloaded
as an input...).

Nick Vatamaniuc


bigodines wrote:
> Hello guys,
>
> I'm trying to learn python by making some small programs that could be
> useful for some bigger propouses. In fact, i've made a small "check
> latest-modified" for webpages and it's working great.
>
> The next step I would like to do is to check if I have new e-mails (I
> don't wanna read it from my program, i just wanna it to tells me "yes,
> you have new mail(s)" or "no".
>
> My question is, how do I log into my google account using urllib2 to
> check this? Does anyone have a sample script that I can use or
> something to help me?
> 
> thanks in advice,
> Matheus

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


Re: Dispatch with multiple inheritance

2006-07-18 Thread Michele Simionato
Michael J. Fromberger ha scritto:

> Consider the following class hierarchy in Python:
> 

> Is there a better (i.e., more elegant) way to handle the case marked
> (**) above?
>
> Curious,
> -M
>
> --
> Michael J. Fromberger | Lecturer, Dept. of Computer Science
> http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA

Look at
http://www.python.org/download/releases/2.3/mro


 Michele Simionato

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


Re: range() is not the best way to check range?

2006-07-18 Thread Simon Forman
tac-tics wrote:
> Simon Forman wrote:
> > To me, and perhaps others, "T =
> > set(xrange(0, 1, 23))" and "n in T"  are somewhat easier to read
> > and write than "not n % 23 and 0 <= n < 1", YMMV.
>
> Eh? How is the first easier to read than the second?? You have a nested
> function call in the first!

I find the first form more immediately comprehensible than the latter.
I know what xrange() does, and I know what set() does, and "nested
function calls" give me no trouble,  whereas the latter form with a
modulus, negation, and comparisons would take me a bit longer both to
compose and/or understand.

If this is not the case for you then by all means please disregard my
posting.  YMMV.

>
> Regardless, testing if a member is part of a ranged set is always going
> to be slower.

Yes.  Roughly 0.001 seconds slower on my five year old computer.
I'm not worried.

> It's the nature of what you're doing. Building a set and
> then searching it takes much longer than a single modulus and
> subtraction (which is all an integer comparison is).

Building the set, yes, but searching the set is very close to the same
speed, even for rather large sets.  If you were performing the search
3 times (like in the OP) it would only take about three thousandths
of a second longer, and that's on my old slow computer.

If I were doing this a thousand times more often, or on a range of a
million or more, or in production code, or with ranges that changed
often, then I would certainly take the time to write out the latter
form.


Peace,
~Simon

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


Re: win32com.client.Dispatch - understanding error messages

2006-07-18 Thread mirandacascade

Duncan Booth wrote:
> Are you really sure that the browser isn't making guesses about what you
> meant and correcting the error for you? Does what remains in the address
> bar when the page is retrieved really match *exactly* what you copied and
> pasted?

Thank you for that pointer.  The answer is: no, it does not match
exactly.  The browser did indeed, as you surmised, make a guess and
correct the error.  The browser added 'http://' to the beginning.  When
'http://' gets added to the beginning of the url parameter, all is well.

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


Re: Recursive function returning a list

2006-07-18 Thread malkarouri
Bruno Desthuilliers wrote:
> Boris Borcic a écrit :
> > Hello Bruno,
> >
> > Bruno Desthuilliers wrote:
> >
> >> Boris Borcic wrote:
> >>
>  Do you have any ideas?
> >>>
> >>>
> >>> you could use a recursive generator, like
> >>>
> >>> def genAllChildren(self) :
> >>> for child in self.children :
> >>> yield child
> >>> for childchild in child.genAllChildren() :
> >>> yield childchild
> >>
> >>
> >>
> >> Or how to *not* address the real problem...
> >>
> >> Boris, using a generator may be a pretty good idea, but *not* as a way
> >> to solve a problem that happens to be a FAQ !-)
> >>
> >
> > Sorry, but I don't understand your reasoning.
>
> It's quite simple. The OP's problem is well-known (it's a FAQ), and easy
> to solve. The righ answer to it is obviously to give a link to the FAQ
> (or take time to re-explain it for the zillionth time), not to propose a
> workaround.
>
> > How can you exclude that
> > the OP /may/ find that a generator neatly solves his problem ?
>
> I don't exclude it, and explicitly mentioned in whole letters that, I
> quote, it "may be a pretty good idea". And actually, the OP's problem is
> really with default values evaluation scheme - something that every
> Python programmer should know, because there are cases where you cannot
> solve it with a generator-based solution !-)
>
> > The use
> > of a default value was not an end in itself, was it ?
>
> If the OP has other reasons to want to use an accumulator based solution
> - which we don't know - then the possibility to use a default value is
> important.
>
> > - and the quirks of
> > default values being FAQ stuff don't change that. Sure if nobody had
> > covered that aspect, but a couple other posters did...
>
> Yes, but you forgot to mention that - and I would not have post any
> comment on your solution if you had explicitly mentioned the FAQ or
> these other answers.
>
> > Mmmmhhh somehow it feels like if there is any issue here, it is about
> > defending the credo "there ought to exist only one obvious way to do it"
> > ?...
>
> Nope, it's about trying to make sure that anyone googling for a similar
> problem will notice the canonical solution somehow.

Sorry, but I kinda agree with Boris here. Not that I am anybody here,
really.

If the question is to use an accumulator based solution, then yes, the
default values answer is definitely the canonical solution.
If the question is to write a recursive function that returns a list,
an accumulator based solution and a generator based solution are two
different ways for doing that. I don't think there is actually a FAQ
saying you must use the accumulator solution.
Actually, the accumulator based solution kind of comes to me
automatically as standard in any programming language, and I believe
that this was established as standard in python, _before_ the
introduction of generators.

Now, personally I find the generator-based solution more intuitive for
me (in the eys of the beholder:). And, looking at the subject of the
thread, guess what was the question?

k

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


vmware/python web dev

2006-07-18 Thread [EMAIL PROTECTED]
someone has made a "virtual appliance" specialized for python web
development. it has a huge list of included software.

if you're interested, see:
http://www.vmware.com/vmtn/appliances/directory/289

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


Re: Coding style

2006-07-18 Thread Carl Banks

Jorge Godoy wrote:
> "Carl Banks" <[EMAIL PROTECTED]> writes:
>
> > Well, I certainly can agree with that, except for the last point. :)  I
> > certainly wouldn't want to keep that unfortunate behavior around just I
> > have something to use as an argument using len to test emptiness.
>
> On the other hand, having this behavior makes it so simple to deal with some
> algorithms because on doesn't need to know if the given object does or does
> not support len()...

First of all, the unfortunate behavior I was referring to was the fact
that iterables that have unknown length are true in a boolean context,
even if they happen to be empty.  Bruno and I had a disagreement over
whether this should also be a wart for lists and such, but I think we
agree that it would be better generators and other iterators raised an
exception in a boolean context.

Getting back to your reply--can you give an example of a useful
function that needs to do what you want?  (Let's disregard iterators
and arrays for now, and focus on older Python types like lists, tuples,
strings, integers, floats, None, etc.)  Can you give me an example of a
useful function that needs to test the truth value of an object, but
that can't rely on it having a length?

The only example I can think of here is a function that does nothing
with an object except pass it to other functions.  Almost anything else
you do with an object pigeonholes it as a sequence or atomic type:
you've already assumed whether it has a length or not.


Carl Banks

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


Re: Coding style

2006-07-18 Thread Terry Reedy

"Patrick Maupin" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> Carl Banks wrote:
>> def process_values(lst):
>> if not lst:
>> return
>> do_expensive_initialization_step()
>> for item in lst:
>> do_something_with(item)
>> do_expensive_finalization_step()
>> What if you called the function like this:
>>
>> process_values(x.strip() for x in values_lst)

> The perverse wish, expressed in the specific example, that SOME piece
> of code SOMEWHERE should PLEASE throw an exception because some idiot
> passed a generator expression rather than a list into a function, is
> not apt to be well received by an audience which strives for generality
> when it makes sense; and I daresay most members of that audience, if
> confronted with the wished-for exception, would fix the function so
> that it quite happily accepted generator expressions, rather than
> changing a conditional to use len() just so that an equivalent
> exception could happen a bit earlier.

Given that the input is going to be scanned by an iterator, it really makes 
sense to me to accept an iterator as input.  (Unless the function is for 
special-case usage in a predefined, never to be expanded, set of 
circumstances in which such generality is not needed.  In such a case, if 
lst: is no problem.)  I think the following, untested rewrite suffices.

def process_values(lst):
it = iter(lst)
try:
item = it.next()
do_expensive_initialization_step()
do_something_with(item) # see note
for item in it:
do_something_with(item)
do_expensive_finalization_step()
except StopIteration:
pass # or any special empty input code

# note: if writing do_something_with(item) is bothersome,
# replace 3 lines with
while True:
do_something_with(item)
try:
   item = it.next
except StopIteration:
break

In general, to work with iterators instead of containers, change

if container:
do_stuff()
else:
do_empty()

to

try:
item = it.next()
do_modified_stuff() # taking into account that have item already
except StopIteration:
do_empty()

Guido has so far vetoed adding .__len__() to the iterator protocol because 
a) it is not always possible and b) he want to keep the protocol as simple 
as it is.

Terry Jan Reedy




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


Re: CSV with comments

2006-07-18 Thread skip
Whoops, missed the second part.

John> Is there any reason to prefer this approach to Daniel's, apart
John> from being stuck with an older (pre-yield) version of Python?

No, it's just what I came up with off the top of my head.

John> A file given to csv.reader is supposed to be opened with "rb" so
John> that newlines embedded in data fields can be handled properly, and
John> also (according to a post by Andrew MacNamara (IIRC)) for DIY
John> emulation of "rU". It is not apparent how well this all hangs
John> together when a filter is interposed, nor whether there are any
John> special rules about what the filter must/mustn't do. Perhaps a few
John> lines for the docs?

Yeah, I was also aware of that.  In the common case though it's not too big
a deal.  If the OP is editing a CSV file manually it probably isn't too
complex (no newlines inside fields, for example).

Skip

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


Re: CSV with comments

2006-07-18 Thread skip

John> This is recursive. Unlikely of course, but if the file contained a
John> large number of empty lines, might this not cause the recursion
John> limit to be exceeded?

Sure, but I was lazy. ;-)

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread skip

>> Hm didn't I leave ctypes in there?  I added calldll because it
>> had a really nice can opener.

Oh, I have no idea (didn't download).  I just sort of assumed if you had
included calldll you probably hadn't included ctypes.

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


Re: Coding style

2006-07-18 Thread Jorge Godoy
"Carl Banks" <[EMAIL PROTECTED]> writes:

> Well, I certainly can agree with that, except for the last point. :)  I
> certainly wouldn't want to keep that unfortunate behavior around just I
> have something to use as an argument using len to test emptiness.

On the other hand, having this behavior makes it so simple to deal with some
algorithms because on doesn't need to know if the given object does or does
not support len()...  

Having to test if something is of certain type then choosing what kind of test
to apply is not something I'd like to have to do all the time.

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


Re: No need to close file?

2006-07-18 Thread Kevin Watters
There's always the new 'with' statement in Python 2.5.  So instead of

> f = open('foo', 'r')
> try:
>for line in f:
>  print line
> finally:
>f.close()
> 

...you do:

with open('foo','r') as f:
for line in f:
print line

It's at least a little bit cleaner, and it will close the file if there's an
exception as well.

(See http://docs.python.org/dev/whatsnew/pep-343.html and don't forget to 
include

from __future__ import with_statement

at the top of the file)

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


Re: Coding style

2006-07-18 Thread Carl Banks

Bruno Desthuilliers wrote:
> Carl Banks a écrit :
> > Bruno Desthuilliers wrote:
> >
> >>There are less risk of a typo with "if a:" than with "if len(a) > 0".
> >
> >
> > So, it's more important to protect against typos than subtle bugs?
> >
>
> People making smart points are really annoying... !-)
>
> wrt/ to the "subtle bug" point, MHO is that a better solution could be
> to have iterators/generators implement __nonzero__ the same way numpy
> arrays do. It may not be a very strong argument, but I actually like the
> fact that empty sequences eval to false just like numeric zeros and None...

Well, I certainly can agree with that, except for the last point. :)  I
certainly wouldn't want to keep that unfortunate behavior around just I
have something to use as an argument using len to test emptiness.


Carl Banks

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


Re: XMLRPC Solution Code

2006-07-18 Thread dylpkls91
Frank Millman wrote:
> I use something called 'srvany' -
>http://support.microsoft.com/kb/q137890/

I am familiar with srvany. Seems like it is a whole bunch easier than
the PyWin32 stuff.

I'll write a wrapper script that can be used like this:
createservice.py -myservicename -myservicepath
or like this:
import createservice
createservice.install_if_needed("myservicename", "myservicepath")


I'll have my XMLRPC programcall createservice.py's install_if_needed
method.
There you have it: a foolproof, automatic, no-hassle service. Thanks
Frank!

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Carl Banks a écrit :
> Bruno Desthuilliers wrote:
> 
>>There are less risk of a typo with "if a:" than with "if len(a) > 0".
> 
> 
> So, it's more important to protect against typos than subtle bugs?
> 

People making smart points are really annoying... !-)

wrt/ to the "subtle bug" point, MHO is that a better solution could be 
to have iterators/generators implement __nonzero__ the same way numpy 
arrays do. It may not be a very strong argument, but I actually like the 
fact that empty sequences eval to false just like numeric zeros and None...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to know if socket is still connected

2006-07-18 Thread John J. Lee
Grant Edwards <[EMAIL PROTECTED]> writes:
[...]
> > Often normal send() and recv() semantics have been mistaught.
> > An alert alien, looking at other common APIs in isolation, 
> > might reasonably wonder whether there is some sort of 
> > still_ok_to_use() sort of check as part of TCP.  As it happens,
> > of course, that doesn't fit with the rest of socket networking,
> > which takes the "modernist" approach of trying send() or recv(),
> > and reporting any exception.
> 
> On most Unices there are some obscure API features that can be
> used to generate a SIGPIPE under some vaguely specified error
> conditions (e.g. TCP keepalive timeout).  I've only read about
> them and never tried to use them, since I couldn't see anything
> in the description of the features that was any benefit over
> the nomral send() and recv() usage.

Sorry for butting in, Grant, but this reminds me of this bug:

http://python.org/sf/1411097


and specifically, of my question in the tracker:

| One problem: I don't understand the need for
| HTTPConnection._safe_read(), rather than checking for an
| EINTR resulting from the recv() call (or WSAEINTR on
| Windows).  Can anybody explain that?


Note the comment in the third paragraph in the method's docstring,
below ("Note that we cannot...", and the "if not chunk" test).  Do you
know of any reason why it should do that (fail to check for EINTR)?
Looks wrong to me.

(I do understand that it's only signals that arrive before *any* data
is read that cause EINTR, but that's the specific case mentioned in
the 3rd para, and a check for that is what's conspicuously absent from
the method implementation.)

def _safe_read(self, amt):
"""Read the number of bytes requested, compensating for partial reads.

Normally, we have a blocking socket, but a read() can be interrupted
by a signal (resulting in a partial read).

Note that we cannot distinguish between EOF and an interrupt when zero
bytes have been read. IncompleteRead() will be raised in this
situation.

This function should be used when  bytes "should" be present for
reading. If the bytes are truly not available (due to EOF), then the
IncompleteRead exception can be used to detect the problem.
"""
s = []
while amt > 0:
chunk = self.fp.read(min(amt, MAXAMOUNT))
if not chunk:
raise IncompleteRead(s)
s.append(chunk)
amt -= len(chunk)
return ''.join(s)


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


Re: Track keyboard and mouse usage

2006-07-18 Thread Lars
Diez B. Roggisch wrote:
> will make the devices world readable. While I haven't thought about any 
> security implications that might have (and am not especially 
> knowledgeable in such things to be honest), I'm convinced it is way less 
> likely to introduce any exploitable holes than suid root would.

Depending on what kind of info these devices produce, couldn't they be 
used to spy on someone typing in a password? (I can't check, I'm on 
FreeBSD.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-18 Thread Carl Banks
Bruno Desthuilliers wrote:
> There are less risk of a typo with "if a:" than with "if len(a) > 0".

So, it's more important to protect against typos than subtle bugs?


Carl Banks

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


Re: Coding style

2006-07-18 Thread Carl Banks
Bruno Desthuilliers wrote:
> "Irrelevant" may not be the best expression of my thought here - it's
> just that Carl's assertion is kind of a tautology and doesn't add
> anything to the discussion. If Python had been designed as statically
> typed (with declarative typing), the rules would be different. Yeah,
> great. And now ?

I was answering someone who said you should use "if lst" because PEP 8
says to.  I proposed that the PEP might be outdated here, and gave
reasons why I think it would be different if it were written today.  (I
also, regrettably, implied the language might have been designed
differently.)  This all might be irrelevant to you, but it's relevant
to the original question of whether that clause of PEP 8 is outdated.
I think it is.

BTW, I'm still waiting for anyone to come up with a real benefit of the
"if lst" test.  I have yet to see a good reason than non-answer
cop-outs "it's Pythonic", "it's stood the test of time", and "it's in
PEP 8".  "It's standard idiom" is about the best I've seen, and that's
pretty weak.  "Saving a few keystrokes" is, as always, not a good
reason.


Carl Banks

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


Re: Object Persistence Using a File System

2006-07-18 Thread Bruno Desthuilliers
Nick Vatamaniuc a écrit :
(please don't top-post - corrected)

> 
> Bruno Desthuilliers wrote:
> 
(snip)

>>A few observations and questions :
>>- you should avoid tests on concrete types as much as possible - at
>>least use isinstance
 >
 > Good point about isinstance. Here is a good explanation why:
 > http://www.canonical.org/~kragen/isinstance/

Err... I'm sorry but justifying the use of explicit tests on concrete 
type not even taking inheritance into consideration with a paper 
explaining why type tests taking inheritance into consideration may be 
bad seems rather strange to me... Or did I missed your point here ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-18 Thread Bruno Desthuilliers
Boris Borcic a écrit :
> Hello Bruno,
> 
> Bruno Desthuilliers wrote:
> 
>> Boris Borcic wrote:
>>
 Do you have any ideas?
>>>
>>>
>>> you could use a recursive generator, like
>>>
>>> def genAllChildren(self) :
>>> for child in self.children :
>>> yield child
>>> for childchild in child.genAllChildren() :
>>> yield childchild
>>
>>
>>
>> Or how to *not* address the real problem...
>>
>> Boris, using a generator may be a pretty good idea, but *not* as a way
>> to solve a problem that happens to be a FAQ !-)
>>
> 
> Sorry, but I don't understand your reasoning.

It's quite simple. The OP's problem is well-known (it's a FAQ), and easy 
to solve. The righ answer to it is obviously to give a link to the FAQ 
(or take time to re-explain it for the zillionth time), not to propose a 
workaround.

> How can you exclude that 
> the OP /may/ find that a generator neatly solves his problem ?

I don't exclude it, and explicitly mentioned in whole letters that, I 
quote, it "may be a pretty good idea". And actually, the OP's problem is 
really with default values evaluation scheme - something that every 
Python programmer should know, because there are cases where you cannot 
solve it with a generator-based solution !-)

> The use 
> of a default value was not an end in itself, was it ?

If the OP has other reasons to want to use an accumulator based solution 
- which we don't know - then the possibility to use a default value is 
important.

> - and the quirks of 
> default values being FAQ stuff don't change that. Sure if nobody had 
> covered that aspect, but a couple other posters did...

Yes, but you forgot to mention that - and I would not have post any 
comment on your solution if you had explicitly mentioned the FAQ or 
these other answers.

> Mmmmhhh somehow it feels like if there is any issue here, it is about 
> defending the credo "there ought to exist only one obvious way to do it" 
> ?...

Nope, it's about trying to make sure that anyone googling for a similar 
problem will notice the canonical solution somehow.

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


Authentication

2006-07-18 Thread bigodines
Hello guys,

I'm trying to learn python by making some small programs that could be
useful for some bigger propouses. In fact, i've made a small "check
latest-modified" for webpages and it's working great.

The next step I would like to do is to check if I have new e-mails (I
don't wanna read it from my program, i just wanna it to tells me "yes,
you have new mail(s)" or "no".

My question is, how do I log into my google account using urllib2 to
check this? Does anyone have a sample script that I can use or
something to help me?

thanks in advice,
Matheus

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


Re: Getting and Setting Cookies

2006-07-18 Thread John J. Lee
"Vlad Dogaru" <[EMAIL PROTECTED]> writes:

> I am trying to use cookies and Python to create a simple login example.
> But I am very disoriented at the existence of two cookie libraries,
> namely Cookie and cookielib. I have seen examples of setting cookies
[...]

>From the cookielib docs:

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

| The cookielib module defines classes for automatic handling of HTTP
| cookies. It is useful for accessing web sites that require small
| pieces of data - cookies - to be set on the client machine by an HTTP
| response from a web server, and then returned to the server in later
| HTTP requests.

(note the *accessing* there)

[...]

| Module Cookie: HTTP cookie classes, principally useful for server-side
| code. The cookielib and Cookie modules do not depend on each
| other.


Module cookielib is for web client code (writing code that works like
a browser).  Module Cookie is for server-side code (writing code to
make a web site work).  You don't make it entirely clear which you're
doing, but it sounds like the latter.


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


Re: Can thread start other threads?

2006-07-18 Thread John Henry
Thanks for the confirmation.

I will see if I can reduce the code down to something managable and
post the failing code.



Diez B. Roggisch wrote:
> John Henry schrieb:
> > Can Python thread start threads?  It appears not.  When I do that, the
> > sub-threads gets to certain point and just sit there.  If I run the
> > code serially and not run the sub-thread code as threads, everything is
> > fine.
>
> It can.
>
> import threading, time
>
>
> class Test(threading.Thread):
>  def __init__(self, num):
>  threading.Thread.__init__(self)
>  self._num = num
>  self.setDaemon(True)
>  self.start()
>
>  def run(self):
>  if self._num > 0:
>  t = Test(self._num - 1)
>  while True:
>  time.sleep(.2)
>  print "T_%i" % self._num
>
>
> t = Test(4)
>
> while True:
>  time.sleep(2.0)
>
>
> > I throught the problem is when you run multiple processes of Pythons...
>
>
> No.
>
> Whatever you do, it must be the cause. Without code - nobody can tell
> you why.
> 
> Diez

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


Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Volker Grabsch a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> schrieb:
> 
>>Carl Banks wrote:
>>
>>>Bruno Desthuilliers wrote:
>>>
>>>I'm well aware of Python's semantics, and it's irrelvant to my
>>>argument.
> 
> [...]
> 
>>>If the language
>>>were designed differently, then the rules would be different.
>>
>>Totally true - and totally irrelevant IMHO.
> 
> 
> I strongly advise not to treat each others thoughts as irrelevant.
> Assuming the opposite is a base of every public dicussion forum.

"Irrelevant" may not be the best expression of my thought here - it's 
just that Carl's assertion is kind of a tautology and doesn't add 
anything to the discussion. If Python had been designed as statically 
typed (with declarative typing), the rules would be different. Yeah, 
great. And now ?

> I assume here is a flaw in Python. To explain this, I'd like to
> make Bruno's point

Actually Carl's point, not mine.

> clearer. As usually, code tells more then
> thousand words (an vice versa :-)).
> 
> Suppose you have two functions which somehow depend on the emptyness
> of a sequence. This is a stupid example, but it demonstrates at
> least the two proposed programming styles:
> 
> --
> 
def test1(x): 
> 
> ... if x:
> ... print "Non-Empty"
> ... else:
> ... print "Empty"
> ... 
> 
def test2(x):
> 
> ... if len(x) > 0:
> ... print "Non-Empty"
> ... else:
> ... print "Empty"
> --
> 
> Bruno

Carl

> pointed out a subtle difference in the behaviour of those
> functions:
> 
> --
> 
a = [] 
test1(a)
> 
> Empty
> 
test1(iter(a))
> 
> Non-Empty
> 
test2(a)
> 
> Empty
> 
test2(iter(a))
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 2, in test2
> TypeError: len() of unsized object
> --
> 
> 
> While test1() returns a wrong/random result when called with an
> iterator, the test2() function breaks when beeing called wrongly.

Have you tried these functions with a numpy array ?

> So if you accidently call test1() with an iterator, the program
> will do something unintended, and the source of that bug will be
> hard to find. So Bruno is IMHO right in calling that the source
> of a suptle bug.

Actually it's Carl who makes that point - MHO being that it's a 
programmer error to call a function with a param of the wrong type.

> However, if you call test2() with an iterator, the program will
> cleanly break early enough with an exception. That is generally
> wanted in Python. You can see this all over the language, e.g.
> with dictionaries:
> 
> --
> 
d = { 'one': 1 }
print d['one']
> 
> 1
> 
print d['two']
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> KeyError: 'two'
> --
> 
> Python could have been designed to return None when d['two'] has been
> called, as some other (bad) programming languages would. This would
> mean that the problem will occur later in the program, making it easy
> to produce a subtle bug. It would be some effort to figure out the
> real cause, i.e. that d had no entry for 'two'.

I don't think the comparison is right. The equivalent situation would be 
to have a function trying to access d['two'] on a dict-like type that 
would return a default value instead of raising a KeyError.

> Luckily, Python throws an exception (KeyError) just at the original
> place where the initial mistake occured. If you *want* to get None in
> case of a missing key, you'll have to say this explicitly:
> 
> --
> 
print d.get('two', None)
> 
> None
> --
> 
> So maybe "bool()" should also break with an exception if an object
> has neither a __nonzero__ nor a __len__ method, instead of defaulting
> to True. 

FWIW, Carl's main example is with numpy arrays, that have *both* methods 
- __nonzero__ raising an expression.

> Or a more strict variant of bool() called nonempty() should
> exist.
> 
> Iterators don't have a meaningful Boolean representation,
> because
> phrases like "is zero" or "is empty" don't make sense for them.

If so, almost no type actually has a "meaningfull" boolean value. I'd 
rather say that iterators being unsized, the mere concept of an "empty" 
iterator has no meaning.

> So
> instead of answering "false", an iterator should throw an exception
> when beeing asked whether he's empty.



> If a function expects an object to have a certain protocol (e.g.
> sequence), and the given object doesn't support that protocol,
> an exception should be raised.

So you advocate static typing ? Note that numpy arrays actually have 
both __le

Re: Coding style

2006-07-18 Thread Bruno Desthuilliers
Volker Grabsch a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> schrieb:
> 
>>PTY wrote:
>>
>>>I was asking whether it was better style to
>>>use len() or not.
>>
>>FWIW, it's also more generic (you could have an object supporting
>>pop() but not __len__()), less error-prone,
> 
> 
> While I agree with all other points, I don't think that it's less
> error-prone. 

There are less risk of a typo with "if a:" than with "if len(a) > 0".

> See my other posting where I worked out this a flaw
> of Python.

See my answer where I don't agree on this being a "flaw" - a "minor 
wart" at most !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help getting xml feed from a url

2006-07-18 Thread John Bokma
"Shan" <[EMAIL PROTECTED]> wrote:

> If i have a list of urls how can I extract or pull their respective xml
> feeds?

What have you tried so far?

-- 
John   MexIT: http://johnbokma.com/mexit/
   personal page:   http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter help

2006-07-18 Thread Harold Fellermann
hi,

groves wrote:
> Now let me tell you that i was able to create a simple listbox which
> had 6 options which one can select, but Now what I want is that from
> the available menu, if I select an option it should give me another
> menu associated with that option. Its like digging up that option to do
> advance search.

If I understood you correctly, this is how I would go for it:
consider to create all submenus during initialization but make them
invisible
(put each of them in a single frame) anf toggle the visibility of these
frames 
in the handler of your option menu.

- harold -

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


Re: range() is not the best way to check range?

2006-07-18 Thread Paul Boddie
John Machin wrote:
> On 19/07/2006 1:05 AM, Dan Bishop wrote:
> >
> > xrange already has __contains__.
>
> As pointed out previously, xrange is a function and one would not expect
> it to have a __contains__ method.

Well, you pointed out that range is a function, but xrange seems to be
a type...

>>> xrange

>>> dir(xrange)
['__class__', '__delattr__', '__doc__', '__getattribute__',
'__getitem__', '__hash__', '__init__', '__iter__', '__len__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
'__setattr__', '__str__']

No __contains__ method, though, at least in 2.4.1.

> The objects returned by xrange do not (according to my reading of the
> 2.4.3 version of Objects/rangeobject.c) have a __contains__ method.

As confirmed by the above evidence.

> I find it difficult to believe that an inefficient __contains__ has been
> implemented since.

So do I. As you go on to say, the usual sequence traversal mechanisms
are probably used to support the "in" operator. Whether it's a pressing
matter to add support for a more efficient mechanism depends on how
often people want to use ranges in the way described. Perhaps I'll
write a patch - who knows? ;-)

Paul

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


Re: tkinter help

2006-07-18 Thread John McMonagle
On Tue, 2006-07-18 at 08:37 -0700, groves wrote:
> hi eveyrbody , i have started working on python tkinter,
> While I was working on one of the tkinter classes..named listbox
> widget. I had a slight problem.
> 
> Now let me tell you that i was able to create a simple listbox which
> had 6 options which one can select, but Now what I want is that from
> the available menu, if I select an option it should give me another
> menu associated with that option. Its like digging up that option to do
> advance search.
> 
> Please I need help as I am making my project
> Thanks to eveyrbody who will take time to read this and solve it .
> 

Perhaps if you posted your code so far we could help - otherwise we
would just be shooting in the dark.



-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

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


Re: Can thread start other threads?

2006-07-18 Thread Diez B. Roggisch
John Henry schrieb:
> Can Python thread start threads?  It appears not.  When I do that, the
> sub-threads gets to certain point and just sit there.  If I run the
> code serially and not run the sub-thread code as threads, everything is
> fine.

It can.

import threading, time


class Test(threading.Thread):
 def __init__(self, num):
 threading.Thread.__init__(self)
 self._num = num
 self.setDaemon(True)
 self.start()

 def run(self):
 if self._num > 0:
 t = Test(self._num - 1)
 while True:
 time.sleep(.2)
 print "T_%i" % self._num


t = Test(4)

while True:
 time.sleep(2.0)


> I throught the problem is when you run multiple processes of Pythons...


No.

Whatever you do, it must be the cause. Without code - nobody can tell 
you why.

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


Re: Capturing instant messages

2006-07-18 Thread Yu-Xi Lim
Nick Vatamaniuc wrote:
> Assuming a one person per one machine per one chat protocol it might be
> possible to recreate the tcp streams (a lot of packet capturing devices
> already do that). So the gateway would have to have some kind of a
> dispatch that would recognize the initialization of a chat loggon and
> start a capture process for each such connection. I imagine with a 1000
> employess he will end up with a 1000 processes running at the same
> time. Another way is to capture all the streams at once that deal with
> the chat protocol and ports and then replay them later and somehow
> cre-create the tcp streams and chat messages in a cron batch job (at
> night or weekend).

As I said, it's tedious, not impossible. :) The AIM Sniff project (perl,
not Python) does most of what you describe, but has bugs because of the
approach.

You're also ignoring the fact that each person may chat with more than
one person. Some protocols route all messages through a central server,
making it impossible to use the IP of the other party as a unique
identifier (not that it's a good idea to use the IP anyway, since the
assumption of one unique and consistent IP per person is weak).
Furthermore, you have to deal with failed messages, resends, etc at the
application layer. And there are also other non-trivial (but thankfully
rarely occurring) issues with TCP stream reconstruction.

Basically, it's looking at the wrong OSI layer. An application layer
protocol is best handled at the application where all the necessary
semantics are easily available. It /is/ an business/organization trying
to conform to SOX, so something as minor as switching and standardizing
IM clients (not necessarily protocols) would be probably the least of
their problems. And probably more manageable than a custom script for a
non-trivial activity.

There are definitely enterprise solutions available. And if you want to
get Python involved in this discussion, consider GAIM, which can be
scripted using Python via a plugin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV with comments

2006-07-18 Thread John Machin
On 19/07/2006 5:34 AM, [EMAIL PROTECTED] wrote:
> >> In csv.reader, is there any way of skip lines that start whith '#' or
> >> empty lines
> 
> Nope.  When we wrote the module we weren't aware of any "spec" that
> specified comments or blank lines.  You can easily write a file wrapper to
> filter them out though:
> 
> class BlankCommentCSVFile:
> def __init__(self, fp):
> self.fp = fp
> 
> def __iter__(self):
> return self
> 
> def next(self):
> line = self.fp.next()
> if not line.strip() or line[0] == "#":
> return self.next()

This is recursive. Unlikely of course, but if the file contained a large 
number of empty lines, might this not cause the recursion limit to be 
exceeded?


> return line
> 
> Use it like so:
> 
> reader = csv.reader(BlankCommentCSVFile(open("somefile.csv")))
> for row in reader:
> print row
> 

Hi Skip,

Is there any reason to prefer this approach to Daniel's, apart from 
being stuck with an older (pre-yield) version of Python?

A file given to csv.reader is supposed to be opened with "rb" so that 
newlines embedded in data fields can be handled properly, and also 
(according to a post by Andrew MacNamara (IIRC)) for DIY emulation of 
"rU". It is not apparent how well this all hangs together when a filter 
is interposed, nor whether there are any special rules about what the 
filter must/mustn't do. Perhaps a few lines for the docs?

Cheers,
John

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


Can thread start other threads?

2006-07-18 Thread John Henry
Can Python thread start threads?  It appears not.  When I do that, the
sub-threads gets to certain point and just sit there.  If I run the
code serially and not run the sub-thread code as threads, everything is
fine.

I throught the problem is when you run multiple processes of Pythons...

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


Re: Cyclic class definations

2006-07-18 Thread John Henry
Thanks for the note, Nick.

I ended up with cycles as a historical reason.  Some code that were
written long time ago did not anticipate that part of it will get
sub-classed.

Thanks again.

Nick Vatamaniuc wrote:
> John,
> Cycles are tricky. Python is an interpreted dynamic language, whatever
> object you instantiate in your methods is a different thing than class
> hierarchy. Your class hierarchy is fine: ClassA->ClassASubclass->ClassC
> and it should work.  If it doesn't, create a quick mock example and
> post it along with the error.
>
> In general try to model your problem to avoid cycles if possible, I
> know sometimes they are un-avoidable, but more often then not, they
> are. Python might or might not allow cycles in certain situations
> (packages, imports, class hierarchy and during usage i.e. in your
> semantics) but regardless, if they make your code hard to understand so
> try to not introduce them if possible.
>
> Hope this helps,
> Nick V.
>
>
> John Henry wrote:
> > Hi list,
> >
> > I am trying to understand better Python packaging.  This might be a
> > messed up class hierachy but how would I break this cyclic relatioship?
> >
> > In file A:
> >
> > from B import B_Class
> >
> > Class_A_Main():
> >def 
> >def SomeMethod(self):
> >   res=B_Class(self)
> >
> > Class_A_SubClass(Class_A_Main):
> >def ...
> >
> >
> > In file B:
> >
> > Class B_Class():
> >def __init__(self,parent):
> >   ...
> >def SomeMethod(self):
> >   res=C_Class(self)
> >
> >
> > In file C:
> >
> > from file A import Class_A_SubClass
> >
> > Class C_Class(Class_A_SubClass):
> >def __init__(self, parent):
> >   ...
> >
> >
> > As you can see, the cyclic relationship exists because C_Class is a
> > sub-class of SubClass which is in turn a sub-class of Class_A_Main and
> > in one of the methods of Class_A, it has a need to create a C_Class
> > object.
> >
> > I tried to merge the files A and C (by placing C_Class behind A_Class)
> > and have the method in A_Class create C_Class directly but that doesn't
> > work because Python says C_Class is not defined when it's processing
> > the A_Class method.   May be somebody can tell me how to "forward
> > declare" a class?
> > 
> > Regards,

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


Re: Defining functions in an implementation file

2006-07-18 Thread Yu-Xi Lim
westymatt wrote:
> I am fairly new to python and I want to put alot of my functions in
> another python file and import or from it into my script so I can call
> the functions.  How is this done?
> 

What you are describing are modules. The Python Tutorial has some
information on this

http://docs.python.org/tut/node8.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: range() is not the best way to check range?

2006-07-18 Thread John Machin
On 19/07/2006 1:05 AM, Dan Bishop wrote:
> Paul Boddie wrote:
> 
>> Yes, he wants range to return an iterator, just like xrange more or
>> less does now. Given that xrange objects support __getitem__, unlike a
>> lot of other iterators (and, of course, generators), adding
>> __contains__ wouldn't be much of a hardship. Certainly, compared to
>> other notational conveniences bounced around on the various development
>> lists, this one would probably provide an order of magnitude
>> improvement on the usual bang per buck development ratio.
> 
> xrange already has __contains__. 

As pointed out previously, xrange is a function and one would not expect 
it to have a __contains__ method.

The objects returned by xrange do not (according to my reading of the 
2.4.3 version of Objects/rangeobject.c) have a __contains__ method.

I find it difficult to believe that an inefficient __contains__ has been 
implemented since.

Perhaps you are unaware that the mere fact that an object supports the 
"in" operation does not mean that this support is provided by a 
__contains__ method. The following section of the manual may help:

"""
The membership test operators (in and not in) are normally implemented 
as an iteration through a sequence. However, container objects can 
supply the following special method with a more efficient 
implementation, which also does not require the object be a sequence.

__contains__(   self, item)
 Called to implement membership test operators. Should return true 
if item is in self, false otherwise. For mapping objects, this should 
consider the keys of the mapping rather than the values or the key-item 
pairs.
"""

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread The Eternal Squire
I'll try to figure out a way to let people know who the FAQ I am :)

The Eternal Squire

Méta-MCI wrote:
> Hi!
>
> Interesting (or fun?).
> Have you a Internet page, or only README?
> 
> @+
> 
> MCI

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread The Eternal Squire
Best interface for roguelike gaming.

Jarek Zgoda wrote:
> The Eternal Squire napisa³(a):
>
> > Diet Python is a flavor of Python with allegro, multiarray, umath,
> > calldll, npstruct and curses builtin, all else nonessential to language
> > ripped out. Total size < 3MB, 1% of PSF Python. Diet Python helps keep
> > clients thin :)
>
> Why do you think curses are essential? I'd rip out them too, they have
> no use on Windows.
> 
> -- 
> Jarek Zgoda
> http://jpa.berlios.de/

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


Re: ScientificPython - LeastSquareFit diverges

2006-07-18 Thread konrad . hinsen
On 18.07.2006, at 15:59, Harold Fellermann wrote:

 def powerlaw((a,b),x) :
> ... return a*x**b

Fitting power laws is a tricky business, you need a pretty good  
initial guess to get convergence.

> Note that I could easily fit the above data using gnuplots internal
> fitting procedure. Any idea what is going wrong here? Is it a known
> problem? Are there any work arounds or other packages?

My suggestion is to fit, at least as a first step, the logarithms of  
your data points:

import Numeric as N

def powerlaw_log((a, b), x) :
 return N.log(a) + b*N.log(x)

params1, chisq = leastSquaresFit(powerlaw_log, (10., -3.),
 [(x, N.log(y)) for x, y, sigma in  
data])


You can then use those parameters as starting values for fitting your  
original problem:

params2, chisq = leastSquaresFit(powerlaw, params1, data)

Doing this for your data yields:

params1: [9469.9675999067185, -2.0881423620750521]

params2: [1591.4025775162165, -1.0112284948049179]

The big difference between the two fits is a further indicator for a  
stability problem. I would trust the first set more than the second one.

As a general rule, the model to be fitted should be a smoothly  
varying function of the parameters, and the same should be true for  
the derivatives.

The second general rule is never to trust a non-linear fit algorithm  
blindly. Look at your data first, see if the model can be a good fit,  
and play with some paramater values to get a feeling for how they  
influence the fit. Plotting your data set, it is immediately clear  
that the first point ruins any nice power law behaviour. You might  
thus prefer to do the fit without the first point, and you will get a  
much better defined exponent:

params1: [31363.301954929859, -2.4047303053979046]
params2: [182522.2346197216, -2.9893640209815757]

Plotting the models corresponding to these two sets together with the  
data, you will see that everything coincides well for large x values,  
meaning that the first two points make all the difference - another  
pointer towards a lack of stability in the fit.

Konrad.
--
-
Konrad Hinsen
Centre de Biophysique Moléculaire, CNRS Orléans
Synchrotron Soleil - Division Expériences
Saint Aubin - BP 48
91192 Gif sur Yvette Cedex, France
Tel. +33-1 69 35 97 15
E-Mail: [EMAIL PROTECTED]
-


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


Re: range() is not the best way to check range?

2006-07-18 Thread tac-tics
Simon Forman wrote:
> To me, and perhaps others, "T =
> set(xrange(0, 1, 23))" and "n in T"  are somewhat easier to read
> and write than "not n % 23 and 0 <= n < 1", YMMV.

Eh? How is the first easier to read than the second?? You have a nested
function call in the first!

Regardless, testing if a member is part of a ranged set is always going
to be slower. It's the nature of what you're doing. Building a set and
then searching it takes much longer than a single modulus and
subtraction (which is all an integer comparison is).

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


Re: range() is not the best way to check range?

2006-07-18 Thread Summercoolness

[EMAIL PROTECTED] wrote:
> it seems that range() can be really slow:
>
> if i in range (0, 1):


My original use was like this:

if i in range (iStart, iEnd):
listData.append(a)

in which iStart is 1000 and iEnd is 1008

so in that case, the program ran fine...
but later on, i wanted to include all data, so I relaxed the range by
setting iStart to 0 and iEnd to  and later on i found that the
program was slow due to this.

So looks like the usage of

   if sDay in ("Tue", "Wed", "Thu"):

is more like good use of "in a list"  but in range(0,1) will be a
big search in a list.

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread Jarek Zgoda
The Eternal Squire napisał(a):

> Diet Python is a flavor of Python with allegro, multiarray, umath,
> calldll, npstruct and curses builtin, all else nonessential to language
> ripped out. Total size < 3MB, 1% of PSF Python. Diet Python helps keep
> clients thin :)

Why do you think curses are essential? I'd rip out them too, they have
no use on Windows.

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


Re: Coding style

2006-07-18 Thread bearophileHUGS
Volker Grabsch wrote:
> IMHO, that flaw of Python should be documented in a PEP as it violates
> Python's priciple of beeing explicit. It also harms duck typing.

I think this may be good food for Python 3.0, the are removing
undefined comparisons too (>), etc.

bye,
bearophile

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


Re: No need to close file?

2006-07-18 Thread Robert Kern
T wrote:
> Thomas Bartkus wrote:
>> "T" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>> Do I need to close the file in this case?  Why or why not?
>>>
>>> for line in file('foo', 'r'):
>>>   print line
>> Are you asking if you can get away without closing it?
>> Or are you asking if it is a good idea to not close it?
>>
>> Good programming practice says that if you open it - you close it.
>>
>> And stay out of trouble ;-)
>> Thomas Bartkus
> 
> How do I close the file in the above case?

You rewrite the faulty code such that the above case isn't the above case 
anymore.

f = open('foo', 'r')
try:
   for line in f:
 print line
finally:
   f.close()

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: No need to close file?

2006-07-18 Thread Grant Edwards
On 2006-07-18, T <[EMAIL PROTECTED]> wrote:

>>> for line in file('foo', 'r'):
>>>   print line

>> Good programming practice says that if you open it - you close it.
>>
>> And stay out of trouble ;-)

> How do I close the file in the above case?

Aye, there's the rub.

You can't close an anonymous file, so you have to give it a name.

   f = file('foo', 'r')
   for line in f:
  print line
   f.close()

-- 
Grant Edwards   grante Yow!  The PILLSBURY
  at   DOUGHBOY is CRYING for
   visi.coman END to BURT REYNOLDS
   movies!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No need to close file?

2006-07-18 Thread T
Thomas Bartkus wrote:
> "T" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Do I need to close the file in this case?  Why or why not?
> >
> > for line in file('foo', 'r'):
> >   print line
>
> Are you asking if you can get away without closing it?
> Or are you asking if it is a good idea to not close it?
>
> Good programming practice says that if you open it - you close it.
>
> And stay out of trouble ;-)
> Thomas Bartkus



How do I close the file in the above case?

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


Re: Coding style

2006-07-18 Thread David M. Cooke
[EMAIL PROTECTED] (David M. Cooke) writes:
>
> Bruno's already mentioned that iterators and generators aren't
> sequences. Numpy arrays act like the other sequence types:
>
 a = numpy.array([])
 a
> array([], dtype=int64)
 len(a)
> 0
 bool(a)
> False
>
> (0-dimensional numpy arrays are pathological anyways)

*cough* as a Numpy developer I should know better. Numpy arrays that
have more than one element don't work in a boolean context:

>>> a = numpy.array([1,2])
>>> bool(a)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

The reason for this is that it really was a common source of errors,
because of the rich comparision semantics used. If a and b are numpy
arrays, 'a == b' is an array of booleans.

Numpy arrays of one element act like scalars in boolean contexts:

>>> a = numpy.array([0])
>>> bool(a)
False
>>> a = numpy.array([1])
>>> bool(a)
True

(this is partly because we define a comphensive hierarchy of scalar
types to match those available in C).

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No need to close file?

2006-07-18 Thread Grant Edwards
On 2006-07-18, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
> T enlightened us with:
>> Do I need to close the file in this case?  Why or why not?
>>
>> for line in file('foo', 'r'):
>>   print line
>
> Nope, it'll get closed automatically when the file object gets garbage
> collected.

Which might not happen until the program exits.  So, for small
programs, you don't have to close it.  Same as C or any other
language.

For large or longrunning programs that open lots of files, it's
generally recommended that you close files when you're done
with them.

-- 
Grant Edwards   grante Yow!  I am NOT a nut
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-18 Thread David M. Cooke
"Carl Banks" <[EMAIL PROTECTED]> writes:

> Patrick Maupin wrote:
>> PTY wrote:
>>
>> > It looks like there are two crowds, terse and verbose.  I thought terse
>> > is perl style and verbose is python style.  BTW, lst = [] was not what
>> > I was interested in :-)  I was asking whether it was better style to
>> > use len() or not.
>>
>> It's not canonical Python to use len() in this case.  From PEP 8:
>>
>> - For sequences, (strings, lists, tuples), use the fact that empty
>>   sequences are false.
>>
>>   Yes: if not seq:
>>if seq:
>>
>>   No: if len(seq)
>>   if not len(seq)
>>
>> The whole reason that a sequence supports testing is exactly for this
>> scenario.  This is not an afterthought -- it's a fundamental design
>> decision of the language.
>
> That might have made sense when Python and string, list, tuple were the
> only sequence types around.
>
> Nowadays, Python has all kinds of spiffy types like numpy arrays,
> interators, generators, etc., for which "empty sequence is false" just
> doesn't make sense.  If Python had been designed with these types in
> mind, I'm not sure "empty list is false" would have been part of the
> language, let alone recommend practice.

Bruno's already mentioned that iterators and generators aren't
sequences. Numpy arrays act like the other sequence types:

>>> a = numpy.array([])
>>> a
array([], dtype=int64)
>>> len(a)
0
>>> bool(a)
False

(0-dimensional numpy arrays are pathological anyways)

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No need to close file?

2006-07-18 Thread [EMAIL PROTECTED]

T wrote:
> Do I need to close the file in this case?  Why or why not?
>
> for line in file('foo', 'r'):
>   print line

I was running a program in IDLE that opened a file for
reading and forgot to add the close.

The program ran and terminated normally.

But when I tried to open it from Windows Explorer,
I got the message that it was still in use. Had to close
IDLE to release it. That wouldn't have happened if I had
closed it from within the program.

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


need help getting xml feed from a url

2006-07-18 Thread Shan
If i have a list of urls how can I extract or pull their respective xml
feeds?

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


Re: pytables - best practices / mem leaks

2006-07-18 Thread py_genetic

py_genetic wrote:
> I have an H5 file with one group (off the root) and two large main
> tables and I'm attempting to aggragate my data into 50+ new groups (off
> the root) with two tables per sub group.
>
> sys info:
> PyTables version:  1.3.2
> HDF5 version:  1.6.5
> numarray version:  1.5.0
> Zlib version:  1.2.3
> BZIP2 version: 1.0.3 (15-Feb-2005)
> Python version:2.4.2 (#1, Jul 13 2006, 20:16:08)
> [GCC 4.0.1 (Apple Computer, Inc. build 5250)]
> Platform:  darwin-Power Macintosh (v10.4.7)
> Byte-ordering: big
>
> Ran all pytables tests included with package and recieved an OK.
>
>
> Using the following code I get one of three errors:
>
> 1. Illegal Instruction
>
> 2. Malloc(): trying to call free() twice
>
> 3. Bus Error
>
> I believe all three stem from the same issue, involving a malloc()
> memory problem in the pytable c libraries.  I also believe this may be
> due to how I'm attempting to write my sorting script.
>
> The script executes fine and all goes well until I'm sorting about
> group 20 to 30 and I throw one of the three above errors depending on
> how/when I'm flush() close() the file.  When I open the file after the
> error using h5ls all tables are in perfact order up to the crash and if
> I continue from the point every thing runs fine until python throws the
> same error again after another 10 sorts or so.  The somewhat random
> crashing is what leads me to believe I have a memory leak or my method
> of doing this is incorrect.
>
> Is there a better way to aggragate data using pytables/python? Is there
> a better way to be doing this?  This seems strait forward enough.
>
> Thanks,
> Conor
>
> #function to agg state data from main neg/pos tables into neg/pos state
> tables
>
> import string
> import tables
>
>
> def aggstate(state, h5file):
>
>   print state
>
>   class PosRecords(tables.IsDescription):
>   sic = tables.IntCol(0, 1, 4, 0, None, 0)
>   numsic = tables.IntCol(0, 1, 4, 0, None, 0)
>   empsiz = tables.StringCol(1, '?', 1, None, 0)
>   salvol = tables.StringCol(1, '?', 1, None, 0)
>   popcod = tables.StringCol(1, '?', 1, None, 0)
>   state = tables.StringCol(2, '?', 1, None, 0)
>   zip = tables.IntCol(0, 1, 4, 0, None, 1)
>
>   class NegRecords(tables.IsDescription):
>   sic = tables.IntCol(0, 1, 4, 0, None, 0)
>   numsic = tables.IntCol(0, 1, 4, 0, None, 0)
>   empsiz = tables.StringCol(1, '?', 1, None, 0)
>   salvol = tables.StringCol(1, '?', 1, None, 0)
>   popcod = tables.StringCol(1, '?', 1, None, 0)
>   state = tables.StringCol(2, '?', 1, None, 0)
>   zip = tables.IntCol(0, 1, 4, 0, None, 1)
>
>
>
>   group1 = h5file.createGroup("/", state+"_raw_records", state+" raw
> records")
>
>   table1 = h5file.createTable(group1, "pos_records", PosRecords, state+"
> raw pos record table")
>   table2 = h5file.createTable(group1, "neg_records", NegRecords, state+"
> raw neg record table")
>
>   table = h5file.root.raw_records.pos_records
>   point = table1.row
>   for x in table.iterrows():
>   if x['state'] == state:
>   point['sic'] = x['sic']
>   point['numsic'] = x['numsic']
>   point['empsiz'] = x['empsiz']
>   point['salvol'] = x['salvol']
>   point['popcod'] = x['popcod']
>   point['state'] = x['state']
>   point['zip'] = x['zip']
>
>   point.append()
>
>   h5file.flush()
>
>   table = h5file.root.raw_records.neg_records
>   point = table2.row
>   for x in table.iterrows():
>   if x['state'] == state:
>   point['sic'] = x['sic']
>   point['numsic'] = x['numsic']
>   point['empsiz'] = x['empsiz']
>   point['salvol'] = x['salvol']
>   point['popcod'] = x['popcod']
>   point['state'] = x['state']
>   point['zip'] = x['zip']
>
>   point.append()
>
>
>   h5file.flush()
>
>
>
> states =
> ['AL','AK','AZ','AR','CA','CO','CT','DC','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY']
>
> h5file = tables.openFile("200309_data.h5", mode = 'a')
>
> for i in xrange(len(states)):
>   aggstate(states[i], h5file)
>
> h5file.close()

The problem with my above posting is that h5file.flush() should be
table.flush() (flush the table not the whole object) although
h5file.flush() is an actual method I don't believe it c

Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread The Eternal Squire
Hm didn't I leave ctypes in there?  I added calldll because it had
a really nice can opener.

The Eternal Squire

[EMAIL PROTECTED] wrote:
> >> Diet Python is a flavor of Python with allegro, multiarray, umath,
> >> calldll, npstruct and curses builtin, all else nonessential to
> >> language ripped out. Total size < 3MB, 1% of PSF Python. Diet Python
> >> helps keep clients thin :)
>
> Just an FYI, but Python 2.5 comes with ctypes, not calldll.  Might be worth
> switching to remain compatible at that level.
> 
> Skip

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


Re: run a string as code?

2006-07-18 Thread py_genetic
Gary Herron wrote:
> py_genetic wrote:
> > py_genetic wrote:
> >
> >> [EMAIL PROTECTED] wrote:
> >>
> >>> py_genetic wrote:
> >>>
>  How can you make python interpret a string (of py code) as code.  For
>  example if you want a py program to modify itself as it runs.  I know
>  this is an advantage of interpreted languages, how is this done in
>  python.  Thanks.
> 
> >>> This might do it...
> >>>
> >>>
> >> print eval.__doc__
> >>
> >>> eval(source[, globals[, locals]]) -> value
> >>>
> >>> Evaluate the source in the context of globals and locals.
> >>> The source may be a string representing a Python expression
> >>> or a code object as returned by compile().
> >>> The globals must be a dictionary and locals can be any mappping,
> >>> defaulting to the current globals and locals.
> >>> If only globals is given, locals defaults to it.
> >>>
> >> For example each time this line is interpreted I would like to use the
> >> new value of the state var which is a global var.  How can I force
> >> state to be identified and used in this string.
> >>
> >> r_table = h5file.root.state_raw_records.neg_records
> >>
> >> r_table = eval("h5file.root.state_raw_records.neg_records") ??
> >> r_table = h5file.root.eval("state")_raw_records.neg_records ?? eval is
> >> not a part of root
> >>
> >> dont think either of these is very logical? Any ideas?  Possibly the
> >> parser mod?
> >>
> >
> > Got it!
> >
> > tmp = "h5file.root."+state+"_raw_records.pos_records"
> > r_table = eval(tmp)
> >
> > works great thanks for the help!
> >
> Yes, it works, but this is not a good place to use eval. Now that we see
> how you want to use it, we can find a *much* better way to do it.
>
> If you want to lookup an attribute of an object, but the attribute name
> is a string in a variable, then use getattr to do the lookup.
>
> If in interpret your code correctly:
>
> attrname = state + "_raw_records"
> obj = getattr(h5file.root, attrname)
> r_table = obj.pos_records
>
> These, of course, could be combined into a single (but not necessarily
> clearer) line.
>
> Gary Herron

So it is eval() is more appropriate when evalution blocks of string
code, and getattr() is more efficient for dealing with objects such as
h5file object above?  Thanks.

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


Re: Using Visual Slick Edit for Python

2006-07-18 Thread jjones
> P.S. Have you already upgraded to v11 and is there anything worthwhile
> in it (Python or otherwise)?

Hi,

We have just released 11.0.1 where we improve and add new support for
scripting and dynamic languages.  A snippet of the press release can be
found below.

SlickEdit v11.0.1 continues to improve support for the Python language
by offering enhanced Context Tagging™, Auto-Completion, Syntax
Indenting, and code navigation.

Thank you,

Jason Jones
SlickEdit
www.slickedit.com

SlickEdit Forums
http://community.slickedit.com/

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


Re: range() is not the best way to check range?

2006-07-18 Thread Simon Forman
K.S.Sreeram wrote:
> Simon Forman wrote:
> > Nick Craig-Wood wrote:
> >> Sets are pretty fast too, and have the advantage of flexibility in
> >> that you can put any numbers in you like
> >>
> >
> > I know this is self-evident to most of the people reading this, but I
> > thought it worth pointing out that this is a great way to test
> > membership in range(lo, hi, step) without doing "the necessary
> > algebra".
> >
> > i.e.  n in set(xrange(0, 1, 23)) ...
>
> This is very very misleading... here are some timings :

Yes it is. I'm sorry about that.

> python -mtimeit "n=5000" "n in set(xrange(0,1))"
> 1000 loops, best of 3: 1.32 msec per loop
>
> python -mtimeit "n=5000" "n in xrange(0,1)"
> 1000 loops, best of 3: 455 usec per loop
>
> python -mtimeit "n=5000" "0 <= n < 1"
> 100 loops, best of 3: 0.217 usec per loop
>
> sets are fast only if you create them *once* and use them again and
> again. even in that case, the sets use up O(n) memory.

That's what I meant.  But I didn't state it clearly.

One of the things I like most about python is that it allows you to
specify the problem that you want to solve without a great deal of
difficulty as to *how* to specify it.  To me, and perhaps others, "T =
set(xrange(0, 1, 23))" and "n in T"  are somewhat easier to read
and write than "not n % 23 and 0 <= n < 1", YMMV.

In the given case a set of ~(1 / 23) ints would not usually be too
burdensome on ram, and the code runs close to the same speed as
compared to the direct calculation:

from timeit import Timer

times = 10
Max = 1
n = 5000
T = set(xrange(0, Max, 23))

s1 = 'n in T'
s2 = 'not n %% 23 and 0 <= n < %s' % Max

setup = 'from __main__ import n, T'


S1 = Timer(s1, setup).repeat(number=times)
S2 = Timer(s2, setup).repeat(number=times)


print "%.3f usec/pass" % (100 * min(S1) / times)
print "%.3f usec/pass" % (100 * min(S2) / times)

On my machine this printed:
0.476 usec/pass
0.552 usec/pass


>
> with comparison operators, you don't need extra memory *and* there is no
> pre-computation required.

When I set Max = 1 in the above test code there was serious
disk thrashing...  ;-)

>
> [sreeram;]
>


FWIW, in production code I would certainly use the comparison
operators.  A kilobyte saved is a kilobyte earned.

Peace,
~Simon

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


Re: No need to close file?

2006-07-18 Thread Thomas Bartkus

"T" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Do I need to close the file in this case?  Why or why not?
>
> for line in file('foo', 'r'):
>   print line

Are you asking if you can get away without closing it?
Or are you asking if it is a good idea to not close it?

Good programming practice says that if you open it - you close it.

And stay out of trouble ;-)
Thomas Bartkus


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


Re: Should this be added to MySQLdb FAQ?

2006-07-18 Thread Nick Vatamaniuc
gmax2006,
Yes, perhaps the MySQLdb project should mention that packages are
usually available in the popular distributions. I am using Ubuntu and
everything I needed for MySQL and Python was in the repositories ,
'apt-get' one-lines is all that is needed. In general though, I found
that more often than not the program I need is already in some
repository somewhere.


gmax2006 wrote:
> Hi,
>
> I went through couple of wrong paths to install MySQLdb on my RedHat
> box. I was trying to download MySQL client from MySQL.com and also
> mySQLdb from SourceForge. After some challenges with compile errors and
> also searching for pre-required RPMs, I found RedHat distribution
> already contains all compiled rpms and all I need are within CDs 3 and
> 4 of RedHat distribution!
>
> In essence, I found that I should check my Linux distribution first,
> then attempt to download stuff from sourceforge!
>
> I also posted the question to this group:
> http://groups.google.ca/group/comp.lang.python/browse_thread/thread/41c53c2c932dfa58/f72f09a863bffdb2?hl=en#f72f09a863bffdb2
>
> If this makes sense, should it be added to MySQLdb FAQ?
> 
> Regards,
> Max

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


Re: No need to close file?

2006-07-18 Thread Nick Vatamaniuc
 I think file object should be closed whether they will be garbage
collected or not. The same goes for DB  and network connections and so
on. Of course in simple short programs they don't have to, but if
someone keeps 1000 open files it might be  better to close them when
done. Besides open files (in 'w' mode) might not be able to be opened
by another process if they are not closed.  In general this is usually
a good habit to have (just like washing dishes right after a meal
rather than hoping someone will do it later eventually ;)

Regards,
Nick V.

Sybren Stuvel wrote:
> T enlightened us with:
> > Do I need to close the file in this case?  Why or why not?
> >
> > for line in file('foo', 'r'):
> >   print line
>
> Nope, it'll get closed automatically when the file object gets garbage
> collected.
>
> Sybren
> --
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?
>  Frank Zappa

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


Re: Augument assignment versus regular assignment

2006-07-18 Thread Piet van Oostrum
> Antoon Pardon <[EMAIL PROTECTED]> (AP) wrote:

>AP> On 2006-07-17, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
 Antoon Pardon <[EMAIL PROTECTED]> (AP) wrote:
>>> 
>AP> On 2006-07-14, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
>>> 
>> Just read what it says. `It is only evaluated once' is quite clear I 
>> would
>> say.
>>> 
>AP> If it is so clear, why don't you explain it? 
>>> 
>>> I have done that in another thread.

>AP> Before I respond I would like you to be more specific
>AP> about where you gave that explanation. The subject
>AP> of the thread would be fine or a message-id perhaps.

<[EMAIL PROTECTED]> (In fact it is in this same thread).
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No need to close file?

2006-07-18 Thread Jarek Zgoda
T napisał(a):

> Do I need to close the file in this case?  Why or why not?
> 
> for line in file('foo', 'r'):
>   print line

No, if you only read from the file.

But anyway, closing file object is considered good practice in many
documents I found, no matter what you do with it.

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


Re: range() is not the best way to check range?

2006-07-18 Thread bearophileHUGS
Dan Bishop:
> xrange already has __contains__.  The problem is, it's implemented by a
> highly-inefficient sequential search.  Why not modify it to merely
> check the bounds and (value - start) % step == 0?

I think this is a nice idea.

Bye,
bearophile

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


Re: No need to close file?

2006-07-18 Thread bearophileHUGS
T wrote:
> Do I need to close the file in this case?  Why or why not?
> for line in file('foo', 'r'):
>   print line

Close the file in Jython, but often it's not necessary in CPython.

Bye,
bearophile

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


Re: Capturing instant messages

2006-07-18 Thread Nick Vatamaniuc
Assuming a one person per one machine per one chat protocol it might be
possible to recreate the tcp streams (a lot of packet capturing devices
already do that). So the gateway would have to have some kind of a
dispatch that would recognize the initialization of a chat loggon and
start a capture process for each such connection. I imagine with a 1000
employess he will end up with a 1000 processes running at the same
time. Another way is to capture all the streams at once that deal with
the chat protocol and ports and then replay them later and somehow
cre-create the tcp streams and chat messages in a cron batch job (at
night or weekend).

Nick V.


Yu-Xi Lim wrote:
> Ed Leafe wrote:
> > I've been approached by a local business that has been advised that
> > they need to start capturing and archiving their instant messaging in
> > order to comply with Sarbanes-Oxley. The company is largely PC, but has
> > a significant number of Macs running OS X, too.
> >
>
> This is going to be quite off-topic.
>
> I'm not entirely familiar with SOX regulations. Is it necessary to
> capture it at the gateway? The best solution would be to provide logging
> at the individual chat clients. Piecing together conversation threads
> from individual packets while filtering out other non-chat junk can be
> extremely tedious.
>
> I understand the standard AIM client doesn't provide logging. Probably
> won't any time soon, since it wasn't made for enterprise. There are
> enterprise gateways for AIM, but I'm not sure of the cost or other
> deployment issues. (Try looking at Jabber) You should consider those. Or
> a switch to a more enterprise-friendly protocol if that's possible.
>
> Other alternatives would be to use a better client. Multi-protocol
> clients like GAIM, Trillian, Miranda, and Adium X generally provide
> logging. Most provide the ability to toggle logging for specific
> sessions, thus reducing privacy issues.

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


Re: Defining functions in an implementation file

2006-07-18 Thread Diez B. Roggisch
westymatt schrieb:
> I am fairly new to python and I want to put alot of my functions in
> another python file and import or from it into my script so I can call
> the functions.  How is this done?


import myfilefullofusefulfunctionsandclasses


Works if you have the file

myfilefullofusefulfunctionsandclasses.py

in your PYTHONPATH somewhere - usually, the current dir and some dirs in 
the installation directory.

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


Re: No need to close file?

2006-07-18 Thread skip

T> Do I need to close the file in this case?  Why or why not?

T> for line in file('foo', 'r'):
T>   print line

No.  The magic of reference counting.

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


Re: Coding style

2006-07-18 Thread Patrick Maupin

Daniel Dittmar wrote:
>
> Premature generalization: the new 'premature optimization'.

Premature specialization: the new 'static typing'.

-- Pat

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


No need to close file?

2006-07-18 Thread T
Do I need to close the file in this case?  Why or why not?

for line in file('foo', 'r'):
  print line

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


Re: Dispatch with multiple inheritance

2006-07-18 Thread Nick Vatamaniuc
Michael,
You only need to call the __init__ method of the superclass if you need
to do something special during initialization. In general I just use
the SuperClass.__init__(self,...) way of calling the super class
constructors. This way, I only initialize the immediate parents and
they will in turn call the init method of their parents and so on.
super() is probably the a better way to do things but I find
SuperClass.__init__(self, ...) more clear. For example your code would
be:
---
class A (object):
def __init__(self):
print "cons A"

class B (object):
def __init__(self):
print "cons B"

class C (A):
def __init__(self):
A.__init__(self)
print "cons C"

class D (B):
def __init__(self):
B.__init__(self)
print "cons D"

class E(D,C):
def __init__(self):
C.__init__(self)
D.__init__(self)
print "cons E"

e=E()
--
Output should be:
cons A
cons C
cons B
cons D
cons E

In general note that  __init__ is NOT a constuctor it is an initializer
(therefore the name __init__ as opposed to __constr__ or __new__). The
object is constructed by Python already and is given to init method as
the 'self' argument. The construction can also be customized inside the
__new__ magic method, but normally you don't even need to know about
__new__.

Hope this helps,
Nick V.

Michael J. Fromberger wrote:
> Consider the following class hierarchy in Python:
>
>   class A (object):
> def __init__(self):
>   print "cons A"
>
>   class B (object):
> def __init__(self):
>   print "cons B"
>
>   class C (A):
> def __init__(self):
>   super(C, self).__init__()
>   print "cons C"
>
>   class D (B):
> def __init__(self):
>   super(D, self).__init__()
>   print "cons D"
>
> Now, suppose I would like to define a new class as follows:
>
>   class E (C, D):
> ...
>
> In the constructor for E, I would like to invoke the constructors of
> both parent classes.  The correct way to do this seems to be exemplified
> by the following:
>
>   class E (C, D):
> def __init__(self):
>   super(E, self).__init__()  # calls C constructor
>   super(A, self).__init__()  # calls D constructor (**)
>   print "cons E"
>
> This works, but I find it somewhat troubling.  It seems to me that one
> should not have to "know" (i.e., write down the names of) the ancestors
> of C in order to dispatch to superclass methods in D, since C and D
> share no common ancestors south of object.
>
> Is there a better (i.e., more elegant) way to handle the case marked
> (**) above?
>
> Curious,
> -M
>
> --
> Michael J. Fromberger | Lecturer, Dept. of Computer Science
> http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA

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


Re: New SourceForge project: Diet Python!!!

2006-07-18 Thread M�ta-MCI
Hi!

Interesting (or fun?).
Have you a Internet page, or only README?

@+

MCI



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


Re: CSV with comments

2006-07-18 Thread skip
>> In csv.reader, is there any way of skip lines that start whith '#' or
>> empty lines

Nope.  When we wrote the module we weren't aware of any "spec" that
specified comments or blank lines.  You can easily write a file wrapper to
filter them out though:

class BlankCommentCSVFile:
def __init__(self, fp):
self.fp = fp

def __iter__(self):
return self

def next(self):
line = self.fp.next()
if not line.strip() or line[0] == "#":
return self.next()
return line

Use it like so:

reader = csv.reader(BlankCommentCSVFile(open("somefile.csv")))
for row in reader:
print row

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


Re: ScientificPython - LeastSquareFit diverges

2006-07-18 Thread Terry Reedy

"Harold Fellermann" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I am trying to fit a powerlaw to a small dataset using
> Scientific.Functions.LeastSquares fit.

This is a bit off-topic here, and normally better for the scipy list, but I 
have some experience with nonlinear least squares.

> Unfortunately, the algorithm seems to diverge and throws an
> OverflowException.

Assuming the program is okay, this means that either the function 
mismatches the data or the initial values are too far off to converge.

> Here is how I try it:
 from Scientific.Functions.LeastSquares import leastSquaresFit

 data = [
> ... (2.5, 589.0, 0.10001),
> ... (7.5, 442.0, 0.10001),
> ... (12.5, 96.0, 0.10001),

I presume that tuples are x, y, some_error_indicator.  But the last does 
not matter here.

 def powerlaw((a,b),x) :
> ... return a*x**b

Did you try plotting logx versus log y to see if you get approximately a 
straight line?  If so, the intercept and slope are estimates of loga and b.
> ...
 params,chisq = leastSquaresFit(powerlaw,(10,-3),data)

I presume (10,-3) is the starting (a,b).  But, for instance 10*7.5**-3 = 
.02, which has no relation to 442, whereas, for instance, 1000*7.5-.75 = 
221, which is in the ballpark, at least.  So (a,b)=(1000, -.75) might have 
a chance.

Terry Jan Reedy



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


Defining functions in an implementation file

2006-07-18 Thread westymatt
I am fairly new to python and I want to put alot of my functions in
another python file and import or from it into my script so I can call
the functions.  How is this done?

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


Re: Cyclic class definations

2006-07-18 Thread Nick Vatamaniuc
John,
Cycles are tricky. Python is an interpreted dynamic language, whatever
object you instantiate in your methods is a different thing than class
hierarchy. Your class hierarchy is fine: ClassA->ClassASubclass->ClassC
and it should work.  If it doesn't, create a quick mock example and
post it along with the error.

In general try to model your problem to avoid cycles if possible, I
know sometimes they are un-avoidable, but more often then not, they
are. Python might or might not allow cycles in certain situations
(packages, imports, class hierarchy and during usage i.e. in your
semantics) but regardless, if they make your code hard to understand so
try to not introduce them if possible.

Hope this helps,
Nick V.


John Henry wrote:
> Hi list,
>
> I am trying to understand better Python packaging.  This might be a
> messed up class hierachy but how would I break this cyclic relatioship?
>
> In file A:
>
> from B import B_Class
>
> Class_A_Main():
>def 
>def SomeMethod(self):
>   res=B_Class(self)
>
> Class_A_SubClass(Class_A_Main):
>def ...
>
>
> In file B:
>
> Class B_Class():
>def __init__(self,parent):
>   ...
>def SomeMethod(self):
>   res=C_Class(self)
>
>
> In file C:
>
> from file A import Class_A_SubClass
>
> Class C_Class(Class_A_SubClass):
>def __init__(self, parent):
>   ...
>
>
> As you can see, the cyclic relationship exists because C_Class is a
> sub-class of SubClass which is in turn a sub-class of Class_A_Main and
> in one of the methods of Class_A, it has a need to create a C_Class
> object.
>
> I tried to merge the files A and C (by placing C_Class behind A_Class)
> and have the method in A_Class create C_Class directly but that doesn't
> work because Python says C_Class is not defined when it's processing
> the A_Class method.   May be somebody can tell me how to "forward
> declare" a class?
> 
> Regards,

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


Re: execute a shell script from a python script

2006-07-18 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Thomas Nelson <[EMAIL PROTECTED]> wrote:
>As described in the docs I pointed to before:
>subprocess.call("foo.sh",shell=True)
>Is the way to do it without args.  I think it is simplest to learn the
>subprocess module because (quoting from the docs) this module intends
>to replace several other, older modules and functions, such as:
>os.system
>os.spawn*
>os.popen*
>popen2.*
>commands.*
>This way you only need to learn one thing.  Actually I would like to
>see some of these older functions deprecated.
.
.
.
A point worth repeating, and I salute your courtesy in doing so.
I had realized neither the deprecation of these interfaces, nor
the documentation to that effect, so I thank you for pointing
them out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dispatch with multiple inheritance

2006-07-18 Thread Michael J. Fromberger
Consider the following class hierarchy in Python:

  class A (object):
def __init__(self):
  print "cons A"

  class B (object):
def __init__(self):
  print "cons B"

  class C (A):
def __init__(self):
  super(C, self).__init__()
  print "cons C"

  class D (B):
def __init__(self):
  super(D, self).__init__()
  print "cons D"

Now, suppose I would like to define a new class as follows:

  class E (C, D):
...

In the constructor for E, I would like to invoke the constructors of 
both parent classes.  The correct way to do this seems to be exemplified 
by the following:

  class E (C, D):
def __init__(self):
  super(E, self).__init__()  # calls C constructor
  super(A, self).__init__()  # calls D constructor (**)
  print "cons E"

This works, but I find it somewhat troubling.  It seems to me that one 
should not have to "know" (i.e., write down the names of) the ancestors 
of C in order to dispatch to superclass methods in D, since C and D 
share no common ancestors south of object.

Is there a better (i.e., more elegant) way to handle the case marked 
(**) above?

Curious,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Augument assignment versus regular assignment

2006-07-18 Thread Terry Reedy

"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On 2006-07-17, Terry Reedy <[EMAIL PROTECTED]> wrote:
>>  Or, whether docs (and reasonable interpretation thereof) and
>> implementation match, which I claim they do it this case.

The claim, in reference to the CPython implementation, that you refer to 
below.

> Well this dispute seems to boil down what is and what is not
> involved in evaluating a target,

Yes, and that is interpreter/implementation dependent.

> and I have come to doubt that
> target evaluation is even a meaningfull concept in python,

Abstractly, it is whatever the interpreter does before it actually attaches 
an object to the name or slot.  Again, the details are interpreter 
dependent.

> so maybe in order that I can understand how you come to that claim,

I looked at the CPython bytecode and saw that for augmented assigment, it 
saved on the stack the internal information it needed for get and set 
instead of recalculating it after the operation.  This is what I expected 
and what I think the docs imply.

> can you explain what a target evaluates to?

The internal information the interpreter needs to do the assignment 
(binding).

> So in a statement like
>  col['t'] = exp
> What is the evaluation of col['t']?

Try some personal introspection.  When you act as a Python interpreter, 
what do you do?

> So I think one should take extra care in the language reference to
> write in a way that is as clear as possible. IMO there is room for
> improvement in the augmented assignment part.

I already agreed.  I might someday suggest a change.

Terry Jan Reedy



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


Re: Cyclic class definations

2006-07-18 Thread John Henry
I think I got the answer by playing around a bit.   It appears you
*don't* need to forward declare things.  For example, the following
code works:

class a:
  def run(self):
new_a=a_sub()
new_a.print_it()

class a_sub(a):
  def print_it(self):
print "Hi"

b=a().run()

Regards,


John Henry wrote:
> Hi list,
>
> I am trying to understand better Python packaging.  This might be a
> messed up class hierachy but how would I break this cyclic relatioship?
>
> In file A:
>
> from B import B_Class
>
> Class_A_Main():
>def 
>def SomeMethod(self):
>   res=B_Class(self)
>
> Class_A_SubClass(Class_A_Main):
>def ...
>
>
> In file B:
>
> Class B_Class():
>def __init__(self,parent):
>   ...
>def SomeMethod(self):
>   res=C_Class(self)
>
>
> In file C:
>
> from file A import Class_A_SubClass
>
> Class C_Class(Class_A_SubClass):
>def __init__(self, parent):
>   ...
>
>
> As you can see, the cyclic relationship exists because C_Class is a
> sub-class of SubClass which is in turn a sub-class of Class_A_Main and
> in one of the methods of Class_A, it has a need to create a C_Class
> object.
>
> I tried to merge the files A and C (by placing C_Class behind A_Class)
> and have the method in A_Class create C_Class directly but that doesn't
> work because Python says C_Class is not defined when it's processing
> the A_Class method.   May be somebody can tell me how to "forward
> declare" a class?
> 
> Regards,

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


Re: tkinter help

2006-07-18 Thread faulkner
add a xscrollcommand and/or yscrollcommand keyword argument to the
construction of your listbox.

def func(*a):
print "i'm a callback!"

L = Tkinter.Listbox(root, yscrollcommand=func)# note no parens
after func


groves wrote:
> hi eveyrbody , i have started working on python tkinter,
> While I was working on one of the tkinter classes..named listbox
> widget. I had a slight problem.
>
> Now let me tell you that i was able to create a simple listbox which
> had 6 options which one can select, but Now what I want is that from
> the available menu, if I select an option it should give me another
> menu associated with that option. Its like digging up that option to do
> advance search.
>
> Please I need help as I am making my project
> Thanks to eveyrbody who will take time to read this and solve it .

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


Re: Accessors in Python (getters and setters)

2006-07-18 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Bruno Desthuilliers wrote:
> >
> >>mystilleef wrote:
> >>Please don't top-post
> >>
> >>>On State and Behavior:
> >>>
> >>>To understand objects in terms of state and behavior you need to
> >>>absolve yourself from implementation details of languages
> >>>and think at an abstract level.
> >>
> >>
> >>
> >>>Take a button object, for example. It has state and behavior. Possible
> >>>states may include, is_active, is_focused, is_mapped, etc. Behavior is
> >>>what the button does when it responds to events, (e.g when you click on
> >>>it, or drag it, or position a pointer over it.) If you've done any form
> >>>of event based programming (GUI/Games/Simulation), this method of
> >>>thinking becomes natural.
> >>>
> >>>As you can see, when I'm designing a button object, I don't care what
> >>>Python does with is_active. I don't care how it accesses. I don't care
> >>>what is_active means to Python. I don't care about Python's __get__
> >>>/__set__ special/latent functions or implementation details. is_active
> >>>to me and every other developer is a state of the button object. And at
> >>>that level that's all that matters. Python can tell me it's just ones
> >>>and zeros for all I care.
> >>>
> >>>In very well designed systems, the state of an object should only be
> >>>changed by the object.
> >>
> >>... as a response to a message.
> >>
> >>
> >>>For example, a third party randomly changing
> >>>is_active, (which Python lets you do freely and easily)
> >>
> >>Unless you make it a read-only property.
> >>
> >
> > So you see the purpose of accessors then?
>
> *where* did I say *anything* that could *possibly* be taken as me not
> seeing the point of computed attributes ?
>
> What I'm saying here is that it's totally useless to duplicate default
> behaviour.
>

And who's doing that?

> >
> >>>from False to
> >>>True may crash your GUI.
> >>
> >>>And I'm not making this up. Things like this
> >>>do really happen depending on the whackyness of your toolkit. So
> >>>sometimes, it is my duty to protect the state of an object. Especially
> >>>if its state cannot afford to be corrupted rendering the system
> >>>unstable. And situations like this are found a plenty in event based
> >>>programming. Which is programming objects based almost entirely on
> >>>state and behavior. As you can see this has nothing to do with Python
> >>>vs Java's vs X's implementation of accessors and how using them sucks,
> >>>or how they aren't Pythonic. Some domains just require this stuff.
> >>
> >>Properties *are* 'accessors'.
> >>
> >
> > I never said they weren't.
>
> Fine.
>
> Now : in a language with support for computed attributes, direct
> attribute access is the default r/w accessors.
>

Depends on your definition of accessors. Otherwise 97% of languages
provide direct access to an object's data attributes.

> >
> >>>One of the requirements for designing robust object systems is ensuring
> >>>the state of objects aren't easily contaminated.
> >>
> >>"contaminated" ???
> >>
> > Make an object's state unreliable. See above example.
>
> That's the word you choose that I find really strange.
>

What's strange about it. If an object's data attribute is supposed to
state that it is false when there are no mark objects in the buffer,
and a third party accidently incorrectly changes the attribute to state
it is True for whatever reasons, you essentially corrupt the objects
state and render the whole system "unreliable," or "buggy". What again
is difficult to grasp?

> >
> >>>That "state" is the
> >>>objects data (read: stuff the object needs to do something "reliably").
> >>
> >>Makes no sens to me.
> >>
> >
> > is_active is an object's data,
>
> class Obj(object):
>   # 
>   @apply
>   def is_active():
> def fget(self):
>   return (self.something and self.computeThis()) \
>   or self.otherCondition()
> def fset(self, val):
>   raise ReadOnlyError()
> def fdel(self):
>   raise UndeletableError()
> return **locals()
>
> According to *your* sayings, Obj.is_active is "behaviour"...
>

Not my saying.  OO says so.

> >>>And this is why many overzealous OO languages do "force" you to use
> >>>accessors.
>
> The only languages I know that "force" you to use accessors are
> Smalltalk and Ruby (and Ruby offers some syntactic sugar for 'default' -
> ie r/w - accessors).
>

Add Eiffel to the list. Java/C++/C#/Ada all recommend it by convention.


> > It's not because they hate you or aren't aware of the
> >>>convenience of having direct access to an object's attributes. It's
> >>>just because these languages convenience/robustness ratios are
> >>>different.
>
> I'm afraid it has very few to do with "robustness".
>

Your opinion.

> >>>Thinking in terms of callable vs non-callable is not helpful for me,
> >>>because it isn't high level enough.
> >>
> >>Allo, Huston ?
> >>
> >>
> >>>Thinking in terms of state and
> >>>behavior is, because it works regardless o

Re: range() is not the best way to check range?

2006-07-18 Thread Grant Edwards
On 2006-07-18, Paul Boddie <[EMAIL PROTECTED]> wrote:

>> It's unclear what you're referring to as "the range".
>
> The notion of something describing a range of values which can be
> expanded to a list or, of relevance here, whose boundaries can be
> tested efficiently.
>
>> Perhaps you're thinking of a slice?  Somethign like
>>
>>   if  (0:1).contains(x):

I didn't mean to imply that would actually work, but I thought
maybe that's what you were proposing.

> Did you mean...?
>
> (0:1) # SyntaxError
> slice(0, 1).contains(x) # AttributeError
> 3 in slice(0, 1) # TypeError
>
> Something like this might suffice if slice could have a __contains__
> method or if people thought of slices as natural things to test
> against.

A slice seems to me to be the obvious way to represent a finite
length algebraic sequence of integers.  However, obvioiusness
is in the eye of the beholder since as you point out below to
the OP, a range() was the obvious way to it.

> Perhaps we could ask the original questioner why they chose to
> use range in such a way - it might indicate a background in
> languages which encourage the construction of ranges and their
> use in comparisons - although being told to RTFM may have
> scared them off.

-- 
Grant Edwards   grante Yow!  Did I say I was a
  at   sardine? Or a bus???
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Cyclic class definations

2006-07-18 Thread John Henry
Hi list,

I am trying to understand better Python packaging.  This might be a
messed up class hierachy but how would I break this cyclic relatioship?

In file A:

from B import B_Class

Class_A_Main():
   def 
   def SomeMethod(self):
  res=B_Class(self)

Class_A_SubClass(Class_A_Main):
   def ...


In file B:

Class B_Class():
   def __init__(self,parent):
  ...
   def SomeMethod(self):
  res=C_Class(self)


In file C:

from file A import Class_A_SubClass

Class C_Class(Class_A_SubClass):
   def __init__(self, parent):
  ...


As you can see, the cyclic relationship exists because C_Class is a
sub-class of SubClass which is in turn a sub-class of Class_A_Main and
in one of the methods of Class_A, it has a need to create a C_Class
object.

I tried to merge the files A and C (by placing C_Class behind A_Class)
and have the method in A_Class create C_Class directly but that doesn't
work because Python says C_Class is not defined when it's processing
the A_Class method.   May be somebody can tell me how to "forward
declare" a class?

Regards,

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


Re: range() is not the best way to check range?

2006-07-18 Thread Grant Edwards
On 2006-07-18, Steve Holden <[EMAIL PROTECTED]> wrote:

>> That said, "for pete's sake" is probably a just an cleaned up
>> version of "for god's sake", so I probably did call pete god.
>
> No, actually you called god pete ;-)

Well that's certainly wrong, because we all know god's name is
Howard.

   Our father who art in heaven,
   Howard be thy name,
      

-- 
Grant Edwards   grante Yow!  .. I have a
  at   VISION! It's a RANCID
   visi.comdouble-FISHWICH on an
   ENRICHED BUN!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessors in Python (getters and setters)

2006-07-18 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Bruno Desthuilliers wrote:
> >
> >>mystilleef wrote:
> >>
> >>>Gerhard Fiedler wrote:
> >>>
> >>>
> On 2006-07-15 06:55:14, mystilleef wrote:
> 
> 
> 
> >In very well designed systems, the state of an object should only be
> >changed by the object.
> 
> IMO that's not quite true. Ultimately, the state always gets changed by
> something else (user interaction, physical events); very few objects are
> completely self-contained in their behavior.
> 
> >>>
> >>>Then in those cases the system becomes a victim of high coupling.
> >>
> >>Time to burn your book and face reality. ObjA sends message Msg1 to
> >>ObjB. Part of the associated behaviour is that in responce to Msg1, objB
> >>changes it's own state. Practical result : ObjB's state has been changed
> >>by ObjA. Practical question : how do you hope to avoid this "hi
> >>coupling" (lol), apart from making all your objects totally autistic ?
> >>
> >
> >
> > Are you serious?
>
> Deadly serious. But I'm afraid you're still missing the point.
>
> > Well, you design an object that serves as a mediator.
> > All objects can then only interact with themselves and the mediator
> > only. Via signals, objects learn to automatically adjust their states
> > and respond to events.
>
> signal -> message -> method call -> change state.
>
> Spell it how you like, add as many indirection levels you want, it still
> boils down to the fact that *something* triggers the state change.
>

Right!

> > This is just one of several methods you can
> > dramatically reduce coupling.
>
> It's just one of several methods that dramatically increases complexity,
> without changing anything to the fact that in the end, *practically*,
> some object ObjA changes its state as a response to a message sent by ObjB.
>

Say that to game/simulation developers.

> > I'm sure glad I didn't burn my book.
>
> No comment.
>
> >
> In most systems (and you possibly have written some of them) are objects
> whose state gets changed by other objects -- possibly through the
> intermediation of setter methods that do nothing else but set the state.
> There's no conceptual difference between directly setting the state or
> calling a setter function that does nothing else but directly setting the
> state -- except for one unnecessary level of indirection in the latter.
> 
> >>>
> >>>
> >>>It depends. If certain conditions need to be met before changing the
> >>>state of an object, then arbitrarily changing it can be dangerous.
> >>
> >>Does this imply a 'method call' *syntax* ?
> >
> >
> > That's language dependent.
> >
> >
> >>Given the existence of
> >>"computed attributes" (ie: support for 'attribute access' *syntax* with
> >>hidden accessors) and the possibility to redefine implementation (from
> >>default attribute r/w access to computed/controlled) without touching
> >>the interface, why advocate the *systematic* use of computed attributes
> >>when it's just duplicating the default behaviour ?
> >>
> >
> >
> > I'm not advocating anything.
>
> cf below on this.
>
> > I'm just stating the use case for
> > accessors and the wisdom behind them. My qualm with implicit accessors
> > remains the name issue.
>
> The "name issue" is *your* problem. And AFAICT, it's a "problem" because
> you refuse to free your mind from a "what's in the book" mindset.
>

What book are we talking about?

> >
> >For example, a third party randomly changing is_active, (which Python
> >lets you do freely and easily) from False to True may crash your GUI.
> >And I'm not making this up. Things like this do really happen depending
> >on the whackyness of your toolkit.
> 
> That's quite true, but a setter that does nothing but change is_active
> doesn't prevent this. If there is logic necessary to prevent state changes
> in certain situations, this should be implemented. But whether you then
> call this a part of the "behavior" (looking at the implementation as being
> a setter method) or a part of the "state" (looking at the implementation 
> as
> being an added feature of the attribute) doesn't really make an objective
> difference.
> 
> >>>
> >>>
> >>>Of course using setters for the sake of just using them is pointless.
> >>
> >>Indeed.
> >>
> >>
> >>>The reason to use them is if pre-conditions or post-conditions need to
> >>>be met. Or to control access to an objects states.
> >>
> >>Then why advocate *systematic* use of them ?
> >>
> >>(snip)
> >
> > I never advocated anything.
>
> You advocated
> """
> 1). Make all attributes of a class private/protected .
> 2). If a "non-callable" attribute is going to be used outside a class,
> think about making it a property and name the property well, because
> you never know...
> """
>

You use accessors when you need to control access to a data attribute.
That's not advocacy, that's common sense.

> >
> >>>State 

Re: Piping external commands

2006-07-18 Thread Simon Forman
[EMAIL PROTECTED] wrote:
> What is the Python translation for this Bash statement:
>
>   tar cf - "[EMAIL PROTECTED]" | bzip2 > "$file".tar.bz2
>
> (Ignoring the fact that "tar cjf" also exists...)
>
> In other words, how does one pipe together arbitrary commands?

For piping subcommands check out the subprocess module, especially
http://docs.python.org/lib/node242.html , for bzip2 check out the bz2
module http://docs.python.org/lib/module-bz2.html , but note, there's
also a tarfile module http://docs.python.org/lib/module-tarfile.html
which can handle bzip2 as well.

HTH,
~Simon

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


Re: range() is not the best way to check range?

2006-07-18 Thread Paul Boddie
Grant Edwards wrote:
>
> It's unclear what you're referring to as "the range".

The notion of something describing a range of values which can be
expanded to a list or, of relevance here, whose boundaries can be
tested efficiently.

> Perhaps you're thinking of a slice?  Somethign like
>
>   if  (0:1).contains(x):

Did you mean...?

(0:1) # SyntaxError
slice(0, 1).contains(x) # AttributeError
3 in slice(0, 1) # TypeError

Something like this might suffice if slice could have a __contains__
method or if people thought of slices as natural things to test
against. Perhaps we could ask the original questioner why they chose to
use range in such a way - it might indicate a background in languages
which encourage the construction of ranges and their use in comparisons
- although being told to RTFM may have scared them off.

Paul

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


Re: range() is not the best way to check range?

2006-07-18 Thread Simon Forman
Diez B. Roggisch wrote:
> Simon Forman wrote:
>
> > Nick Craig-Wood wrote:
> >>
> >> Sets are pretty fast too, and have the advantage of flexibility in
> >> that you can put any numbers in you like
> >>
> >
> > I know this is self-evident to most of the people reading this, but I
> > thought it worth pointing out that this is a great way to test
> > membership in range(lo, hi, step) without doing "the necessary
> > algebra".
> >
> > i.e.  n in set(xrange(0, 1, 23)) ...
>
> No, its not. It works, but it works by no means faster than
>
> n in range(0, 1, 23)
>
> Both need O(n), which is a bit slow compared to
>
> (((n - 15) % 23) == 0 and n >= 15 and n < 1)
>
> that will run in O(1)
>
> Diez

You're right, of course.  I should have said that if you're testing
such a membership, say, 3 times AND you (like me) are slightly
rusty on the algebra and prefer to let the computer do it, then you
could use something like:

test_set = set(xrange(0, 1, 23))

if n in test_set:
...

;-)
~Simon

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


Re: range() is not the best way to check range?

2006-07-18 Thread K.S.Sreeram
Simon Forman wrote:
> Nick Craig-Wood wrote:
>> Sets are pretty fast too, and have the advantage of flexibility in
>> that you can put any numbers in you like
>>
> 
> I know this is self-evident to most of the people reading this, but I
> thought it worth pointing out that this is a great way to test
> membership in range(lo, hi, step) without doing "the necessary
> algebra".
> 
> i.e.  n in set(xrange(0, 1, 23)) ...

This is very very misleading... here are some timings :

python -mtimeit "n=5000" "n in set(xrange(0,1))"
1000 loops, best of 3: 1.32 msec per loop

python -mtimeit "n=5000" "n in xrange(0,1)"
1000 loops, best of 3: 455 usec per loop

python -mtimeit "n=5000" "0 <= n < 1"
100 loops, best of 3: 0.217 usec per loop

sets are fast only if you create them *once* and use them again and
again. even in that case, the sets use up O(n) memory.

with comparison operators, you don't need extra memory *and* there is no
pre-computation required.

[sreeram;]



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: statistical analysis tools in python?

2006-07-18 Thread Thomas Nelson
Actually, after a little looking, the simple stats.py module at
http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html
is exactly what I needed.  It may not be as fast or as comprehensive as
scipy or R, but installation simply involves downloading the module and
importing into the code, and it has the ttests I was looking for.
Thanks,
THN

[EMAIL PROTECTED] wrote:
> And there is a python interface to R, so that you can call R routines from
> Python.  R is a free stat language that has all the tests you've mentioned,
> 
> Gerry

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


Should this be added to MySQLdb FAQ?

2006-07-18 Thread gmax2006
Hi,

I went through couple of wrong paths to install MySQLdb on my RedHat
box. I was trying to download MySQL client from MySQL.com and also
mySQLdb from SourceForge. After some challenges with compile errors and
also searching for pre-required RPMs, I found RedHat distribution
already contains all compiled rpms and all I need are within CDs 3 and
4 of RedHat distribution!

In essence, I found that I should check my Linux distribution first,
then attempt to download stuff from sourceforge!

I also posted the question to this group:
http://groups.google.ca/group/comp.lang.python/browse_thread/thread/41c53c2c932dfa58/f72f09a863bffdb2?hl=en#f72f09a863bffdb2

If this makes sense, should it be added to MySQLdb FAQ?

Regards,
Max

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


Re: question about what lamda does

2006-07-18 Thread [EMAIL PROTECTED]
I stand corrected. Not sure where I got that from, improper
defragmentation due to sleep depravation perhaps...

K.S.Sreeram wrote:
> [EMAIL PROTECTED] wrote:
> > The two primary differences between using def and using lambda is that
> > lambda is limited to a single expression and def cannot be used within
> > another function.
>
> 'def' can certainly be used within another function :
>
> def make_adder( delta ) :
> def adder( x ) :
> return x + delta
> return adder
>
> [sreeram;]
>
>
> --enigFDB411206B54B101CC680F5A
> Content-Type: application/pgp-signature
> Content-Disposition: inline;
>   filename="signature.asc"
> Content-Description: OpenPGP digital signature
> X-Google-AttachSize: 253

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


  1   2   3   >