Re: Why is dictionary.keys() a list and not a set?

2005-11-27 Thread Christoph Zwerschke
Martin v. Löwis schrieb:

>> As Mike has written in his last posting, you could easily "fix" that 
>> by tweaking the equality relation as well. So technically speaking, 
>> Mike is probably right.
> 
> No. If you define both __hash__ and __eq__ consistently, then __hash__
> would meet the specification. As posted in the example, __hash__ does
> not meet the specification, contrary to Mike's claim that it does.

Ok, the example was incomplete, but in principle, this could be fixed by 
adding a tweaked __eq__ method. So for completeness sake:

class mylist2(list):
 def __hash__(self): return id(self)
 def __eq__(self, other): return self is other
 def __ne__(self, other): return self is not other

list = mylist2

a = list([1])
b = list([1])

print a, b, a == b, a != b

> If you have a=[1] and b=[1], then *always* a==b; you cannot
> change the semantics of list displays.

Surely, since you can't change the methods of built-in types. But you 
can create your own local list displays with a tweaked semantics as in 
the above example.

Anyway, the original question was: Are mylist1 and mylist2 (as above) to 
be considered "hashable" types or not? I think "technically" speaking, 
they are, and the "technical" definition is the only one that counts.

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


Re: How can I do this in Python?

2005-11-27 Thread Jonathan Gardner
I don't know what engine you are using. Basically all you have to do is
render the login form at the url of the page that needs the login.
You're going to have to hook in the authentication code before you
render the page normally. For instance, this is a common way I've been
doing it in various engines I use:

(1) Check to see if the user is logging in by looking at the
parameters. If they login successfully, record that in the session and
continue as normal.

(2) Normal operation being... check to see if they are logged in
according to their session. (The code in (1) will set up their session
to be logged in if they just logged in.) If they aren't and they need
to be, show the login page. Otherwise, show the regular content.

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


Re: Syntax

2005-11-27 Thread Fredrik Lundh
Terry Hancock wrote:

> > I don't think there are any *security* reasons, but
> > stylistically, "import os" is greatly preferred. When
> > someone else reads your code, they will immediately know
> > where getcwd() comes from.
>
> It's not a question of "security" in the usual sense, but
> the first syntax imports a lot of stuff into the current
> namespace, increasing the risk of unintentionally clobbering
> local names. So it's certainly "riskier" in the sense of
> "likely to cause bugs".

or just "likely to result in confusing error messages".

>>> from os import *
>>> f = open("myfile.txt", "r")
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: an integer is required





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


Re: interactive prompts

2005-11-27 Thread Ben Finney
Michael Williams <[EMAIL PROTECTED]> wrote:
> how do I force the environmental variables set by one  'popen' or
> 'pexpect' to propagate throughout the entire Python  session so that
> any commands called will see those env variables?

A process's environment must be inherited from its parent, or set by
the process itself. Child processes can't affect their parent
process's environment. (This is the way it works in Unix, it's not
specific to Python.)

-- 
 \  "A society that will trade a little liberty for a little order |
  `\will lose both, and deserve neither."  -- Thomas Jefferson, in |
_o__)  a letter to Madison |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython Licence vs GPL

2005-11-27 Thread Steven D'Aprano
On Sat, 26 Nov 2005 09:54:24 -0800, Alex Martelli wrote:

>> My understanding is that both Oracle and SAP make most of their money
>> through consulting and customization rather than licencing or sales. I
> 
> Have you checked their quarterly statements recently?  

Obviously not.

Thanks for going beyond the call of duty to research the facts in such
detail. I'm surprised that Adobe is selling so many licences -- I don't
know anyone who has paid for Adobe software in many years -- and you can
take that any way you like. (Kids! Pirating software is stealing!!!) 

I can't argue with anything you've written, except to say that we've
obviously got different ideas of what consists of software sales.

I know that there is a general sense of "sales" that effectively means
"any source of income from services or goods". There is also a more
restrictive (there's that word again...) sense of a sale being a transfer
of ownership. In that stricter sense, nobody sells software -- they
merely licence it.

The sense of "software sales" I mean is intermediate between the two. The
way I mean "sales", when Joe Public goes to acmesoft.com, pays $99 on his
credit card number to download Acmesoft FooMaker, that's a sale. When he
discovers that he also needs 37 Client Access Licences at $19 each, that's
_not_ a software sale, and neither is the $150 per year for support and
upgrades: that's revenue from licencing, not sales.

You're usage of sales may differ, and I'm not going to argue that one is
better than the other. By my meaning, Red Hat doesn't sell RH Enterprise
Linux, but charges for support. By your meaning, Red Hat does sell RHEL.
I'm good with that definition too, so long as we can agree on one or the
other.


-- 
Steven.

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


Re: wxPython Licence vs GPL

2005-11-27 Thread Rikard Bosnjakovic
Steven D'Aprano wrote:

> (Kids! Pirating software is stealing!!!) 

Or evaluating, depending of how you look at it.


-- 
Sincerely,  |http://bos.hack.org/cv/
Rikard Bosnjakovic  | Code chef - will cook for food

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


Re: Comparison problem

2005-11-27 Thread Fredrik Lundh
Peter Hansen wrote:

> Actually, it's not so much baroque as it is safe... item[0] will fail if
> the string is empty, while item[0:1] will return '' in that case.
>
> Of course, as you point out, .startswith() is the better approach anyway.

$ timeit -s "s = 'abc'" "s[:1] == 'a'"
100 loops, best of 3: 0.852 usec per loop

$ timeit -s "s = 'abc'; w ='a'" "s[:len(w)] == w"
100 loops, best of 3: 1.27 usec per loop

$ timeit -s "s = 'abc'; c=s.startswith" "c('a')"
100 loops, best of 3: 1.75 usec per loop

$ timeit -s "s = 'abc'" "s.startswith('a')"
10 loops, best of 3: 2.28 usec per loop





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


Re: Why are there no ordered dictionaries?

2005-11-27 Thread Christoph Zwerschke
Bengt Richter wrote:

>>d.keys[:] = newkeyseq
> 
> Do you really mean just re-ordering the keys without a corresponding reording 
> of values??
> That would be a weird renaming of all values. Or do you means that any key 
> should still
> retrieve the same value as before if used as d[key]? In which case the values 
> must undergo
> the same permutation as the keys. I.e., you are assuming key->value pairings 
> remain stable
> through any key reorderings?

Since it is considered as being a dictionary in the first place, the 
key->value pairings should of course stay stable. In the usual 
implementation based on an ordinary dictionary with an additional key 
list ("sequence" in the Foord/Larosa and "_keys" in the Bejamin/Winter 
implementation), you would only set the key list, since the value list 
is generated dynamically. But if your implementation keeps internal 
values or items lists, these need to be adjusted as well.

I will assume that d has is a Foord/Larosa ordered dict with "sequence" 
attribute in the following.

Then, with other words,

d.keys[:] = newkeyseq

should do the same as:

d.sequence = newkeyseq

> Exactly what, though? should e.g.
> d.keys[3] =  newk3
> mean (not a suggested implementation, just to define semantics)
> keys = d.keys()
> if newk3 in keys and keys.index(newk3)!=3:
> raise ValueError,'Attempt to introduce duplicate key'
> items = d.items()
> items[3] = (newk3, items[3][1])
> d.clear()
> d.update(items)

Yes, that would be the correct semantics. Of course this should not be 
the real implementation and use KeyError instead of ValueError. With 
other words,

d.keys[i] = newkey

sould be the same as:

if d.sequence[i] != newkey:
 if newkey in d.sequence:
  raise KeyError,'Attempt to introduce duplicate key'
 else:
  d.sequence[i] = newkey

> This would allow what you might call renaming in place.
> Similarly
> d.keys[i:j] = newkeysij
> might have the semantics of
> keys = d.keys()
> outside = set(keys[:i])+set(keys[j:])
> if outside & set(newkeysij) or len(newkeysij) != len(set(newkeysij)):
> raise ValueError,'Attempt to introduce duplicate key(s)'
> items = d.items()
> items[i:j] = [(k, items[kx+i][1]) for kx,k in enumerate(newkeysij)]
> d.clear()
> d.update(items)
> 
> Is this what is desired?

Not quite, because it does not preserve the key->value pairings (see 
above) and it would behave strangely or raise an exception if the new 
slice is larger. The following code would do:

keys = d.keys()
outside = set(keys[:i])|set(keys[j:])
if outside & set(newkeysij) or len(newkeysij) != len(set(newkeysij)):
 raise ValueError,'Attempt to introduce duplicate key(s)'
items = d.items()
items[i:j] = [(k, d.get(k, None)) for k in newkeysij]
d.clear()
d.update(items)

(Note that there was a bug in the second line. You cannot add sets.)

Again, this would be equivalent to:

seq = d.sequence
newseq = seq[:]
newseq[i:j] = newkeysij
if len(newseq) != len(set(newseq)):
 raise KeyError,'Attempt to introduce duplicate key(s)'
for k in set(seq[i:j]) - set(newkeysij):
 del d[k]
for k in set(newkeysij) - set(seq[i:j]):
 d[k] = None
d.sequence = newseq

>>You don't keep track of the item lists, they need to be built on every 
>>occasion.
> 
> That depends on how you implement ;-)

Ok, I was thinking of the usual implementations.

> Back from holiday, so maybe I'll hack something out.

Let us know when you have something to check out.

Maybe Fuzzyman can make some moderate improvements to the existing 
odict.py, and you can do something more "radical". Then we have two 
"reference implementations" and can compare how they prove regarding 
performance and usability.

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


Re: Why are there no ordered dictionaries?

2005-11-27 Thread Christoph Zwerschke
Christoph Zwerschke wrote:

> I will assume that d has is a Foord/Larosa ordered dict with "sequence" 
> attribute in the following.
> 
> Then, with other words,
> 
> d.keys[:] = newkeyseq
> 
> should do the same as:
> 
> d.sequence = newkeyseq

At least in the case where newkeyseq is a permutation of d.sequence.

Otherwise, it should behave like the given implementation for setting 
slices, i.e.

- if newkeyseq has duplicate elements, an exception should be raised.
- if newkeyseq has elements not in d.sequence, then the dictionary 
should be updated with corresponding None values
- if d.sequence has elements not in newkeyseq then these elements should 
be deleted from the dictionary

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


Re: wxPython Licence vs GPL

2005-11-27 Thread Steven D'Aprano
On Sat, 26 Nov 2005 21:39:13 +0100, Martin P. Hellwig wrote:

> The software was sold in 3 separates modules requiring a yearly renewal, 

The software is hardly sold if you have to renew that "sale" every year.
That's more like a lease. I'd call it revenue from licencing, not revenue
from sales.

Of course you're welcome to describe it as sales. It is an arbitrary
choice one way or another -- the main thing is to not talk at
cross-purposes, as we obviously have been doing.

-- 
Steven.

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


Re: Comparison problem

2005-11-27 Thread [EMAIL PROTECTED]
I think no matter what language you programs it, it is hard to
understand. Can you break it up into sub-problems first ? Like first
parsing the inventory file into a python dict, then also the fields
from web to another dict ?

Chris wrote:
> Hi,
>
> I'm new to python, and I'm trying to write a small python script for a
> webpage.  The script opens up a file called inventory, reads the
> contents, and checks the contents against the data from the form in my
> webpage.  Now I have to do some slicing to get the name of the form
> elements (in this case, checkboxes), to resemble the values in the
> inventory file.  Here's my python part:
>
> #!/usr/local/bin/python
> import cgi
> import types
> from Cookie import *
> form=cgi.FieldStorage()
> user_answer=[]
> error='false'
> item=''
> qty=''
> def main():
>   print"Content-type: text/html\n"
>   i=open("inventory","r")
>   keys=form.keys()
>   for key in keys:
>field=form[key]
>if type(field)==types.InstanceType:
> item=field.value
> if item[0:1]=="-":
>  item=item[ :-7]
>  item=item[1:]
>  infile=open("inventory","r")
>  while infile:
>   dummy=infile.readline()
>   if dummy=='':break
>   print item
>   print ", "+dummy
>   if (dummy == item): 
>print"Found it"
>   else:
>print"Didn\'t Find it"
>   print ""
>  infile.close()
> else:
>  #print"  Quantity: "
>  #print item
>  print""
> #print field.value
>else:
> print"BAD"
> main()
>
> Let me know if more information is needed.  Any assistance will be
> greatly appreciated.

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


Re: Why are there no ordered dictionaries?

2005-11-27 Thread Fuzzyman
Note that I've done two things with the Foord/Larosa dict. ;-)

I've implemented slicing, including slice assignment and deletion. I've
also 'hidden' ``sequence``, but you can pass arguments to keys, values
and items.

I've done a second (experimental) implementation of a custom keys
object. This is effectively the managed list - which you can call as a
method or mutate in place. You can't delete members from 'keys' but you
can do slice assignment so long as the sequence you're replacing is the
same length (and is a re -ordering of the set being replaced).

I'll post it on Monday, and if people like it I'll complete it.

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: Which License Should I Use?

2005-11-27 Thread mojosam
> First thing first, you need to find out if you are an
> "employee", not in the normal sense, but legal sense.

You're right.  I know there has been a lot of case law to come down the
pike over the years, due to all sorts of issues.  One of my friends is
a cab driver.  His contract says that he is an independent contractor.
Yet his state (Oregon) has three criteria that have to be met.  One of
these is he has to set his own hours.  He doesn't; the cab company
tells him when he works.  This fails the independent contractor test,
so the cab company is legally exposed if any of the cabbies wants to
press any employment-law issues.

So there are too many variables and unknowns, and it varies by
jurisdiction.

I started this thread under the mistaken hope that there was some sort
of license that would force the code to stay open source.  Although
that isn't realistic, it doesn't change the fact that I should choose a
license that best fits my needs.

I will consult a lawyer about these issues.  Also, if my
client/employer won't let me keep my code, I'll just have to keep my
code away from them.  Maybe I can find a commercial tool and tell them
that they will have to buy that.

Ron Britton 
nk67v8o02 at 
sneakemail.com

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


Re: Why are there no ordered dictionaries?

2005-11-27 Thread Christoph Zwerschke
Bengt Richter schrieb:

> OTOH,
>  >>> {}[:]
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: unhashable type
> I.e., slices are not valid keys for ordinary dicts, and slices tie in
> very well with the ordered aspect of ordered dicts, so that's an
> argument for permitting it via the indexing syntax, not just items[:]
> or items()[:] which have related but not identical semantics.

I see it like that. BTW, the above error message is pretty bad.

 > I wonder who is going to use it for what.

I think re-ordering will be a very rare use case anyway and slicing even 
more. As a use case, I think of something like mixing different 
configuration files and default configuration parameters, while trying 
to keep a certain order of parameters and parameters blocks.

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


Re: How to get started in GUI Programming?

2005-11-27 Thread Claudio Grondi

<[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> I am trying to learn GUI programming in Python, but have to confess I
> am finding it difficult.
>
> I am not an experienced programmer - just someone who from time to
> time writes small programs for my use.  Over the years I have moved
> from GWBASIC to QBASIC to Visual Basic, and now trying to move across
> to a Linux platform.  Python seems to be the best compromise between
> the limitations of command line basic programming and the total
> incomprehensibility of C.
>
> Googling around it seems the best GUI is either Tkinter or PyGtk.  I
> found a book which recommended PyGtk, as it had a graphical design
> option,  Glade.  Coming from a VB background I latched onto that and
> bought the book (Beginning Python, Wrox), but it was a disappointment
> (or more accurately a complete waste of money) - there was
> insufficient detail in the text.
>
> I've found the tutorial and reference manual on the PyGtk web site,
> but although I've made some progress, I keep reaching points where I
> have insufficient background to understand them. Currently I'm stuck
> on dialog boxes (the code seems immensely complex for the equivalent of
>   MsgBox("Do you really want to do this ",vbYesNo) and I haven't
> got it to work properly yet) and loading graphical images in anything
> other than their original size, but every new step brings another
> struggle
>
> I've seen reference to a Tkinter book - something like 'Python
> and Tkinter Programming' but it seems to be out of print and
> unavailable.
>
> Can anyone offer any suggestions as to the least painful way forwards?
>

>From what you write I conclude, that it is maybe a very good idea to stay
with Visual Basic and use it to create the appropriate ActiveX components
you need in Python and then register them to use it from Python. This way
you can 'marry' what you have already created in Visual Basic easily with
Python.
>From what I currently know, there is no 100% cross-platform solution for GUI
related tasks, because each platform has own specifics which usually are
very interesting for use in own programming and that kills as a consequence
the cross-platform usage.

# For example a Yes/No/Abort dialog box can be achieved using the WSHOM.OCX
available in Windows as follows:

import win32com.client
axWshShell = win32com.client.Dispatch("WScript.Shell") # WSHOM.OCX

axWshShell_Popup_Icon_Critical =   16
axWshShell_Popup_Button_AbortRetryIgnore   =2
axWshShell_Popup_NoAutoclose   =0

intRetVal = axWshShell.Popup(
### Raise a message box:
   " The Popup() Text" + "\n" +
   "",
   axWshShell_Popup_NoAutoclose,
   " The Popup() Title:",
   axWshShell_Popup_Icon_Critical + axWshShell_Popup_Button_AbortRetryIgnore
)

axWshShell_Popup_Clicked_Abort =3  # [Abort]  button
axWshShell_Popup_Clicked_Retry =4  # [Retry]  button
axWshShell_Popup_Clicked_Ignore=5  # [Ignore] button

if(intRetVal ==  axWshShell_Popup_Clicked_Abort):
  print 'Abort clicked, return value = %i'%(intRetVal,)

if(intRetVal ==  axWshShell_Popup_Clicked_Retry):
  print 'Retry clicked, return value = %i'%(intRetVal,)

if(intRetVal ==  axWshShell_Popup_Clicked_Ignore):
  print 'Ignore clicked, return value = %i'%(intRetVal,)

Hope this is what are you looking for, isn't it?

Claudio


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


Re: The imp module and cyclic imports

2005-11-27 Thread Matthias Kramm
> the problem you're seeing appears also if you use "import web.one"
> or "from web import one" or "__import__('web.one')".

Thanks for the hint. You're right. This isn't actually imp related. The
standard import also fails.

> if you replace the "from web import" statements with plain imports,
> everything will work as expected.  just change
>
>from web import one
>
> to
>
>   import one

Unfortunately, this fails if one.py and two.py are in different
directories/packages.
With a setup like
web1/one.py
web2/two.py
there doesn't seem to be any way to make one.py and two.py reference
each other via (non-delayed) imports.

It's interesting, though, that cyclic imports work when using the plain
"import foo" import, but not with the "from package import foo" style.
Especially since the former also used to fail (google for "python
cyclic imports" on groups.google.com). I wonder whether the "from"
style imports were overlooked when the cyclic problem was fixed.

Greetings

Matthias

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


Re: Which License Should I Use?

2005-11-27 Thread [EMAIL PROTECTED]
Yup, these independent contractor test doctrines bite both way and in
your case, it is not in your advantage, usually.

I would suggest that whatever tools you want to make to enhance the
work(even it is inspired by your current task), don't use it on this
employer/client, at least not on their premise(including property say a
notebook provided by them) and must not let anyone know that you use it
to help you do the work about them.

mojosam wrote:
> > First thing first, you need to find out if you are an
> > "employee", not in the normal sense, but legal sense.
>
> You're right.  I know there has been a lot of case law to come down the
> pike over the years, due to all sorts of issues.  One of my friends is
> a cab driver.  His contract says that he is an independent contractor.
> Yet his state (Oregon) has three criteria that have to be met.  One of
> these is he has to set his own hours.  He doesn't; the cab company
> tells him when he works.  This fails the independent contractor test,
> so the cab company is legally exposed if any of the cabbies wants to
> press any employment-law issues.
>
> So there are too many variables and unknowns, and it varies by
> jurisdiction.
>
> I started this thread under the mistaken hope that there was some sort
> of license that would force the code to stay open source.  Although
> that isn't realistic, it doesn't change the fact that I should choose a
> license that best fits my needs.
>
> I will consult a lawyer about these issues.  Also, if my
> client/employer won't let me keep my code, I'll just have to keep my
> code away from them.  Maybe I can find a commercial tool and tell them
> that they will have to buy that.
> 
> Ron Britton 
> nk67v8o02 at 
> sneakemail.com

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


pyext - google

2005-11-27 Thread tim

Hi,

I'm playing around with the python external for PureData. (pyext)
I want to enable a patch to lookup something on the net.
I modified the "search.py" example from Dive Into Python and kind of 
pasted it into the simple.py example from the pyext docs to be loaded in 
a pd patch.
Loading the script in the patch works, and it receives messages and 
sends messages back, so I think on the pd side I've got it set up right.

If I call my "srch" function (see script) I get this error:

Traceback (most recent call last):
 File "c:/pd/scripts\\searchggl.py", line 86, in srch_1
   res = searchgoogle(q)
 File "c:/pd/scripts\\searchggl.py", line 101, in searchgoogle
   results = _server.doGoogleSearch(
 File "C:\\Python24\\lib\\site-packages\\SOAPpy\\Client.py", line 470, 
in __call__

   return self.__r_call(*args, **kw)
 File "C:\\Python24\\lib\\site-packages\\SOAPpy\\Client.py", line 492, 
in __r_call

   self.__hd, self.__ma)
 File "C:\\Python24\\lib\\site-packages\\SOAPpy\\Client.py", line 406, 
in __call

   raise p
SOAPpy.Types.faultType: deserialize a 'http://www.w3.org/1999/XMLSchema:Symbol' using encoding 
style 'http://schemas.xmlsoap.org/soap/encoding/'.>


attached are the original search.py script, and my modified pd-pyext 
version.


Any clues appreciated!
Tim
"""Search Google from the command line

This program is part of "Dive Into Python", a free Python book for
experienced programmers.  Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim ([EMAIL PROTECTED])"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/20 18:53:59 $"
__copyright__ = "Copyright (c) 2004 Mark Pilgrim"
__license__ = "Python"

from SOAPpy import WSDL

# you'll need to configure these two values;
# see http://www.google.com/apis/
WSDLFILE = '/path/to/copy/of/GoogleSearch.wsdl'
APIKEY = 'YOUR_GOOGLE_API_KEY'

_server = WSDL.Proxy(WSDLFILE)
def search(q):
"""Search Google and return list of {title, link, description}"""
results = _server.doGoogleSearch(
APIKEY, q, 0, 10, False, "", False, "", "utf-8", "utf-8")
return [{"title": r.title.encode("utf-8"),
 "link": r.URL.encode("utf-8"),
 "description": r.snippet.encode("utf-8")}
for r in results.resultElements]

if __name__ == '__main__':
import sys
for r in search(sys.argv[1])[:5]:
print r['title']
print r['link']
print r['description']
print
# py/pyext - python script objects for PD and MaxMSP
#
# Copyright (c) 2002-2003 Thomas Grill ([EMAIL PROTECTED])
# For information on usage and redistribution, and for a DISCLAIMER OF ALL
# WARRANTIES, see the file, "license.txt," in this distribution.  
#

"""This is an example script for the py/pyext object's basic functionality.

pyext Usage:
- Import pyext

- Inherit your class from pyext._class

- Specfiy the number of inlets and outlets:
Use the class members (variables) _inlets and _outlets
If not given they default to 1
You can also use class methods with the same names to return the 
respective number

- Constructors/Destructors
You can specify an __init__ constructor and/or an __del__ destructor.
The constructor will be called with the object's arguments

e.g. if your PD or MaxMSP object looks like
[pyext script class arg1 arg2 arg3]

then the __init__(self,args) function will be called with a tuple 
argument
args = (arg1,arg2,arg3) 
With this syntax, you will have to give at least one argument.
By defining the constructor as __init__(self,*args) you can also 
initialize 
the class without arguments.

- Methods called by pyext
The general format is 'tag_inlet(self,args)' resp. 
'tag_inlet(self,*args)':
tag is the PD or MaxMSP message header.. either bang, float, 
list etc.
inlet is the inlet (starting from 1) from which messages are 
received.
args is a tuple which corresponds to the content of the 
message. args can be omitted.

The inlet index can be omitted. The method name then has the format 
'tag_(self,inlet,args)'.
Here, the inlet index is a additional parameter to the method

You can also set up methods which react on any message. These have the 
special forms
_anything_inlet(self,args)
or
_anything_(self,inlet,args) 

Please see below for examples.

Any return values are ignored - use _outlet (see below).

Generally, you should avoid method_, method_xx forms for your non-pyext 
class methods.
Identifiers (variables and functions) with leading underscores are 
reserved for pyext.

- Send messages to outlets:
Use the inherited _outlet method.
You can either use the form
self._outlet(outlet,arg1,arg2,arg3,arg4) ... where all args are 
atoms (no sequence types!)
or
self._outlet(outlet,arg)

Has this problem been fiexed ?

2005-11-27 Thread Xiao Jianfeng
Hello,

I'm trying to build python2.4.2 on IRIX6.5(cc version MIPSpro Compilers:
Version 7.3.1.3m).
But the socket module failed to compile.

I found this in ./Modules/socketmodule.c, line 193:

/* XXX Using _SGIAPI is the wrong thing,
194 but I don't know what the right thing is. */
195 #undef _SGIAPI /* to avoid warning */
196 #define _SGIAPI 1


I think maybe somebody have already fixed this problem.

Or any hints on how to compile socket module on IRIX?

Thanks very much.

Regards,

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

Estimating memory use?

2005-11-27 Thread Roy Smith
I've got a large text processing task to attack (it's actually a genomics 
task; matching DNA probes against bacterial genomes).  I've got roughly 
200,000 probes, each of which is a 25 character long text string.  My first 
thought is to compile these into 200,000 regexes, but before I launch into 
that, I want to do a back of the envelope guess as to how much memory that 
will take.

Is there any easy way to find out how much memory a Python object takes?  
If there was, it would be simple to compile a random small collection of 
these patterns (say, 100 of them), and add up the sizes of the resulting 
regex objects to get a rough idea of how much memory I'll need.  I realize 
I could just compile them all and watch the size of the Python process 
grow, but that seems somewhat brute force.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get started in GUI Programming?

2005-11-27 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> I am trying to learn GUI programming in Python, but have to confess I
> am finding it difficult.

Don't do it if you can prevent it.

GUI - toolkits are very complex beasts and at least to me a source of
pain far more as a joy. Python cannot help you making them
significantly simpler but on the contrary add just another level of
indirection. Python normally shines when you have to glue libraries
together or programming simply Python scripts for a broad range of
purposes but if the wrapped library publishes a huge interface with
hundreds of classes and thousands of methods and attributes the benfit
of Pythons abstraction converges to zero. Python does not offer a good
toolchain to take up with Swing, WinForms or Qt to name just a few
delivered with IDEs that are very helpfull in developing GUI apps. Not
to talk about documentation...

Conclusion: if you are already familiar with BASIC I would just
continue writing BASIC apps using VisualBasic dotNet, Windows Forms as
the underlying GUI toolktit and VisualStudio as IDE. Forget the
coolness factor of the language. Cool people never care a lot what
other people think. If you finally want to glue assemblys/controls
together in Python this is still possible with IronPython or
Python-dotNet ( which is a CPython binding to the CLR, available at
Zope.org ).

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


Dr. Dobb's Python-URL! - weekly Python news and links (Nov 26)

2005-11-27 Thread Cameron Laird
QOTW:  "... '[B]ut assume that I have some other use case' isn't a valid
use case". - Fredrik Lundh

"Rolling your own solution, on the other hand, can end in a long road
discovering what those CORBA people were doing for all those years." - Paul
Boddie


NOTW:  sceptifications.


Steven D'Aprano carefully details a common confusion among
newcomers about empty lists and initialization:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/8480fae54a64fc15/

Inyeol Lee and others illustrate use of regular expression
syntax having to do with repeated patterns:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b5e7abb4ff1e156c/

Metakit 2.4.9.5 corrects a potential disk-full error, and
improves performance greatly in certain circumstances:
http://www.equi4.com/pub/mk/CHANGES
http://www.equi4.com/metakit.html

William Peterson jokes that, "[i]f you ask ten people on 
this newsgroup [about GUI construction newcomers] you'll
probably get twelve opinions"--and then the community 
promptly proves him right:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/6fd1ea6b4a2d31f8/

Having arrived in the twenty-first century, clp now has 
its own (provisional) podcast:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b39581f59dce9191/

David Wahler cogently perverts^H^H^H^H^H^H^H^Hextends pickle
to serialize *classes* (as opposed to their instances):

http://groups.google.com/group/comp.lang.python/browse_thread/thread/10a03f094303a91c/

Fully-general backward-compatibility has substantial costs,
often greater than the version migration it's supposed to
spare us.  Several of the regulars discuss this seriously:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/423d9dfa80456966/

__slots__ are only a (memory) optimization, restricted to
well-defined circumstances, explains the martellibot:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1cc68de7af477386/

A good thing about Cheetah is that it cooperates with Python's
inheritance:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/f063406b648c7d0c/


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%2

Re: Why is dictionary.keys() a list and not a set?

2005-11-27 Thread Martin v. Löwis
Christoph Zwerschke wrote:
> Anyway, the original question was: Are mylist1 and mylist2 (as above) to 
> be considered "hashable" types or not?

I long forgot was the original question was (I thought it was
"Why is dictionary.keys() a list and not a set?" :-); anyway,
the answer to this question is certainly "yes".

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


Tablelist-tcl-tk-tile

2005-11-27 Thread malv
Wanting to explore tk under python, I must say that it seems to be very
difficult to find the required information in one single place.
I would like to give tk a try but as I need as a test something
equivalent of the Qt datagrid, I don't seem manage yet to get the
latest releases of tablelist, tcl, tk and tile going.
Did anybody manage to make the recent releases work in Python 2.4?
I manged to do some things with tablelist v4.2 but with the 8.4
versions of tcl/tk. However, for future work including tile, it would
seem wise to start out from 8.5.
In order to make tcl8.5, tk8.5 go, I suppose the 8.4 versions have to
be removed.
Do I have to remove and recompile python 2.4 as well? Is there any
compact writup on how to get going without having to delve into the
inner workings and wrapping of tcl?
Thx.
malv

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


Re: Why is dictionary.keys() a list and not a set?

2005-11-27 Thread Christoph Zwerschke
Martin v. Löwis wrote:

> I long forgot was the original question was (I thought it was
> "Why is dictionary.keys() a list and not a set?" :-)

Er, yes. Probably we should have opened a new thread instead: 
"Improvement of the std lib doc concerning keys of sets/dicts".

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


Cross-Platform Readkey (one more try...)

2005-11-27 Thread Dustan
I've posted this before, but not gotten an answer:

I found this site that has code that does readkey for Windows, Unix,
and in an updated version, Mac:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
The Mac readkey class returns a character whether or not a key was
pressed.  I modified the Windows class to do the same when I downloaded
it, but I have no idea how to make the Unix class to do so. Any help???

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


Re: Tablelist-tcl-tk-tile

2005-11-27 Thread Kevin Walzer
malv wrote:
> Wanting to explore tk under python, I must say that it seems to be very
> difficult to find the required information in one single place.
> I would like to give tk a try but as I need as a test something
> equivalent of the Qt datagrid, I don't seem manage yet to get the
> latest releases of tablelist, tcl, tk and tile going.
> Did anybody manage to make the recent releases work in Python 2.4?
> I manged to do some things with tablelist v4.2 but with the 8.4
> versions of tcl/tk. However, for future work including tile, it would
> seem wise to start out from 8.5.
> In order to make tcl8.5, tk8.5 go, I suppose the 8.4 versions have to
> be removed.
> Do I have to remove and recompile python 2.4 as well? Is there any
> compact writup on how to get going without having to delve into the
> inner workings and wrapping of tcl?
> Thx.
> malv
> 
Tcl/Tk 8.5 has not yet been released--it's still in alpha testing. Last 
I heard the target release date was next spring or summer.

I'm coming to Python from the Tcl/Tk world, and the limited testing of 
Tile (v. 0.7.2) and tablelist (0.4.2) that I've done works fine (this is 
with Python 2.4.2 and Tcl/Tk 8.4.10).

-- 
Cheers,

Kevin Walzer, PhD
WordTech Software - "Tame the Terminal"
http://www.wordtech-software.com
sw at wordtech-software.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython Licence vs GPL

2005-11-27 Thread Martin P. Hellwig
Steven D'Aprano wrote:
> On Sat, 26 Nov 2005 21:39:13 +0100, Martin P. Hellwig wrote:
> 
>> The software was sold in 3 separates modules requiring a yearly renewal, 
> 
> The software is hardly sold if you have to renew that "sale" every year.
> That's more like a lease. I'd call it revenue from licencing, not revenue
> from sales.
> 
> Of course you're welcome to describe it as sales. It is an arbitrary
> choice one way or another -- the main thing is to not talk at
> cross-purposes, as we obviously have been doing.
> 
I agree

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


passing artibrary strings into a database

2005-11-27 Thread schwehr
Hi All,

I was wondering if there is a helper library out there that will nicely
encode artibrary text so that I can put in into a TEXT field in a
database and then retrieve it without getting into trouble with ',",new
lines or  other such things that would foul the sql insert call and or
be a security hazard?  This feels like a newbee type question, but I
haven't found anything with a quick search.

Thanks,
-kurt

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


Re: passing artibrary strings into a database

2005-11-27 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I was wondering if there is a helper library out there that will nicely
> encode artibrary text so that I can put in into a TEXT field in a
> database and then retrieve it without getting into trouble with ',",new
> lines or  other such things that would foul the sql insert call and or
> be a security hazard?

don't ever use string formatting to add values to an SQL statement.
the right way to pass variables to the database engine is to use para-
meters (aka bound variables):

cursor.execute(
"insert into table (col1, col2) values ?, ?",
value1, value2
)

the exact marker depends on the database; use the paramstyle attribute
to figure out what's the right parameter marker to use for your database.
see the DB-API 2 spec for more information:

http://www.python.org/peps/pep-0249.html





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


Re: passing artibrary strings into a database

2005-11-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:
> Hi All,
> 
> I was wondering if there is a helper library out there that will nicely
> encode artibrary text so that I can put in into a TEXT field in a
> database and then retrieve it without getting into trouble with ',",new
> lines or  other such things that would foul the sql insert call and or
> be a security hazard?  This feels like a newbee type question, but I
> haven't found anything with a quick search.

Use paramtetrized cursor.execute(..) That is instead of doing

c.execute("insert into foo values ('%s')" % mytext)

do

c.execute("insert into foo values (?)", mytext)

Attention, the actual style of a parameter is dependand on your 
database, e.g. oracle uses a differnet one:

c.execute("insert into foo values (:mytext)", dict(mytext=mytext))


The actual style to use is given in the docs, or can be queried with

connection.paramstyle

I recommend reading the DB-API 2.0 specs.

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


Re: Estimating memory use?

2005-11-27 Thread Tim N. van der Leeuw
Hi,

What is your 'static' data (database), and what is your input-data?
Those 200.000 probes are your database? Perhaps they can be stored as
pickled compiled regexes and thus be loaded in pickled form; then you
don't need to keep them all in memory at once -- if you fear that
memory usage will be too big.

I don't know if perhaps other string-matching techniques can be used
btw; you don't need the full power of regexes I guess to match DNA
string patterns.
Perhaps you should investigate that a bit, and do some performance
tests?

cheers,

--Tim

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


Re: passing artibrary strings into a database

2005-11-27 Thread schwehr
Thanks!  Looks like I need to get a newer version of pysqlite into the
fink package tree since pysqlite 1.0.1 does not appear support that

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


Re: wxPython Licence vs GPL

2005-11-27 Thread Paul Boddie
Fredrik Lundh wrote:
> Steven D'Aprano wrote:
> > Fine. If you want to take rights away from the people you redistribute
> > somebody else's software to, then the GPL is not for you.
>
> the people you distribute somebody else's open source software to
> still have the same rights to that software as you have.  GPL or not
> GPL doesn't change that a bit.

It's true that the original software would still be available under the
original licence and that commercial, closed source usage of that
software doesn't actually affect its availability. Moreover, many (if
not most) copyright regimes demand that you acknowledge the different
copyrights on the entire work, regardless of how permissive the
licences on the different portions of that work are. It's certainly
true that an end-user of a closed source repackaging of the original
software could discover where the software originated and be aware of
their rights to that software under less restrictive terms, but I
suppose that part of the idea behind licences like the LGPL (which is
more relevant to this particular point) and the GPL is to eliminate the
detective work needed to discover what is in the binary black box and
to make clear the end-user's rights to portions of that work "up
front": both requiring the distribution of, or the offer to distribute,
the source code.

> I find it a lot more annoying when people grab my stuff, make trivial
> additions or bugfixes to it, and GPL the result instead of contributing
> it back.

This presumably goes to the heart of the recent Zope vs. Plone
licensing discussion as well, although with less emphasis on the
trivial nature of the work. As I noted there, one could make one's
licences GPL-incompatible if such behaviour appears offensive, but that
would probably be counterproductive in several respects.

Paul

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


Fractal curve

2005-11-27 Thread Steve Heyburn

Hello there,
I am studying programming at University and we are basing the course on Python. We are currently looking at fractal curves and I was wondering if you could email me code for a dragon curve please, or a similar fractal curve.
 
Thank you
Steve

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

nesting for statements?

2005-11-27 Thread tpcolson
I'm not what you'd call a "programmer" of any sort, so perhaps this
question may seem arcane and result in a plethora of "you idiot"
threads, but here goes:

ArcGIS 9.1 has a neat interface with python (2.1-2.4), allowing me to
do all sorts of spatial operations within python, namely, repetitive
functions.


In the below code, I'm trying to iterate thru multiple values of the
variable "Discretisation error factor" using a for statement that
temporarily populates "Disc", which is used as input in "Discretisation
error factor" in the gp.TopoToRaster._sa function.


For each iteration of "Discretisation error factor", I'm trying to name
the output file "outa", "outb", "out"

Not quite sure how to implement that. There are lots of examples on
nested for loops out there, but nothing on combing that with a output
file naming sheme.

The gp.TopoToRaster_sa function by itself without all the for
statements works fine.

Appreciate any help on this, other wise I have to manually  interpolate
hundreds of LiDAR point clouds, each, 10 times for diff. values of DEF.



# TopoToRaster_sample.py
# Description: Interpolate a series of point features onto a
rectangular raster using TopoToRaster
# Requirements: None
# Author: ESRI
# Date: 12\\01\\03

# Import system modules
import sys, string, os, win32com.client

# Create the Geoprocessor object
from win32com.client import Dispatch
gp = Dispatch("esriGeoprocessing.GpDispatch.1")

# Check out any necessary licenses
gp.CheckOutExtension("spatial")

# Iterate 2 thru 4 in increments of 2 for DEF
# Name the "2" dem "outa" and the "4" dem "outb"
for x in range(2,4):
Disc = int(x)
names = ["a","b"]
for y in names:
Out_Dem = "out"+y


try:

# Process: Topo to Raster...
gp.TopoToRaster_sa("C:\\temp\\falls_lidar.shp Z PointElevation",
   Out_Dem, # Variable for name of output raster.
This should increment name of output based on the for statement
   "5", # Output raster cell size: each pixel is 5
feet by 5 feet
   "2103763.27 813746.12 2111850.32 822518.65",
#extent of raster borders, SPF, NC, NAD83
   "20", # #Grid Margin
   "", #Smallest z value to be used in
interpolation (optional)
   "", #Largest z value to be used in interpolation
(optional)
   "NO_ENFORCE", #Drainage option
   "SPOT", #Spot data option
   "40", #Maximum number of iterations (optional)
   "", #Roughness penalty (optional)
   Disc, #Discretisation error factor: This should
increment DEF based on the for statement
   "0", #Vertical standard error (optional)
   "", #Tolerance 1 (optional)
   "" #Tolerance 2 (optional)
   )
except:
print "ERROR OCCURED"
print gp.GetMessages()

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


Re: wxPython Licence vs GPL

2005-11-27 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
   ...
> Thanks for going beyond the call of duty to research the facts in such

You're welcome!  Like most amateur investors, I kid myself that research
makes my stock picks better (considering the tiny amounts one actually
invests, I doubt that any dollar difference divided by the time needed
to do research actually reaches to minimum hourly wage, so, it's more in
the nature of an excuse, I guess;-).

> detail. I'm surprised that Adobe is selling so many licences -- I don't
> know anyone who has paid for Adobe software in many years -- and you can
> take that any way you like. (Kids! Pirating software is stealing!!!) 

For reasons that escape me, I appear to observe a much lower inclination
to piracy in the Mac world -- which may help explain why Adobe makes
over 1/4 of their sales there, according to one of their tables, even
though they get strong competition from Apple itself.  E.g: surely
professional Acrobat must sell less when the OS itself ensures any app
can "print" to PDF, as MacOS X does; in the video field, of which I know
nothing first-hand, I'm told Apple's Final Cut, express and pro, vastly
outsells Adobe's comparable offerings; etc.  I guess these effects, and
the fact that Macs are less than 10% of laptops and desktops, are
overcompensated by a combination of Mac users' higher propensity to
purchase rather than pirate, and the higher prevalence of "creative
professionals" in the Mac crowd.


> "any source of income from services or goods". There is also a more
> restrictive (there's that word again...) sense of a sale being a transfer
> of ownership. In that stricter sense, nobody sells software -- they
> merely licence it.

This "legalistic" take has generally little to do with the *accounting*
interpretation of "selling" -- and since you were asking specifically
about *profits*, accounting is really the only way to answer.

But, if "transfer of ownership" is what you mean, you're STILL totally
wrong in doubting that there is a lot of profit being made today by
selling software -- transfering ownership of software.  What do you
think the IT giants of India MOSTLY make profits on?  While they're
relentlessly trying to branch out to other sources, such as consulting
and all kinds of services, and starting to show interesting results in
these expansion efforts, still today MOST of their profits come from
writing software for some customer firm and transferring ownership of
the software in question -- i.e., SELLING software by this strict legal
definition.

In terms of accounting (GAAP) this might in fact be better framed as a
service -- "writing software on your behalf" rather than "transferring
to you the ownership of this software written to your specifications";
and the operating margins, now that the market for top professionals in
Bangalore &c has heated up so much, are aligned with "resellers of
services", lower than those of "sellers of software" in the normal
accounting interpretation.

But you can't have it both ways -- if you mean "selling" in the normal
accounting sense, you're wrong as I showed in the last post; if you mean
in the legalistic sense, you're wrong as I'm showing here.  For each
dollar of profit anybody makes, you can no doubt deny it comes from
selling software in SOME sense of "selling", since the legalistic
meaning conflicts with the accounting one -- but fix any ONE meaning,
and you're still wrong.  Including the strangely mixed one here...:

> The sense of "software sales" I mean is intermediate between the two. The
> way I mean "sales", when Joe Public goes to acmesoft.com, pays $99 on his
> credit card number to download Acmesoft FooMaker, that's a sale. When he

OK, then among companies which make profits selling software are
BestBuy, CompUSA and so on -- you're welcome to drill down into their
detailed financial reports yourself, but just consider the amounts of
precious shelf space that they devote to shrink-wrapped boxes of games,
anti-virus thingies, and the like... do you think those retailers don't
have any sense of which side their bread is buttered on?-)  As a very
rough 0th-order approximation, you can take it that those chains'
*profits* come in very roughly equal parts from sales of hardware,
software, and services (mostly extended warranties on the HW they sell,
but also out of warranties repairs, etc etc) -- the sales volumes are
WAY higher for HW, lower for SW and lowest for services, but the margins
go the other way 'round, by far.

This sense of "selling software" of course has nothing to do with
licenses: some of the software these retailers "sell" is covered by
various commercial licenses, some by GPL or other open source licenses,
and some is even in the public domain.  So you could say they're in fact
selling pretty colored boxes with shrink-wrap, containing a booklet and
a CD (and the ownership of these physical components is indeed
transferred, so the legalistic meaning of "sale" is fully satis

Re: Estimating memory use?

2005-11-27 Thread Alex Martelli
Roy Smith <[EMAIL PROTECTED]> wrote:
   ...
> Is there any easy way to find out how much memory a Python object takes?

No, but there are a few early attempts out there at supplying SOME ways
(not necessarily "easy", but SOME).  For example, PySizer, at
.


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


Re: best cumulative sum

2005-11-27 Thread David Isaac
"Peter Otten" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I think that the test for an empty iterator makes ireduce() unintuitive.

OK.
I misunderstood you point.
But that is needed to match the behavior of reduce.
>>> reduce(operator.add,[],42)
42

Thanks,
Alan


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


Re: Estimating memory use?

2005-11-27 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Alex Martelli) wrote:

> Roy Smith <[EMAIL PROTECTED]> wrote:
>...
> > Is there any easy way to find out how much memory a Python object takes?
> 
> No, but there are a few early attempts out there at supplying SOME ways
> (not necessarily "easy", but SOME).  For example, PySizer, at
> .
> 
> 
> Alex
>   

Looks interesting, thanks.

I've already discovered one (very) surprising thing -- if I build a dict 
containing all my regexes (takes about 3 minutes on my PowerBook) and 
pickle them to a file, re-loading the pickle takes just about as long as 
compiling them did in the first place.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which License Should I Use?

2005-11-27 Thread Andrew Koenig
"mojosam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I will be doing the bulk of the coding on my own time, because I need
> to be able to take these tools with me when I change employers.
> However, I'm sure that in the course of using these tools, I will need
> to spend time on the job debugging or tweaking them.  I do not want my
> current employer to have any claim on my code in any way.  Usually if
> you program on company time, that makes what you do a "work for hire".
> I can't contaminate my code like that.  Does that mean the GPL is the
> strongest defense in this situation?

It probably means that the only reliable defense is to get a written release 
from your employer.  If you want to be more confident about the situation, 
consult a lawyer.



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


Re: Which license should I use?

2005-11-27 Thread Andrew Koenig
""Björn Lindström"" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Mike Meyer <[EMAIL PROTECTED]> writes:

> If they have the rights to the code, they can sell it, under the GPL or
> any license of their choosing. In addition, if you GPL it, your employer
> will be able to sell it, just like anyone else.

If they have the rights to the code, you don't get to decide on the terms 
under which it will be distributed (if at all) -- they do.


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

Re: Which License Should I Use?

2005-11-27 Thread Andrew Koenig
"mojosam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I would have to talk to a lawyer to be sure, but right now, I think I
> can argue that anything I do on my own time belongs to me.  I'm
> technically a consultant right now (even though I'm spending 40
> hours/week with the one "client").  I can take on other clients, as
> long as they don't directly compete.  This means they're hiring my
> expertise.  If I bring my own tools, that's part of my expertise.  I do
> recall there was a clause in the contract that anything I did on their
> time belonged to them.  For my next client, I should definitely include
> a clause about rereleasing open source changes.

Yup.  If you're not an employee (that is, if you get a 1099 form rather than 
a W-2 form from your client), then any work you do belongs to you *except* 
for what you agree in writing belongs to them.  So if you write code that's 
not part of any deliverable, it's yours.

Of course, they might object to your using their facilities, or working on 
their time, on stuff that isn't part of a deliverable.  But that's a 
separate problem entirely.


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


Re: best cumulative sum

2005-11-27 Thread Peter Otten
David Isaac wrote:

> "Peter Otten" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> I think that the test for an empty iterator makes ireduce() unintuitive.
> 
> OK.
> I misunderstood you point.
> But that is needed to match the behavior of reduce.
 reduce(operator.add,[],42)
> 42

Wouldn't an implementation that gives

list(ireduce(add, [], 42)) --> [42]
list(ireduce(add, [1], 42)) --> [42, 43]
list(ireduce(add, [1, 2], 42)) --> [42, 43, 45]
list(ireduce(add, [])) --> []
list(ireduce(add, [1])) --> [1]
list(ireduce(add, [1, 2])) --> [1, 3]

be sufficiently similar, too? E. g.

from itertools import chain

def ireduce(op, iterable, *init):
iterable = chain(init, iterable)
accu = iterable.next()
yield accu
for item in iterable:
accu = op(accu, item)
yield accu

Peter

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


Re: Which License Should I Use?

2005-11-27 Thread Robert Kern
Andrew Koenig wrote:
> "Robert Kern" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>You're in something of a gray area, but one that has seen a lot of
>>litigation. Although you are "technically" a consultant, you are
>>probably considered an employee with regards to the "work made for hire"
>>doctrine. You should probably have a chat with a lawyer soon (I am not
>>one! TINLA!).
> 
> I'm pretty sure that there was a change to the copyright laws a few years 
> ago (perhaps as part of the DMCA), that made it clear that you own 
> everything you produce, unless you're a W-2 employee or there is a written 
> agreement to the contrary.

The US Copyright Office does not agree with you.

  http://www.copyright.gov/circs/circ09.pdf

But you can read the text of the DMCA itself.

  http://www.eff.org/IP/DMCA/hr2281_dmca_law_19981020_pl105-304.html

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Which License Should I Use?

2005-11-27 Thread Andrew Koenig
"Robert Kern" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> You're in something of a gray area, but one that has seen a lot of
> litigation. Although you are "technically" a consultant, you are
> probably considered an employee with regards to the "work made for hire"
> doctrine. You should probably have a chat with a lawyer soon (I am not
> one! TINLA!).

I'm pretty sure that there was a change to the copyright laws a few years 
ago (perhaps as part of the DMCA), that made it clear that you own 
everything you produce, unless you're a W-2 employee or there is a written 
agreement to the contrary.



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


Re: Which License Should I Use?

2005-11-27 Thread Robert Kern
Andrew Koenig wrote:

> Yup.  If you're not an employee (that is, if you get a 1099 form rather than 
> a W-2 form from your client), then any work you do belongs to you *except* 
> for what you agree in writing belongs to them.  So if you write code that's 
> not part of any deliverable, it's yours.

Please stop saying things that are demonstrably untrue and could get
people into legal trouble if they believed you.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: Estimating memory use?

2005-11-27 Thread Fredrik Lundh
Roy Smith wrote:

> I've already discovered one (very) surprising thing -- if I build a dict
> containing all my regexes (takes about 3 minutes on my PowerBook) and
> pickle them to a file, re-loading the pickle takes just about as long as
> compiling them did in the first place.

the internal RE byte code format is version dependent, so pickle stores the
patterns instead.





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


Basic about Python class

2005-11-27 Thread Manuel11g
Hello,
I am a new programmer in Python and a need some help. Where can i get a
basic tutorial about Class. I don't know nothing about Object Oriented
Programming. Can you help me?

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


Re: Fractal curve

2005-11-27 Thread Steve Holden
Steve Heyburn wrote:
> Hello there,
> 
> I am studying programming at University and we are basing the course on 
> Python. 
> We are currently looking at fractal curves and I was wondering if you could 
> email me code for a dragon curve please, or a similar fractal curve.
> 

   http://www.google.com/search?q=dragon+curve+python


-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


How to enable bash mode at the interative mode?

2005-11-27 Thread Anthony Liu
That is, at the Python interactive mode, if I hit the
upper arrow key, it'll bring up the last line of code.

At
http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c
, it seems that Michael Spalinski suggests of
reinstalling Python.

Any easier way to achieve this feature?

Thanks.




__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nesting for statements?

2005-11-27 Thread Paul Watson
[EMAIL PROTECTED] wrote:
> I'm not what you'd call a "programmer" of any sort, so perhaps this
> question may seem arcane and result in a plethora of "you idiot"
> threads, but here goes:
> 
> ArcGIS 9.1 has a neat interface with python (2.1-2.4), allowing me to
> do all sorts of spatial operations within python, namely, repetitive
> functions.
> 
> 
> In the below code, I'm trying to iterate thru multiple values of the
> variable "Discretisation error factor" using a for statement that
> temporarily populates "Disc", which is used as input in "Discretisation
> error factor" in the gp.TopoToRaster._sa function.
> 
> 
> For each iteration of "Discretisation error factor", I'm trying to name
> the output file "outa", "outb", "out"
> 
> Not quite sure how to implement that. There are lots of examples on
> nested for loops out there, but nothing on combing that with a output
> file naming sheme.
> 
> The gp.TopoToRaster_sa function by itself without all the for
> statements works fine.
> 
> Appreciate any help on this, other wise I have to manually  interpolate
> hundreds of LiDAR point clouds, each, 10 times for diff. values of DEF.
> 
> 
> 
> # TopoToRaster_sample.py
> # Description: Interpolate a series of point features onto a
> rectangular raster using TopoToRaster
> # Requirements: None
> # Author: ESRI
> # Date: 12\\01\\03
> 
> # Import system modules
> import sys, string, os, win32com.client
> 
> # Create the Geoprocessor object
> from win32com.client import Dispatch
> gp = Dispatch("esriGeoprocessing.GpDispatch.1")
> 
> # Check out any necessary licenses
> gp.CheckOutExtension("spatial")
> 
> # Iterate 2 thru 4 in increments of 2 for DEF
> # Name the "2" dem "outa" and the "4" dem "outb"
> for x in range(2,4):
> Disc = int(x)
> names = ["a","b"]
> for y in names:
> Out_Dem = "out"+y
> 
> 
> try:
> 
> # Process: Topo to Raster...
> gp.TopoToRaster_sa("C:\\temp\\falls_lidar.shp Z PointElevation",
>Out_Dem, # Variable for name of output raster.
> This should increment name of output based on the for statement
>"5", # Output raster cell size: each pixel is 5
> feet by 5 feet
>"2103763.27 813746.12 2111850.32 822518.65",
> #extent of raster borders, SPF, NC, NAD83
>"20", # #Grid Margin
>"", #Smallest z value to be used in
> interpolation (optional)
>"", #Largest z value to be used in interpolation
> (optional)
>"NO_ENFORCE", #Drainage option
>"SPOT", #Spot data option
>"40", #Maximum number of iterations (optional)
>"", #Roughness penalty (optional)
>Disc, #Discretisation error factor: This should
> increment DEF based on the for statement
>"0", #Vertical standard error (optional)
>"", #Tolerance 1 (optional)
>"" #Tolerance 2 (optional)
>)
> except:
> print "ERROR OCCURED"
> print gp.GetMessages()

I think you want a filename generated for each pass through the loop.  I 
would suggest generating the filenames before you ever start the loop in 
a list.  Then, reference the filename list while you are in the loop. 
You could also construct the filename while you are in the loop.

sor = 2 # start of range
eor = 4 # end of range

filenames = ['file' + chr((x-sor) + ord('a')) for x in range(sor, eor)]

for x in range(sor, eor):
 print filenames[x - sor]

If you do not want to create all of the filenames in memory at one time, 
you could generated them during the loop.  However, this will not work 
well when you code is run on a system not using ASCII character encoding.

for x in range(sor, eor):
 print 'file' + chr((x - sor) + ord('a'))

Something using string.ascii_lowercase would work better.  My guess is 
that on the mainframe using EBCDIC character encoding that 
string.ascii_lowercase still contains the LATIN SMALL LETTER characters, 
just as it does on ASCII-based systems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic about Python class

2005-11-27 Thread Brett Hoerner
Manuel11g wrote:
> Hello,
> I am a new programmer in Python and a need some help. Where can i get a
> basic tutorial about Class. I don't know nothing about Object Oriented
> Programming. Can you help me?

http://diveintopython.org/object_oriented_framework/index.html

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


Re: Estimating memory use?

2005-11-27 Thread MrJean1
There is a function mx_sizeof() in the mx.Tools module from eGenix
which may be helpful.  More at




/Jean Brouwers


PS) This is an approximation for memory usage which is useful in
certain, simple cases.

Each built-in type has an attribute __basicsize__ which is the size in
bytes needed to represent the basic type.  For example
str.__basicsize__ returns 24 and int.__basictype__ returns 12.

However, __basicsize__ does not include the space needed to store the
object value.  For a string, the length of the string has to be added
(times the character width).  For example, the size of string "abcd"
would at least approximately str.__basicsize__ + len("abcd") bytes,
assuming single byte characters.

In addition, memory alignment should be taken into account by rounding
the size up to the next multiple of 8 (or maybe 16, depending on
platform, etc.).

An approximation for the amount of memory used by a string S (of single
byte characters) aligned to A bytes would be

   (str.__basicsize__  +  len(S)  +  A - 1)  &  A

Things are more complicated for types like list, tuple and dict and
instances of a class.

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


XMLSchema Parsing

2005-11-27 Thread km
Hi all,
i'd like to know if there are any good XMLSchema (.xsd files) parsing modules 
in python.
regards,
KM

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


Re: Estimating memory use?

2005-11-27 Thread MrJean1
The name of the function in mx.Tools is sizeof() and not mx_sizeof().
My apologies.

Also, it turns out that the return value of mx.Tools.sizeof() function
is non-aligned.  For example mx.Tools.sizeof("abcde") returns 29 which
is fine, but not entirely "accurate".

/Jean Brouwers

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


Re: ownership problem?

2005-11-27 Thread Gabriel Zachmann
> the problem isn't determining who owns it, the problem is determining
> who's supposed to release it.  that's not a very common problem in a

that's about what i meant.
i think, in c++, the "ownership problem" means the problem to determine who 
and when is to delete an object, or to keep track thereof.
The object could be something as simple as a list element.

Best regards,
Gabriel.

-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to enable bash mode at the interative mode?

2005-11-27 Thread Piet van Oostrum
> Anthony Liu <[EMAIL PROTECTED]> (AL) escribió:

>AL> That is, at the Python interactive mode, if I hit the
>AL> upper arrow key, it'll bring up the last line of code.

>AL> At
>AL> 
>http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c
>AL> , it seems that Michael Spalinski suggests of
>AL> reinstalling Python.

>AL> Any easier way to achieve this feature?

Just installing the readline module was sufficient in MacOSX (Apple's
python). Maybe it is the same for other implementations?
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which License Should I Use?

2005-11-27 Thread Mike Meyer
"Andrew Koenig" <[EMAIL PROTECTED]> writes:
> I'm pretty sure that there was a change to the copyright laws a few years 
> ago (perhaps as part of the DMCA), that made it clear that you own 
> everything you produce, unless you're a W-2 employee or there is a written 
> agreement to the contrary.

Definitely not. The most recent change to the copyright laws made
works of music recorded to fullfill a contract "work for hire" by
default.

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


Re: New docs for set elements/dictionary keys

2005-11-27 Thread Mike Meyer
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>> Personally, I think we'd be better off to come up with a term for this
>> property that doesn't have a commonly understood meaning that has such
>> broad areas of disagreement with the property. I've been using
>> "hashable", which I would currently define as "has a __hash__ method
>> with the properties described in the __hash__ documentation, or does
>> not have either a __cmp__ or a __eq__ method."
> I would like to use "hashable" as a term as well, but it appears that
> many people would understand that to mean "has a __hash__
> implementation" (i.e. hash(x) returns a value, instead of raising an
> exception).

Well, the two aren't quite the same thing: hash returns a value on
some things that don't have a __hash__. But that is close to the
meaning I want to give it. What meaning did you have in mind?

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


Re: New docs for set elements/dictionary keys

2005-11-27 Thread Martin v. Löwis
Mike Meyer wrote:
>>>Personally, I think we'd be better off to come up with a term for this
>>>property that doesn't have a commonly understood meaning that has such
>>>broad areas of disagreement with the property. I've been using
>>>"hashable", which I would currently define as "has a __hash__ method
>>>with the properties described in the __hash__ documentation, or does
>>>not have either a __cmp__ or a __eq__ method."
>>
>>I would like to use "hashable" as a term as well, but it appears that
>>many people would understand that to mean "has a __hash__
>>implementation" (i.e. hash(x) returns a value, instead of raising an
>>exception).
> 
> 
> Well, the two aren't quite the same thing: hash returns a value on
> some things that don't have a __hash__. But that is close to the
> meaning I want to give it. What meaning did you have in mind?

Me, personally, I had your definition in mind: hashable should indicate
"returns a value constant over time and consistent with comparison".

I suggested that most people would consider "hashable" to mean:
hash() returns a value. To those people, it is a minor detail whether 
you get the fallback implementation of hash() or whether there is a
default __hash__ implementation for all objects that don't otherwise
define __hash__.

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


RE: Python as Guido Intended

2005-11-27 Thread Delaney, Timothy (Tim)
Bryan wrote:

> i agree with you... pyrex should be part of the python distribution :)

And this has been discussed on python-dev. Greg has stated though that
he doesn't feel it's ready (there are other factors, but this one is
overriding). There were also discussions about the fact that to get
maximum performance out of pyrex, it's necessary to produce very
non-pythonic code.

FWIW, I'm strongly in favour of Pyrex eventually becoming part of the
Python distribution.

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


Re: Profiling with hotshot and wall clock time

2005-11-27 Thread Carl Friedrich Bolz
Hi!

Geert Jansen wrote:
> I'm trying to profile an application that I believe is blocking on I/O 
> for a significant amount of time. In trying to dig down where this 
> happens, I profiled the application with hotshot. The results are not 
> really usable however as it seems to display the amount of CPU time 
> which for my application is much lower than the total run time.
> 
> Is possible to use hotshot with wall clock time, i.e. is it possible to 
> have the code fragment below show one second as opposed to zero? The old 
> profiler seems to have functionality choosing a timer function but it 
> crashed on my code.

There is a nice profiling module that PyPy has used profitably recently: 
it is called lsprof and can be found at (svn repository):

http://codespeak.net/svn/user/arigo/hack/misc/lsprof/

It was written by Brett Rosen and Ted Czotter, with further changes from 
Michael Hudson and Armin Rigo.

I did not really check what timer function it uses, although it seems to 
provide more exact results than hotshot while maintaining the speed of 
same. It seems to handle your example just fine:

 >>> import lsprof
 >>> import time
 >>> def f():
...   time.sleep(1)
...
 >>> lsprof.profile(f).pprint()
CallCountRecursiveTotal(ms)   Inline(ms) module:lineno(function)
10999.0380999.0380   <>:1(f)



(profiling time.sleep directly does not work, but I guess that this is 
also not so useful).

Cheers,

Carl Friedrich Bolz

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


exception KeyboardInterrupt and os.system command

2005-11-27 Thread darren kirby
Hello all.

I have a python script here which is just a wrapper for 2 or more system 
commands. I would estimate the program spends at least 95.5% of 'real' time 
running the system commands.

I want to trap the [crtl-c] key combo and exit (somewhat) gracefully if the 
user decides to abort the program. I am using os.system for the system call, 
and I have wrapped the entire main loop in a try: except KeyboardInterrupt 
statement to try to attain these ends.

As it is though, if the program is currently in the system command, only that 
system command is terminated, and the next loop of my program starts.

Is there a way to make this work? ie: terminate the entire script? Will popen 
do this? I don't really want to use popen because all I need is for the 
system command to run, and check the exit status. Also, popen will pooch the 
output of the system commands (which I want to be printed to the console) 
because the system commands (faad, mpg123, and oggenc) have buffered output 
which won't properly be displayed if I simply print each line of the file 
object returned by popen. 

I don't want to use subprocess because I can't expect my users to have 2.4 
installed...

OS is Linux, if it matters.

If you need to see the code it is here:
http://badcomputer.org/unix/dir2ogg/dir2ogg.bot

Although, this code is the program as it stands, not the code I am testing.

Thanks,
-d
-- 
darren kirby :: Part of the problem since 1976 :: http://badcomputer.org
"...the number of UNIX installations has grown to 10, with more expected..."
- Dennis Ritchie and Ken Thompson, June 1972


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

Re: exception KeyboardInterrupt and os.system command

2005-11-27 Thread Diez B. Roggisch
darren kirby wrote:
> Hello all.
> 
> I have a python script here which is just a wrapper for 2 or more system 
> commands. I would estimate the program spends at least 95.5% of 'real' time 
> running the system commands.
> 
> I want to trap the [crtl-c] key combo and exit (somewhat) gracefully if the 
> user decides to abort the program. I am using os.system for the system call, 
> and I have wrapped the entire main loop in a try: except KeyboardInterrupt 
> statement to try to attain these ends.
> 
> As it is though, if the program is currently in the system command, only that 
> system command is terminated, and the next loop of my program starts.
> 
> Is there a way to make this work? ie: terminate the entire script? Will popen 
> do this? I don't really want to use popen because all I need is for the 
> system command to run, and check the exit status. Also, popen will pooch the 
> output of the system commands (which I want to be printed to the console) 
> because the system commands (faad, mpg123, and oggenc) have buffered output 
> which won't properly be displayed if I simply print each line of the file 
> object returned by popen. 


 From "man system":

"""
   The system() function hands the argument string to the command inter-
  preter sh(1).  The calling process waits for the shell to finish 
execut-
  ing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.
"""

So - I guess its popen2 or nothing :)

Regards,

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


Re: exception KeyboardInterrupt and os.system command

2005-11-27 Thread jepler
You can tell by the exit code from system() whether the subprocess
exited due to a signal.  Consider this code:
import os
while 1:
print os.system("sleep 1")
unless you happen to hit ctrl-c at the right time, you'll see it print
"2" (and "0" when the sleep finishes).  The exit code can be interpreted
according to the waitpid manpage, though I am not sure where the Python
equivalent of the WIFSIGNALED and WTERMSIG macros are.

Jeff


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

Re: How to enable bash mode at the interative mode?

2005-11-27 Thread Carl Friedrich Bolz
Anthony Liu wrote:
> That is, at the Python interactive mode, if I hit the
> upper arrow key, it'll bring up the last line of code.
> 
> At
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c
> , it seems that Michael Spalinski suggests of
> reinstalling Python.
> 
> Any easier way to achieve this feature?
> 
> Thanks.

You are probably missing the readline module. What operating 
system/python version are you using?

Cheers,

Carl Friedrich Bolz

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


importing a method

2005-11-27 Thread Flavio
hi,

I have an object defined with a number of hardcoded methods.

Class soandso:
def __init__(self):
self.this = 0
self.that = 1
def meth1(self):
...
def meth2(self):
...
def custom(self):
pass

I want to allow the user to write a python module that declares a
function so that myprogram can import it and attribute it to the custom
method of the soandso object. So far so good, that is an easy thing to
do in Python.

import usermodule
a=soandso()
a.custom = usermodule.function

But, what if the method had to access the self attributes (self.this
and self.that) of the soandso object?

Can it be done? and if so, what is the most Pythonic way of doing it?

thanks in advance,

Flávio

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


Re: Writing pins to the RS232

2005-11-27 Thread [EMAIL PROTECTED]
First of all I'd like to thank all of you for your input.  It's nice to
have a place to throw ideas around and get some feedback.

I think the reason the serial source code I'm using is using javax.comm
stuff which is possibly part of Jython is because I'm on Mac OS X.
However this is just my guess as all of this is translucent to me and
difficult for me to decipher.

While I realize this is more on a driver/hardware level it's
interesting that it's so difficult to use a different protocol for an
existing driver.  For example, all serial does is a series of high and
low voltages on specific pins.  Why should it be so hard to use an
existing driver and hold a pin on high?  I guess the answer is, because
the driver is operating system specific, and because all of the drivers
and code that use that driver use the hardware in a very specific way.
If you ever wanted to use it for a different purpose you'd have to
start all the way at the bottom again.  While I can just use a serial
protocol to tell a chip to do what I'm looking for it seems like an
extra piece of hardware I don't need.

Looking into pyparallel, it seems this is much closer to my needs.  Now
I just need to purchase a usb to parallel adapter and do some further
experimenting.  Looking up some diagrams of how the parallel ports work
and some useful documentation I don't think I'll be running into any
more problems.

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


Re: Syntax

2005-11-27 Thread Peter Hansen
Terry Hancock wrote:
>>[EMAIL PROTECTED] wrote:
>>>One of these two ways you're not supposed to use for
>>>security reasons, but I'm spacing on which one.
> 
> It's not a question of "security" in the usual sense, but
> the first syntax imports a lot of stuff into the current
> namespace, increasing the risk of unintentionally clobbering
> local names. So it's certainly "riskier" in the sense of
> "likely to cause bugs".

There's also the case where the names which are imported are not static. 
  That is, they are bound to certain objects at the time of the "import 
*" but later on they can change.  While this is perhaps a sign of design 
problems in the imported module, the problem that results is that when 
those names are rebound, modules which imported them with "*" still have 
the old objects, not the new ones.  Using "import module" and 
referencing things with "module.name" doesn't suffer from the same 
potential for problems (in addition to it being more readable etc).

-Peter

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


Re: Comparison problem

2005-11-27 Thread Peter Hansen
Fredrik Lundh wrote:
> Peter Hansen wrote:
>>Actually, it's not so much baroque as it is safe... item[0] will fail if
>>the string is empty, while item[0:1] will return '' in that case.
>>
>>Of course, as you point out, .startswith() is the better approach anyway.
> 
> $ timeit -s "s = 'abc'" "s[:1] == 'a'"
> 100 loops, best of 3: 0.852 usec per loop
> 
> $ timeit -s "s = 'abc'; w ='a'" "s[:len(w)] == w"
> 100 loops, best of 3: 1.27 usec per loop
> 
> $ timeit -s "s = 'abc'; c=s.startswith" "c('a')"
> 100 loops, best of 3: 1.75 usec per loop
> 
> $ timeit -s "s = 'abc'" "s.startswith('a')"
> 10 loops, best of 3: 2.28 usec per loop

"Unless you have a need to optimize, in which case use timeit to find 
which approach works better.  If speed is not your primary concern, then 
.startswith() is probably the better approach since it is more readable 
to most people."

Thanks for the help with expanding on my original statement /F.  ;-)

-Peter

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


SCU3 and Python packaged for U3 (with SCU3) V 0.1 released

2005-11-27 Thread Philippe C. Martin
Dear all,

I am very happy to announce the release of SCU3 V 0.1 and SCU3Python.u3p V.
0.1.

SCU3 is a python wrapper for U3 compliante devices
SCU3Python.u3p is a Python binary (2.4.2) packaged with SCU3 that allows to
launch idle from the U3 device launchpad

Both may be found on www.snakecard.com, download section.

Best regards,

Philippe


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


Re: Writing pins to the RS232

2005-11-27 Thread Roy Smith
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> While I realize this is more on a driver/hardware level it's
> interesting that it's so difficult to use a different protocol for an
> existing driver.  For example, all serial does is a series of high and
> low voltages on specific pins.  Why should it be so hard to use an
> existing driver and hold a pin on high?

It's been a long time since I've looked at this low-level hardware, but the 
answer is almost certainly, "No just 'so hard', but 'impossible'".

A serial port is driven by a thing called a UART (Universal Asynchronous 
Receiver/Transmitter).  Back when I was playing with these things, a UART 
was a discrete chip; these days I'm sure it's just a minor part of a more 
complex I/O processor, but I suspect the basic idea is the same.  You load 
a character to be transmitted into a register on the UART and the hardware 
takes care of all the low-level gunk like clocking the bits out at the 
correct rate, adding start and stop bits, and computing parity.  And the 
reverse for the receive side of the house (which is usually the more 
complicated part).  There just isn't any way to tell the hardware to do 
anything other than it was designed to do.

Could you design a piece of hardware which could function as both a serial 
port and what you want?  Sure you could, but it would cost more, and PC 
design today is a matter of shaving 10 cents here and 30 cents there.

It's like looking at a microwave oven and saying, "Can't this thing be 
reprogrammed to be a communications relay?"  Well, sure, it's got some of 
the same parts, but the parts were put together in a way that makes food 
get hot, not in a way that makes data bits get transmitted to someplace.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception KeyboardInterrupt and os.system command

2005-11-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:
> You can tell by the exit code from system() whether the subprocess
> exited due to a signal.  Consider this code:
> import os
> while 1:
> print os.system("sleep 1")
> unless you happen to hit ctrl-c at the right time, you'll see it print
> "2" (and "0" when the sleep finishes).  The exit code can be interpreted
> according to the waitpid manpage, though I am not sure where the Python
> equivalent of the WIFSIGNALED and WTERMSIG macros are.

Boy, one never stops learning

But I have some trouble understanding that - when I write a test-script 
that returns 1 as exit-code, os.system returns 256. Inn fact, returnung 
n means that 256*n is returned from os.system.

But 256 is _also_ returned when C-c is used. Any idea why that's the case?

Regards,

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


Re: Estimating memory use?

2005-11-27 Thread François Pinard
[Fredrik Lundh]

> the internal RE byte code format is version dependent, so pickle 
> stores the patterns instead.

Oh!  Nice to know.  That explains why, when I was learning Python, my 
initial experiment with pickles left me with the (probably wrong) 
feeling that they were not worth the trouble.

It might be worth a note in the documentation, somewhere appropriate.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing pins to the RS232

2005-11-27 Thread [EMAIL PROTECTED]
ahhh I understand now

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


Re: How to enable bash mode at the interative mode?

2005-11-27 Thread Anthony Liu
Hi, thanks.

Look what I have:

$ python
Python 2.4.2 (#1, Nov 20 2005, 13:03:38) 
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2

Yes, I realize that I don't have readline module
available.

The same Mandrake system has Python 2.3 as well, and
it has the readline module.

I don't know how to install the readline module.  I
tried what was suggested from the newsgroup, but got
an error at make:

make: *** [Modules/readline.o] Error 1

Thanks

--- Carl Friedrich Bolz <[EMAIL PROTECTED]> wrote:

> Anthony Liu wrote:
> > That is, at the Python interactive mode, if I hit
> the
> > upper arrow key, it'll bring up the last line of
> code.
> > 
> > At
> >
>
http://groups.google.com/group/comp.lang.python/browse_thread/thread/fb8c2fd9eed0d/736fac8c33e84d0c?lnk=st&q=python+%22upper+arrow%22&rnum=2&hl=en#736fac8c33e84d0c
> > , it seems that Michael Spalinski suggests of
> > reinstalling Python.
> > 
> > Any easier way to achieve this feature?
> > 
> > Thanks.
> 
> You are probably missing the readline module. What
> operating 
> system/python version are you using?
> 
> Cheers,
> 
> Carl Friedrich Bolz
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




__ 
Yahoo! Music Unlimited 
Access over 1 million songs. Try it free. 
http://music.yahoo.com/unlimited/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing a method

2005-11-27 Thread Ben Finney
Flavio <[EMAIL PROTECTED]> wrote:
> Class soandso:
> def __init__(self):
> self.this = 0
> self.that = 1
> def meth1(self):
> ...
> def meth2(self):
> ...
> def custom(self):
> pass
> 
> I want to allow the user to write a python module that declares a
> function so that myprogram can import it and attribute it to the custom
> method of the soandso object. So far so good, that is an easy thing to
> do in Python.
> 
> import usermodule
> a=soandso()
> a.custom = usermodule.function

Apparently you haven't tested whether this works. It doesn't:

>>> class Foo(object):
...   pass
...
>>> def bar(*args):
...   print "bar() got arguments:", args
...
>>> bar("spam", "eggs")
bar() got arguments: ('spam', 'eggs')
>>> Foo.bar_method = bar
>>> Foo.bar_method("spam", "eggs")
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as first 
argument (got str instance instead)
  
> But, what if the method had to access the self attributes (self.this
> and self.that) of the soandso object?

To become a method, the function must be bound to an instance, and the
method will then receive the instance as the first argument when
called as a method.

To do this on an already-defined function, use new.instancemethod.

>>> import new
>>> help(new.instancemethod)

-- 
 \  "One time a cop pulled me over for running a stop sign. He |
  `\said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'"  -- Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing a method

2005-11-27 Thread Chris Curvey
why not just have your user subclass "soandso" and override the
definition of "custom"?

from soandso import soandso
class MyClass(soandso):
   def custom(self):
   self.theother = 3

c = MyClass()

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


Re: best cumulative sum

2005-11-27 Thread [EMAIL PROTECTED]

Peter Otten wrote:
> David Isaac wrote:
>
> > "Peter Otten" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> >> I think that the test for an empty iterator makes ireduce() unintuitive.
> >
> > OK.
> > I misunderstood you point.
> > But that is needed to match the behavior of reduce.
>  reduce(operator.add,[],42)
> > 42
>
> Wouldn't an implementation that gives
>
> list(ireduce(add, [], 42)) --> [42]
> list(ireduce(add, [1], 42)) --> [42, 43]
> list(ireduce(add, [1, 2], 42)) --> [42, 43, 45]
> list(ireduce(add, [])) --> []
> list(ireduce(add, [1])) --> [1]
> list(ireduce(add, [1, 2])) --> [1, 3]
>
> be sufficiently similar, too? E. g.
>
> from itertools import chain
>
> def ireduce(op, iterable, *init):
> iterable = chain(init, iterable)
> accu = iterable.next()
> yield accu
> for item in iterable:
> accu = op(accu, item)
> yield accu
>
I believe there is only one initializer in reduce. Also it is possible
to not provide it.

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


General question about Python design goals

2005-11-27 Thread Christoph Zwerschke
Sometimes I find myself stumbling over Python issues which have to do 
with what I perceive as a lack of orthogonality.

For instance, I just wanted to use the index() method on a tuple which 
does not work. It only works on lists and strings, for no obvious 
reason. Why not on all sequence types?

Or, another example, the index() method has start and end parameters for 
lists and strings. The count() method also has start and end parameters 
for strings. But it has no such parameters for lists. Why?

However when I ask such things I noticed I get answers like: "Is there a 
use case?" "You can do it some other way so it is not worth bothering."

Let me ask back: Do I really need to bother and justify it with a use 
case in a case where the language can be easily made more consistent or 
orthogonal without breaking anything?

What about design goals such as:

- orthogonality
- coherence, consistency
- principle of least astonishment ("Python fits my brain")
- simplicity ("kiss" principle)
- aesthetics, symmetry

Actually, which priority have the above design goals for Python? Are 
other design goals considered more important?

If I compare them with the "Zen of Python", I find some of the above:

consistency -> Special cases aren't special enough to break the rules
simplicity -> Simple is better than complex
aesthetics -> Beautiful is better than ugly

Actually, concerning the last two, you already need to understand the 
Zen of Python to decide if something is "simple" or even "beautiful", so 
they are not really suitable to *define* the Zen of Python. For me, a 
programming language is beautiful if it is orthogonal and coherent. But 
for others, this may be different. Somehow, I'm missing a direct 
allusion to the following in the Zen of Python:

- orthogonality
- principle of least astonishment

Maybe I am I lacking the satori of a real Python Zen master?

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


Re: General question about Python design goals

2005-11-27 Thread Robert Kern
Christoph Zwerschke wrote:
> Sometimes I find myself stumbling over Python issues which have to do 
> with what I perceive as a lack of orthogonality.
> 
> For instance, I just wanted to use the index() method on a tuple which 
> does not work. It only works on lists and strings, for no obvious 
> reason. Why not on all sequence types?
> 
> Or, another example, the index() method has start and end parameters for 
> lists and strings. The count() method also has start and end parameters 
> for strings. But it has no such parameters for lists. Why?
> 
> However when I ask such things I noticed I get answers like: "Is there a 
> use case?" "You can do it some other way so it is not worth bothering."
> 
> Let me ask back: Do I really need to bother and justify it with a use 
> case in a case where the language can be easily made more consistent or 
> orthogonal without breaking anything?

Yes. If it's not going to be used, then there's not much point.
Practicality beats purity, and all that.

However, I will note that if you were to present us with a working patch
with documentation and unittests, then you'll probably get responses
along the lines of "Thank you!", instead.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: General question about Python design goals

2005-11-27 Thread Paul Rubin
Robert Kern <[EMAIL PROTECTED]> writes:
> Yes. If it's not going to be used, then there's not much point.
> Practicality beats purity, and all that.

Geez man, "practicality beats purity" only means that if maintaining
purity of something is impractical, you can judiciously let purity
slide.  It doesn't mean every slapdash kludge you can throw together
is acceptable for a widely-used distro, just because it works for the
cases you happened to think of at the moment you wrote it.

Wanting to handle the .count() parameters the same way for lists and
strings does not present any practical obstacles.  So purity is not in
conflict with practicality there.  The lack of orthogonality for that
operation is simply a wart.
-- 
http://mail.python.org/mailman/listinfo/python-list


PYTHONDOCS on OSX

2005-11-27 Thread Robert Hicks
How do I set this variable in my .bash_profile? I have the html docs in
/usr/local/PythonDocs.

Thanks for any help...

Robert

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


Re: New docs for set elements/dictionary keys

2005-11-27 Thread Mike Meyer
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:
> Me, personally, I had your definition in mind: hashable should indicate
> "returns a value constant over time and consistent with comparison".
>
> I suggested that most people would consider "hashable" to mean:
> hash() returns a value. To those people, it is a minor detail whether
> you get the fallback implementation of hash() or whether there is a
> default __hash__ implementation for all objects that don't otherwise
> define __hash__.

True. I think we ought to leave the behavioral requirements up to the
__hash__ docs, as it's already there. We can use hashable that way,
and maybe define it by implication:

Any object for which hash() returns an appropriate value(1) can be
used as a dictionary key/set element. Lists, sets and dicts are not
hashable, and can not be used. Tuples can be used if all the things
they contain are hashable. instances of all other builin types can be
used. Instances of most classes written in Python can be used(2).

1) See the __hash__ documentation for details on what an approriate
value is.

2) Instances that have a __hash__ method that returns an appropriate
value can be used. Instances that don't have a __cmp__ or an __eq__
method can be used even if they don't have a __hash__ method.

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


Re: General question about Python design goals

2005-11-27 Thread Robert Kern
Paul Rubin wrote:
> Robert Kern <[EMAIL PROTECTED]> writes:
> 
>>Yes. If it's not going to be used, then there's not much point.
>>Practicality beats purity, and all that.
> 
> Geez man, "practicality beats purity" only means that if maintaining
> purity of something is impractical, you can judiciously let purity
> slide.  It doesn't mean every slapdash kludge you can throw together
> is acceptable for a widely-used distro, just because it works for the
> cases you happened to think of at the moment you wrote it.

Fine. Allow me to rephrase. Development is primarily motivated by
practical needs and guided by notions of purity. Use cases are the
primary tool for communicating those practical needs. If you can't think
of a single use case, what's the point of implementing something? Or
rather, why should someone else implement it if you don't know how you
would use it?

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: General question about Python design goals

2005-11-27 Thread Aahz
In article <[EMAIL PROTECTED]>,
Christoph Zwerschke  <[EMAIL PROTECTED]> wrote:
>
>For instance, I just wanted to use the index() method on a tuple which 
>does not work. It only works on lists and strings, for no obvious 
>reason. Why not on all sequence types?

Because Guido believes that tuples should be primarily used as
lightweight replacements for C structs.  Therefore they have minimal
functionality.

>Or, another example, the index() method has start and end parameters for 
>lists and strings. The count() method also has start and end parameters 
>for strings. But it has no such parameters for lists. Why?

That's a fair cop.  Submit a patch and it'll probably get accepted.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: General question about Python design goals

2005-11-27 Thread Christoph Zwerschke
>>Let me ask back: Do I really need to bother and justify it with a use 
>>case in a case where the language can be easily made more consistent or 
>>orthogonal without breaking anything?

Robert Kern wrote:

> Yes. If it's not going to be used, then there's not much point.
> Practicality beats purity, and all that.

I have nothing against "practicality beats purity". But to stay with the 
examples I have given, in how far is writing list(t).index(x) more 
practical than t.index(x)?

And by the way, if we are speaking about practicality here, are we 
speaking about practicality for the Python developers or for the Python 
users? This may be sometimes be in opposition.

Let me give an extreme example: Assume the count() method for strings 
would have been called "numberofsubstringsinthestring()" and I argue it 
should be called "count()" because that is shorter and how it is called 
for lists. What should I give as a "use case" here? Must I give "use 
cases" if the issue is about convenience/simplicity/elegance?

> However, I will note that if you were to present us with a working patch
> with documentation and unittests, then you'll probably get responses
> along the lines of "Thank you!", instead.

Not everybody has the time and skills to provide that. Ordinary people 
from the Python user base should be given the opportunity to make 
suggestions for improvement - of course not in the tone of "I 
demand...", but they should not be automatically regarded as "demanding" 
if they just utter their opinion or make a suggestion either.

Even if I had the time and skills, before starting to work on a patch, 
unittests etc. I still would first discuss with others whether my 
suggestion is reasonable and would be appreciated by the "user base", 
developers and the BDFL. Just take the example of the following patch:
https://sourceforge.net/tracker/?func=detail&atid=305470&aid=403693&group_id=5470

It was not rejected by reason of missing unittests or documentation, but 
the very idea was rejected.

Actually, I'm not keen on being a protagonist for this issue or starting 
a hard-bitten discussion about this and defend the idea if everybody is 
against or nobody cares. It does not bother me that much either.

But it just led me to the general question: Which significance actually 
have design features such as orthogonality for Python?

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


Re: General question about Python design goals

2005-11-27 Thread Robert Kern
Christoph Zwerschke wrote:
>>>Let me ask back: Do I really need to bother and justify it with a use 
>>>case in a case where the language can be easily made more consistent or 
>>>orthogonal without breaking anything?
> 
> Robert Kern wrote:
> 
>>Yes. If it's not going to be used, then there's not much point.
>>Practicality beats purity, and all that.
> 
> I have nothing against "practicality beats purity". But to stay with the 
> examples I have given, in how far is writing list(t).index(x) more 
> practical than t.index(x)?

I'm not arguing that the things you mentioned shouldn't be changed. I'm
saying that use cases really are important in making design decisions.
You just provided one. Congratulations.

> And by the way, if we are speaking about practicality here, are we 
> speaking about practicality for the Python developers or for the Python 
> users? This may be sometimes be in opposition.

As Paul noted, it was a misuse of the phrase. I withdraw it.

>>However, I will note that if you were to present us with a working patch
>>with documentation and unittests, then you'll probably get responses
>>along the lines of "Thank you!", instead.
> 
> Not everybody has the time and skills to provide that. Ordinary people 
> from the Python user base should be given the opportunity to make 
> suggestions for improvement - of course not in the tone of "I 
> demand...", but they should not be automatically regarded as "demanding" 
> if they just utter their opinion or make a suggestion either.
> 
> Even if I had the time and skills, before starting to work on a patch, 
> unittests etc. I still would first discuss with others whether my 
> suggestion is reasonable and would be appreciated by the "user base", 
> developers and the BDFL. Just take the example of the following patch:
> https://sourceforge.net/tracker/?func=detail&atid=305470&aid=403693&group_id=5470
> 
> It was not rejected by reason of missing unittests or documentation, but 
> the very idea was rejected.

And it also appears to have nothing to do with the lack of proffered use
cases but (primarily) Guido's thoughts about how the different objects
are supposed to be used. That's why use cases are so important. They
allow developers to talk about real, concrete issues.

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: General question about Python design goals

2005-11-27 Thread Christoph Zwerschke
>>For instance, I just wanted to use the index() method on a tuple which 
>>does not work. ...

Aahz wrote:

> Because Guido believes that tuples should be primarily used as
> lightweight replacements for C structs.  Therefore they have minimal
> functionality.

But the problem is that the tutorials and manuals give the impression 
that the difference between lists and tuples is only mutablity versus 
immutability. They don't talk about such considerations and honestly 
speaking even now I know that it does seem more plausible for me.

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


How to make tkFileDialog GUI larger?

2005-11-27 Thread John Wheez
Hi all,

I'm using teh  tkFileDialog to let teh user select a directory. We have 
long names which make
it difficult to view the directories.

For some reason the GUI windows doesn;t expand on Windows like it does 
on OS X or Linux.
Is there a method to make the widths of the  tkFileDialog windows larger 
when using Windows XP?

Thanks for any info.

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


Re: General question about Python design goals

2005-11-27 Thread Peter Hansen
Christoph Zwerschke wrote:
> But it just led me to the general question: Which significance actually 
> have design features such as orthogonality for Python?

Probably very little.  Python has not so much been designed as evolved. 
  Plus it's a fairly mature language (over 14 years old), and I think in 
such a case that elements of design tend to be obscured by the many 
changes layered on top.  (For example, I hardly recognize the C++ that I 
learned in the language that struggles on today.)

While the goal of orthogonality may factor into some people's reasons 
for implementing certain changes, it's not (apparently) a primary 
motivation for many of the ones doing work on the Python core.  If more 
people with such motivations had been working on the core, it's likely 
Python would have more of these sorts of "gaps" filled in.

(The corollary, of course, is that there would be other gaps, and they 
would be more practical ones, so other people would probably be 
suggesting things like "wouldn't it be good if Python had a Unicode type 
instead of all these little-used functions that make the language nice 
and orthogonal but aren't really necessary". ;-) )

-Peter

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


Re: General question about Python design goals

2005-11-27 Thread [EMAIL PROTECTED]

Christoph Zwerschke wrote:
> >>For instance, I just wanted to use the index() method on a tuple which
> >>does not work. ...
>
> Aahz wrote:
>
> > Because Guido believes that tuples should be primarily used as
> > lightweight replacements for C structs.  Therefore they have minimal
> > functionality.
>
> But the problem is that the tutorials and manuals give the impression
> that the difference between lists and tuples is only mutablity versus
> immutability. They don't talk about such considerations and honestly
> speaking even now I know that it does seem more plausible for me.
That is the problem of the tutorial or manual, don't read them as if
they are ISO specs.

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


Re: New docs for set elements/dictionary keys

2005-11-27 Thread Christoph Zwerschke
Mike Meyer wrote:

> Any object for which hash() returns an appropriate value(1) can be
> used as a dictionary key/set element. Lists, sets and dicts are not
> hashable, and can not be used. Tuples can be used if all the things
> they contain are hashable. instances of all other builin types can be
> used. Instances of most classes written in Python can be used(2).
> 
> 1) See the __hash__ documentation for details on what an approriate
> value is.
> 
> 2) Instances that have a __hash__ method that returns an appropriate
> value can be used. Instances that don't have a __cmp__ or an __eq__
> method can be used even if they don't have a __hash__ method.

I think that is not so bad. How about this simplification:

Any hashable object(1) can be used as a dictionary key/set element. 
Lists, sets and dicts are not hashable, and can not be used. Tuples can 
be used if all the things they contain are hashable. Instances of all 
other built-in types and most user-defined classes are hashable.

(1) Objects for which the hash() function returns an appropriate 
(proper?) value. See the __hash__ documentation for details.

-- Christoph


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


Re: reading internet data to generate random numbers.

2005-11-27 Thread Levi Campbell
thank you, that was what I needed.

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


Re: General question about Python design goals

2005-11-27 Thread Paul Rubin
Robert Kern <[EMAIL PROTECTED]> writes:
> Fine. Allow me to rephrase. Development is primarily motivated by
> practical needs and guided by notions of purity. 

That's bogus; if there was a discrepancy someone noticed and had to
work around, there's already been a practical failure, just not a
severe one.  Development should be guided by doing things right when
possible, making allowances for practical considerations that
sometimes call for compromise.  It's generally far better to do
something right the first time than to do something broken and have to
fix it later.  Those XP platitudes about prototyping and refactoring
are for when the program is still under development and the
requirements have not yet been discovered, and unfixed bogosity
affects just a few people (developers and testers).  When a program
has been declared finished and shipped to millions of users, any
bogosity remaining in it has a much larger effect, so bogosity should
be minimized.

> Use cases are the primary tool for communicating those practical
> needs. If you can't think of a single use case, what's the point of
> implementing something? Or rather, why should someone else implement
> it if you don't know how you would use it?

I can't think of a single use case for the addition (+) operator
working where either of the operands happens to be the number
0x15f1ef02d9f0c2297e37d44236d8e8ddde4a34c96a8200561de00492cb94b82 (a
random number I just got out of /dev/urandom).  I've never heard of
any application using that number, and the chances of it happening by
coincidence are impossibly low.  But if Python were coded in a way
that made the interpreter crash on seeing that number, I'd call that
a bug needing fixing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: General question about Python design goals

2005-11-27 Thread Jean-Paul Calderone
On 27 Nov 2005 19:49:26 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> 
wrote:
>Robert Kern <[EMAIL PROTECTED]> writes:
>> Use cases are the primary tool for communicating those practical
>> needs. If you can't think of a single use case, what's the point of
>> implementing something? Or rather, why should someone else implement
>> it if you don't know how you would use it?
>
>I can't think of a single use case for the addition (+) operator
>working where either of the operands happens to be the number
>0x15f1ef02d9f0c2297e37d44236d8e8ddde4a34c96a8200561de00492cb94b82 (a
>random number I just got out of /dev/urandom).  I've never heard of
>any application using that number, and the chances of it happening by
>coincidence are impossibly low.  But if Python were coded in a way
>that made the interpreter crash on seeing that number, I'd call that
>a bug needing fixing.

If you seriously believe what you just wrote, you have failed to
understand the phrase "use case" (and possibly a lot of other
things related to programming ;)

However (fortunately for you) I suspect you don't.  If you really
did, you may want to pick up one of those platitude-filled XP books
and give it a careful read.  You may find there's more there than
you were previously aware.

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


should python have a sort list-map object in the std-lib?

2005-11-27 Thread Tim Henderson
Hi

The question why are there no sorted dictionaries in python, seems to
pop up with unseeming regularity. That question in itself in
nonsensical sense dictionaries are hash-maps, however should python
have a sorted map type object is a good question.

clearly many people like have a sorted map, and sorting the keys every
time seems rather wasteful, as does keeping a separate sorted list of
the keys.

a related question is, in python is it more efficient to a maintain a
list type in sorted order by inserting each new object in the correct
location (by say finding it with a binary search and then using del
list[x]) or appending each new item to the end of said list and using
the built-in .sort method, or sorted() function?
--
Tim Henderson
mail me: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: General question about Python design goals

2005-11-27 Thread Aahz
In article <[EMAIL PROTECTED]>,
Christoph Zwerschke  <[EMAIL PROTECTED]> wrote:
>Aahz wrote:
>> Christoph deleted his own attribution:
>>>
>>>For instance, I just wanted to use the index() method on a tuple which 
>>>does not work. ...
>>
>> Because Guido believes that tuples should be primarily used as
>> lightweight replacements for C structs.  Therefore they have minimal
>> functionality.
>
>But the problem is that the tutorials and manuals give the impression 
>that the difference between lists and tuples is only mutablity versus 
>immutability. They don't talk about such considerations and honestly 
>speaking even now I know that it does seem more plausible for me.

Then feel free to submit patches for the docs.

PS: If you want further responses from me, please follow standard Usenet
quoting conventions (like those above).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison problem

2005-11-27 Thread Tim Henderson
of course the more correct way is most likely the use of short circuit
evaluation. so somthing along lines of

if (len(item) > 0) and (item[0] == '-'): pass

would probably be the correct approach.

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


  1   2   >