Re: Python Problem

2007-09-12 Thread A.T.Hofkamp
On 2007-09-11, Wiseman <[EMAIL PROTECTED]> wrote:
>
>  Hi,
>
> OK - it works in WindowsXP.
> I installed "enchant" on my SuSE 10.0 (using YAST). 
> The enchant Suse package looks like a general Linux package, not a
> Python specific.

You'd seem to be right judging by this web-page:
http://www.novell.com/products/linuxpackages/suselinux/enchant.html

As you can see, there is no file installed at a path with "python" in it.

> What am I missing?

Python bindings to the library perhaps?
You may be more lucky with an enchant-dev package (if it exists). I am however
not a Suse user and not an echant user (well, not from my Python code at least).


Albert

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


Re: Get the complete command line as-is

2007-09-12 Thread Laurent Pointal
wangzq a écrit :
> Hello,
> 
> I'm passing command line parameters to my browser, I need to pass the
> complete command line as-is, for example:
> 
> test.py "abc def" xyz
> 
> If I use ' '.join(sys.argv[1:]), then the double quotes around "abc
> def" is gone, but I need to pass the complete command line ("abc def"
> xyz) to the browser, how can I do this?
> 
> I'm on Windows.

As Windows command-line parsing seem to remove some chars, maybe you can 
try to use the GetCommandLine() function from Win32 API (I dont know if 
it is available in pywin32 package - you may need to write a wrapper 
with ctypes).

See http://msdn2.microsoft.com/en-us/library/ms683156.aspx


A+

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


An ordered dictionary for the Python library?

2007-09-12 Thread Mark Summerfield
I feel that Python lacks one useful data structure: an ordered
dictionary.

I find such data structures v. useful in C++. I know that in Python
the sort function is v. fast, but often I prefer never to sort but
simply to use an ordered data structure in the first place.
(I'm aware that for ordered lists I can use the bisect module, but I
want an ordered key-value data structure.)

I think other people must find such things useful. There are three
implementations on the Python Cookbook site, and one on PyPI, all in
pure Python (plus I have my own implementation, also pure Python).

I would suppose that it would be better if it was implemented in C---
for example, my own pure Python ordered dict loads data about eight
times slower than the built-in dict. Nonetheless, I still find it
worth using for the convenience it offers.

Do other Python programmers feel this lack? Is this worth a PEP?

[I originally asked about this on the P3K mailing list, but then
realised that it isn't version-specific really.]

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


Re: Python Problem

2007-09-12 Thread Marc 'BlackJack' Rintsch
On Wed, 12 Sep 2007 09:09:02 +0200, A.T.Hofkamp wrote:

> On 2007-09-11, Wiseman <[EMAIL PROTECTED]> wrote:
>>
>>  Hi,
>>
>> OK - it works in WindowsXP.
>> I installed "enchant" on my SuSE 10.0 (using YAST). 
>> The enchant Suse package looks like a general Linux package, not a
>> Python specific.
> 
> You'd seem to be right judging by this web-page:
> http://www.novell.com/products/linuxpackages/suselinux/enchant.html
> 
> As you can see, there is no file installed at a path with "python" in it.
> 
>> What am I missing?
> 
> Python bindings to the library perhaps?
> You may be more lucky with an enchant-dev package (if it exists). I am however
> not a Suse user and not an echant user (well, not from my Python code at 
> least).

PyEnchant seems to be an independent project:

  http://pyenchant.sourceforge.net/

So there is either an extra package for SuSE or the OP has to build it
himself.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating HTML

2007-09-12 Thread Evan Klitzke
On Wed, 2007-09-12 at 01:33 -0300, Sebastian Bassi wrote:
> Hello,
> 
> What are people using these days to generate HTML? I still use
> HTMLgen, but I want to know if there are new options. I don't
> want/need a web-framework a la Zope, just want to produce valid HTML
> from Python.

It's not applicable for everything, but if you're planning on using
Python to generate web pages you should really be using Cheetah
templates. Very simple to use template system that is also very
powerful, and you don't need to use it in conjunction with a heavy web
application framework. See http://www.cheetahtemplate.org/

-- 
Evan Klitzke <[EMAIL PROTECTED]>

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


Re: Python 3K or Python 2.9?

2007-09-12 Thread Bruno Desthuilliers
TheFlyingDutchman a écrit :
> Python user and advocate Bruce Eckel is disappointed with the
> additions (or lack of additions) in Python 3:
> 
> http://www.artima.com/weblogs/viewpost.jsp?thread=214112
> 

I'd say Mr Eckel fails to graps some of the great points about Python's 
object model - the rant about the use of 'self' is a sure clue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Michele Simionato
On Sep 12, 9:33 am, Mark Summerfield <[EMAIL PROTECTED]>
wrote:
> I feel that Python lacks one useful data structure: an ordered
> dictionary.
>
> I find such data structures v. useful in C++. I know that in Python
> the sort function is v. fast, but often I prefer never to sort but
> simply to use an ordered data structure in the first place.
> (I'm aware that for ordered lists I can use the bisect module, but I
> want an ordered key-value data structure.)
>
> I think other people must find such things useful. There are three
> implementations on the Python Cookbook site, and one on PyPI, all in
> pure Python (plus I have my own implementation, also pure Python).
>
> I would suppose that it would be better if it was implemented in C---
> for example, my own pure Python ordered dict loads data about eight
> times slower than the built-in dict. Nonetheless, I still find it
> worth using for the convenience it offers.
>
> Do other Python programmers feel this lack? Is this worth a PEP?
>

Yes, this is a serious lack in the standard library.

 Michele Simionato

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


Re: __getattr__ and static vs. instantiated

2007-09-12 Thread Bruno Desthuilliers
tvaughan a écrit :
> Hi,
> 
> Let's say I have:
> 
> class Persistable(object):
> 
> __attrs__ = {}
> 
> def __getattr__(self, name):
> if name in self.__attrs__:
> return self.__attrs__[name]['value']
> else:
> return Object.__getattr__(self, name)
> 
> def __setattr__(self, name, value):
> if name in self.__attrs__:
> self.__attrs__[name]['value'] = value
> else:
> Object.__setattr__(self, name, value)
> 
> And the I have:
> 
> class Person(Persistable):
> 
> __storm_table__ = 'person'
> 
> id = Int(primary=True)
> 
> __attrs__ = {
> 'name': {
> 'lang': 'en',
> 'value': Unicode(),
> },
> }
> 
> def __init__(self):
> self.id = int(random.random() * 1000)
> 
> I can do this:
> 
> person = Person()
> person.name = 'Jane Smith'
> 
> But I cannot do:
> 
> Person.name = 'Jane Smith'

yes, you can. But it won't do the same thing.

> or use Person.name in a Storm query like:
> 
> Person.name == 'Jane Smith'

It will obviously raise an AttributeError if the class Person doesn't 
have a 'name' attribute.

> __getattr__ is only called when using an instantiated class,

A class's '__getattr__' method is only triggered when looking up 
attributes on an instance of the class, yes.

> and
> never, it seems, in a static case. Why? How do I work around this?

Since classes are instances of their type, the obvious solution would be 
to define a custom metaclass implementing __getattr__. I didn't try, but 
it might work.

Now is this the best thing to do is another question. You seems not to 
be aware of the descriptor protocol - which is used to implement methods 
and properties. This lets you define 'smart' attributes. You'll find 
relevant documentation here:
http://docs.python.org/ref/descriptors.html
and here:
http://users.rcn.com/python/download/Descriptor.htm


Also, you seem to be trying to roll your own ORM. There are already 
quite a few existing ones - SQLAlchemy being probably the best one 
already, and also a good base (no pun) for building your own solutions.

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread stef
Mark Summerfield wrote:
> I feel that Python lacks one useful data structure: an ordered
> dictionary.
>
> I find such data structures v. useful in C++. I know that in Python
> the sort function is v. fast, but often I prefer never to sort but
> simply to use an ordered data structure in the first place.
> (I'm aware that for ordered lists I can use the bisect module, but I
> want an ordered key-value data structure.)
>
> I think other people must find such things useful. There are three
> implementations on the Python Cookbook site, and one on PyPI, all in
> pure Python (plus I have my own implementation, also pure Python).
>
> I would suppose that it would be better if it was implemented in C---
> for example, my own pure Python ordered dict loads data about eight
> times slower than the built-in dict. Nonetheless, I still find it
> worth using for the convenience it offers.
>
> Do other Python programmers feel this lack? Is this worth a PEP?
>
>   
Yes I think it's really useful,
(or at least I'm used to it in other languages ;-)
If you're going to extend the dictionary,
there's one other flag I'm continuously missing:
"case-insensitive" key.

cheers,
Stef Mientki

> [I originally asked about this on the P3K mailing list, but then
> realised that it isn't version-specific really.]
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating HTML

2007-09-12 Thread Bruno Desthuilliers
Evan Klitzke a écrit :
> On Wed, 2007-09-12 at 01:33 -0300, Sebastian Bassi wrote:
>> Hello,
>>
>> What are people using these days to generate HTML? I still use
>> HTMLgen, but I want to know if there are new options. I don't
>> want/need a web-framework a la Zope, just want to produce valid HTML
>> from Python.
> 
> It's not applicable for everything, but if you're planning on using
> Python to generate web pages you should really be using Cheetah
> templates. Very simple to use template system that is also very
> powerful, and you don't need to use it in conjunction with a heavy web
> application framework. See http://www.cheetahtemplate.org/
> 

Same for Mako (http://www.makotemplates.org), which has IMHO a much 
nicer syntax (Cheetah looks too much like line noise IMHO).
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I work on VIM for python code such as cscope for C code?

2007-09-12 Thread Evan
Hi, guys ~~

How can i work on VIM for python code?  I use cscope plugin on VIM for
C code before, it helps me to  different function and search C
variable where it is defined.

I'm now starting to learn python, and I'd like to know how works on
VIM.

I saw that the VIM is support python such as syntax highlighting,
autocmd,etc. but I really want to know if it can work with TAG.

Do I need to downlaod other software/plugin?

Thanks,

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


Re: Help With PyParsing of output from win32pdhutil.ShowAllProcesses()

2007-09-12 Thread Paul McGuire
On Sep 11, 1:12 pm, Steve <[EMAIL PROTECTED]> wrote:
> Hi All (especially Paul McGuire!)
>
> Could you lend a hand in the grammar and paring of the output from the
> function win32pdhutil.ShowAllProcesses()?
>
> This is the code that I have so far (it is very clumsy at the
> moment) :
>

>
> Many thanks!
>
> Steve

Steve -

Well, your first issue is not a pyparsing one, but one of redirecting
stdout.  win32pdhutil.ShowAllProcesses does not *return* the output
you listed, it just prints it to stdout.  The value returned is None,
which is why you are having trouble parsing it (even after converting
None to a string).

For you to parse out this data, you will need to redirect stdout to a
string buffer, run ShowAllProcesses, and then put stdout back the way
it was.  Python's cStringIO module is perfect for this:


from cStringIO import StringIO
import sys
import win32pdhutil

save_stdout = sys.stdout
process_info = StringIO()
sys.stdout = process_info

win32pdhutil.ShowAllProcesses()
sys.stdout = save_stdout
sProcess_Info = process_info.getvalue()


*Now* you have all that data captured into a processable string.

As others have mentioned, this data is pretty predictably formatted,
so pyparsing may be more than you need.  How about plain old split?


for line in sProcess_Info.splitlines()[1:]:
data = line.split()
print data


Done!

Still have an urge to parse with pyparsing?  Here are some comments on
your grammar:

- Your definition of process_name was not sufficient on my system.  I
had some processes running whose names includes numeric digits and
other non-alphas.  I needed to modify process_name to:

process_name = pyparsing.Word(pyparsing.alphanums+"_.-")

- Similarly, some of my values returned by ShowAllProcesses had
negative values, so your definition of integer needs to comprehend an
optional leading '-' sign.  (This actually sounds like a bug in
win32pdhutil - I don't think any of these listed quantities should
report a negative value.)

- Whenever I have integers in a grammar, I usually convert them to
ints at parse time, using a parse action:

integer.setParseAction( lambda tokens : int(tokens[0]) )

- The tabular format of this data, and the fact that the initial entry
in each row appears to be a label of some sort invites the use of the
pyparsing Dict class.  I note that you are already trying to extract
keys from the parsed data, so it looks like you are already thinking
along these lines.  (Unfortunately, it is very likely you will get
duplicate keys, since process names do not have to be unique - this
will involve some loss of data in this example.)  The Dict class auto-
generates results names in the parsed results.  Dict turns out to be
awkward to use directly, so I added the dictOf method to simplify
things.  The concept of dictOf(keyExpr,valueExpr) is "parse a list of
dict entries, each of which is a key-value pair; while parsing, label
each entry with the parsed key."  In your example, this would be:

ProcessList = heading + pyparsing.dictOf(process_name,
pyparsing.OneOrMore(integer) )

The key is a leading process_name, and the value is the following list
of integers.  With this, you can print out the results using:


data = ProcessList.parseString(sProcess_Info)

print "data keys:", data.keys()
for k in sorted(data.keys()):
print k, ":", data[k]


Getting:

BCMWLTRY : [684, 0, 0, 0, 54353920, 53010432]
CLI : [248, 0, 0, 0, 171941888, 153014272]
D4 : [2904, 0, 0, 0, 37527552, 36413440]
F-StopW : [2064, 0, 0, 0, 33669120, 30121984]
...
(again, note that the multiple entries for "CLI" have been reduced to
a single dict entry)

You could get similar results using something like:

data = dict((vals[0],vals[1:]) for vals in
map(str.split,sProcess_Info.splitlines()))

But then you would never have learned about dictOf!

Enjoy!
-- Paul

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


Re: Excel process still running after program completion - SOLVED

2007-09-12 Thread Tal Einat
On Sep 11, 8:29 pm, Chris <[EMAIL PROTECTED]> wrote:
> On Sep 11, 1:26 pm, Chris <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 11, 12:59 pm, "Hamilton, William " <[EMAIL PROTECTED]> wrote:
>
> > > > From: Chris
>
> > > > I have a python script that is driving Excel and using the win32com
> > > > module. However, upon program completion there's still an Excel.exe
> > > > process running in the background that I must terminate through Task
> > > > Manager. Reading up on other threads indicate that maybe I still have
> > > > some Excel objects referenced within my code. Is this why the process
> > > > doesn't terminate?
>
> > > > The related (I hope) parts of my code is here.
>
> > > > x1App = Dispatch("Excel.Application")
> > > > Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls")
> > > > x1App.Visible = 1
> > > > for sheets in Book1.Worksheets:
> > > >  if sheets.Name == file_name:
> > > >   sheetExists = True
> > > > if sheetExists != True:
> > > >  activeSheet =
> > > > Book1.Worksheets.Add(After=Book1.Worksheets(1))
> > > >  activeSheet.Name = file_name
> > > >  testNum[file_name] = 0
> > > > Book1.Worksheets(file_name).Select()
> > > > Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original
> > > > File Name"
> > > > Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value =
> > > > file_name
> > > > Book1.ActiveSheet.Pictures().Insert(output).Select()
> > > > Book1.SaveAs(Filename=path)
> > > > x1App.ActiveWorkbook.Close(SaveChanges=0)
> > > > x1App.Quit()
> > > > del x1App
> > > > del Book1
> > > > del activeSheet
>
> > > > What am I missing?
>
> > > In my Excel projects, I terminate it with:
>
> > > xlBook.Close()
> > > xlApp.Quit()
>
> > > I haven't had a problem with Excel staying open after the program ends.
>
> > > (On a tangent, I want to find the person who thought it was a good idea
> > > to use the same symbol in a font for 1, l, and I and do some unpleasant
> > > things.)
>
> > > --
> > > -Bill Hamilton
>
> > That doesn't really fix the problem as I'm pretty sure its identical
> > code for
> > x1App.ActiveWorkbook.Close(SaveChanges=0)
>
> > I think where my problem lies is within my for each loop where I
> > search to see if the worksheet with the name already exists
> > for sheets in Book1.Worksheets:
> >  if sheets.Name == file_name:
> >sheetExists = True
>
> > Since I'm assuming that it creates objects for each of the sheets and
> > I don't delete them...
>
> Which I'm right... I added this code and now there's no EXCEL.EXE
> process after my script completes
>
> for sheets in Book1.Worksheets:
>   if sheets.Name == file_name:
> sheetExists = True
>   sheets = None
>   del sheets

You just need to 'del sheets' once after the loop, no need to do it in
every iteration. After your original loop the 'sheets' variable still
pointed to the last sheet object, probably causing it not to be
properly cleaned up. This is the only thing that your change fixes,
but it is simpler (and more readable) to just do it once after the
loop.

(Please add SOLVED or FIXED to the subject when your issue has been
resolved, so that people like me don't read the whole thread only to
find that their help is no longer needed.)

- Tal

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


Re: Difference between two times (working ugly code, needs polish)

2007-09-12 Thread Iain King
On Sep 12, 1:31 am, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> > I suppose really oneDay should be a global (i.e. outside the function
> > definition). Apart from that it would be hard to improve on: obvious,
> > easy to read, in short - pythonic.
>
> > Are you concerned about daylight savings? That could certainly introduce
> > a whole new level of complexity into the problem. Let's hope not ...
>
> I'm not concerned with DST; this is a script which checks my Ebay
> auctions (I have some things for sale), and sends me e-mail whenever
> someone bids. It's run by cron every half hour -- it keeps me from
> compulsively checking my auctions. ^_^
>
> In any case, DST isn't an issue because the same machine generates
> both timestamps, and all I use it for is to stop displaying auctions
> after they are 10 days old, so I don't get all my old crap filling up
> the alert e-mail or skewing the total dollar amount for all active
> auctions.
>
> Thanks.
> Shawn

Just to be picky - your function returns the number of days between
two dates, but it's called isOld, which looks like it should return a
boolean.  i.e.  it looks like it would be used as:

if not isOld(auctionDate, currentTime):
checkForBid()

rather than how I assume it is used:

if isOld(auctionDate, currentTime) <= 10:
checkForBid()

I'd call it daysDiff or something similar, or make it more specific so
that it works like the first block of code above:

ONEDAY = 60*60*24
OLDNESS_THRESHOLD = 10

def isOld(lastUpdate, runTimeStamp):
lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:
%M"))
runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_
%H:%M"))
return (runTimeStamp - lastUpdate) / ONEDAY  >=  OLDNESS_THRESHOLD

if not isOld(auctionDate, currentTime):
checkForBid()

Iain

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


setattr vs readonly property

2007-09-12 Thread james_027
hi,

My main purpose for using setattr(object, attr, value) for assign
values from a dict that has some keys that may not be present on some
object's attibute, which makes it work for me. My problem is dealing
with read only attribute like sample_attribute =
property(f_get=_get_sample_attribute). what approach should I use? Or
is my first approach In the first place right?

Thanks
james

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


Re: need scsh in a wikip article

2007-09-12 Thread [EMAIL PROTECTED]
> someone please add scsh there.

Why can't YOU add scsh or I am missing something??

Andrey

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


Re: setattr vs readonly property

2007-09-12 Thread Diez B. Roggisch
james_027 wrote:

> hi,
> 
> My main purpose for using setattr(object, attr, value) for assign
> values from a dict that has some keys that may not be present on some
> object's attibute, which makes it work for me. My problem is dealing
> with read only attribute like sample_attribute =
> property(f_get=_get_sample_attribute). what approach should I use? Or
> is my first approach In the first place right?

Since read-only properties are very concise written as this:


class Foo(object):
   @property
   def ro_prop(self):
   return "whatever"

I'd say that's the way to go - using __getattr__ for this will lead to
rather convoluted code IHMO.

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


Re: Get Only the Last Items in a Traceback

2007-09-12 Thread Peter Otten
Am Wed, 12 Sep 2007 02:09:28 + schrieb [EMAIL PROTECTED]:

> I'm running code via the "exec in context" statement within a much
> larger program.  What I would like to do is capture any possible
> errors and show a pretty traceback just like the Python interactive
> interpreter does, but only show the part of the traceback relating to
> the code sent to exec.
> 
> For example here is the code I'm using:
> 
> try:
> exec code
> except Exception,Err:
> traceback.print_exc()
> 
> Which gives me something like this when it catches an exception:
> 
> Traceback (most recent call last):
>   File "/py", line 843, in run
> semi_safe_exec.safe_eval(code.replace('\r',''),context,5)
>   File ".py", line 400, in safe_eval
> exec_timed(code, context, timeout_secs)
>   File ".py", line 353, in exec_timed
> exec code in context
>   File "", line 7, in ?
>   File "", line 5, in func2
>   File "", line 2, in func1
> ZeroDivisionError: integer division or modulo by zero
> 
> What I want to print instead is just something like:
> 
> Traceback (most recent call last):
>   File "", line 7, in ?
>   File "", line 5, in func2
>   File "", line 2, in func1
> ZeroDivisionError: integer division or modulo by zero
> 
> Thanks in advance for the help.
> 
> -Greg
> 
> P.S. if it matters, for this example, code in exec code is:
> 
> def func1():
> print 7/0
> 
> def func2():
> func1()
> 
> func2()

Your assessment is wrong. You only get the extra lines in the traceback if
you don't immediately wrap the exec statement in a try ... except block:

$ cat snip_traceback1.py
import traceback

def alpha():
try:
beta()
except Exception, e:
traceback.print_exc()

def beta():
gamma()

def gamma():
exec s in {}

s = """ 
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

$ python snip_traceback1.py 
Traceback (most recent call last):
  File "snip_traceback1.py", line 5, in alpha
beta()
  File "snip_traceback1.py", line 10, in beta
gamma()
  File "snip_traceback1.py", line 13, in gamma
exec s in {}
  File "", line 7, in 
  File "", line 3, in delta
  File "", line 6, in epsilon
ZeroDivisionError: integer division or modulo by zero

So the first step is to move the try ... except closer to the exec:

$ cat snip_traceback2.py
import traceback

def alpha():
beta()

def beta():
gamma()

def gamma():
try:
exec s in {}
except Exception, e:
traceback.print_exc()

s = """ 
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

$ python snip_traceback2.py 
Traceback (most recent call last):
  File "snip_traceback2.py", line 11, in gamma
exec s in {}
  File "", line 7, in 
  File "", line 3, in delta
  File "", line 6, in epsilon
ZeroDivisionError: integer division or modulo by zero

You are almost there. Now let's strip off the outermost traceback:

$ cat snip_traceback3.py
import sys
import traceback

def alpha():
beta()

def beta():
gamma()

def gamma():
try:
exec s in {}
except Exception, e:
etype, value, tb = sys.exc_info()
traceback.print_exception(etype, value, tb.tb_next)

s = """ 
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

$ python snip_traceback3.py 
Traceback (most recent call last):
  File "", line 7, in 
  File "", line 3, in delta
  File "", line 6, in epsilon
ZeroDivisionError: integer division or modulo by zero

Heureka.

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


MemoryError on reading mbox file

2007-09-12 Thread Christoph Krammer
Hello everybody,

I have to convert a huge mbox file (~1.5G) to MySQL.

I tried with the following simple code:

for m in mailbox.mbox(fileName):

  msg  = m.as_string(True)
  hash = md5.new(msg).hexdigest()

  try:
dbcurs.execute("""INSERT INTO archive (hash, msg) VALUES (%s,
%s)""", (hash, msg))
  except MySQLdb.OperationalError, err:
print "%s  Error (%d): %s" % (file, err[0], err[1])
  else:
print "%s: Message successfully added to database" % (hash,
spamSource)

The problem seems to be the size of file, every time I try to execute
the script, after about 2 messages, the following error occurs:

Traceback (most recent call last):
  File "email_to_mysql_mbox.py", line 21, in 
for m in mailbox.mbox(fileName):
  File "/usr/lib/python2.5/mailbox.py", line 98, in itervalues
value = self[key]
  File "/usr/lib/python2.5/mailbox.py", line 70, in __getitem__
return self.get_message(key)
  File "/usr/lib/python2.5/mailbox.py", line 633, in get_message
string = self._file.read(stop - self._file.tell())
MemoryError

My system has 512M RAM and 768M swap, which seems to run out at an
early stage of this. Is there a way to clean up memory for messages
already processed?

Thanks and regards,
 Christoph

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


Re: need scsh in a wikip article

2007-09-12 Thread Timofei Shatrov
On Wed, 12 Sep 2007 02:10:09 -0700, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
tried to confuse everyone with this message:

>> someone please add scsh there.
>
>Why can't YOU add scsh or I am missing something??
>

Maybe he is banned?

-- 
|Don't believe this - you're not worthless  ,gr-.ru
|It's us against millions and we can't take them all... |  ue il   |
|But we can take them on!   | @ma  |
|   (A Wilhelm Scream - The Rip)|__|
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating HTML

2007-09-12 Thread Diez B. Roggisch
Sebastian Bassi wrote:

> Hello,
> 
> What are people using these days to generate HTML? I still use
> HTMLgen, but I want to know if there are new options. I don't
> want/need a web-framework a la Zope, just want to produce valid HTML
> from Python.

KID, Genshi, Mako. And a bazillion others. I prefer the first two ones
because the force you to use valid XML and produce HTML/XHMTL out of that.

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


Re: function to do dynamic import?

2007-09-12 Thread Peter Otten
Am Wed, 12 Sep 2007 11:54:51 +1000 schrieb bambam:

> def gim():
> exec "global gamel"
> exec "import gamel"
> 
> Unfortunately, does not have the desired effect.
> Steve.

Both statements have to be part of a single exec:

def gim():
modulename = "gamel" # determined at runtime
exec "global %s; import %s" % (modulename, modulename)

It may work, but it is still a bad idea to create global variables with a
name not known until runtime.

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


Re: Get Only the Last Items in a Traceback

2007-09-12 Thread Michael Ströder
[EMAIL PROTECTED] wrote:
> I'm running code via the "exec in context" statement within a much
> larger program.  What I would like to do is capture any possible
> errors and show a pretty traceback just like the Python interactive
> interpreter does, but only show the part of the traceback relating to
> the code sent to exec.
> 
> For example here is the code I'm using:
> 
> try:
> exec code
> except Exception,Err:
> traceback.print_exc()

Guess what's argument limit is for. Excerpt from the Python docs:

 snip 
print_exc(  [limit[, file]])
This is a shorthand for print_exception(sys.exc_type, sys.exc_value,
sys.exc_traceback, limit, file). (In fact, it uses sys.exc_info() to
retrieve the same information in a thread-safe way instead of using the
deprecated variables.)
 snip 

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setattr vs readonly property

2007-09-12 Thread David
> My main purpose for using setattr(object, attr, value) for assign
> values from a dict that has some keys that may not be present on some
> object's attibute, which makes it work for me. My problem is dealing
> with read only attribute like sample_attribute =
> property(f_get=_get_sample_attribute). what approach should I use? Or
> is my first approach In the first place right?

You could try catching the exception thrown when you attempt to assign
to a read-only attribute. Although you may get consistency issues. ie
your object doesn't have all the details from the dict, but the
calling code expects them to be set. Perhaps you should provide
"setter" methods for the properties also, so that your objects
internal state gets set correctly.

eg: in your class declaration:

def setfoo(self, value):
   # Add code here to check 'value' and set internal 'foo' state correctly
   self._foo = value

def getfoo(self):
   return self._foo

foo = property(setfoo, getfoo)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MemoryError on reading mbox file

2007-09-12 Thread David
>
> My system has 512M RAM and 768M swap, which seems to run out at an
> early stage of this. Is there a way to clean up memory for messages
> already processed?

It may be that Python's garbage collection isn't keeping up with your app.

You could try periodically forcing it to run. eg:

import gc
gc.collect()

You can also finetune the GC settings and check what is using up your memory.

More info here: http://docs.python.org/lib/module-gc.html
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Charles Fox
I've just started playing around with Python, as a possible
replacement for a mix of C++, Matlab and Lisp.  The language looks
lovely and clean with one huge exception:  I do a lot of numerical
modeling, so I deal with objects (like neurons) described
mathematically in papers, by equations like
a_dot = -k(a-u)
In other languages, this translates nicely into code, but as far as I
can tell, Python needs the ugly:
self.a_dot = -self.k(self.a-self.u)
For large equations this is going to make my code seriously unreadable
to the point of needing to switch back to Matlab -- and it seems to go
against everything else about python's simplicity and elegance.  Am I
missing something?  Is there something like a 'with' command that lets
me set the scope, like

with self:
  .a_dot = -.k(.a-.u)

It's premature to make language suggestions as I am new to the
language, but I would have though that making a 'with self' explicit
in all methods would have been neat, so I could just write
  .a_dot = -.k(.a-.u)
which would still avoid confusion with local function variables, since
'.a' is different from 'a'.

Please help if I am missing something -- this looks like a great
language but I am going to mad trying to read numerical code full of
'self.'s breaking up the equations.

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread thebjorn
On Sep 12, 9:33 am, Mark Summerfield <[EMAIL PROTECTED]>
wrote:
> I feel that Python lacks one useful data structure: an ordered
> dictionary.
>
> I find such data structures v. useful in C++. I know that in Python
> the sort function is v. fast, but often I prefer never to sort but
> simply to use an ordered data structure in the first place.
> (I'm aware that for ordered lists I can use the bisect module, but I
> want an ordered key-value data structure.)
[...]
> Do other Python programmers feel this lack? Is this worth a PEP?

I usually make a distinction between a sorted dict, where iteration
(and potentially positional indexing) happens in sorted key order; and
an ordered dict where items maintain insertion order. I use the latter
all the time, and e.g. Django's model metaclass does some minor magic
to overcome the fact that field-order is lost by the time your
metaclass gets control, since the attributes are passed as a regular
dict.

-- bjorn

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread David
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

You could try this in your functions:

s = self

Then you can use code like this: s.a_dot = s.k(s.a-s.u)

Another option, if you use the vars a lot in a given function, is to
copy them to local vars. This can also slightly speed up your code
(fewer member lookups).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Michele Simionato
On Sep 12, 12:21 pm, Charles Fox <[EMAIL PROTECTED]> wrote:
> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)
> For large equations this is going to make my code seriously unreadable
> to the point of needing to switch back to Matlab -- and it seems to go
> against everything else about python's simplicity and elegance.  Am I
> missing something?  Is there something like a 'with' command that lets
> me set the scope, like
>
> with self:
>   .a_dot = -.k(.a-.u)
>
> It's premature to make language suggestions as I am new to the
> language, but I would have though that making a 'with self' explicit
> in all methods would have been neat, so I could just write
>   .a_dot = -.k(.a-.u)
> which would still avoid confusion with local function variables, since
> '.a' is different from 'a'.
>
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

You can always use aliases

a = self.a
u = self.u
...

or even s = self

or play games with dictionaries.


 Michele Simionato

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


Re: Python 3K or Python 2.9?

2007-09-12 Thread Ivan Voras

Bruno Desthuilliers wrote:

TheFlyingDutchman a écrit :

Python user and advocate Bruce Eckel is disappointed with the
additions (or lack of additions) in Python 3:

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


I'd say Mr Eckel fails to graps some of the great points about Python's 
object model - the rant about the use of 'self' is a sure clue.


What does "self" have to do with an object model? It's an 
function/method argument that might as well be hidden in the compiler 
without ever touching the role it has (if not, why?). I agree that it's 
needless noise in a language.




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

Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread David
On 9/12/07, David <[EMAIL PROTECTED]> wrote:
> > Please help if I am missing something -- this looks like a great
> > language but I am going to mad trying to read numerical code full of
> > 'self.'s breaking up the equations.
>
> You could try this in your functions:
>
> s = self
>
> Then you can use code like this: s.a_dot = s.k(s.a-s.u)
>
> Another option, if you use the vars a lot in a given function, is to
> copy them to local vars. This can also slightly speed up your code
> (fewer member lookups).
>

Also, there is no rule saying you need to use "self", it's just a
convention. You can declare your methods like this instead:

def foo(s, arg1, arg2):
  s.a_dot = s.k(s.a-s.u)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Diez B. Roggisch
> 
> with self:
>   .a_dot = -.k(.a-.u)
> 
> It's premature to make language suggestions as I am new to the
> language, but I would have though that making a 'with self' explicit
> in all methods would have been neat, so I could just write
>   .a_dot = -.k(.a-.u)
> which would still avoid confusion with local function variables, since
> '.a' is different from 'a'.
> 
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

This is a FAQ - and the short answer is: no, you don't miss anything, and
it's not going change. If you want, you can shorten the expressions like
this:

s = self
s.a * s.b

Or choose any other valid name, e.g. the underscore.

Another (yet rather ugly) alternative would be to push the names into the
global namespace. But that could of course create major mayhem! So take
this with a huge grain of salt:

globals().update(self.__dict__)

a * b

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Bruno Desthuilliers
Charles Fox a écrit :
> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)

"ugliness" is a very subjective notion. As far as I'm concerned, I hate 
the "m_myMember" C++ convention, and have always used the 'this' (or 
whatever it's named) pointer/reference/pseudo-reference/whatever in 
languages where it's implicit - because I don't like such an important 
thing to be implicit.

  self.a_dot = - self.k(self.a - self.u)

> For large equations this is going to make my code seriously unreadable

Ok, but this is another problem.

> to the point of needing to switch back to Matlab -- and it seems to go
> against everything else about python's simplicity and elegance.  Am I
> missing something? 

Yes.

> Is there something like a 'with' command that lets
> me set the scope, like
> 
> with self:
>   .a_dot = -.k(.a-.u)

Nope. There's a 'with' statement, but it has nothing to do with this.

The obvious solution to your problem is to make local references to the 
needed attributes at the start of your method, ie:

def some_calc(self, whatever):
   k = self.k # yes, it works for methods too
   a = self.a
   u = self.u

   self.a_dot = -k(a-u)

> It's premature to make language suggestions as I am new to the
> language, but I would have though that making a 'with self' explicit
> in all methods would have been neat, so I could just write
>   .a_dot = -.k(.a-.u)
> which would still avoid confusion with local function variables, since
> '.a' is different from 'a'.
> 
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

The mandatory 'self' (FWIW, you can name it as you want, 'self' is just 
a convention) has long been the topic of lot of debates. While I do 
understand your motivations, there are actually good reasons for this 
design choice, but understanding these reasons requires some knowledge 
of Python's object model internals. As far as I'm concerned, I'm quite 
happy with the current design, but I don't do much maths !-)

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


Re: Difference between two times (working ugly code, needs polish)

2007-09-12 Thread Shawn Milochik
> Just to be picky - your function returns the number of days between
> two dates, but it's called isOld, which looks like it should return a
> boolean.  i.e.  it looks like it would be used as:
>
> if not isOld(auctionDate, currentTime):
> checkForBid()
>
> rather than how I assume it is used:
>
> if isOld(auctionDate, currentTime) <= 10:
> checkForBid()
>
> I'd call it daysDiff or something similar, or make it more specific so
> that it works like the first block of code above:

You're absolutely right; I started writing it with one purpose in mind
and changed it midstream. I actually renamed it yesterday to dayDiff.
;o)

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


Re: Generating HTML

2007-09-12 Thread jkn
I used to use Cheetah, but have switched recently to Jinja:

http://jinja.pocoo.org/

Mainly this is because the syntax is similar to Django's templates,
and eventually I plan on migrating to Django.

jon N

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


RE: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Ryan Ginstrom
> On Behalf Of Charles Fox
> described mathematically in papers, by equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as 
> far as I can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)

In addition to the other advice you've received, if you don't need to
preserve state, you could avoid the "self" business by putting your
functions in a module instead of an object.

def k(a):
return a**3

def dot(a, u)
return -k(a-u)

Python modules are also objects, so they can serve in place of class
instances much of the time.

Regards,
Ryan Ginstrom

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


Re: unexpected behavior: did i create a pointer?

2007-09-12 Thread Bruno Desthuilliers
neoedmund a écrit :
> On Sep 7, 4:07 pm, gu <[EMAIL PROTECTED]> wrote:
(snip pb and code)
>> now, in the second "for" cycle and in functionA() i only 'touch' copyOfA
>> (altering it). as i don't touch the variable "a", i expect it not to be
>> affected by any change, but copyOfA acts like a pointer to a and
>> altering copyOfA's values result in altering the values of "a", so the
>> result that i expect is:
(snip)
> no language act like want you tought, or the assignment operation will
> be too expensive.

IIRC, php4 was doing copies for arrays...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3K or Python 2.9?

2007-09-12 Thread Bjoern Schliessmann
Ivan Voras wrote:

> What does "self" have to do with an object model? It's an
> function/method argument that might as well be hidden in the
> compiler without ever touching the role it has (if not, why?). I
> agree that it's needless noise in a language.

If this was needless, why do C++ and Java have the "this" pointer?

Regards,


Björn

-- 
BOFH excuse #390:

Increased sunspot activity.

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


Re: Compiler Python

2007-09-12 Thread Bjoern Schliessmann
Bruno Desthuilliers wrote:
> Bjoern Schliessmann a écrit :

>> I'm not really about the syntax of your question,
 ^(sure)
> 
> lol !-)

;) It wasn't mean ironically, I really forgot the "sure".

Regards,


Björn

-- 
BOFH excuse #322:

Your Pentium has a heating problem - try cooling it with ice cold
water.(Do not turn of your computer, you do not want to cool down
the Pentium Chip while he isn't working, do you?)

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


Sea-or-land test

2007-09-12 Thread kpalamartchouk
Could you advise if there exists a simple package, containing function
that would take geographic coordinates and return information on
whether this point belongs to land or sea? No great accuracy is needed
-- I am interested in just major features, like those seen on coarse
world maps.

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


Re: How can I work on VIM for python code such as cscope for C code?

2007-09-12 Thread Joe Riopel
On 9/12/07, Evan <[EMAIL PROTECTED]> wrote:
> Hi, guys ~~
>
> How can i work on VIM for python code?  I use cscope plugin on VIM for
> C code before, it helps me to  different function and search C
> variable where it is defined.

Change to the top level directory that contains your python source
files, and do
find -name '*.py' > cscope.files
cscope -b

Then it should work.

> Do I need to downlaod other software/plugin?

You might, if do you not have the cscope_maps.vim plugin. If not you
can get it http://cscope.sourceforge.net/cscope_vim_tutorial.html and
just put it in your vim plugins directory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get Only the Last Items in a Traceback

2007-09-12 Thread Peter Otten
Am Wed, 12 Sep 2007 11:21:48 +0200 schrieb Michael Ströder:

> [EMAIL PROTECTED] wrote:
>> I'm running code via the "exec in context" statement within a much
>> larger program.  What I would like to do is capture any possible
>> errors and show a pretty traceback just like the Python interactive
>> interpreter does, but only show the part of the traceback relating to
>> the code sent to exec.
>> 
>> For example here is the code I'm using:
>> 
>> try:
>> exec code
>> except Exception,Err:
>> traceback.print_exc()
> 
> Guess what's argument limit is for. Excerpt from the Python docs:

Unfortunately traceback.print_exc(limit=N) trims the wrong end of the
traceback:

>>> def alpha(): beta()
... 
>>> def beta(): gamma()
... 
>>> def gamma(): 1/0
... 
>>> try:
... alpha()
... except:
... traceback.print_exc()
... 
Traceback (most recent call last):
  File "", line 2, in 
  File "", line 1, in alpha
  File "", line 1, in beta
  File "", line 1, in gamma
ZeroDivisionError: integer division or modulo by zero
>>> try:
... alpha()
... except:
... traceback.print_exc(limit=1)
... 
Traceback (most recent call last):
  File "", line 2, in 
ZeroDivisionError: integer division or modulo by zero
>>>

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

Re: cpython list __str__ method for floats

2007-09-12 Thread Bjoern Schliessmann
[david] wrote:

> Leaving aside the question of why str should return repr,

str doesn't "return" repr. str returns a "nice string
representation" of an object. This "nice string representation" of
a list is the opening square bracket, the repr of its contents
seperated by comma, and the closing square bracket.
Here, it *only* makes sense to have a list printed
with the repr of their contents.

> 13.301 is not 'the float in full precision':
> it is an arbitrary translation of the float.

Do you know IEEE 754?
 
> The idea that 13.3 is a 'rounded' value for the number,
> and that 13.301 is not a 'rounded' value of
> the number, is a common error of intuitive mathematics.

I'm intrigued how /you/'d explain this, please do explain.

> I hope that when you say that this is a FAQ, you don't
> mean that the community has solidified on this naive
> interpretation :~)

No, I mean that your complaint is not at all new. Reading the
archives you could have learned a lot about this topic.

Regards,


Björn

-- 
BOFH excuse #247:

Due to Federal Budget problems we have been forced to cut back on
the number of users able to access the system at one time. (namely
none allowed)

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


SIP examples

2007-09-12 Thread Srijit Kumar Bhadra
I am trying to learn SIP (http://www.riverbankcomputing.co.uk/sip/)
these days. I do not see any examples similar to SWIG. 
http://www.swig.org/doc.html
has lots of examples. But for SIP, all I see is a reference guide
(http://www.riverbankcomputing.com/Docs/sip4/sipref.html).
Examples help. Where can I get examples for SIP 4.7?

Regards,
/Srijit

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


Re: Generating HTML

2007-09-12 Thread Walter Dörwald
Sebastian Bassi wrote:

> Hello,
> 
> What are people using these days to generate HTML? I still use
> HTMLgen, but I want to know if there are new options. I don't
> want/need a web-framework a la Zope, just want to produce valid HTML
> from Python.

If you want something that works similar to HTMLgen, you could use XIST:
http://www.livinglogic.de/Python/xist/

Servus,
   Walter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3K or Python 2.9?

2007-09-12 Thread Stefan Behnel
Bjoern Schliessmann wrote:
>> What does "self" have to do with an object model? It's an
>> function/method argument that might as well be hidden in the
>> compiler without ever touching the role it has (if not, why?). I
>> agree that it's needless noise in a language.
> 
> If this was needless, why do C++ and Java have the "this" pointer?

Be careful when you use the word "needless" in the context of Java.

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


Re: Generating HTML

2007-09-12 Thread Stefan Behnel
Sebastian Bassi wrote:
> What are people using these days to generate HTML? I still use
> HTMLgen, but I want to know if there are new options. I don't
> want/need a web-framework a la Zope, just want to produce valid HTML
> from Python.

There's also lxml.html, which has straight forward support for generating HTML
and comes with a lot of nice goodies for HTML handling:

http://codespeak.net/lxml/dev/lxmlhtml.html#creating-html-with-the-e-factory

Note that this requires lxml 2.0, which is currently in alpha status.

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Jeremy Sanders
Charles Fox wrote:

> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like

I thought it was horrible when I started, but now when looking at somebody
else's C++ code I find it very hard to work out whether something is a
global, a member or a local variable, unless they use some sort of naming
convention.

If you alias self as "s", it's only two more characters per variable access,
which is the same as the C++ "m_" naming convention.

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Spring Python 0.3.0 is released!

2007-09-12 Thread Goldfish
Spring Python (http://springpython.python-hosting.com) version 0.3.0
was released yesterday.

Key improvements include:
* Make the web components WSGI-compatible, firstly working with
CherryPy.
* Extend PetClinic to use database accounts and have password
encoding.
* Add an ExceptionTranslationFilter so PetClinic handles errors more
sophisticated.
* Relicense Spring Python underneath GPLv3.
* Generally, clean up the code and test cases. Also start using code
coverage tools to improve quality of testing.

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


Re: Python Database Apps

2007-09-12 Thread Ed Leafe
On Sep 11, 2007, at 2:56 PM, [EMAIL PROTECTED] wrote:

> It's gonna be a desktop app.  The
> database engine is going to be the critical component.  I like sqlite
> so that I don't need a database server on the client side.  It would
> help though if there is a way to sync between multiple clients to a
> central server database.  That's the tough part.  To give you a better
> idea of what i'm trying to do, I am trying to write an app where
> multiple technicians have an issue tracker that is available both
> offline and online.  I was looking to use sqlite as the local side
> that would sync new and updated issues to a central server when
> online.  Any technician may work on any issue.  Generally they will
> not be working on the same issue at the same time.  The technicians
> are geographically diverse (anywhere in the southeast US, not in an
> office.)

As far as the server goes, you can't go wrong with PostgreSQL, as  
others have mentioned. I have more experience with MySQL, but their  
recent licensing changes have simply made it easier to go with  
Postgres, as I don't have to worry about which clause of which  
document I might be violating.

For the local data store, SQLite is far and away the best choice,  
since you don't have to use two types of data access, as you would if  
you went with SQL on the server and, say, pickling on the local.

If you create both data stores with the same structure, you can use  
UUIDs as your keys, along with a timestamp flag for records that are  
added or modified when disconnected so that you can re-sync later.  
You will have to handle conflicts (i.e., someone changed a record  
that another also changed while disconnected) on your own,  
implementing your own business logic to determine who "wins", and how  
the conflicted data is handled.

I'll close with a plug for our product: Dabo. It is a desktop  
application framework with support for SQLite, PostgreSQL, MySQL,  
Firebird and Microsoft SQL Server databases. For disconnected data,  
you would simply define a local connection (to SQLite) and a remote  
connection (to your server database), and switch between the two  
depending on whether you are disconnected or not. The framework will  
handle the rest, allowing you to focus on the stuff that is unique to  
your app, such as the conflict resolution and business logic.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Steven D'Aprano
On Wed, 12 Sep 2007 03:21:58 -0700, Charles Fox wrote:

> I've just started playing around with Python, as a possible replacement
> for a mix of C++, Matlab and Lisp.  The language looks lovely and clean
> with one huge exception:  I do a lot of numerical modeling, so I deal
> with objects (like neurons) described mathematically in papers, by
> equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)

I think you've been seriously mislead. You don't NEED self. That's only 
for writing classes.

Although Python is completely object oriented, and everything is an 
object, you don't have to put your code in classes.

Instead of doing something like this:

class Adder(object):
"""Pointless class to add things."""
def __init__(self, value):
self.value = other
def add(self, other):
x = self.value + other
return float(x)

you don't need a class. Just write a function:

def add(x, other):
"""Function that adds other to x."""
return float(x + other)

Here's how I would write your function above:

def function(a, u, k):
"""Calculate a_dot from a, u and k."""
return -k(a-u)

And here is how I would use it:

a = 57 # or whatever...
u = 54
k = 3
a_dot = function(a, u, k)


See? Not a single "self" in sight.


You might also like to read about a strange, bizarre programming that 
forces you to put everything inside classes:

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html




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


Re: Python 3K or Python 2.9?

2007-09-12 Thread Duncan Booth
Ivan Voras <[EMAIL PROTECTED]> wrote:

>> I'd say Mr Eckel fails to graps some of the great points about 
Python's
>  
>> object model - the rant about the use of 'self' is a sure clue.
> 
> What does "self" have to do with an object model? It's an 
> function/method argument that might as well be hidden in the compiler 
> without ever touching the role it has (if not, why?). I agree that 
it's 
> needless noise in a language.

You could add some syntax to Python such that '.x' was equivalent to 
'.x' (either completely implicitly 
or with some surrounding block that lets you specify the assumed 
variable. 

That wouldn't break anything in the syntax but the general feeling of 
the Python community is that such a change would be undesirable as it is 
better to write the variable name out explicitly.

As for omitting 'self' from method definitions, at first site you might 
think the compiler could just decide that any 'def' directly inside a 
class could silently insert 'self' as an additional argument. This 
doesn't work though because not everything defined in a class has to be 
an instance method: static methods don't have a self parameter at all, 
class methods traditionally use 'cls' instead of 'self' as the name of 
the first parameter and it is also possible to define a function inside 
a class block and use it as a function. e.g.

class Weird:
   def factory(arg):
   """Returns a function based on its argument"""

   foo = factory("foo")
   bar = factory("bar")
   del factory

When factory is called, it is a simple function not a method. If it had 
gained an extra parameter then either you would have to explicitly pass 
it an instance of a not yet defined class when calling it, or the 
compiler would have to somehow know that it had been defined with the 
extra parameter and add it.

Basically it all boils down to having a consistent set of rules. Ruby 
has one set of rules, but Python has a different set. Python's rules 
mean you can interchange functions and methods more easily [at a cost of 
having to write self out explicitly/with the advantage that you can 
easily see references to self](delete as preferred). There is no 
difference between:

class C:
   def method(self): pass

and

def foo(self): pass
class C: pass
C.method = foo

both of these result in effectively the same class (although the second 
one has a different name for the method in tracebacks).

That consistency really is important. Whenever I see a 'def' I know 
exactly what parameters the resulting function will take regardless of 
the context.

Another area to consider is what happens when I do:

foo = FooClass()

foo.bar(x)
# versus
f = foo.bar
f(x)

Both of these work in exactly the same way in Python: the self parameter 
is bound to the method when you access 'foo.bar', not when you make the 
call. That isn't the case in some other scripting languages. e.g. in 
Javascript the first one would call bar with the magic 'this' parameter 
set to foo, but in the second case it calls bar with 'this' set to the 
global object.

My point here is that in Python the magic is clearly defined and 
overridable (so we can have static or class methods that act 
differently).

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Steven D'Aprano
On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:

> I feel that Python lacks one useful data structure: an ordered
> dictionary.
> 
> I find such data structures v. useful in C++.
[snip]


Personally, I've never missed an ordered dict. What do people use them 
for?

In fact, I'm not sure what people mean by ordered dicts. I assume they 
mean the keys are ordered, not the values. But ordered by what? Insertion 
order? Modification order? Alphabetical order? 


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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Michele Simionato
On Sep 12, 2:42 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:
> In fact, I'm not sure what people mean by ordered dicts. I assume they
> mean the keys are ordered, not the values. But ordered by what? Insertion
> order? Modification order? Alphabetical order?

Insertion order.

 M.S.

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


Re: SIP examples

2007-09-12 Thread Diez B. Roggisch
Srijit Kumar Bhadra wrote:

> I am trying to learn SIP (http://www.riverbankcomputing.co.uk/sip/)
> these days. I do not see any examples similar to SWIG.
> http://www.swig.org/doc.html has lots of examples. But for SIP, all I see
> is a reference guide
> (http://www.riverbankcomputing.com/Docs/sip4/sipref.html). Examples help.
> Where can I get examples for SIP 4.7?

Download pyqt, and look into it. Together with the reference, that's pretty
sufficient.

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


Re: Python Database Apps

2007-09-12 Thread Goldfish
I use MySQL and also sqlite. However, I also use Spring Python (http://
springpython.python-hosting.com) to use both its DatabaseTemplate
utility class and also the remoting functionality. This way, I can
have the database code sitting on the server, and then export the data
access functions remotely to clients. It is also relatively easy to
swap out database engines.

For the record: Spring Python is my pet project. I use it myself, and
recommend it to others as well.

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Steven D'Aprano
On Wed, 12 Sep 2007 09:51:02 +0200, stef wrote:

> If you're going to extend the dictionary, there's one other flag I'm
> continuously missing: "case-insensitive" key.

Completely untested and probably buggy as anything, but here's an 
absolutely minimal case-insensitive dictionary.

class CaselessDict(dict):
def __setitem__(self, key, value):
super(CaselessDict, self).__setitem__(key.lower(), value)
def __getitem__(self, key):
return super(CaselessDict, self).__getitem__(key.lower())


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


Re: cpython list __str__ method for floats

2007-09-12 Thread Duncan Booth
Bjoern Schliessmann <[EMAIL PROTECTED]> 
wrote:

>> The idea that 13.3 is a 'rounded' value for the number,
>> and that 13.301 is not a 'rounded' value of
>> the number, is a common error of intuitive mathematics.
> 
> I'm intrigued how /you/'d explain this, please do explain.

I think he is correct here: 13.301 is not exactly 
representable in IEEE 754. It is a rounded approximation to the true 
value just as is 13.3.

An argument can be made that instead of rounding the internal value to 
17 digits which is sufficient to ensure that you can roundtrip float->
string->float for all values, you could just round it to the minimum 
number of digits which guarantee the float->string->float roundtrip for 
that particular value.

Consider this as we gradually lose the more significant digits we see 
that last digit wasn't exactly 1 at all:

>>> 13.3
13.301
>>> 13.3-13
0.30071
>>> (13.3-13)*10-3
7.1054273576010019e-015

but why shouldn't Python do this instead?:

>>> 13.3
13.3
>>> 13.3-13
0.3
>>> (13.3-13)*10-3
7.1054273576e-015

These values will still roundtrip to the exact same internal 
representations. BTW, I didn't have to work too hard to figure out what 
that last value should be, the first is cut/paste from CPython, the 
second is what IronPython gives you.

I believe the claim is that using the full 17 digits ensures the round-
tripping works even if you serialise and deserialise on different 
systems, so perhaps we all pay a cost in our interactive sessions for 
something which should really be buried deep in IPC code.

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


pythonesque constructs for c++

2007-09-12 Thread Josh
One of the best features of python is its ease of use, and the ease of use 
of its modules. Modules like os, os.path, and datetime are invaluable!

Does anyone know of analagous c++ libraries? It seems to me that most of the 
functionality of these modules could easily be replicated in c++. Before I 
go about doing that, I was just wondering if anyone knows if they already 
exist?

thanks,
Josh


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


Is the wxPython list down?

2007-09-12 Thread kyosohma
Hi,

Does anyone know if the wxPython mailing list is having issues? I
subscribe to it and haven't seen anything come through since
09/06/2007. I went to ActiveState's archives and the last message
there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/
Threaded/wxPython-users).

Thanks,

Mike

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


Re: Basic GUI

2007-09-12 Thread kyosohma
Don,

On Sep 11, 10:54 pm, Don Hanlen <[EMAIL PROTECTED]> wrote:
> I'm writing a simple GUI that:
> ..gets info via telnet protocol (and sends)
> ..gets info via http (and sends)
> ..gets user-info from (currently)
> ...Tkinter Text windoze
> ...Tkinter buttons and such
> ..displays info in various Tkinter windoze
> ...graphic AND text...
>
> I can accomplish all of these functions individually and now seem to
> need to set up multi-processes to combine 'em.  Back in my C days, I'd
> have used fork/exec to do so, but I'm confused by the number of
> modules available in Python.  Is there a "best" for portability and
> simplicity?  (Or am I on the wrong track here?)
>
> I could solve my problems with the following psuedo-code made into
> real code:
> 
> import blah
>
> t = blah.fork(runthisprogram.py)
>
> #OK still in main
> t.sendinfo(info)
> info = t.receiveinfo()
> 
> #runthisprogram.py
> def sendinfobacktopapa():
> ? eventhere
> def getinfofrompapa():
> ? eventhere
> 
>
> It seems to me that propagating events *may* be the best way to
> communicate.  I'm wide open, including to non-multi-process solutions.
>
> Thanks for your comments, I searched old posts for a while, various
> other Python info-sources, and couldn't find an answer.
> --
> don


You can also use threads, which is a little bit more portable than
using Python's fork methodology, or so I've read. The concepts on this
page can be applied to any GUI toolkit you choose:
http://wiki.wxpython.org/LongRunningTasks

I've used them with wxPython, but iirc, Lutz does something quite
similar with Tkinter in his latest edition of "Programming Python".

I think what Michele is referring to is the subprocess module, which
is also useful.

Mike

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


Re: Sea-or-land test

2007-09-12 Thread kyosohma
On Sep 12, 6:54 am, [EMAIL PROTECTED] wrote:
> Could you advise if there exists a simple package, containing function
> that would take geographic coordinates and return information on
> whether this point belongs to land or sea? No great accuracy is needed
> -- I am interested in just major features, like those seen on coarse
> world maps.

This may be of use to you: http://cheeseshop.python.org/pypi/geopy

or http://blog.case.edu/bmb12/2006/09/geocoding_tools_for_python_and_caseclasses

Should be helpful anyway.

Mike

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


Re: encoding latin1 to utf-8

2007-09-12 Thread Harshad Modi
thx for response ,
i think, my file has wrong encoding format.
thanks for guide and advise

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


Re: Is the wxPython list down?

2007-09-12 Thread stef
[EMAIL PROTECTED] wrote:
> Hi,
>
> Does anyone know if the wxPython mailing list is having issues? I
>   
Yes the server has hardware problems,
Robin Dunn (moderator), is informed about it.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is the wxPython list down?

2007-09-12 Thread Frank Millman
On Sep 12, 3:10 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> Does anyone know if the wxPython mailing list is having issues? I
> subscribe to it and haven't seen anything come through since
> 09/06/2007. I went to ActiveState's archives and the last message
> there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/
> Threaded/wxPython-users).
>
> Thanks,
>
> Mike

This is from the wxPython home page -

"(8-Sept-2007) Yes, the mail lists are down. There were multiple disk
failures in RAID5 array of the machine that hosts the mail lists. The
hardware has been replaced and data is being restored from tape
backups."

I noticed that cvs seems to be down as well - maybe it was on the same
server.

Frank

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Dave Hansen
On Sep 12, 5:21 am, Charles Fox <[EMAIL PROTECTED]> wrote:
> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)
> For large equations this is going to make my code seriously unreadable
> to the point of needing to switch back to Matlab -- and it seems to go
> against everything else about python's simplicity and elegance.  Am I

It goes back to the Zen of Python (import this): Explicit is better
than implicit.  And it's a boon to future maintainers of your code

> missing something?  Is there something like a 'with' command that lets
> me set the scope, like
>
> with self:
>   .a_dot = -.k(.a-.u)

The name "self" is just a convention.  You can give it any name you
wish.  Using "s" is common.

As others have mentioned, you can also provide local synonyms if the
dot syntax is too onerous.  But make sure you use the member access
syntax if the result of an expression is an immutable type.  For
example, I assume a_dot is a mutable type, such as a list.  If so,
then you could simply use

   a_dot, k, a, u = self.a_dot, self.k, self.a, self.u
   a_dot = -k(a-u)

However, if it's an immutable type, such as a scalar, strung, or
tuple, you need

   self.a_dot = -k(a-u)

And it gets trickier if you have members taking intermediate values...

>
> It's premature to make language suggestions as I am new to the

That's for sure  ;-)

Regards,

   -=Dave

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


Re: library to launch program in linux

2007-09-12 Thread idzwan . nizam
On Sep 7, 2:49 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2007-09-06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I'm a new user. What library should I use so that I canlaunch
> >programin linux using python? Thank you in advance.
>
> subprocess
>
> --
> Grant Edwards   grante Yow! Hello, GORRY-O!!
>   at   I'm a GENIUS from HARVARD!!
>visi.com

can you please show me the sample code using subprocess library. I
would like user to have few option, program they could run. say,
firefox and x chat. thank you

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


Re: pythonesque constructs for c++

2007-09-12 Thread Szabolcs Horvát
Josh wrote:
> One of the best features of python is its ease of use, and the ease of use 
> of its modules. Modules like os, os.path, and datetime are invaluable!
> 
> Does anyone know of analagous c++ libraries? It seems to me that most of the 
> functionality of these modules could easily be replicated in c++. Before I 
> go about doing that, I was just wondering if anyone knows if they already 
> exist?

Check out Boost.

http://www.boost.org/
http://www.boost.org/libs/filesystem/doc/index.htm
http://www.boost.org/doc/html/date_time.html

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Mark Summerfield
On 12 Sep, 13:46, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> On Sep 12, 2:42 pm, Steven D'Aprano <[EMAIL PROTECTED]
>
> cybersource.com.au> wrote:
> > On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:
> > In fact, I'm not sure what people mean by ordered dicts. I assume they
> > mean the keys are ordered, not the values. But ordered by what? Insertion
> > order? Modification order? Alphabetical order?
>
> Insertion order.
>
>  M.S.


Actually I meant by key order, so insertion order doesn't matter at
all. If you need a dictionary-like data structure that respects
insertion order you could use a list of (key, value) tuples.

Another respondent asked about use cases.

I have found time and again that I needed (key, value) pairs where the
key is some string that provides a representation for human readers
and the value is some internal key (e.g., database ID) that the system
uses internally. In these cases I often need to present the user with
a list of items from which to choose and want to present them in
sorted order. Naturally, I could use an ordinary dict and then do
this:

for string in sorted(d.keys()):
process(string)

But what happens when I need to do this a *lot* and when the number of
items is hundreds or a few thousands? I'm having to sort again and
again, since it is often the case that the items in the list changes
during the runtime of the application. So my solution in C++ is to use
an ordered dictionary (a map in C++ jargon), which in Python means I
can simply write:

for string in od.keys():
process(string)

Another situation where this is useful is if you need to hold lists of
strings preserving case but want them to be presented case-
insensitively. Here, you populate the ordered dictionary like this:

for string in somelist:
od[string.lower()] = string

Now you can iterate over od in case-insensitive order and yet still
have access to the case-sensitive original, and never have to
explicitly sort the strings.

I think it comes down to the nail and hammer issue: if you have a
hammer all problems look nail shaped. In Python we have dict and list
so everything looks suitable for those data structures. But having had
a wrench (ordered dictionaries) in C++, I find that some problems need
a wrench. I think that once Python programmers have access to an
ordered dictionary some proportion of them will find it painful to
program without it, so I really think it belongs in the standard
library.

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


Re: Is the wxPython list down?

2007-09-12 Thread kyosohma
On Sep 12, 8:26 am, stef <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
>
> > Does anyone know if the wxPython mailing list is having issues? I
>
> Yes the server has hardware problems,
> Robin Dunn (moderator), is informed about it.
>
> cheers,
> Stef Mientki

And to think, we're always told that that doesn't happen with RAID5.
Guess I should have checked the website. Thanks Stef and Frank.

Mike

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Michele Simionato
On Sep 12, 3:54 pm, Mark Summerfield <[EMAIL PROTECTED]>
wrote:
> On 12 Sep, 13:46, Michele Simionato <[EMAIL PROTECTED]>
>
> Actually I meant by key order, so insertion order doesn't matter at
> all. If you need a dictionary-like data structure that respects
> insertion order you could use a list of (key, value) tuples.
>
> Another respondent asked about use cases.
>
> I have found time and again that I needed (key, value) pairs where the
> key is some string that provides a representation for human readers
> and the value is some internal key (e.g., database ID) that the system
> uses internally. In these cases I often need to present the user with
> a list of items from which to choose and want to present them in
> sorted order. Naturally, I could use an ordinary dict and then do
> this:
>
> for string in sorted(d.keys()):
> process(string)
>
> But what happens when I need to do this a *lot* and when the number of
> items is hundreds or a few thousands? I'm having to sort again and
> again, since it is often the case that the items in the list changes
> during the runtime of the application. So my solution in C++ is to use
> an ordered dictionary (a map in C++ jargon), which in Python means I
> can simply write:
>
> for string in od.keys():
> process(string)
>

For your use case I would wrap a list [(key, value)] with a dict-like
object and I would use the bisect module in the standard library to
keep
the inner list ordered.

 M.S.

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Bruno Desthuilliers
Dave Hansen a écrit :
(snip)
> As others have mentioned, you can also provide local synonyms if the
> dot syntax is too onerous.  But make sure you use the member access
> syntax if the result of an expression is an immutable type.  For
> example, I assume a_dot is a mutable type, such as a list.  If so,
> then you could simply use
> 
>a_dot, k, a, u = self.a_dot, self.k, self.a, self.u
>a_dot = -k(a-u)
> 
> However, if it's an immutable type, such as a scalar, strung, or
> tuple, you need
> 
>self.a_dot = -k(a-u)

Hmmm... Actually, whether self.a_dot is an instance of a mutable or 
immutable type won't change anything - in both case, it's only the 
*local* name a_dot that'll be rebound. So  as soon as you want to 
rebind (iow:assign to) an attribute, you *need* to use 
self.the_attr_name on the LHS.

Of course, *mutating* is a different situation...

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> In fact, I'm not sure what people mean by ordered dicts. I assume they
> mean the keys are ordered, not the values. But ordered by what?
> Insertion order? Modification order? Alphabetical order? 

All of the above at different times. Usually I think they mean original 
insertion order, I'd more often like modification order though.

Insertion order can certainly be useful: any situation where you currently 
keep items in a list because the original order is important but also copy 
them into a dictionary or set because you need fast lookup. 
e.g. if you want only unique items out of a list but need to preserve order 
of first occurrence.

Another example would be uml->code round tripping: you parse in an existing 
file containing method definitions, then update the method definitions from 
a UML model and write the file out again: ArchGenXML does exactly that, but 
last I looked the methods were written out in whatever order the dictionary 
stored them which really messes up version control. It really should 
preserve the order that methods appeared in the file.

Modification order would be great for a cache. Touch items whenever they 
are referenced and then whenever the cache gets too big just pop the oldest 
until you get back to the desired size.

Alphabetical or other sorted order when you want to get smallest/largest or 
next smaller/larger then a specific item. I don't agree you necessarily 
mean ordered by key rather than value, I think you could specify any 
sortkey and expect updating the value to restore the ordering. Maybe if you 
are recording some stats and want to regularly output the top 10?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Roel Schroeven
Michele Simionato schreef:
> On Sep 12, 2:42 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:
>> In fact, I'm not sure what people mean by ordered dicts. I assume they
>> mean the keys are ordered, not the values. But ordered by what? Insertion
>> order? Modification order? Alphabetical order?
> 
> Insertion order.

Mark referred to C++ and the sort function, so I assume he meant 
alphabetical order (or the equivalent for types other than strings).

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: MemoryError on reading mbox file

2007-09-12 Thread Christoph Krammer
On 12 Sep., 12:20, David <[EMAIL PROTECTED]> wrote:
> It may be that Python's garbage collection isn't keeping up with your app.
>
> You could try periodically forcing it to run. eg:
>
> import gc
> gc.collect()

I tried this, but the problem is not solved. When invoking the garbage
collection after every loop run, the amount of memory indicated by top
stays the same for a very long time until at some point (at different
messages), while it is executing the loop header, the memory increases
until it hits 100% and swap hit also 100% => MemoryError

Can there be a problem within the mailbox module while processing too
large files?

Regards,
 Christoph


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


Dynamically removing methods in new-style classes

2007-09-12 Thread agupta0318
I am trying unsuccessfully to remove some methods from an instance,
based on values passed in to the constructor as in the following
example:

#===
class A(object):

def __init__(self, id):
self._id = id
return

def clean(self):
if (self._id == 1):
del self.test1
elif (self._id == 2):
del self.test2
pass
return

def test1(self):
print "in test1"
return

def test2(self):
print "in test2"
return

#=
if (__name__ == '__main__'):
try:
a = A(1)
a.clean()
a.test2()
a.test1()
except AttributeError, exc:
import traceback
traceback.print_exc()
pass

#==
I get the following error:
Traceback (most recent call last):
  File "DynamicMethods.py", line 30, in ?
a.clean()
  File "DynamicMethods.py", line 11, in clean
del self.test1
AttributeError: test1

With the older python classes I could have done:
self.__class__.__dict__[''test1"] to achieve the desired result.

I appreciate any help you could provide with this.

Thanks.

Amit Gupta

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


Re: library to launch program in linux

2007-09-12 Thread Grant Edwards
On 2007-09-12, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

>>> I'm a new user. What library should I use so that I canlaunch
>>> programin linux using python? Thank you in advance.

> can you please show me the sample code using subprocess library.

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

> I would like user to have few option, program they could run.
> say, firefox and x chat.

I'd like to be 15 years younger.

-- 
Grant Edwards   grante Yow! I'm definitely not
  at   in Omaha!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MemoryError on reading mbox file

2007-09-12 Thread Hrvoje Niksic
Christoph Krammer <[EMAIL PROTECTED]> writes:

> I have to convert a huge mbox file (~1.5G) to MySQL.

Have you tried commenting out the MySQL portion of the code?  Does the
code then manage to finish processing the mailbox?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically removing methods in new-style classes

2007-09-12 Thread Hrvoje Niksic
[EMAIL PROTECTED] writes:

> I am trying unsuccessfully to remove some methods from an instance,

You can't remove the method from an instance because the method is
stored in its class.

> With the older python classes I could have done:
> self.__class__.__dict__[''test1"] to achieve the desired result.

self.__class__.test1 still works, doesn't it?  Removing methods can be
achieved the same way:

>>> x=X()
>>> class X(object):
...  def blah(self): pass
...
>>> x=X()
>>> x.blah
>
>>> del type(x).blah
>>> x.blah
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'X' object has no attribute 'blah'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Database Apps

2007-09-12 Thread [EMAIL PROTECTED]
On Sep 12, 8:39 am, Ed Leafe <[EMAIL PROTECTED]> wrote:
> On Sep 11, 2007, at 2:56 PM, [EMAIL PROTECTED] wrote:
>
> > It's gonna be a desktop app.  The
> > database engine is going to be the critical component.  I like sqlite
> > so that I don't need a database server on the client side.  It would
> > help though if there is a way to sync between multiple clients to a
> > central server database.  That's the tough part.  To give you a better
> > idea of what i'm trying to do, I am trying to write an app where
> > multiple technicians have an issue tracker that is available both
> > offline and online.  I was looking to use sqlite as the local side
> > that would sync new and updated issues to a central server when
> > online.  Any technician may work on any issue.  Generally they will
> > not be working on the same issue at the same time.  The technicians
> > are geographically diverse (anywhere in the southeast US, not in an
> > office.)
>
> As far as the server goes, you can't go wrong with PostgreSQL, as
> others have mentioned. I have more experience with MySQL, but their
> recent licensing changes have simply made it easier to go with
> Postgres, as I don't have to worry about which clause of which
> document I might be violating.
>
> For the local data store, SQLite is far and away the best choice,
> since you don't have to use two types of data access, as you would if
> you went with SQL on the server and, say, pickling on the local.
>
> If you create both data stores with the same structure, you can use
> UUIDs as your keys, along with a timestamp flag for records that are
> added or modified when disconnected so that you can re-sync later.
> You will have to handle conflicts (i.e., someone changed a record
> that another also changed while disconnected) on your own,
> implementing your own business logic to determine who "wins", and how
> the conflicted data is handled.
>
> I'll close with a plug for our product: Dabo. It is a desktop
> application framework with support for SQLite, PostgreSQL, MySQL,
> Firebird and Microsoft SQL Server databases. For disconnected data,
> you would simply define a local connection (to SQLite) and a remote
> connection (to your server database), and switch between the two
> depending on whether you are disconnected or not. The framework will
> handle the rest, allowing you to focus on the stuff that is unique to
> your app, such as the conflict resolution and business logic.
>
> -- Ed Leafe
> --http://leafe.com
> --http://dabodev.com

Thanks for ideas Ed.  I am checking out dabo now.  I do have a few
questions about it.  Packaging.  Is it easy to package into a quick
install for windows.  The users are going to want to get too in
depth.  Second, data sources.  When I'm adding a data source to the
window in class designer, it always picks up the one I created (which
incidentally was a sample, my form for connection manager isn't
working at the moment.)  My idea is to have the the local sqlite
database as the only viewable data source, and the server side only
for syncing.  So they logon, sync up, sync down, and view.  I'm
worried about having to get them to install python, dabo, and the app.

Darien

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


Re: Dynamically removing methods in new-style classes

2007-09-12 Thread Michele Simionato
On Sep 12, 4:28 pm, [EMAIL PROTECTED] wrote:
> I am trying unsuccessfully to remove some methods from an instance,

Usuall one does not remove methods, but wraps the object and delegates
only to
a restricted number of methods. Is this solution viable? If not, you
may be
forced to change the class of the instance, or to play trick such as

def removed_method(self):
   raise NotImplementedError

self.test1 = removed_method.__get__(self)

  Michele Simionato

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


RE: An ordered dictionary for the Python library?

2007-09-12 Thread Hamilton, William
> From: Michele Simionato
> 
> On Sep 12, 3:54 pm, Mark Summerfield <[EMAIL PROTECTED]>
> wrote:
> > On 12 Sep, 13:46, Michele Simionato <[EMAIL PROTECTED]>
> >
> > Actually I meant by key order, so insertion order doesn't matter at
> > all. If you need a dictionary-like data structure that respects
> > insertion order you could use a list of (key, value) tuples.
> >
> > Another respondent asked about use cases.
> >
> > I have found time and again that I needed (key, value) pairs where
the
> > key is some string that provides a representation for human readers
> > and the value is some internal key (e.g., database ID) that the
system
> > uses internally. In these cases I often need to present the user
with
> > a list of items from which to choose and want to present them in
> > sorted order. Naturally, I could use an ordinary dict and then do
> > this:
> >
> > for string in sorted(d.keys()):
> > process(string)
> >
> > But what happens when I need to do this a *lot* and when the number
of
> > items is hundreds or a few thousands? I'm having to sort again and
> > again, since it is often the case that the items in the list changes
> > during the runtime of the application. So my solution in C++ is to
use
> > an ordered dictionary (a map in C++ jargon), which in Python means I
> > can simply write:
> >
> > for string in od.keys():
> > process(string)
> >
> 
> For your use case I would wrap a list [(key, value)] with a dict-like
> object and I would use the bisect module in the standard library to
> keep
> the inner list ordered.


Or subclass dict to carry along a sorted list of keys with it and return
that when dict.keys() is called.  Even better, only have .keys() sort
the keys list when a key has been added to it since the last call.


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


Re: MemoryError on reading mbox file

2007-09-12 Thread Istvan Albert
On Sep 12, 5:27 am, Christoph Krammer <[EMAIL PROTECTED]>
wrote:

> string = self._file.read(stop - self._file.tell())
> MemoryError

This line reads an entire message into memory as a string. Is it
possible that you have a huge email in there (hundreds of MB) with
some attachment encoded as text?

Either way, the truth is that many modules in the standard library are
not well equipped to deal with large amounts of data. Many of them
were developed before gigabyte sized files were even possible to store
let alone process. Hopefully P3K will alleviate many of these problems
by its extensive use of generators.

For now I would recommend that you split your mbox file into several
smaller ones. (I think all you need is to split at the To: fields) and
run your script on these individual files.

i.








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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Charles Fox
Thanks guys -- yeah these two stategies (short s.varname; and explicit
rescoping, a=self.a etc) are more or less what I was using.  That's
still kind of annoying though.

The s.varname approach still makes numerical code much harder to read.

I had a nasty bug with the boilerplate approach when forgetting to
reassign some of the variables back to members (self.a=a).  And that's
a lot of boilerplate you need -- I thought the python way was to
minimize redundant code?  (Ditching header files and curley brackets
was a main reason for me coming here).

I see the argument for making self explicit -- what would be wrong
with just .a instead of self.a though?  That's still explicit but much
easier to read.  (I think I've seen that somewhere else, is it C#?)

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Tim Golden
Charles Fox wrote:
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using.  That's
> still kind of annoying though.
> 
> The s.varname approach still makes numerical code much harder to read.
> 
> I had a nasty bug with the boilerplate approach when forgetting to
> reassign some of the variables back to members (self.a=a).  And that's
> a lot of boilerplate you need -- I thought the python way was to
> minimize redundant code?  (Ditching header files and curley brackets
> was a main reason for me coming here).
> 
> I see the argument for making self explicit -- what would be wrong
> with just .a instead of self.a though?  That's still explicit but much
> easier to read.  (I think I've seen that somewhere else, is it C#?)

Charles, while you are quite right to air your ideas, do bear in mind
that this issue has been thrashed out again and again on this group
and in other forums. I hope you have at least read the FAQ:

http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls

and PEP 3099:

http://www.python.org/dev/peps/pep-3099/

If you take the trouble to search the archives of this list alone
for, say, explicit+self, you'll see that there are quite strong arguments
(and argumentors) on both sides. In that sort of situation the status quo
tends to hold sway. (And in this case, GvR has only recently responded to
similar comments by Bruce Eckels -- a couple of heavyweights -- in a way
which makes it unlikely that this is going to change).

I think it's one of those things which comes down, fairly enough, to: we
do things this way and it works for us; other languages do other things
and it works for them.

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


Re: Get Only the Last Items in a Traceback

2007-09-12 Thread [EMAIL PROTECTED]
On Sep 12, 5:17 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>
> Your assessment is wrong. You only get the extra lines in the traceback if
> you don't immediately wrap the exec statement in a try ... except block:
>
> $ cat snip_traceback1.py
> import traceback
>
> def alpha():
> try:
> beta()
> except Exception, e:
> traceback.print_exc()
>
> def beta():
> gamma()
>
> def gamma():
> exec s in {}
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback1.py
> Traceback (most recent call last):
>   File "snip_traceback1.py", line 5, in alpha
> beta()
>   File "snip_traceback1.py", line 10, in beta
> gamma()
>   File "snip_traceback1.py", line 13, in gamma
> exec s in {}
>   File "", line 7, in 
>   File "", line 3, in delta
>   File "", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> So the first step is to move the try ... except closer to the exec:
>
> $ cat snip_traceback2.py
> import traceback
>
> def alpha():
> beta()
>
> def beta():
> gamma()
>
> def gamma():
> try:
> exec s in {}
> except Exception, e:
> traceback.print_exc()
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback2.py
> Traceback (most recent call last):
>   File "snip_traceback2.py", line 11, in gamma
> exec s in {}
>   File "", line 7, in 
>   File "", line 3, in delta
>   File "", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> You are almost there. Now let's strip off the outermost traceback:
>
> $ cat snip_traceback3.py
> import sys
> import traceback
>
> def alpha():
> beta()
>
> def beta():
> gamma()
>
> def gamma():
> try:
> exec s in {}
> except Exception, e:
> etype, value, tb = sys.exc_info()
> traceback.print_exception(etype, value, tb.tb_next)
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback3.py
> Traceback (most recent call last):
>   File "", line 7, in 
>   File "", line 3, in delta
>   File "", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> Heureka.
>
> Peter

Thanks for the help, Peter.  That's exactly what I need.  Now could I
use your tb.tb_next trick a couple times and thus avoid moving the try/
except?

-Greg

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Michele Simionato
On Sep 12, 4:43 pm, Charles Fox <[EMAIL PROTECTED]> wrote:
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using.  That's
> still kind of annoying though.
>
> The s.varname approach still makes numerical code much harder to read.
>
> I had a nasty bug with the boilerplate approach when forgetting to
> reassign some of the variables back to members (self.a=a).  And that's
> a lot of boilerplate you need -- I thought the python way was to
> minimize redundant code?  (Ditching header files and curley brackets
> was a main reason for me coming here).

You still can play with dictionaries, for instance:

def __init__(self, a, b, c):
   vars(self).update(locals())

correspond to

self.a = a
self.b = b
self.c = c

(and actually also to self.self =self).

> I see the argument for making self explicit -- what would be wrong
> with just .a instead of self.a though?  That's still explicit but much
> easier to read.  (I think I've seen that somewhere else, is it C#?)

This has been proposed many times. But self is handy because you can
give
a different name to it: for instance it becomes cls when you are
inside a classmethod.


Michele Simionato

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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Grant Edwards
On 2007-09-12, Tim Golden <[EMAIL PROTECTED]> wrote:

> I think it's one of those things which comes down, fairly
> enough, to: we do things this way and it works for us; other
> languages do other things and it works for them.

But not as nearly well as our way works for us, of course. ;)

-- 
Grant Edwards   grante Yow! I'm meditating on
  at   the FORMALDEHYDE and the
   visi.comASBESTOS leaking into my
   PERSONAL SPACE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread J. Clifford Dyer
On Wed, Sep 12, 2007 at 07:43:51AM -0700, Charles Fox wrote regarding Re: 
newbie: self.member syntax seems /really/ annoying:
> 
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using.  That's
> still kind of annoying though.
> 
> The s.varname approach still makes numerical code much harder to read.
> 

For what it's worth, if you stick with python for a while, you will stop 
noticing the self, and be able to see what you're looking for quite clearly.  

Moreso if you use s.

Cheers,
Cliff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is the wxPython list down?

2007-09-12 Thread Chris Mellon
On 9/12/07, Frank Millman <[EMAIL PROTECTED]> wrote:
> On Sep 12, 3:10 pm, [EMAIL PROTECTED] wrote:
> > Hi,
> >
> > Does anyone know if the wxPython mailing list is having issues? I
> > subscribe to it and haven't seen anything come through since
> > 09/06/2007. I went to ActiveState's archives and the last message
> > there is from the 7th (http://aspn.activestate.com/ASPN/Mail/Browse/
> > Threaded/wxPython-users).
> >
> > Thanks,
> >
> > Mike
>
> This is from the wxPython home page -
>
> "(8-Sept-2007) Yes, the mail lists are down. There were multiple disk
> failures in RAID5 array of the machine that hosts the mail lists. The
> hardware has been replaced and data is being restored from tape
> backups."
>
> I noticed that cvs seems to be down as well - maybe it was on the same
> server.
>

CVS is down because wx has moved to SVN, which is still up and running
fine. svn.wxwidgets.org.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: eGenix mxODBC and mxODBC Zope DA on 64-bit FreeBSD

2007-09-12 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING

   eGenix.com mxODBC Database Interface

  eGenix.com mxODBC Zope Database Adapter

   for 64-bit FreeBSD


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mxODBC-on-FreeBSD-amd64-GA.html



eGenix mxODBC Distribution

The eGenix mxODBC Distribution is a Python database interface add-on
distribution for our eGenix mx Base Distribution. It comes with mxODBC,
our universal ODBC database interface for Python.

Customers who have purchased licenses for other platforms and wish to
move their installation to FreeBSD 64-bit, can do so without having to
buy a new license. The licenses will continue to work on the 64-bit
platform.

Users of mxODBC 2.0 will have to purchase new licenses from our online
shop in order to upgrade to mxODBC 3.0.

You can request 30-day evaluation licenses on the product page.

Downloads
-

Please visit the eGenix mxODBC Distribution page for downloads,
instructions on installation and documentation of the packages.

http://www.egenix.com/products/python/mxODBC/

Note that in order to use the eGenix mxODBC Distribution you need to
install the eGenix mx Base Distribution first.



eGenix mxODBC Zope DA


eGenix mxODBC Zope DA is our database interface for Zope and Plone. It
is based on the mxODBC interface.

Customers who have purchased licenses for other platforms and wish to
move their installation to FreeBSD 64-bit, can do so without having to
buy a new license. The licenses will continue to work on the 64-bit
platform.

You can request 30-day evaluation licenses on the product page.

Downloads
-

Please visit the eGenix mxODBC Zope DA product page for downloads,
instructions on installation and documentation of the packages.

http://www.egenix.com/products/zope/mxODBCZopeDA/



More Information

For more information on our products, licensing and download
instructions, please write to [EMAIL PROTECTED]

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Sep 12 2007)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2007-08-22: Released mxODBC 3.0.1  http://python.egenix.com/

 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611


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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread kyosohma

Charles Fox wrote:
> I've just started playing around with Python, as a possible
> replacement for a mix of C++, Matlab and Lisp.  The language looks
> lovely and clean with one huge exception:  I do a lot of numerical
> modeling, so I deal with objects (like neurons) described
> mathematically in papers, by equations like
> a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
> self.a_dot = -self.k(self.a-self.u)
> For large equations this is going to make my code seriously unreadable
> to the point of needing to switch back to Matlab -- and it seems to go
> against everything else about python's simplicity and elegance.  Am I
> missing something?  Is there something like a 'with' command that lets
> me set the scope, like
>
> with self:
>   .a_dot = -.k(.a-.u)
>
> It's premature to make language suggestions as I am new to the
> language, but I would have though that making a 'with self' explicit
> in all methods would have been neat, so I could just write
>   .a_dot = -.k(.a-.u)
> which would still avoid confusion with local function variables, since
> '.a' is different from 'a'.
>
> Please help if I am missing something -- this looks like a great
> language but I am going to mad trying to read numerical code full of
> 'self.'s breaking up the equations.

I don't know if it'll help or not, but you might try using matplotlib,
numpy or pymat. One of those may make it easier to do your
calculations.

Mike

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


Re: Enum class with ToString functionality

2007-09-12 Thread Neil Cerutti
On 2007-09-11, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> Perhaps Ben should have followed the usual practice of
> commercial, closed- source software developers and started
> counting his version numbers at one instead of zero, miss a few
> releases, use randomly large increments occasionally, and ended
> up with a current version number of 2.7.1 for the exact same
> level of functionality.
>
> Or he could have called it "Enum XP" (for "eXtra Programming"
> perhaps) or "Enum 2007". The next minor release could be "Enum
> 2008", and the next major update could be called "Enum
> Professional Capowie!!!".

I like the (priviledged) code names adopted by the Linux
community for special versions, e.g., Enum 2.7.1 (Flapjacks).
This would really tie the Enum-using community together, and make
messages about it much cuter.

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


Re: National grid to lat long conversion

2007-09-12 Thread Astley Le Jasper
Hi,

I was a bit limited with time so in the end used an online service
with an API which is great for the limited number of look-ups I
needed. It can be found at:

http://www.nearby.org.uk/

It was also very useful for site for other conversions and lookups.

I manage to find a couple of other examples in other languages which I
might have used as the basis for some pythonification.

PHP
- http://www.megalithia.com/search/llfuncshighlight.php
- http://www.jstott.me.uk/phpcoord/

Javascript
- http://www.movable-type.co.uk/scripts/latlong-gridref.html

Cheers

Neil

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


is it possible to use different font within one wxpython static text widget?

2007-09-12 Thread hyena
problem is as title, bear me if this too silly or too naive.

I use wx.statictext widget to show some information in GUI, there are some 
numbers in the text to be emphasized in bigger other color. For example, in 
sentence "the travel speed of this car is 40 km /hour", I would like "40" to 
be bigger and in red color. I know I can use several statictext to get this 
effect. But i am quite relucktant to do so since I am quite unfamiliar with 
manageing the layout of widgets.

Is there a convinient way to have this done? Thanks for any .input



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


Re: Python 3K or Python 2.9?

2007-09-12 Thread Alex Martelli
Duncan Booth <[EMAIL PROTECTED]> wrote:
   ...
> As for omitting 'self' from method definitions, at first site you might
> think the compiler could just decide that any 'def' directly inside a
> class could silently insert 'self' as an additional argument. This 
> doesn't work though because not everything defined in a class has to be
> an instance method: static methods don't have a self parameter at all,
> class methods traditionally use 'cls' instead of 'self' as the name of
> the first parameter and it is also possible to define a function inside
> a class block and use it as a function. e.g.

Actually you could do the "magic first-parameter insertion" just when
returning a bound or unbound method object in the function's __get__
special method, and that would cover all of the technical issues you
raise.  E.g.:

> class Weird:
>def factory(arg):
>"""Returns a function based on its argument"""
> 
>foo = factory("foo")
>bar = factory("bar")
>del factory
> 
> When factory is called, it is a simple function not a method. If it had

Sure, that's because the function object itself is called, not a bound
or unbound method object -- indeed. factory.__get__ never gets called
here.

> class C:
>def method(self): pass
> 
> and
> 
> def foo(self): pass
> class C: pass
> C.method = foo
> 
> both of these result in effectively the same class (although the second
> one has a different name for the method in tracebacks).

And exactly the same would occur if the self argument was omitted from
the signature and magically inserted when __get__ does its job.

> That consistency really is important. Whenever I see a 'def' I know 
> exactly what parameters the resulting function will take regardless of
> the context.

And this non-strictly-technical issue is the only "true" one.

> Another area to consider is what happens when I do:
> 
> foo = FooClass()
> 
> foo.bar(x)
> # versus
> f = foo.bar
> f(x)
> 
> Both of these work in exactly the same way in Python: the self parameter

And so they would with the "__get__ does magic" rule, NP.

> My point here is that in Python the magic is clearly defined and 
> overridable (so we can have static or class methods that act 
> differently).

And so it would be with that rule, since staticmethod &c create
different descriptor objects.

Really, the one and only true issue is that the Python community doesn't
like "magic".  It would be perfectly feasible, we just don't wanna:-).


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


Re: newbie: self.member syntax seems /really/ annoying

2007-09-12 Thread Chris Mellon
On 9/12/07, Charles Fox <[EMAIL PROTECTED]> wrote:
> Thanks guys -- yeah these two stategies (short s.varname; and explicit
> rescoping, a=self.a etc) are more or less what I was using.  That's
> still kind of annoying though.
>
> The s.varname approach still makes numerical code much harder to read.
>
> I had a nasty bug with the boilerplate approach when forgetting to
> reassign some of the variables back to members (self.a=a).  And that's
> a lot of boilerplate you need -- I thought the python way was to
> minimize redundant code?  (Ditching header files and curley brackets
> was a main reason for me coming here).
>
> I see the argument for making self explicit -- what would be wrong
> with just .a instead of self.a though?  That's still explicit but much
> easier to read.  (I think I've seen that somewhere else, is it C#?)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


This is terrible and horrible, please don't use it. That said,
presenting the magic implicit_self context manager!

from __future__ import with_statement
import sys

class implicit_self(object):
def __init__(self, obj):
self.obj = obj
def __enter__(self):
local = sys._getframe(1).f_locals
local.update(self.obj.__dict__)
def __exit__(self, exc, obj, tb):
local = sys._getframe(1).f_locals
for k in self.obj.__dict__:
setattr(self.obj, k, local[k])

if __name__ == '__main__':
class Test(object):
pass
t = Test()
t.a = 10
t.b = 20
with implicit_self(t):
print a
print b
a = 40
b = a * 2

print t.a
print t.b
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get Only the Last Items in a Traceback

2007-09-12 Thread Peter Otten
Am Wed, 12 Sep 2007 15:09:02 + schrieb [EMAIL PROTECTED]:

> On Sep 12, 5:17 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>>
>> Your assessment is wrong. You only get the extra lines in the traceback if
>> you don't immediately wrap the exec statement in a try ... except block:

>> $ cat snip_traceback3.py
>> import sys
>> import traceback
>>
>> def alpha():
>> beta()
>>
>> def beta():
>> gamma()
>>
>> def gamma():
>> try:
>> exec s in {}
>> except Exception, e:
>> etype, value, tb = sys.exc_info()
>> traceback.print_exception(etype, value, tb.tb_next)
>>
>> s = """
>> def delta():
>> epsilon()
>>
>> def epsilon():
>> 1/0
>> delta()
>> """
>>
>> if __name__ == "__main__":
>> alpha()
>>
>> $ python snip_traceback3.py
>> Traceback (most recent call last):
>>   File "", line 7, in 
>>   File "", line 3, in delta
>>   File "", line 6, in epsilon
>> ZeroDivisionError: integer division or modulo by zero
>>
>> Heureka.

> Thanks for the help, Peter.  That's exactly what I need.  

Indeed. But not exactly what you want, it seems.

> Now could I
> use your tb.tb_next trick a couple times and thus avoid moving the try/
> except?

Of course you can cut off the traceback at arbitrary positions. Here's an
example that uses the filename:

import traceback
import sys

def tb_filename(tb):
return tb.tb_frame.f_code.co_filename

def tb_iter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def alpha():
try:
beta()
except Exception, e:
etype, value, tb = sys.exc_info()
filename = tb_filename(tb)
for tb in tb_iter(tb):
if tb_filename(tb) != filename:
break
traceback.print_exception(etype, value, tb)

def beta():
gamma()

def gamma():
exec s in {}

s = """ 
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

Did I mention it already? It's better to move the try ... except.

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


Re: An ordered dictionary for the Python library?

2007-09-12 Thread Chris Mellon
On 9/12/07, Mark Summerfield <[EMAIL PROTECTED]> wrote:
> On 12 Sep, 13:46, Michele Simionato <[EMAIL PROTECTED]>
> wrote:
> > On Sep 12, 2:42 pm, Steven D'Aprano <[EMAIL PROTECTED]
> >
> > cybersource.com.au> wrote:
> > > On Wed, 12 Sep 2007 07:33:45 +, Mark Summerfield wrote:
> > > In fact, I'm not sure what people mean by ordered dicts. I assume they
> > > mean the keys are ordered, not the values. But ordered by what? Insertion
> > > order? Modification order? Alphabetical order?
> >
> > Insertion order.
> >
> >  M.S.
>
>
> Actually I meant by key order, so insertion order doesn't matter at
> all. If you need a dictionary-like data structure that respects
> insertion order you could use a list of (key, value) tuples.
>

These sort of disagreements about what such a beast should "obviously"
do are a good part of the reason why one doesn't exist in the standard
library. A sorted dict is so trivial that it's not really seen as
necessary, since all you have to do is sort the keys(). An ordered
dict is generally better satisfied with a list, as you've seen.
There's implementations of all these for people who want something
wrapped up in the cookbook.


>But what happens when I need to do this a *lot* and when the number of
>items is hundreds or a few thousands?

keys = sorted(d.keys())
for k in key:
   ...

You've got two choices: either you insert more than you iterate, in
which case sorting at the point of iteration is the most efficient
option, or you iterate more than you insert, in which case sorting
after you insert is easy. There's no way that an ordered dict
implementation could satisfy both constraints. Can you honestly think
of a use case where the performance of your sorting is a bottleneck
*and* it's a suitably general case that a standard lib class should
optimize for that specific case? Even in this short thread we've seen
3 different ideas of what the dict should do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to use different font within one wxpython static text widget?

2007-09-12 Thread kyosohma
On Sep 12, 10:26 am, "hyena" <[EMAIL PROTECTED]> wrote:
> problem is as title, bear me if this too silly or too naive.
>
> I use wx.statictext widget to show some information in GUI, there are some
> numbers in the text to be emphasized in bigger other color. For example, in
> sentence "the travel speed of this car is 40 km /hour", I would like "40" to
> be bigger and in red color. I know I can use several statictext to get this
> effect. But i am quite relucktant to do so since I am quite unfamiliar with
> manageing the layout of widgets.
>
> Is there a convinient way to have this done? Thanks for any .input


Without knowing what kind of interface you're making, I can only shoot
in the dark. From your question, I would think that the FancyText
widget would suffice. Other widgets that would be harder to use would
be the StyledTextCtrl and the HtmlWindow (which I use for About
dialogs).

Check out the wxPython Demo for sample code on each of these widgets
and sizers. Also see the Wiki for tips and tricks on using Sizers.
There's a new SizedControl that's supposed to simplify creating
layouts, although I haven't used it. And there's also XRC too.

Mike

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


  1   2   3   >