Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Nick Vatamaniuc
Yeah hash(hash(immutable))=hash(immutable) it seems. Not sure this is a
specification but it happens that way:
--
$ >>> hash('abc')
-1600925533
$ >>> hash(hash('abc'))
-1600925533
$ >>> hash(hash(hash(('abc'
-1600925533
>>>
-
Of course then hash(0)=0, hash(1)=0 and also hash(2**32)=1, all this in
standard CPython on IA32.

Nick Vatamaniuc



Ganesan Rajagopal wrote:
> > "Terry" == Terry Hancock <[EMAIL PROTECTED]> writes:
>
> > Note that it is trivial to catch collisions on entry and correct them:
>
> > key = hash(url_string)
> > i  = 0
> > if d.has_key(key):
> >while d.has_key(key):
> >i += 1
>
> hash is a number. It's sufficient to do
>
> while d.has_key(key):
> key += 1
>
> > I am a little surprised that hash(hash(s)) == hash(s), is that actually
> > true?
> 
> >>> hash(42)
> 42
> 
> Ganesan
> 
> -- 
> Ganesan Rajagopal

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


Re: Determining if an object is a class?

2006-07-12 Thread Michele Simionato
[EMAIL PROTECTED] wrote:
> I need to find out if an object is a class.
> Which is quite simply awful...does anyone know of a better way to do
> this?

inspect.isclass

 M.S.

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


Re: Problem with "&" charater in xml.

2006-07-12 Thread Kirt
How do i append characters to a string?

actually my entire handler code is
class oldHandler(ContentHandler):


def __init__(self):
self.fn = 0
self.dn = 0
self.i=[]
self.x=""
self.y=""
self.z=""
self.t=0
self.xx=''

def startElement(self, name, attrs):
if name=='dirname':
self.dn=1
if name=='name':
self.fn=1
if name=='time':
self.t=1

def characters(self,str):
if self.dn:
self.x=str

if self.fn:
self.y=str
if self.t:
self.z=str
ss= self.x+'/'+self.y+','+self.z+ '\r \n'
self.i.append(ss)
def endElement(self, name):
if name == 'dirname':
self.dn=0
if name=='name':
self.fn=0
if name=='time':
self.t=0


def endDocument(self):
f=open('old.txt', 'w')
self.i.sort
f.writelines(self.i)
f.close
so my old.txt now looks like this
y+def.txt,200607130417
C:\Documents and Settings\Administrator\Desktop\1\hii
wx\abc.txt,200607130415

But i wont the output as
C:\Documents and Settings\Administrator\Desktop\1\bye
w&y\def.txt,200607130417
C:\Documents and Settings\Administrator\Desktop\1\hii
wx\abc.txt,200607130415


Stefan Behnel wrote:
> Kirt wrote:
> > i have walked a directory and have written the foll xml document.
> > one of the folder had "&" character so i replaced it by "&"
> > #--test1.xml
> > 
> >   C:\Documents and Settings\Administrator\Desktop\1\bye
> > w&y 
> >   
> >   def.txt
> >   200607130417
> >   
> > 
> >  
> >   C:\Documents and Settings\Administrator\Desktop\1\hii
> > wx
> >   
> >   abc.txt
> >   200607130415
> >   
> >  >
> > now in my python code i want to parse this doc and print the directory
> > name.
> > ###--handlerfilename---handler.py
> > from xml.sax.handler import ContentHandler
> > class oldHandler(ContentHandler):
> >def __init__(self):
> > self.dn = 0
> > def startElement(self, name, attrs):
> > if name=='dirname':
> > self.dn=1
> >
> > def characters(self,str):
> > if self.dn:
> >print str
>
>
> The problem is here. "print" adds a newline. Don't use print, just append the
> characters (to a string or list) until the endElement callback is called.
>
>
> > def endElement(self, name):
> > if name == 'dirname':
> > self.dn=0
> >
> >
> > #-
> > #main code--- fnameart.py
> > import sys
> > from xml.saximport  make_parser
> > from handlers importoldHandler
> >
> > ch = oldHandler()
> > saxparser = make_parser()
> >
> > saxparser.setContentHandler(ch)
> > saxparser.parse(sys.argv[1])
> > #-
> > i run the code as:  $python art.py test1.xml
> >
> > i am getting output as:
> >
> > C:\Documents and Settings\Administrator\Desktop\1\bye w
> > &
> > y
> > C:\Documents and Settings\Administrator\Desktop\1\hii wx
> >
> > where as i need an output which should look like this.
> > C:\Documents and Settings\Administrator\Desktop\1\bye w&y
> >
> > C:\Documents and Settings\Administrator\Desktop\1\hii wx
> > 
> > Can someone tell me the solution for this.
> >

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


Re: Determining if an object is a class?

2006-07-12 Thread placid

[EMAIL PROTECTED] wrote:
> I need to find out if an object is a class.  Using new style classes
> this is very easy:
>
> class Test(object): pass
>
> obj = Test
>or
> obj = Test()
>
> if type(obj) == type:
> # this is a class object..
> else:
> # this not a class object
>
> But this fails for old style classes.  For example:
>
> class OldStyleObject: pass
>

Why is there old and new classes? What are the differences?

--Cheers

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


Re: Problem with "&" charater in xml.

2006-07-12 Thread Stefan Behnel
Kirt wrote:
> i have walked a directory and have written the foll xml document.
> one of the folder had "&" character so i replaced it by "&"
> #--test1.xml
> 
>   C:\Documents and Settings\Administrator\Desktop\1\bye
> w&y 
>   
>   def.txt
>   200607130417
>   
> 
>  
>   C:\Documents and Settings\Administrator\Desktop\1\hii
> wx
>   
>   abc.txt
>   200607130415
>   
>  
> now in my python code i want to parse this doc and print the directory
> name.
> ###--handlerfilename---handler.py
> from xml.sax.handler import ContentHandler
> class oldHandler(ContentHandler):
>def __init__(self):
>   self.dn = 0
> def startElement(self, name, attrs):
>   if name=='dirname':
>   self.dn=1
> 
>   def characters(self,str):
>   if self.dn:
>print str


The problem is here. "print" adds a newline. Don't use print, just append the
characters (to a string or list) until the endElement callback is called.


> def endElement(self, name):
>   if name == 'dirname':
>   self.dn=0
> 
> 
> #-
> #main code--- fnameart.py
> import sys
> from xml.sax  import  make_parser
> from handlers import  oldHandler
> 
> ch = oldHandler()
> saxparser = make_parser()
> 
> saxparser.setContentHandler(ch)
> saxparser.parse(sys.argv[1])
> #-
> i run the code as:  $python art.py test1.xml
> 
> i am getting output as:
> 
> C:\Documents and Settings\Administrator\Desktop\1\bye w
> &
> y
> C:\Documents and Settings\Administrator\Desktop\1\hii wx
> 
> where as i need an output which should look like this.
> C:\Documents and Settings\Administrator\Desktop\1\bye w&y
> 
> C:\Documents and Settings\Administrator\Desktop\1\hii wx
> 
> Can someone tell me the solution for this.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stderr, stdout, and errno 24

2006-07-12 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Wesley Henwood <[EMAIL PROTECTED]> wrote:
>To capture output from python scripts run from a C++ app I've added the
>following code at the beggening of the C++ app:
>
>PyRun_SimpleString("import grabber");
>PyRun_SimpleString("import sys");
>PyRun_SimpleString("class a:\n\tdef
>write(self,s):\n\t\tograbber.grab(s)\n");
>PyRun_SimpleString("import sys\nsys.stderr=a()\nsys.stdout=a()");
>
>Its hard to read that way, here's what it expands to:
>import grabber
>import sys
>class a:
>def write(self, s)
>grabber.grab(s)
>
>grabber is a C++ extension, the grab function prints displays the
>captured text in a Windows app.  After running about 450+ scripts in a
>row, I get "IOError Errno 24 Too many open files."
>
>I've searched this group and the net and determined that stderr and
>stdout may open files, is that correct?  If so would each running of a
>script be opening new files related to stderr and stdout and not
>closing them?  I'm just guessing.

I'm guessing, but it sounds like perhaps you're creating an object which has
an open file handle for output for each script that's run. When the
script finishes, if that object still exists, it will keep a file
handle open and eventually you'll hit the system limit on open file
handles for one process. 

It's also possible that your C++ app is the one which is failing to
close file handles created for running the scripts - there's no easy
way to tell from the information posted. 

You need to examine carefully what happens to any stdin/stdout/stderr
files which are created to execute scripts and ensure that they are
all properly closed (or, in the case of Python, if you don't
explicitly close them, that any references to the files cease to exist
after the script runs). I'd personally recommend explicit closing
here.




-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Paul Rubin
Ganesan Rajagopal <[EMAIL PROTECTED]> writes:
> hash is a number. It's sufficient to do
> 
> while d.has_key(key):
> key += 1

This is called linear probing and is not considered that great a
collision resolution strategy for hash tables.  Really, if you want an
exhaustive study about hashing, see Knuth vol 3.  If you're just
trying to get the application doing something reasonable, let the
database do its job.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with "&" charater in xml.

2006-07-12 Thread Kirt

i have walked a directory and have written the foll xml document.
one of the folder had "&" character so i replaced it by "&"
#--test1.xml

  C:\Documents and Settings\Administrator\Desktop\1\bye
w&y 
  
  def.txt
  200607130417
  

 
  C:\Documents and Settings\Administrator\Desktop\1\hii
wx
  
  abc.txt
  200607130415
  
http://mail.python.org/mailman/listinfo/python-list


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Ganesan Rajagopal
> "Terry" == Terry Hancock <[EMAIL PROTECTED]> writes:

> Note that it is trivial to catch collisions on entry and correct them:

> key = hash(url_string)
> i  = 0
> if d.has_key(key):
>while d.has_key(key):
>i += 1

hash is a number. It's sufficient to do

while d.has_key(key):
key += 1
   
> I am a little surprised that hash(hash(s)) == hash(s), is that actually
> true?

>>> hash(42)
42

Ganesan

-- 
Ganesan Rajagopal

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


Re: testing array of logicals

2006-07-12 Thread Paul Rubin
"John Henry" <[EMAIL PROTECTED]> writes:
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test

print (False not in map(bool, logflags))

Possibly more "pure" alternative (untested):

from operator import and_
print reduce(and_, map(bool, logflags))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Terry Hancock
Nick Vatamaniuc wrote:
>  The original post just said that he wanted to index some values by
>  their urls and didn't really care about the urls themselves, so I
>  suggested that he just use the hash of the key as the key. The
>  dictionary will then take a hash of that [note that:
>  hash(string)=hash(hash(string)) ] then the dictionary will not keep
>  the reference to the urls and GC will collect them. So instead of
>  dic[urlstring']=value he will do dic[hash(urlstring)]=value. But then
>  to retrieve he will have to do old_value=dic[hash(urlstring]].

Note that it is trivial to catch collisions on entry and correct them:

key = hash(url_string)
i  = 0
if d.has_key(key):
   while d.has_key(key):
   i += 1
   d[key + repr(i)] = val
else:
   d[key] = val

or something along those lines. No need to keep the original string.

Obviously this is only efficient if collisions are rare.
   
I am a little surprised that hash(hash(s)) == hash(s), is that actually
true?

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Accessors in Python (getters and setters)

2006-07-12 Thread Alex Martelli
Gerhard Fiedler <[EMAIL PROTECTED]> wrote:
   ...
> I'm not sure about which languages you are talking (pretty much all that
> allow public methods also allow public attributes), but in general I think

Smalltalk is a very well known object-oriented language that behaves
otherwise, just as one example.


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


Re: testing array of logicals

2006-07-12 Thread Alex Martelli
John Henry <[EMAIL PROTECTED]> wrote:

> Hi list,
> 
> Is there a more elagant way of doing this?
> 
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test

test = sum(bool(x) for x in logflags)==len(logflags)

is yet another possibility (without the effectiveness of
shortcircuiting, just like the quoted approach).  Some might prefer

test = not sum(not x for x in logflags)

but that's starting to border on the obscure;-).

If by "logicals" you mean "bool" instances (True and False) only, then

test = sum(logflags) == len(logflags)

is simpler and fast than, but equivalent to, my first suggestion.


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


RE: Determining if an object is a class?

2006-07-12 Thread Dino Viehland
The first check is also off - it should if issubclass(type(Test), type): 
otherwise you miss the metaclass case:

class foo(type): pass

class Test(object):
__metaclass__ = foo

obj = Test
if type(obj) == type: 'class obj'
else: 'not a class'

just on the off-chance you run into a metaclass :)

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Clay Culver
Sent: Wednesday, July 12, 2006 2:07 PM
To: python-list@python.org
Subject: Re: Determining if an object is a class?

Ahh much better.  Thanks.

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


Deadline for abstracts in two days - Python-Workshop September 8, 2006 in Leipzig, Germany

2006-07-12 Thread mmueller
=== Reminder===

The deadline for submitting abstracts for the the workshop on September
8 in Leipzig is July 15.  It is only two days away!!

If you would like to give a presentation, please send your abstract to
[EMAIL PROTECTED]

The workshop topics are listed at
http://www.python-academy.de/workshop/themen.html

While the workshop language will be German, English presentations are
accepted.  So, if you work in Germany, Austria or Switzerland but don't
think your German is good enough for a presentation, you are welcome to
speak in English.


=== Erinnerung ==

Der letzte Termin für die Einreichung einer Kurzfassung für den
Workshop am 8. September in Leipzig ist der 15.07.2006. Es sind also
nur noch zwei Tage!!

Wer einen Vortrag halten möchte, die Kurzfassung bitte an
[EMAIL PROTECTED] senden.

Die Themen des Workshops sind unter
http://www.python-academy.de/workshop/themen.html
zu finden.

=== Workshop "Python im deutschsprachigen Raum" ===

Am 8. September 2006 findet in Leipzig der Workshop "Python im
deutschsprachigen Raum" statt.

Der Workshop ist als Ergänzung zu den internationalen und
europäischen Python-Zusammenkünften gedacht.
Die Themenpalette der Vorträge ist sehr weit gefasst und
soll alles einschließen, was mit Python im deutschsprachigen
Raum zu tun hat.

Eine ausführliche Beschreibung der Ziele des Workshops,
der Workshop-Themen sowie Details zu Organisation und
Anmeldung sind unter
http://www.python-academy.de/workshop
nachzulesen.

Vorträge können bis zum 15. Juli angemeldet werden.
Dazu bitte eine Kurzfassung an [EMAIL PROTECTED] senden.
Zu jedem Vortrag kann ein Artikel eingereicht werden,
der in einem Proceedings-Band Ende des Jahres erscheinen wird.


=== Wichtige Termine ===

15.07.2005 Vortragsanmeldung mit Kurzfassung
31.07.2006 Einladung und vollständiges Programm
15.08.2006 Letzter Termin für Frühbucherrabatt
08.09.2006 Workshop
15.09.2006 Letzter Termin für die Einreichung der publikationsfähigen
Beiträge
Dezember 2006 Veröffentlichung des Tagungsbandes


=== Bitte weitersagen ===

Der Workshop soll auch Leute ansprechen, die
bisher nicht mit Python arbeiten.
Wer mithelfen möchte den Workshop bekannt zu machen,
kann einen Link auf
http://www.python-academy.de/workshop setzen.
Auch außerhalb des Internets kann der Workshop durch den Flyer
http://www.python-academy.de/download/workshop_call_for_papers.pdf
bekannt gemacht werden. Einfach doppelseitig ausdrucken oder kopieren
und
ein paar Exemplare am Schwarzen Brett von Universitäten, Firmen,
Organisationen usw. aushängen.

Wir freuen uns auf eine rege Teilnahme,
Mike Müller
Stefan Schwarzer

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


Re: What is a type error?

2006-07-12 Thread Chris Smith
Marshall <[EMAIL PROTECTED]> wrote:
> David Hopwood wrote:
> > Marshall wrote:

> > > Mightn't it also be possible to
> > > leave it up to the programmer whether a given contract
> > > was compile-time or runtime?
> >
> > That would be possible, but IMHO a better option would be for an IDE to give
> > an indication (by highlighting, for example), which contracts are 
> > dynamically
> > checked and which are static.
> >
> > This property is, after all, not something that the program should depend 
> > on.
> > It is determined by how good the static checker currently is, and we want 
> > to be
> > able to improve checkers (and perhaps even allow them to regress slightly in
> > order to simplify them) without changing programs.
> 
> Hmmm. I have heard that argument before and I'm conflicted.
> 
> I can think of more reasons than just runtime safety for which I'd
> want proofs. Termination for example, in highly critical code;
> not something for which a runtime check will suffice. On the
> other hand the points you raise are good ones, and affect
> the usability of the language.

There doesn't seem to be a point of disagreement here.  Programmers 
often need to require certain properties to be checked at compile-time.  
Others could go either way.  There is no property that a program would 
rationally desire to *require* be checked at runtime; that would only 
occur because the compiler doesn't know how to check it at compile time.

-- 
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: statistical analysis tools in python?

2006-07-12 Thread gblais
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


Re: Accessors in Python (getters and setters)

2006-07-12 Thread Gerhard Fiedler
On 2006-07-12 06:17:27, mystilleef wrote:

> But developers tend to pay more attention to given methods/functions
> less crappy names, at least when compared to data attributes. This
> stems from the fact that in many languages data attributes aren't
> usually part of the API, as well as the whole OO(Encapsulation) blah
> blah. 

I'm not sure about which languages you are talking (pretty much all that
allow public methods also allow public attributes), but in general I think
you should get away from the distinction attribute vs method (which doesn't
make much sense in any language) and start looking at the distinction
public vs private (which is what you really are talking about) -- and start
giving the appropriate care to naming public entities, no matter /what/
they are. (Besides, I don't know many coding rules that say that creating
an accessor get/setTemporaryBuffer that acts on the private member tmp is
good style.)

I'm just starting to get started with Python, but it seems that the leading
underscore marks private entities. So why don't you precede everything with
an underscore that doesn't have a name that fulfills your criteria for a
decent public name -- no matter what kind of entity it is?

It seems you are basically complaining that you used a crappy name in a
public API. Well... you shouldn't, not in Python, and not in any other
language :)  And there's no way around it, not in Python, and not in any
other language, than to rename that entity in the public API. Which can be
a major hassle, close to impossible. There are all kinds of public APIs
with crappy names (using accessors and all :) that got created early on and
never changed. Stuff happens.

Maybe you didn't know about the underscore way to mark private entities.
Maybe this doesn't work as I think it does (from reading this thread). But
maybe it does, and maybe that's then just part of the learning curve for
you. (And I'm sure you're not alone... :)

Gerhard

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


Re: What is a type error?

2006-07-12 Thread Marshall
David Hopwood wrote:
> Marshall wrote:
>
> > Wouldn't it be possible to do them at compile time? (Although
> > this raises decidability issues.)
>
> It is certainly possible to prove statically that some assertions cannot fail.
>
> The ESC/Java 2 (http://secure.ucd.ie/products/opensource/ESCJava2/docs.html)
> tool for JML (http://www.cs.iastate.edu/~leavens/JML/) is one system that does
> this -- although some limitations and usability problems are described in
> .

I look forward to reading this. I read a paper on JML a while ago and
found it quite interesting.


> > Mightn't it also be possible to
> > leave it up to the programmer whether a given contract
> > was compile-time or runtime?
>
> That would be possible, but IMHO a better option would be for an IDE to give
> an indication (by highlighting, for example), which contracts are dynamically
> checked and which are static.
>
> This property is, after all, not something that the program should depend on.
> It is determined by how good the static checker currently is, and we want to 
> be
> able to improve checkers (and perhaps even allow them to regress slightly in
> order to simplify them) without changing programs.

Hmmm. I have heard that argument before and I'm conflicted.

I can think of more reasons than just runtime safety for which I'd
want proofs. Termination for example, in highly critical code;
not something for which a runtime check will suffice. On the
other hand the points you raise are good ones, and affect
the usability of the language.


Marshall

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


Re: Find and Delete all files with .xxx extension

2006-07-12 Thread John McMonagle
On Wed, 2006-07-12 at 16:12 -1000, normt's subject read:

> Find and Delete all files with .xxx extension


How ?  In the current directory/folder ?  Recursively search through all
the directories/folders from a certain path ?

I suggest you look at the os module (section about Files and
Directories)

http://docs.python.org/lib/os-file-dir.html




-- 
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: What is a type error?

2006-07-12 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
> > Joachim Durchholz wrote:
> >> Marshall schrieb:
> >>> I can see the lack of a formal model being an issue, but is the
> >>> imperative bit really all that much of an obstacle? How hard
> >>> is it really to deal with assignment? Or does the issue have
> >>> more to do with pointers, aliasing, etc.?
> >> Actually aliasing is *the* hard issue.
> >
> > Okay, sure. Nice explanation.
> >
> > But one minor point: you describe this as an issue with "imperative"
> > languages. But aliasing is a problem associated with pointers,
> > not with assignment.
>
> Aliasing is not a problem if the aliased data is immutable.

Okay, sure. But for the problem you describe, both imperativeness
and the presence of pointers is each necessary but not sufficient;
it is the two together that causes the problem. So it strikes
me (again, a very minor point) as inaccurate to describe this as
a problem with imperative languages per se.


>  > One can have assignment, or other forms
> > of destructive update, without pointers; they are not part of the
> > definition of "imperative."
>
> Sure.
> You can have either of destructive updates and pointers without
> incurring aliasing problems. As soon as they are combined, there's trouble.

Right. To me the response to this clear: give up pointers. Imperative
operations are too useful to give up; indeed they are a requirement
for certain problems. Pointers on the other hand add nothing except
efficiency and a lot of confusion. They should be considered an
implementation technique only, hidden behind some pointerless
computational model.

I recognize that this is likely to be a controversial opinion.



> Functional programming languages often drop assignment entirely. (This
> is less inefficient than one would think. If everything is immutable,
> you can freely share data structures and avoid some copying, and you can
> share across abstraction barriers. In programs with mutable values,
> programmers are forced to choose the lesser evil of either copying
> entire data structures or doing a cross-abstraction analysis of who
> updates what elements of what data structure. A concrete example: the
> first thing that Windows does when accepting userland data structures
> is... to copy them; this were unnecessary if the structures were immutable.)

I heartily support immutability as the default, for these and other
reasons.


> Some functional languages restrict assignment so that there can exist at
> most a single reference to any mutable data structure. That way, there's
> still no aliasing problems, but you can still update in place where it's
> really, really necessary.

Are we speaking of uniqueness types now? I haven't read much about
them, but it certainly seems like an intriguing concept.


> I know of no professional language that doesn't have references of some
> kind.

Ah, well. I suppose I could mention prolog or mercury, but then
you used that troublesome word "professional." So I will instead
mention a language which, if one goes by number of search results
on hotjobs.com for "xxx progammer" for different value of xxx, is
more popular than Java and twice as popular as C++. It lacks
pointers (although I understand they are beginning to creep in
in the latest version of the standard.) It also posesses a quite
sophisticated set of facilities for declarative integrity constraints.
Yet for some reason it is typically ignored by language designers.

http://hotjobs.yahoo.com/jobseeker/jobsearch/search_results.html?keywords_all=sql+programmer


Marshall

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


Find and Delete all files with .xxx extension

2006-07-12 Thread normt



Please do so.
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.1.394 / Virus Database: 268.9.10/386 - Release Date: 07/12/2006
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: stderr, stdout, and errno 24

2006-07-12 Thread Dave Hansen
On 12 Jul 2006 18:09:42 -0700 in comp.lang.python, "Wesley Henwood"
<[EMAIL PROTECTED]> wrote:

>To capture output from python scripts run from a C++ app I've added the
>following code at the beggening of the C++ app:
>
>PyRun_SimpleString("import grabber");
>PyRun_SimpleString("import sys");
>PyRun_SimpleString("class a:\n\tdef
>write(self,s):\n\t\tograbber.grab(s)\n");
>PyRun_SimpleString("import sys\nsys.stderr=a()\nsys.stdout=a()");
>
>Its hard to read that way, here's what it expands to:
>import grabber
>import sys
>class a:
>def write(self, s)
>grabber.grab(s)

Actually, that last line will more like
>ograbber.grab(s)

At least, if what you posted above is accurate...

It's not the question you asked, but if you want to make that easier
to read, you can do something like

   PyRun_SimpleString("import grabber");
   PyRun_SimpleString("import sys");

   PyRun_SimpleString("class a:\n"
  "   def write(self,s):\n"
  "  grabber.grab(s)\n");

   PyRun_SimpleString("import sys\n"
  "sys.stderr=a()\n"
  "sys.stdout=a()\n");


C++, like Python, will concatenate strings seperated only by
whitespace.

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: statistical analysis tools in python?

2006-07-12 Thread Robert Kern
Thomas Nelson wrote:
> Sorry if this is a FAQ, but I couldn't find a good summary through
> google.  What kinds of statistical analysis tools exist in python? 

The third hit for "python statistics" is a good overview of what's available:

   http://www.astro.cornell.edu/staff/loredo/statpy/

> I
> really just need t-tests, chi-squared test, and other such tests of
> statistical significance.  A few things point to numpy and scipy, but I
> was surprised to find the documentation for numpy is not freely
> available,

So? The web page does give an overview of what numpy has, and the sample 
chapters go into more depth.

> and I thought it would be wise to ask here before I download
> it and start hunting through the source code for what I want.  Is numpy
> the best option for my simple needs?

numpy tries to be an array package, not a stats package and thus has nothing 
for 
statistical tests. However, scipy has plenty of stats functionality going well 
beyond what you've specify.

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


statistical analysis tools in python?

2006-07-12 Thread Thomas Nelson
Sorry if this is a FAQ, but I couldn't find a good summary through
google.  What kinds of statistical analysis tools exist in python?  I
really just need t-tests, chi-squared test, and other such tests of
statistical significance.  A few things point to numpy and scipy, but I
was surprised to find the documentation for numpy is not freely
available, and I thought it would be wise to ask here before I download
it and start hunting through the source code for what I want.  Is numpy
the best option for my simple needs?  Also I was a little surprised to
find nothing in the builtin python modules that can find standard
deviation, quartiles, etc.  Is this for any particular reason, or
perhaps no one has shown any interest?  I'd be willing to work on a
project to make simple single-variable analysis part of the builtin
python distribution.

Thanks all,

THN

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


stderr, stdout, and errno 24

2006-07-12 Thread Wesley Henwood
To capture output from python scripts run from a C++ app I've added the
following code at the beggening of the C++ app:

PyRun_SimpleString("import grabber");
PyRun_SimpleString("import sys");
PyRun_SimpleString("class a:\n\tdef
write(self,s):\n\t\tograbber.grab(s)\n");
PyRun_SimpleString("import sys\nsys.stderr=a()\nsys.stdout=a()");

Its hard to read that way, here's what it expands to:
import grabber
import sys
class a:
def write(self, s)
grabber.grab(s)

grabber is a C++ extension, the grab function prints displays the
captured text in a Windows app.  After running about 450+ scripts in a
row, I get "IOError Errno 24 Too many open files."

I've searched this group and the net and determined that stderr and
stdout may open files, is that correct?  If so would each running of a
script be opening new files related to stderr and stdout and not
closing them?  I'm just guessing.

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


Re: Execute Commands on Remote Computers over Network

2006-07-12 Thread dylpkls91
I'm sorry, I should have clarified. I want to execute commands on
networked computers running Windows XP. Thank you for you
concern anyway. Does this mean that the Paramiko module only works on
Unix systems?

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread kdotsky
> depending on your application, a bloom filter might be a good enough:
>
>  http://en.wikipedia.org/wiki/Bloom_filter
>

Thanks (everyone) for the comments.  I like the idea of the bloom
filter or using an md5 hash, since a rare collision will not be a
show-stopper in my case.

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


Re: What is a type error?

2006-07-12 Thread David Hopwood
Marshall wrote:
> Joachim Durchholz wrote:
[...]
>>Preconditions/postconditions can express anything you want, and they are
>>an absolutely natural extensions of what's commonly called a type
>>(actually the more powerful type systems have quite a broad overlap with
>>assertions).
>>I'd essentially want to have an assertion language, with primitives for
>>type expressions.
> 
> Now, I'm not fully up to speed on DBC. The contract specifications,
> these are specified statically, but checked dynamically, is that
> right? In other words, we can consider contracts in light of
> inheritance, but the actual verification and checking happens
> at runtime, yes?

For DBC as implemented in Eiffel, yes.

> Wouldn't it be possible to do them at compile time? (Although
> this raises decidability issues.)

It is certainly possible to prove statically that some assertions cannot fail.

The ESC/Java 2 (http://secure.ucd.ie/products/opensource/ESCJava2/docs.html)
tool for JML (http://www.cs.iastate.edu/~leavens/JML/) is one system that does
this -- although some limitations and usability problems are described in
.

> Mightn't it also be possible to
> leave it up to the programmer whether a given contract
> was compile-time or runtime?

That would be possible, but IMHO a better option would be for an IDE to give
an indication (by highlighting, for example), which contracts are dynamically
checked and which are static.

This property is, after all, not something that the program should depend on.
It is determined by how good the static checker currently is, and we want to be
able to improve checkers (and perhaps even allow them to regress slightly in
order to simplify them) without changing programs.

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


Re: Inheritance error: class Foo has no attribute "bar"

2006-07-12 Thread [EMAIL PROTECTED]
I checked my code today and your suggestion did fix the problem.  I
used your second idea of having the default class attributes with
individual instance attributes.  I ran into one problem where I kept
getting the error

" File "\\user1\jacksocl\Python_stuff\CMRPG\CharCreation.py", line 262,
in __init__
self.intel = Character.attrib_dict["intel"]
AttributeError: class Character has no attribute 'attrib_dict'
Script terminated."

but I figured out it was because I was calling the Character class
expressly in the Marine subclass when I wanted to rename a dictionary
value.  It was just a simple remedy of changing the called dictionary
from "Character.attrib_dict" to "self.attrib_dict".

It gets so confusing keeping track of all things OOP items, though it's
quite a bit worse learning it in C++.

Thanks for your help.
Steven D'Aprano wrote:
> On Sun, 09 Jul 2006 04:24:01 +, crystalattice wrote:
>
> > I've finally figured out the basics of OOP; I've created a basic character
> > creation class for my game and it works reasonably well. Now that I'm
> > trying to build a subclass that has methods to determine the rank of a
> > character but I keep getting errors.
> >
> > I want to "redefine" some attributes from the base class so I can use them
> > to help determine the rank. However, I get the error that my base class
> > doesn't have the dictionary that I want to use. I've tried several things
> > to correct it but they don't work (the base class is called "Character"
> > and the subclass is called "Marine"):
>
> Without seeing your class definitions, it is hard to tell what you are
> doing, but I'm going to take a guess: you're defining attributes in the
> instance instead of the class.
>
> E.g.
>
> class Character():
> def __init__(self):
> self.attrib_dict = {}
>
> attrib_dict is now an instance attribute. Every instance will have one,
> but the class doesn't.
>
> I'm thinking you probably want something like this:
>
> class Character():
> attrib_dict = {}
> def __init__(self):
> pass
>
> Now attrib_dict is an attribute of the class. However, it also means that
> all instances will share the same values! Here's one possible solution to
> that:
>
> class Character():
> default_attribs = {}
> def __init__(self):
> self.attribs = self.default_attribs.copy()
>
> Now there is one copy of default character attributes, shared by the class
> and all it's instances, plus each instance has it's own unique set of
> values which can be modified without affecting the defaults.
> 
> 
> Hope this clears things up for you.
> 
> 
> -- 
> Steven.

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> do it this way am I going to get the memory savings I am after?  Will
> the hash function always generate unique keys?  Also, would the same
> technique work for a set?

A hash function that always generates unique hashes is called a
perfect hash.  They tend to be slow, and of course, to generate one,
you need to know all the keys in advance.

If you use a long cryptographic hash like md5 or sha, the chances of 
collision is very small.  That's probably your best bet.

In general, if your hash is N bits long, you will probably get
collisions once you have around 2**(N/2) keys.  sha is a 160
bit hash so getting collisions by accident is extremely unlikely.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Diez B. Roggisch

Please don't top post. I had to fix that below.

>>> Any other thoughts or considerations are appreciated.
>> You could try and create a md5 sum of your strings and use that as key. It
>> _should_ be good enough, but I'm no crypto expert so take that with a grain
>> of salt.

 > It should be enough but it might be a little slower than hash(string).

hash alone won't be sufficient, as it is guaranteed to have to much 
collisions. The OP already figured that out, btw.

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Fredrik Lundh
Nick Vatamaniuc wrote:

> I never said there will be no collisions. For clarity, can you quote
> the exact phrase where I mentioned that?

the text I quoted is only true if you can guarantee that there will be 
no collisions.



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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Nick Vatamaniuc
Fred,

I never said there will be no collisions. For clarity, can you quote
the exact phrase where I mentioned that?

To say that there will be no collision is nonsense because the # of
possible long url strings is certainly larger than 2^32, applying the
pigeon hole principle you could easily show that there will be
collisions.

The point is to make collision as unlikely as possible for the human
readable text (that is make them as uniform as possible), that is why
creating good cryptographic hashes is not easy.  Not that the Python
hash function work as hard as an MD5 (it is probably a multiplication
and a modulo if I had to guess). But this is a topic beyond scope of
this thread.

The original post just said that he wanted to index some values by
their urls and didn't really care about the urls themselves, so I
suggested that he just use the hash of the key as the key. The
dictionary will then take a hash of that [note that:
hash(string)=hash(hash(string)) ]  then  the dictionary will not keep
the reference to the urls and GC will collect them. So instead of
dic[urlstring']=value he will do dic[hash(urlstring)]=value. But then
to retrieve he will have to do old_value=dic[hash(urlstring]].

Hopefully this make my point more clear,
Nick V.

Fredrik Lundh wrote:
> Nick Vatamaniuc wrote:
>
> > If you don't really want to store the keys, just use
> > dic[hash(key)]=value, this way the dictionary will have the same shape
> > and distribution of keys as dic[key]=value because
> > hash('abc')=hash(hash('abc'))  but the long string of actual keys are
> > not referenced by the dictionary.
>
> how come you're so sure that there will never be any collisions ?
> 
> 

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


Re: How to delete a Python package

2006-07-12 Thread Nick Vatamaniuc
Skip,
I agree. Some kind of a manifest or log file would be great and
probably not that hard to implement.
Nick


[EMAIL PROTECTED] wrote:
> Nick> Uninstall support is hard, you would turn distutils (setup.py)
> Nick> into a package management system, but wait...!  there are already
> Nick> package managers that do exactly that (rpm, deb, Windows
> Nick> Installer).
>
> Note that I don't really care about uninstall support, certainly not enough
> to go through the pain of editing distutils.  I'd be happy if the installer
> wrote a MANIFEST file that tells me what files and directories it did
> install.  I'm not as worried about dependencies or overlaps between packages
> as much as making sure that when I want to get rid of package X I can
> actually delete all of its files.  I also realize that's not truly package
> management in the rpm/deb sense, but that would be good enough for me.
>
> My message was simply pointing out that telling people "use RPM or DEB" is
> not really acceptable.  Not everyone uses Linux.  Or Windows.  Or Macs.
> Python is a cross-platform language.  Through distutils it includes a basic
> cross-platform installation facility.  It probably ought to also have a
> corresponding basic cross-platform uninstall facility.
> 
> Skip

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


Re: Determining if an object is a class?

2006-07-12 Thread Clay Culver
Ahh much better.  Thanks.

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


Re: Determining if an object is a class?

2006-07-12 Thread infidel
>>> import types
>>> class OldStyle: pass
... 
>>> type(OldStyle) == types.ClassType
True

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


Determining if an object is a class?

2006-07-12 Thread Clay_Culver
I need to find out if an object is a class.  Using new style classes
this is very easy:

class Test(object): pass

obj = Test
   or
obj = Test()

if type(obj) == type:
# this is a class object..
else:
# this not a class object

But this fails for old style classes.  For example:

class OldStyleObject: pass

>>> type(OldStyleObject)


But I have no way of comparing the return value to anything:
>>> type(OldStyleObject) == classobj
Error, classobj not defined!

Since this is all duck typed, I have no idea what the class will be
passed in as, so I can't just compare the raw object.  I have a
solution for this:

if str(type(Test)).find('classobj') != -1:
# this is a class object

Which is quite simply awful...does anyone know of a better way to do
this?

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


Re: Generating all ordered substrings of a string

2006-07-12 Thread Gerard Flanagan

[EMAIL PROTECTED] wrote:
> Hi,
>  I want to generate all non-empty substrings of a string of length >=2.
> Also,
> each substring is to be paired with 'string - substring' part and vice
> versa.
>  Thus, ['abc'] gives me [['a', 'bc'], ['bc', 'a'], ['ab', 'c'], ['c',
> 'ab'], ['b', 'ac'], ['ac', 'b']] etc.
>  Similarly, 'abcd' should give me [['a', 'bcd'], ['bcd', 'a'], ['abc',
> 'd'], ['d', 'abc'], ['b', 'acd'], ['acd', 'b'],['c', 'abd'], ['abd', 'c'],
> ['ab', 'cd'], ['cd', 'ab'], ['bc', 'ad'], ['ad', 'bc'], ['ac',
> 'bd'],['bd','ac']]
>

from a previous post
(http://groups.google.com/group/comp.lang.python/browse_frm/thread/fa40c76544b1c515/cef5b578bb00e61b?lnk=st&q=&rnum=23#cef5b578bb00e61b)

def nkRange(n,k):
m = n - k + 1
indexer = range(0, k)
vector = range(1, k+1)
last = range(m, n+1)
yield vector
while vector != last:
high_value = -1
high_index = -1
for i in indexer:
val = vector[i]
if val > high_value and val < m + i:
high_value = val
high_index = i
for j in range(k - high_index):
vector[j+high_index] = high_value + j + 1
yield vector

def kSubsets(s, k):
for vector in nkRange(len(s),k):
yield ''.join( s[i-1] for i in vector )

print list( kSubsets('abcd',2) )

['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

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


Re: How to delete a Python package

2006-07-12 Thread Jack
I'd second Skip's point. Now that setup.py does install, and it knows what 
to
uninstall (because it copied the files in the first place) I think it's a 
good idea
to have "setup.py uninstall" support. :)

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
>Nick> Uninstall support is hard, you would turn distutils (setup.py)
>Nick> into a package management system, but wait...!  there are already
>Nick> package managers that do exactly that (rpm, deb, Windows
>Nick> Installer).
>
> Note that I don't really care about uninstall support, certainly not 
> enough
> to go through the pain of editing distutils.  I'd be happy if the 
> installer
> wrote a MANIFEST file that tells me what files and directories it did
> install.  I'm not as worried about dependencies or overlaps between 
> packages
> as much as making sure that when I want to get rid of package X I can
> actually delete all of its files.  I also realize that's not truly package
> management in the rpm/deb sense, but that would be good enough for me.
>
> My message was simply pointing out that telling people "use RPM or DEB" is
> not really acceptable.  Not everyone uses Linux.  Or Windows.  Or Macs.
> Python is a cross-platform language.  Through distutils it includes a 
> basic
> cross-platform installation facility.  It probably ought to also have a
> corresponding basic cross-platform uninstall facility.
>
> Skip 


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


Re: What is a type error?

2006-07-12 Thread Darren New
Joachim Durchholz wrote:
> Actually, in a functional programming language (FPL), you write just the 
> postconditions and let the compiler generate the code for you.

Certainly. And my point is that the postcondition describing "all valid 
chess boards reachable from this one" is pretty much going to be as big 
as an implementation for generating it, yes? The postcondition will 
still have to contain all the rules of chess in it, for example. At best 
you've replaced loops with some sort of universal quanitifier with a 
"such that" phrase.

Anyway, I expect you could prove you can't do this in the general case. 
Otherwise, you could just write a postcondition that asserts the output 
of your function is machine code that when run generates the same 
outputs as the input string would. I.e., you'd have a compiler that can 
write other compilers, generated automatically from a description of the 
semantics of the input stream and the semantics of the machine the code 
is to run on. I'm pretty sure we're not there yet, and I'm pretty sure 
you start running into the limits of computability if you do that.

-- 
   Darren New / San Diego, CA, USA (PST)
 This octopus isn't tasty. Too many
 tentacles, not enough chops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete a Python package

2006-07-12 Thread skip

Nick> Uninstall support is hard, you would turn distutils (setup.py)
Nick> into a package management system, but wait...!  there are already
Nick> package managers that do exactly that (rpm, deb, Windows
Nick> Installer).

Note that I don't really care about uninstall support, certainly not enough
to go through the pain of editing distutils.  I'd be happy if the installer
wrote a MANIFEST file that tells me what files and directories it did
install.  I'm not as worried about dependencies or overlaps between packages
as much as making sure that when I want to get rid of package X I can
actually delete all of its files.  I also realize that's not truly package
management in the rpm/deb sense, but that would be good enough for me.

My message was simply pointing out that telling people "use RPM or DEB" is
not really acceptable.  Not everyone uses Linux.  Or Windows.  Or Macs.
Python is a cross-platform language.  Through distutils it includes a basic
cross-platform installation facility.  It probably ought to also have a
corresponding basic cross-platform uninstall facility.

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


Re: What is a type error?

2006-07-12 Thread Joachim Durchholz
Darren New schrieb:
> There are also problems with the complexity of things. Imagine a 
> chess-playing game trying to describe the "generate moves" routine. 
> Precondition: An input board with a valid configuration of chess pieces. 
> Postcondition: An array of boards with possible next moves for the 
> selected team.  Heck, if you could write those as assertions, you 
> wouldn't need the code.

Actually, in a functional programming language (FPL), you write just the 
postconditions and let the compiler generate the code for you.

At least that's what happens for those FPL functions that you write down 
without much thinking. You can still tweak the function to make it more 
efficient. Or you can define an interface using preconditions and 
postconditions, and write a function that fulfills these assertions 
(i.e. requires no more preconditions than the interface specifies, and 
fulfills at least the postcondition that the interface specifies); here 
we'd have a postcondition that's separate from the code, too.
I.e. in such cases, the postconditions separate the accidental and 
essential properties of a function, so they still have a role to play.

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


Re: What is a type error?

2006-07-12 Thread Joachim Durchholz
Marshall schrieb:
> Joachim Durchholz wrote:
>> Marshall schrieb:
>>> I can see the lack of a formal model being an issue, but is the
>>> imperative bit really all that much of an obstacle? How hard
>>> is it really to deal with assignment? Or does the issue have
>>> more to do with pointers, aliasing, etc.?
>> Actually aliasing is *the* hard issue.
> 
> Okay, sure. Nice explanation.
> 
> But one minor point: you describe this as an issue with "imperative"
> languages. But aliasing is a problem associated with pointers,
> not with assignment.

Aliasing is not a problem if the aliased data is immutable.

 > One can have assignment, or other forms
> of destructive update, without pointers; they are not part of the
> definition of "imperative."

Sure.
You can have either of destructive updates and pointers without 
incurring aliasing problems. As soon as they are combined, there's trouble.

Functional programming languages often drop assignment entirely. (This 
is less inefficient than one would think. If everything is immutable, 
you can freely share data structures and avoid some copying, and you can 
share across abstraction barriers. In programs with mutable values, 
programmers are forced to choose the lesser evil of either copying 
entire data structures or doing a cross-abstraction analysis of who 
updates what elements of what data structure. A concrete example: the 
first thing that Windows does when accepting userland data structures 
is... to copy them; this were unnecessary if the structures were immutable.)

Some functional languages restrict assignment so that there can exist at 
most a single reference to any mutable data structure. That way, there's 
still no aliasing problems, but you can still update in place where it's 
really, really necessary.

I know of no professional language that doesn't have references of some 
kind.

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


Re: Compiling Python using the Portland Group compiler

2006-07-12 Thread Nick Vatamaniuc
Konrad,
I would  try to find out if pgcc has any compatibility switches. I saw
you turned optimization "off" but sometimes there is more you can do
disable some of the advanced behind the scenes magic. So apply all
those switches, run the tests and then try them one by one to find out
how many you can enable before test fail again. If you compiled it as
64bit application, try to compile as a regular 32bit and see what
happens.
Nick V.


Konrad Hinsen wrote:
> I am trying to install Python 2.4.3 on an AMD Opteron system using
> the Portland Group's compiler (pgcc). Using
>
> CC="pgcc -DNCURSES_ENABLE_STDBOOL_H=0" OPT="-O0" LINKFORSHARED="-Wl,-
> export-dynamic" ./configure --without-cxx
>
> I finally managed to obtain an executable that would start and work,
> but it fails a couple of test cases:
>
> 1) test_coercion reports wrong results for operations with complex
> numbers. For example,
> 2**(2.+0j) yields (1+0j).
>
> 2) test_compare reports some wrong results, such as
>
>   (2+0j) != (2+0j)
>
> However, typing
>
>   (2+0j) == (2+0j)
>
> into the interpreter yields "True". Perhaps the bug is in the
> execution of the test suite.
>
> 3) test_compile reports wrong results as well:
>
> test test_compile failed -- Traceback (most recent call last):
>File "/work/experiences/biophys/hinsen/install/Python-2.4.3/Lib/
> test/test_compile.py", line 164, in test_literals_with_leading_zeroes
>  self.assertEqual(eval("0777j"), 777j)
> AssertionError: 777j != 777j
>
> However,
>   eval("0777j") == 777j
> yields "True".
>
> 4) test_cpickle crashes with a segmentation fault.
>
>
> Has anyone encountered such failures before? Does anyone have useful
> suggestions for analyzing them?
>
> 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: hinsen ät cnrs-orleans.fr
> -

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


Re: scipy

2006-07-12 Thread Terry Reedy

"Aage Andersen" <[EMAIL PROTECTED] (REMOVE)> wrote in message 
news:[EMAIL PROTECTED]
>I am exploring the modules scipy and linalg using python under Win XP and 
>IDLE.
[...]
> Comments welcome.

scipy questions are best discussed on the scipy list. 



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


Re: How to delete a Python package

2006-07-12 Thread Nick Vatamaniuc
Skip,

Uninstall support is hard, you would turn distutils (setup.py) into a
package management system, but wait...!  there are already package
managers that do exactly that (rpm, deb, Windows Installer).

If no distro installer package is available for your Python module --
build it yourself and when done share with others, you are probably
already using a lot of stuff created by others, so if you see something
missing, add it, and give back to the community.

Or you could just use the package folder locally in your project to
begin with and never bother with a system-wide install. In general, for
a 'clean' system try not to use multiple installers or incompatible
package managers to put stuff in your system directories -- it will
create a mess over time.

I use Ubuntu, and so far I was able to find all the Python modules I
need as an installable .deb file, that is why I suggested Linux.
Actually as far as I am  concerned, having all your modules, IDEs, and
libraries available in a nicely organized repository, available at the
touch of an 'agt-get'  command is a pretty good reason to switch.

Nick V.


[EMAIL PROTECTED] wrote:
> >> As a rule, if you use a Linux distribution, you should just install
> >> the package and then remove the package using the package manager.
>
> Grant> That's fine except a lot of python packages aren't available in
> Grant> any of the various Linux distro package formats.
>
> And one or two people don't use Linux yet.
> 
> Uninstall support would be a good idea...
> 
> Skip

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


Re: scipy

2006-07-12 Thread Robert Kern
Aage Andersen wrote:
> I am exploring the modules scipy and linalg using python under Win XP and 
> IDLE.
> 
> Defining m=matrix( .. ) and trying to compute the inverse of m:
> 
 inverse(m)
> 
> I get an array:
> 
 array( .. )
> 
> This is unfortunate. I would rather have a matrix returned as the rules for 
> manipulating matrices and arrays differ.

Please ask these questions on scipy-user.

   http://www.scipy.org/Mailing_Lists

Recent SVN revisions of numpy.linalg should treat matrix objects sensibly. The 
scipy.linalg functions still need similar treatment. Patches are welcome.

 matrix( .. ) + n
> 
> does not give the same as
> 
 array( .. ) + n.
> 
> Trying to compute the determinant of a matrix m
> 
 det(m)
> 
> my computer resets IDLE and I get an error messages.

You can enter a bug ticket in our Trac after registering. We will need to know 
what version of scipy and numpy you are using and the exact error messages that 
you are seeing.

   http://projects.scipy.org/scipy/scipy

-- 
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: testing array of logicals

2006-07-12 Thread Gary Herron
John Henry wrote:
> Hi list,
>
> Is there a more elagant way of doing this?
>
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test
>
> --
> Thanks,
>
>   
The builtin "reduce" does that kind of thing for any function you wish
to apply across the list.So then its only a matter of giving it a
function that "and"s two arguments:

Either:
reduce(lambda a,b: a and b,   logFlags)
or
   def and2(a,b):
   return a and b

  reduce(and2, logFlags)

Gary Herron


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


Re: testing array of logicals

2006-07-12 Thread Ant

John Henry wrote:
> Hi list,
>
> Is there a more elagant way of doing this?
>
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test

There's reduce, but it's not as explicit, and see F's post RE
efficiency:

>>> x = [True, True, True]
>>> y = [True, False, True]
>>> print reduce(lambda a, b: a and b, x)
True
>>> print reduce(lambda a, b: a and b, y)
False
>>>

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


Re: testing array of logicals

2006-07-12 Thread Stefan Behnel
John Henry wrote:
> Is there a more elagant way of doing this?
> 
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test

Py2.5:

  test = all( logflags )

Py2.4 (although somewhat ugly):

  try:
test = itertools.ifilterfalse( logflags ).next()
  except StopIteration:
test = True

otherwise: your above code will do just fine. Note that you can shortcut,
though, if any of the flags evaluates to False:

  test = True
  for x in logflags:
  if not x:
  test = False
  break

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


Re: testing array of logicals

2006-07-12 Thread Fredrik Lundh
John Henry wrote:

> Is there a more elagant way of doing this?
> 
> # logflags is an array of logicals
> test=True
> for x in logflags:
>test = test and x
> print test

your code checks all members, even if the first one's false.  that's not 
very elegant.  here's a better way to do it:

 def all(S):
 for x in S:
 if not x:
return False
 return True

 print all(logfiles)

if you upgrade to 2.5, you can get rid of the function definition; "all" 
  is a built-in in 2.5.

also see:

 http://www.artima.com/weblogs/viewpost.jsp?thread=98196



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


Re: How to display name of elements in list?

2006-07-12 Thread [EMAIL PROTECTED]
Pretty sure he meant 1.5.1.

Found the documentation for the program he's using here:
http://www.hpcu.uq.edu.au/Manuals/MSC/msc/docs/marc/python/python_manual.pdf


It looks like the PyTensor object *should* have .xx, .xy, etc
properties, but they may be accessible through a matrix, i.e. .t(i,j)

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


Re: PDF with nonLatin-1 characters

2006-07-12 Thread Stefan Behnel
victor wrote:
> I want to generate a report and the PDF fits perfectly. Though there is
> an issue of using different encoding in the doc. I tried PyPS with no
> success. I need a lib that can make PDFs with an arbitrary set of fonts
> (possibly embed them into the document). What would you suggest?

I'd suggest generating LaTeX code and using PDFlatex. It's pretty hard to get
better results from any other tool.

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


Re: What is a type error?

2006-07-12 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
> > I can see the lack of a formal model being an issue, but is the
> > imperative bit really all that much of an obstacle? How hard
> > is it really to deal with assignment? Or does the issue have
> > more to do with pointers, aliasing, etc.?
>
> Actually aliasing is *the* hard issue.

Okay, sure. Nice explanation.

But one minor point: you describe this as an issue with "imperative"
languages. But aliasing is a problem associated with pointers,
not with assignment. One can have assignment, or other forms
of destructive update, without pointers; they are not part of the
definition of "imperative." (Likewise, one can have pointers without
assignment, although I'm less clear if the aliasing issue is as
severe.)


Marshall

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


testing array of logicals

2006-07-12 Thread John Henry
Hi list,

Is there a more elagant way of doing this?

# logflags is an array of logicals
test=True
for x in logflags:
   test = test and x
print test

--
Thanks,

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


Re: Generating all ordered substrings of a string

2006-07-12 Thread Thorsten Kampe
* [EMAIL PROTECTED] (2006-07-11 10:20 +)
>  I want to generate all non-empty substrings of a string of length >=2.
> Also,
> each substring is to be paired with 'string - substring' part and vice
> versa.
>  Thus, ['abc'] gives me [['a', 'bc'], ['bc', 'a'], ['ab', 'c'], ['c',
> 'ab'], ['b', 'ac'], ['ac', 'b']] etc.
>  Similarly, 'abcd' should give me [['a', 'bcd'], ['bcd', 'a'], ['abc',
> 'd'], ['d', 'abc'], ['b', 'acd'], ['acd', 'b'],['c', 'abd'], ['abd', 'c'],
> ['ab', 'cd'], ['cd', 'ab'], ['bc', 'ad'], ['ad', 'bc'], ['ac',
> 'bd'],['bd','ac']]

No, you don't want to generate all substrings, you want to generate
all partions of a given set with length 2:

filter(lambda x: len(x) == 2, part(['abcd']))

I've written an utility that generates all possible partions of a set;
the "pairing" as you call it, is trivial, so you can do it yourself

def part(seq):
import copy
partset = [[]]
for item in seq:
newpartset = []
for partition in partset:
for index in range(len(partition)):
newpartset.append(copy.deepcopy(partition))
newpartset[-1][index].append(item)
partition.append([item])
newpartset.append(partition)
partset = newpartset
return partset
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-07-12 Thread Joachim Durchholz
Marshall schrieb:
> So, what exactly separates a precondition from a postcondition
> from an invariant? I have always imagined that one writes
> assertions on parameters and return values, and those
> assertions that only reference parameters were preconditions
> and those which also referenced return values were postconditions.
> Wouldn't that be easy enough to determine automatically?

Sure.
Actually this can be done in an even simpler fashion; e.g. in Eiffel, it 
is (forgive me if I got the details wrong, it's been several years since 
I last coded in it):

   foo (params): result_type is
   require
 -- list of assertions; these become preconditions
   do
 -- subroutine body
   ensure
 -- list of assertions; these become postconditions
   end

> And what's an invariant anyway?

In general, it's a postcondition to all routines that create or modify a 
data structure of a given type.

Eiffel does an additional check at routine entry, but that's just a 
last-ditch line of defense against invariant destruction via aliases, 
not a conceptual thing. Keep aliases under control via modes (i.e. 
"unaliasable" marks on local data to prevent aliases from leaving the 
scope of the data structure), or via locking, or simply by disallowing 
destructive updates, and you don't need the checks at routine entry anymore.

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


scipy

2006-07-12 Thread Aage Andersen
I am exploring the modules scipy and linalg using python under Win XP and 
IDLE.

Defining m=matrix( .. ) and trying to compute the inverse of m:

>>> inverse(m)

I get an array:

>>>array( .. )

This is unfortunate. I would rather have a matrix returned as the rules for 
manipulating matrices and arrays differ.

>>> matrix( .. ) + n

does not give the same as

>>> array( .. ) + n.

Trying to compute the determinant of a matrix m

>>>det(m)

my computer resets IDLE and I get an error messages.

Comments welcome.

Aage 


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


Re: What is a type error?

2006-07-12 Thread Joachim Durchholz
Marshall schrieb:
> I can see the lack of a formal model being an issue, but is the
> imperative bit really all that much of an obstacle? How hard
> is it really to deal with assignment? Or does the issue have
> more to do with pointers, aliasing, etc.?

Actually aliasing is *the* hard issue.
Just one data point: C compiler designers spend substantial effort to 
determine which data structures cannot have aliasing to be able to apply 
optimizations.

This can bite even with runtime assertion checking.
For example, ordinarily one would think that if there's only a fixed set 
of routines that may modify some data structure A, checking the 
invariants of that structure need only be done at the exit of these 
routines.
Now assume that A has a reference to structure B, and that the 
invariants involve B in some way. (E.g. A.count = A->B.count.)
There's still no problem with that - until you have a routine that 
exports a reference to B, which gets accessed from elsewhere, say via C.
Now if I do
   C->B.count = 27
I will most likely break A's invariant. If that assignment is in some 
code that's far away from the code for A, debugging can become 
exceedingly hard: the inconsistency (i.e. A violating its invariant) can 
live for the entire runtime of the program.

So that innocent optimization "don't check all the program's invariants 
after every assignment" immediately breaks with assignment (unless you 
do some aliasing analysis).

In an OO language, it's even more difficult to establish that some data 
structure cannot be aliased: even if the code for A doesn't hand out a 
reference to B, there's no guarantee that some subclass of A doesn't. 
I.e. the aliasing analysis has to be repeated whenever there's a new 
subclass, which may happen at link time when you'd ordinarily don't want 
to do any serious semantic analysis anymore.

There's another way around getting destroyed invariants reported at the 
time the breakage occurs: lock any data field that goes into an 
invariant (or a postcondition, too). The rationale behind this is that 
from the perspective of assertions, an alias walks, smells and quacks 
just like concurrent access, so locking would be the appropriate answer. 
The problem here is that this means that updates can induce *very* 
expensive machinery - imagine an invariant that says "A->balance is the 
sum of all the transaction->amount fields in the transaction list of A", 
it would cause all these ->amount fields to be locked as soon as a 
transaction list is hooked up with the amount. OTOH one could argue that 
such a locking simply makes cost in terms of debugging time visible as 
runtime overhead, which isn't entirely a Bad Thing.


There are all other kinds of things that break in the presence of 
aliasing; this is just the one that I happen to know best :-)

Without mutation, such breakage cannot occur. Invariants are just the 
common postconditions of all the routines that may construct a structure 
of a given type.

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


Re: Advice for Python Reporting Tool

2006-07-12 Thread Mike Kent
rwboley wrote:

> My question is: how can I make that graphing step easier?  Ideally I'd
> like the chart to exist on it's own page, but I have no idea where to
> even begin to implement this.  Any thoughts would be appreciated.

I've seen several people recommend matplotlib for this kind of thing.

http://matplotlib.sourceforge.net/

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


Re: Editing File

2006-07-12 Thread D
Thanks to all for the suggestions - I am going to give them a try this
afternoon.  I am still fairly new to Python, so this will definitely be
a good learning experience. :)

Maric Michaud wrote:
> Le mercredi 12 juillet 2006 17:00, D a écrit :
> > Thanks, guys.  So overall, would it just be easier (and not too rigged)
> > if any changes were made by just editing the text file?  I want to do
> > this project the right way, but if it's going to be a big pain to
> > implement the edit function, just modifying the text file directly
> > isn't that big of a deal..
>
> If you don't want to rely on third party libraries, and want a human-readable
> format I'll suggest using csv file format :
>
> and this way ?
>
> In [47]: class Z(object) :
>: def __init__(self, val) : self.val = val
>:
>:
>
> In [48]: lst = [Z(i) for i in range(2) + [ str(e) for e in range(2) ] ]
>
> In [49]: [ (e, e.val) for e in lst ]
> Out[49]:
> [(<__main__.Z object at 0xa76c252c>, 0),
>  (<__main__.Z object at 0xa76c27ac>, 1),
>  (<__main__.Z object at 0xa76c23ac>, '0'),
>  (<__main__.Z object at 0xa76c23ec>, '1')]
>
> In [51]: csv.writer(file('config.csv', 'w')).writerows([
> (type(i.val).__name__, i.val) for i in lst])
>
> In [52]: print file('config.csv').read()
> int,0
> int,1
> str,0
> str,1
>
>
> In [53]: l = [ Z(eval(class_)(val)) for class_, val in
> csv.reader(file('config.csv')) ]
>
> In [54]: [ (e, e.val) for e in l ]
> Out[54]:
> [(<__main__.Z object at 0xa76c218c>, 0),
>  (<__main__.Z object at 0xa76c260c>, 1),
>  (<__main__.Z object at 0xa76c256c>, '0'),
>  (<__main__.Z object at 0xa76c25cc>, '1')]
>
>
>
>
> --
> _
>
> Maric Michaud
> _
>
> Aristote - www.aristote.info
> 3 place des tapis
> 69004 Lyon
> Tel: +33 426 880 097

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


Advice for Python Reporting Tool

2006-07-12 Thread rwboley
I'm currently learning my way through Python and in the process
developing a reporting tool for the company I'm working for.

Basically the tool rips through an existing .XML file to grab the
information needed and spits it out in a nicely formated html page that
is easily read by anyone.  This part works great, however I'm finding
myself a bit lost on the next step.

My employers want a graph added to the functionality.  Prior to this,
they have been loading the .XML file into excel and forming a crude
pivot table.  Of the table a nice looking graph is generated.

My question is: how can I make that graphing step easier?  Ideally I'd
like the chart to exist on it's own page, but I have no idea where to
even begin to implement this.  Any thoughts would be appreciated.

Thanks!
Ryan

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


Re: What is a type error?

2006-07-12 Thread Darren New
Marshall wrote:
> So, what exactly separates a precondition from a postcondition
> from an invariant?

A precondition applies to a routine/method/function and states the 
conditions under which a function might be called. For example, a 
precondition on "stack.pop" might be "not stack.empty", and 
"socket.read" might have a precondition of "socket.is_open", and 
"socket.open_a_new_connection" might have a precondition of 
"socket.is_closed".

A postcondition applies to a routine/method/function and states (at 
least part of) what that routine guarantees to be true when it returns, 
assuming it is called with true preconditions. So "not stack.empty" 
would be a postcondition of "stack.push". If your postconditions are 
complete, they tell you what the routine does.

An invariant is something that applies to an entire object instance, any 
time after the constructor has completed and no routine within that 
instance is running (i.e., you're not in the middle of a call). There 
should probably be something in there about destructors, too. So an 
invariant might be "stack.is_empty == (stack.size == 0)" or perhaps 
"socket.is_open implies (socket.buffer != null)" or some such.

The first problem with many of these sorts of things are that in 
practice, there are lots of postconditions that are difficult to express 
in any machine-readable way. The postcondition of "socket.read" is that 
the buffer passed as the first argument has valid data in the first "n" 
bytes, where "n" is the return value from "socket.read", unless 
"socket.read" returned -1.  What does "valid" mean there? It has to 
match the bytes sent by some other process, possibly on another machine, 
disregarding the bytes already read.

You can see how this can be hard to formalize in any particularly useful 
way, unless you wind up modelling the whole universe, which is what most 
of the really formalized network description techniques do.

Plus, of course, without having preconditions and postconditions for OS 
calls, it's difficult to do much formally with that sort of thing.

You can imagine all sorts of I/O that would be difficult to describe, 
even for things that are all in memory: what would be the postcondition 
for "screen.draw_polygon"? Any set of postconditions on that routine 
that don't mention that a polygon is now visible on the screen would be 
difficult to take seriously.

There are also problems with the complexity of things. Imagine a 
chess-playing game trying to describe the "generate moves" routine. 
Precondition: An input board with a valid configuration of chess pieces. 
Postcondition: An array of boards with possible next moves for the 
selected team.  Heck, if you could write those as assertions, you 
wouldn't need the code.

-- 
   Darren New / San Diego, CA, USA (PST)
 This octopus isn't tasty. Too many
 tentacles, not enough chops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Tim Chase
> how come you're so sure that there will never be any collisions ?

because none of his strings want their insurance to go up...

:*)

-tkc



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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Fredrik Lundh
Nick Vatamaniuc wrote:

> If you don't really want to store the keys, just use
> dic[hash(key)]=value, this way the dictionary will have the same shape
> and distribution of keys as dic[key]=value because
> hash('abc')=hash(hash('abc'))  but the long string of actual keys are
> not referenced by the dictionary.

how come you're so sure that there will never be any collisions ?



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


Re: threading troubles

2006-07-12 Thread sreekant
Oh dear. For the time being I will leave it with fork and leave it at that.

Ta
sree

> You may be missing nothing. If I recall correctly a similar problem was
> once reported on the pygtk-list. Some investigation showed that some
> programs couldn't be reliably run from a thread, using os.system.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete a Python package

2006-07-12 Thread skip

>> As a rule, if you use a Linux distribution, you should just install
>> the package and then remove the package using the package manager.

Grant> That's fine except a lot of python packages aren't available in
Grant> any of the various Linux distro package formats.

And one or two people don't use Linux yet.

Uninstall support would be a good idea...

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


Re: first book about python

2006-07-12 Thread gregarican
Once you are ready to take the plunge another good document is the
Python tutorial written by Guido Von Rossum himself
(http://docs.python.org/tut/). It's not a full fledged 300 page
manifesto but it's covers the basic of the language.

IOANNIS MANOLOUDIS wrote:
> I guess it's better to wait for the for dummies book.
> I should focus instead in taking the LPIC-2 exams in September.
> Ioannis

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


Re: How to delete a Python package

2006-07-12 Thread Grant Edwards
On 2006-07-12, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote:

>> Installing a Python package is easy, most of time just
>> "Setup.py install" However, setup.py doesn't seem to support
>> an uninstall command. If I want to delete a package that I
>> do not use any more, should I just manually delete the
>> corresponding sub directory under Lib\site-packages?

> As a rule,  if you use a Linux distribution, you should just install
> the package and then remove the package using the package manager.

That's fine except a lot of python packages aren't available in
any of the various Linux distro package formats.

> Distutils uninstallation is not supported. Of course you could
> manually delete the directory in site-packages in most, but
> not all (!) cases, that should remove all the files of the
> package.

-- 
Grant Edwards   grante Yow!  I hope something GOOD
  at   came in the mail today so
   visi.comI have a REASON to live!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete a Python package

2006-07-12 Thread Nick Vatamaniuc
Jack,

As a rule,  if you use a Linux distribution, you should just install
the package and then remove the package using the package manager.
Distutils uninstallation is not supported. Of course you could manually
delete the directory in site-packages in most, but not all (!) cases,
that should remove all the files of the package.

Nick Vatamaniuc

Jack wrote:
> Installing a Python package is easy, most of time just
> "Setup.py install" However, setup.py doesn't seem to support
> an uninstall command. If I want to delete a package that I
> do not use any more, should I just manually delete the
> corresponding sub directory under Lib\site-packages?

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


Re: PDF with nonLatin-1 characters

2006-07-12 Thread Nick Vatamaniuc
victor,

Have you tried Reportlab ( http://www.reportlab.org/rl_toolkit.html )?
That sounds like what you might need.

-Nick Vatamaniuc

victor wrote:
> I want to generate a report and the PDF fits perfectly. Though there is
> an issue of using different encoding in the doc. I tried PyPS with no
> success. I need a lib that can make PDFs with an arbitrary set of fonts
> (possibly embed them into the document). What would you suggest?

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Nick Vatamaniuc
Dictionaries are hash tables in Python.

If you don't really want to store the keys, just use
dic[hash(key)]=value, this way the dictionary will have the same shape
and distribution of keys as dic[key]=value because
hash('abc')=hash(hash('abc'))  but the long string of actual keys are
not referenced by the dictionary.

Now you couldn't do dic.keys() and see your urls, and every time you
want to do dic['abc'] you would get a KeyError exception.

Hope this helps,
Nick Vatamaniuc

[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > Hello,
> > I am using some very large dictionaries with keys that are long strings
> > (urls).  For a large dictionary these keys start to take up a
> > significant amount of memory.  I do not need access to these keys -- I
> > only need to be able to retrieve the value associated with a certain
> > key, so I do not want to have the keys stored in memory.  Could I just
> > hash() the url strings first and use the resulting integer as the key?
> > I think what I'm after here is more like a tradition hash table.  If I
> > do it this way am I going to get the memory savings I am after?  Will
> > the hash function always generate unique keys?  Also, would the same
> > technique work for a set?
> >
>
> I just realized that of course the hash is not always going to be
> unique, so this wouldn't really work.  And it seems a hash table would
> still need to store the keys (as strings) so that string comparisons
> can be done when a collision occurs.  I guess there's no avoiding
> storing they keys?

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Nick Vatamaniuc
It should be enough but it might be a little slower than hash(string).

Diez B. Roggisch wrote:
> [EMAIL PROTECTED] wrote:
>
> > Hello,
> > I am using some very large dictionaries with keys that are long strings
> > (urls).  For a large dictionary these keys start to take up a
> > significant amount of memory.  I do not need access to these keys -- I
> > only need to be able to retrieve the value associated with a certain
> > key, so I do not want to have the keys stored in memory.  Could I just
> > hash() the url strings first and use the resulting integer as the key?
> > I think what I'm after here is more like a tradition hash table.
>
> python dictionaries are "traditional" hash-tables.
>
> > If I
> > do it this way am I going to get the memory savings I am after?  Will
> > the hash function always generate unique keys?  Also, would the same
> > technique work for a set?
> >
> > Any other thoughts or considerations are appreciated.
>
> You could try and create a md5 sum of your strings and use that as key. It
> _should_ be good enough, but I'm no crypto expert so take that with a grain
> of salt.
> 
> Diez

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


Re: check type when assignment

2006-07-12 Thread Nick Vatamaniuc
pipe,

In general it is not possible in one line. You have to do it before
hand or after with an if statement.

As a sidenote though you probably shouldn't use isinstance(), you might
need it less than you think you do, especially if you are using it to
check for some interface. For example, do you really care if bc is of
_type_ klass or just that bc just implements method x, y, z and has
arguments a, b,c? The two things seem to be the same, because they are
the same in C++ or Java, but they are not the same in Python. In Python
an interface and type inheritance can be orthogonal to each other. One
could add methods to objects or change them at will after
instantication such that the type hierarchy would be preserved but the
interface would be broken, or alternatively you could have an object of
a different type that fully implements the interface and  could easily
be used in the code but just because it doesn't pass the isinstance()
test it is flagged as un-usable.
So in your code you could just test for the interface (methods and/or
attributes) with hasattr(bc, 'method') or even better just call the
method and see what happens, if it doesn't exist it will raise an
exception.

A much better explanation about the use and abuse of isinstance() is
here:
http://www.canonical.org/~kragen/isinstance/

Hope this helps,
Nick V.

pipehappy wrote:
> Hello everyone:
>
> Is there a way to check the type when do assignment?
>
> if I write:
> ab = bc
> and want to make sure the return value of isinstance(bc, klass) is True
> or I will raise
> a exception.
> 
> Any suggestion?

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


Re: What is a type error?

2006-07-12 Thread Marshall
Joachim Durchholz wrote:
> Marshall schrieb:
>
> > I can certainly see how DbC would be useful without subtyping.
> > But would there still be a reason to separate preconditions
> > from postconditions? I've never been clear on the point
> > of differentiating them (beyond the fact that one's covariant
> > and the other is contravariant.)
>
> There is indeed.
> The rules about covariance and contravariance are just consequences of
> the notion of having a subtype (albeit important ones when it comes to
> designing concrete interfaces).
>
> For example, if a precondition fails, something is wrong about the
> things that the subroutine assumes about its environment, so it
> shouldn't have been called. This means the error is in the caller, not
> in the subroutine that carries the precondition.
>
> The less important consequence is that this should be reflected in the
> error messages.
>
> The more important consequences apply when integrating software.
> If you have a well-tested library, it makes sense to switch off
> postcondition checking for the library routines, but not their
> precondition checking.
> This applies not just for run-time checking: Ideally, with compile-time
> inference, all postconditions can be inferred from the function's
> preconditions and their code. The results of that inference can easily
> be stored in the precompiled libraries.
> Preconditions, on the other hand, can only be verified by checking all
> places where the functions are called.

Interesting!

So, what exactly separates a precondition from a postcondition
from an invariant? I have always imagined that one writes
assertions on parameters and return values, and those
assertions that only reference parameters were preconditions
and those which also referenced return values were postconditions.
Wouldn't that be easy enough to determine automatically?

And what's an invariant anyway?


Marshall

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hello,
> I am using some very large dictionaries with keys that are long strings
> (urls).  For a large dictionary these keys start to take up a
> significant amount of memory.  I do not need access to these keys -- I
> only need to be able to retrieve the value associated with a certain
> key, so I do not want to have the keys stored in memory.  Could I just
> hash() the url strings first and use the resulting integer as the key?
> I think what I'm after here is more like a tradition hash table. 

python dictionaries are "traditional" hash-tables.

> If I 
> do it this way am I going to get the memory savings I am after?  Will
> the hash function always generate unique keys?  Also, would the same
> technique work for a set?
> 
> Any other thoughts or considerations are appreciated.

You could try and create a md5 sum of your strings and use that as key. It
_should_ be good enough, but I'm no crypto expert so take that with a grain
of salt.

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


PDF with nonLatin-1 characters

2006-07-12 Thread victor
I want to generate a report and the PDF fits perfectly. Though there is 
an issue of using different encoding in the doc. I tried PyPS with no 
success. I need a lib that can make PDFs with an arbitrary set of fonts 
(possibly embed them into the document). What would you suggest?

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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I just realized that of course the hash is not always going to be
> unique, so this wouldn't really work.  And it seems a hash table would
> still need to store the keys (as strings) so that string comparisons
> can be done when a collision occurs.

btw, Python's dictionary type *is* a highly-optimized implementation of 
a "traditional hash table".



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


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Will the hash function always generate unique keys?

no.  hash() is designed for dictionaries (hash tables), not for use as a 
cryptographic hash.

depending on your application, a bloom filter might be a good enough:

 http://en.wikipedia.org/wiki/Bloom_filter

(see the links section for a Python implementation)



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


Re: What is a type error?

2006-07-12 Thread Marshall
Joachim Durchholz wrote:
> Darren New schrieb:
> > As far as I understand it, Eiffel compilers don't even make use of
> > postconditions to optimize code or eliminate run-time checks (like null
> > pointer testing).
>
> That's correct.
>
> I think a large part of the reasons why this isn't done is that Eiffel's
> semantics is (a) too complicated (it's an imperative language after
> all), and (b) not formalized, which makes it difficult to assess what
> optimizations are safe and what aren't.

I can see the lack of a formal model being an issue, but is the
imperative bit really all that much of an obstacle? How hard
is it really to deal with assignment? Or does the issue have
more to do with pointers, aliasing, etc.?


Marshall

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


How to delete a Python package

2006-07-12 Thread Jack
Installing a Python package is easy, most of time just
"Setup.py install" However, setup.py doesn't seem to support
an uninstall command. If I want to delete a package that I
do not use any more, should I just manually delete the
corresponding sub directory under Lib\site-packages? 


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


Re: Sets and Membership Tests

2006-07-12 Thread Nick Vatamaniuc
JK,
As a general rule, let Python call the "magic" __method__ methods
behind the scenes. So don't call obj.__hash()__ or obj.__len__ or
obj.__le__ just use hash(obj), len(obj) or <=. Of course there are
exceptions, for example when calling the __init__() method of a
supercalass inside the __init__ method of your class and perhaps a few
others...
Nick V.


JKPeck wrote:
> Thanks for the advice.  Once assured that __hash__ etc was the right
> route, I found that using hash() instead of object.__hash__() gave me
> stable hash valules.  (I am hashing strings that I know to be unique.)
>
> The "no luck" situation was that a set would accept the same object
> multiple times, not recognizing that it was truly the same object.
>
>
> Nick Vatamaniuc wrote:
> > JK,
> >
> > You are correct to implement __hash__ and __eq__. The problem is how
> > you implemented them. Usually your __eq__ method should compare the
> > necessary attributes of the objects for equality. The __hash__ should
> > return a 32-bit integer. Your best bet is probably to return a hash of
> > hashes of your attributes that are used in equality comparison. What
> > this means is that your attributes used to produce the __hash__ should
> > also be hashable. This is important yet not immediatly obvious. So you
> > could for example return hash( (attribute1, attribute2, attribute3) ),
> > where attribute1, attribute2, attribute3 are all hashable.
> >  Of course, you provided no code and no error messages (the
> > 'SoFarNoLuck' exception is not descriptive enough ; )
> >
> > Hope this helps
> >
> >
> >
> > JKPeck wrote:
> > > I would like to be able use sets where the set members are objects of a
> > > class I wrote.
> > > I want the members to be distinguished by some of the object content,
> > > but I have not figured out how a set determines whether two (potential)
> > > elements are identical.  I tried implementing __eq__ and __ne__ and
> > > __hash__ to make objects with identical content behave as identical for
> > > set membership, but so far no luck.
> > >
> > > I could subclass set if necessary, but I still don't know what I would
> > > need to override.
> > > 
> > > TIA for any advice you can offer.

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


Re: check type when assignment

2006-07-12 Thread Bruno Desthuilliers
Diez B. Roggisch wrote:
> pipehappy wrote:
> 
> 
>>Hello everyone:
>>
>>Is there a way to check the type when do assignment?
>>
>>if I write:
>>ab = bc
>>and want to make sure the return value of isinstance(bc, klass) is True
>>or I will raise
>>a exception.
> 
> 
> In general, not doable. The assignment operator is not overloadable.
> 
> Only if you use assignments of the form
> 
> a.foo = bar
> 
> you could overwrite the __setattribute__-method 

(Or use a Descriptor)

> to achieve what you want. 


> 
> Diez


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Data access from multiple code modules

2006-07-12 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Jeremy Jones wrote:
> 
> 
>>What does main.py do?  Are you creating an instance of the gui thingy?
>>If so, you could just pass DataObject into your gui thingy either into
>>the constructor or to a setter once you create an instance of it.
> 
> 
> It's a wxPython app. I created the GUI initialy using wxGlade which
> gave me a small myapp.py script, a file containing the main application
> frame (containing a listbook controll) and several files containing
> panel classes. Each panel class contains controlls for performing
> various operations on the data set (adding records, deleting them,
> running various transformations).

Do you mean the code effectively doing these operations is in the gui ?
If yes, it would be better to factor it out IMHO.

> I can't say I understand how it all
> works at a deep level,
> although I've been hacking it about quite
> successfuly so far.
> 
> Presumably if I pass DataObject through to the Frame object, and from
> there through to the Panel objects then presumably this will solve the
> probelm?

Presumably !-)

> I guess it would be passed by reference so all the panels
> would be working on the same data object?

Python doesn't really have a "pass by value" semantic, since "variables"
are really just names bound to (ie : refering to) objects. So when it
comes to arguments passing, the argument *name* is local to the function
(rebinding the name won't affect the binding in the caller's namespace),
but what's bound to the name is really a reference to the object (so
mutating the object will effectively affect it).

> Doh! How simple. Why didn't I think of that? I'm too used to procedural
> scripts where you'd just put everything in a global data structure. I
> know this is bad,

Well, depends on the size of the script. But it sure doesn't scale !-)

And FWIW, even with procedural, it's possible (and usually better) to
pass arguments around instead of having a big global datastructure.
Classes are handy when many functions needs to share state (work on a
same dataset), but there's no way to have one call the other and pass it
the dataset.

> but it's hard to get out of that mentality.

Seems you're on the right way !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: don't need dictionary's keys - hash table?

2006-07-12 Thread kdotsky
[EMAIL PROTECTED] wrote:
> Hello,
> I am using some very large dictionaries with keys that are long strings
> (urls).  For a large dictionary these keys start to take up a
> significant amount of memory.  I do not need access to these keys -- I
> only need to be able to retrieve the value associated with a certain
> key, so I do not want to have the keys stored in memory.  Could I just
> hash() the url strings first and use the resulting integer as the key?
> I think what I'm after here is more like a tradition hash table.  If I
> do it this way am I going to get the memory savings I am after?  Will
> the hash function always generate unique keys?  Also, would the same
> technique work for a set?
>

I just realized that of course the hash is not always going to be
unique, so this wouldn't really work.  And it seems a hash table would
still need to store the keys (as strings) so that string comparisons
can be done when a collision occurs.  I guess there's no avoiding
storing they keys?

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


Re: Multi-threaded FTP Question

2006-07-12 Thread dbandler
Thanks so much for your help on this.  The server that I'm connecting
to is the culprit.  They only allow five connections at a time.

I assumed that it was a code issue.  I think that we're conditioned to
expect that the problem is on the software side of things.

-Derek


[EMAIL PROTECTED] wrote:
> [EMAIL PROTECTED] wrote:
> > I'm trying to use ftp in python in a multi-threaded way on a windows
> > box - python version 2.4.3.  Problem is that it appears that it's only
> > possible to have five instances/threads at one point in time.  Errors
> > look like:
> >
> >File "C:\Python24\lib\ftplib.py", line 107, in __init__
> > self.connect(host)
> >   File "C:\Python24\lib\ftplib.py", line 132, in connect
> > self.welcome = self.getresp()
> >   File "C:\Python24\lib\ftplib.py", line 208, in getresp
> > resp = self.getmultiline()
> >   File "C:\Python24\lib\ftplib.py", line 194, in getmultiline
> > line = self.getline()
> >   File "C:\Python24\lib\ftplib.py", line 184, in getline
> > if not line: raise EOFError
> > EOFError
> >
> > Is it possible to have more than five simultaneous ftp connections?
> >
> > Thanks.
> >
> > Derek
>
> It might be XP SP2's worm protection as well:
> 
> http://www.speedguide.net/read_articles.php?id=1497

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


Re: Editing File

2006-07-12 Thread Maric Michaud
Le mercredi 12 juillet 2006 17:00, D a écrit :
> Thanks, guys.  So overall, would it just be easier (and not too rigged)
> if any changes were made by just editing the text file?  I want to do
> this project the right way, but if it's going to be a big pain to
> implement the edit function, just modifying the text file directly
> isn't that big of a deal..

If you don't want to rely on third party libraries, and want a human-readable 
format I'll suggest using csv file format :

and this way ?

In [47]: class Z(object) :
   : def __init__(self, val) : self.val = val
   :
   :

In [48]: lst = [Z(i) for i in range(2) + [ str(e) for e in range(2) ] ]

In [49]: [ (e, e.val) for e in lst ]
Out[49]:
[(<__main__.Z object at 0xa76c252c>, 0),
 (<__main__.Z object at 0xa76c27ac>, 1),
 (<__main__.Z object at 0xa76c23ac>, '0'),
 (<__main__.Z object at 0xa76c23ec>, '1')]

In [51]: csv.writer(file('config.csv', 'w')).writerows([ 
(type(i.val).__name__, i.val) for i in lst])

In [52]: print file('config.csv').read()
int,0
int,1
str,0
str,1


In [53]: l = [ Z(eval(class_)(val)) for class_, val in 
csv.reader(file('config.csv')) ]

In [54]: [ (e, e.val) for e in l ]
Out[54]:
[(<__main__.Z object at 0xa76c218c>, 0),
 (<__main__.Z object at 0xa76c260c>, 1),
 (<__main__.Z object at 0xa76c256c>, '0'),
 (<__main__.Z object at 0xa76c25cc>, '1')]




-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Editing File

2006-07-12 Thread Tal Einat
akameswaran  gmail.com  gmail.com> writes:

> 
> 
> D wrote:
> > Thanks, guys.  So overall, would it just be easier (and not too rigged)
> > if any changes were made by just editing the text file?
[snip]
> have you used pickle?  if the data is as simple as you say it is, you
> will be able to read the pickle file.  2nd, it will be a lot less code
> really.  You just load and unpickle the file into a variable.  After
> any edit in the gui, repickle it to the same file.  You would have to
> do the same if you edited the text file, except you would need a couple
> of lines code to parse the string, etc.
> 

If you don't plan to edit your data by hand, Pickle is a nice and simple choice.
To save you from coding the persistency bits, you can use Python's built-in
shelve module.

Shelve uses Pickle to serialize Python objects but it does most of the
persistency stuff for you. It is very simple and clean to use. One nice feature
is that can open a shelve in auto-writeback mode, so upon assignment to one of
the shelve's keys (it's like a dict) the shelve is automatically re-serialized
to the file on disk. This saves headaches like remembering to serialize the data
upon exit cleanup, crashes resulting in data loss, etc.

Shelve is the simplest tool I know of. YAML sounds nice and readable, I haven't
tryed it out yet. You could use XML easily enough with ElementTree.

Good luck!

- Tal



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


Re: How to display name of elements in list?

2006-07-12 Thread Diez B. Roggisch
> rlcompleter is overrated, and only works on Unix/Linux/etc.
> 
> IDLE's interpreter has an auto-completion extension, which is bundled in
> Python2.5.

I don't use idle, and don't want to. So for me rlcomlpeter2 is a good thing.
And under windows, it at least works under cygwin.

Diez

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


Re: check type when assignment

2006-07-12 Thread Diez B. Roggisch
pipehappy wrote:

> Hello everyone:
> 
> Is there a way to check the type when do assignment?
> 
> if I write:
> ab = bc
> and want to make sure the return value of isinstance(bc, klass) is True
> or I will raise
> a exception.

In general, not doable. The assignment operator is not overloadable.

Only if you use assignments of the form

a.foo = bar

you could overwrite the __setattribute__-method to achieve what you want. 


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


don't need dictionary's keys - hash table?

2006-07-12 Thread kdotsky
Hello,
I am using some very large dictionaries with keys that are long strings
(urls).  For a large dictionary these keys start to take up a
significant amount of memory.  I do not need access to these keys -- I
only need to be able to retrieve the value associated with a certain
key, so I do not want to have the keys stored in memory.  Could I just
hash() the url strings first and use the resulting integer as the key?
I think what I'm after here is more like a tradition hash table.  If I
do it this way am I going to get the memory savings I am after?  Will
the hash function always generate unique keys?  Also, would the same
technique work for a set?

Any other thoughts or considerations are appreciated.

Thank You.

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


Re: check type when assignment

2006-07-12 Thread Tal Einat
pipehappy  gmail.com> writes:

> 
> Hello everyone:
> 
> Is there a way to check the type when do assignment?
> 
> if I write:
> ab = bc
> and want to make sure the return value of isinstance(bc, klass) is True
> or I will raise
> a exception.
> 
> Any suggestion?
> 

1. Check your condition before the assignment: (IMO one-liners are over-rated)

if not isinstance(bc, klass):
raise TypeError # or do whatever else is appropriate
ab = bc

2. If you really insist on doing this in a single statement (in the assignment
itself), write a function for it:

def assert_type(obj, klass):
if not isinstance(bc, klass):
raise TypeError
return obj
ab = assert_type(bc, klass)

Or to be more generic:

def assert_return(obj, func):
assert func(obj)
return obj

ab = assert_return(bc, lambda obj:isinstance(obj, klass))

- Tal

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


Re: timeit module for comparing the performance of two scripts

2006-07-12 Thread Georg Brandl
3c273 wrote:
> "John Machin" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> You appear to know what a switch is. I'm therefore surprised that you
>> appear not to
>> know that the convention is that any program that uses
>> command-line switches should do something informative when run with a -h
>> switch.
>>
> Doh! Me thinks Windows at work "python /?" (No good!), Linux at home
> "python -h" (Ah ha!). I still think it should be in the docs somewhere.

python /? now works in 2.5 SVN.

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


Re: Data access from multiple code modules

2006-07-12 Thread Jeremy Jones

[EMAIL PROTECTED] wrote:



> Doh! How simple. Why didn't I think of that? I'm too used to procedural
> scripts where you'd just put everything in a global data structure. I
> know this is bad, but it's hard to get out of that mentality.

Sounds like you got it.  Just pass it on down as needed.

- jmj

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


Re: Editing File

2006-07-12 Thread Jeremy Jones

D wrote:
> Thanks, guys.  So overall, would it just be easier (and not too rigged)
> if any changes were made by just editing the text file?  I want to do



> [EMAIL PROTECTED] wrote:



> > Might be overkill - but pickle the  data memeber that contains the
> > information.  If you use text instead of binary pickling it should
> > still be editable by hand.  for a single line of text it may be a bit
> > much - but it's still probably quicker than opening a file, parsing
> > etc.

Look at pickle, but I'd recommend against it if you're anticipating
needing to edit the file by hand.  It's just a little on the ugly side.
 Glance at Yaml (I think it's the pyyaml project in the cheeseshop) as
well.  Here's the code needed to "parse" in a .yaml file:

config = yaml.load(open(self.config_file, "r"))

Here's the code needed to serialize it back in a pretty format:

yaml.dump(config, config_file_obj, default_flow_style=False)

And here's a piece of a .yaml file itself:

feeds:
  http://leo.am/podcasts/floss:
name: FLOSS Weekly
mode: dl
  http://revision3.com/diggnation/feed/high.mp3.xml:
name: Revision3 - Diggnation w/Kevin Rose & Alex Albrecht
mode: dl
  http://geekmuse.net/podcast/:
name: Geek Muse
mode: dl

http://www.itconversations.com/rss/category-rss.php?k=achange2005&e=1:
name: Accelerating Change 2005
mode: dl

Nice and clean.

- Jeremy M. Jones

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


Re: How to display name of elements in list?

2006-07-12 Thread Tal Einat
Diez B. Roggisch  nospam.web.de> writes:
> 
> What you should do is to install rlcompleter2...
[snip]
> 
> Another option is to look into the source of that module and identify the
> objects created. Documentation is overrated - use the source, Luke!

rlcompleter is overrated, and only works on Unix/Linux/etc.

IDLE's interpreter has an auto-completion extension, which is bundled in
Python2.5.

You can also get a much better version of IDLE which includes a more robust
version of the completion extension from Idle-Spoon:
http://idlespoon.python-hosting.com/


stefan writes:
>
> Just start an interactive Python session and play with the object you are
> trying to explore. That should get you going.

+1
Python is fun - just open an interpreter and play around!


- Tal

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


check type when assignment

2006-07-12 Thread pipehappy
Hello everyone:

Is there a way to check the type when do assignment?

if I write:
ab = bc
and want to make sure the return value of isinstance(bc, klass) is True
or I will raise
a exception.

Any suggestion?

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


Re: Editing File

2006-07-12 Thread [EMAIL PROTECTED]

D wrote:
> Thanks, guys.  So overall, would it just be easier (and not too rigged)
> if any changes were made by just editing the text file?  I want to do
> this project the right way, but if it's going to be a big pain to
> implement the edit function, just modifying the text file directly
> isn't that big of a deal..
have you used pickle?  if the data is as simple as you say it is, you
will be able to read the pickle file.  2nd, it will be a lot less code
really.  You just load and unpickle the file into a variable.  After
any edit in the gui, repickle it to the same file.  You would have to
do the same if you edited the text file, except you would need a couple
of lines code to parse the string, etc.

check here for a simple example :
http://wiki.python.org/moin/UsingPickle

>
> [EMAIL PROTECTED] wrote:
> > D wrote:
> > > Hi, I currently have a Python app with a Tkinter GUI frontend that I
> > > use for system administration.  Everytime it launches, it reads a text
> > > file which contains info about each host I wish to monitor - each field
> > > (such as IP, hostname, etc.) is delimited by !!.  Now, I want to be
> > > able to edit host information from within the GUI - what would  be the
> > > best way to go about this?  Basically I just need to either edit the
> > > original host line, or write a new host line and delete the
> > > original..thanks!
> >
> > Might be overkill - but pickle the  data memeber that contains the
> > information.  If you use text instead of binary pickling it should
> > still be editable by hand.  for a single line of text it may be a bit
> > much - but it's still probably quicker than opening a file, parsing
> > etc.

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


Re: Editing File

2006-07-12 Thread D
Thanks, guys.  So overall, would it just be easier (and not too rigged)
if any changes were made by just editing the text file?  I want to do
this project the right way, but if it's going to be a big pain to
implement the edit function, just modifying the text file directly
isn't that big of a deal..

[EMAIL PROTECTED] wrote:
> D wrote:
> > Hi, I currently have a Python app with a Tkinter GUI frontend that I
> > use for system administration.  Everytime it launches, it reads a text
> > file which contains info about each host I wish to monitor - each field
> > (such as IP, hostname, etc.) is delimited by !!.  Now, I want to be
> > able to edit host information from within the GUI - what would  be the
> > best way to go about this?  Basically I just need to either edit the
> > original host line, or write a new host line and delete the
> > original..thanks!
>
> Might be overkill - but pickle the  data memeber that contains the
> information.  If you use text instead of binary pickling it should
> still be editable by hand.  for a single line of text it may be a bit
> much - but it's still probably quicker than opening a file, parsing
> etc.

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


  1   2   >