Re: ConfigParser: writes a list but reads a string?

2006-01-16 Thread Sybren Stuvel
Terry Carroll enlightened us with:
> It looks like ConfigParser will accept a list to be writing to the
> *.ini file; but when reading it back in, it treats it as a string.

It doesn't say so explicitly in the manual, but I did find this:

  """The values in defaults must be appropriate for the "%()s" string
  interpolation."""

So if the defaults go through %s, perhaps all values do.

> Is there a pythonic way to read in a list from a .INI file with
> ConfigParser?

I'd pickle() the list, and store that instead. Then you can unpicle()
it and regain your list.

> I would not expect this conversion; rather, an exception when trying
> to write the list if the list is not supported.

I agree with you.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the method for class destroy

2006-01-16 Thread Fredrik Lundh
"K Satish" wrote:

>  Like __init__ which is called when object instatiated, what is the method
> when object destroys.

__del__

see http://docs.python.org/ref/customization.html (and make sure you read
the note and the warning carefully)

 



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


trap the Newwindow2 event on wxPython with IE ActiveX

2006-01-16 Thread oyster
Hi, everyone. I work on windows os and want to write a IE based webbrowser.  For I find that the only method which can handle most of the HTML standard is to embed IE object, I want to change demo\wxIEHtmlWin.py (from old wxPython) into a kind of multi-tab webbrowser( like greenbrowser, maxthon). Now the question is: how can I deal with the NewWindow2 Event? How can I get the url when a new window is to be created, and display this webpage in my app other than a new IE? That is to say:

    self.ie = wxPython.iewin.wxIEHtmlWin(self, -1)    wxPython.iewin.EVT MSHTML NEWWINDOW2(self, -1, self.OnNewWindow2)
 def OnNewWindow2(self, evt):    #how to program here?
The artilce on http://support.microsoft.com/kb/q184876/ describes "How To Use the WebBrowser Control NewWindow2 Event" in VB as
Private Sub WebBrowser1_NewWindow2(ppDisp As Object,   Cancel As Boolean)   Dim frmWB As Form1   Set frmWB = New Form1
   frmWB.WebBrowser1.RegisterAsBrowser = TRUE
   Set ppDisp = frmWB.WebBrowser1.Object   frmWB.Visible = TrueEnd Sub
Since except "self", OnNewWindow2 only need one extra parameter other that 2, I donno how to change this code into python one? 
Because I know almost nothing about VB and ActiveX, can somebody give me a ready-to-run simple demo or demo based demo\wxIEHtmlWin.py?
Thanx in adavance.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why keep identity-based equality comparison?

2006-01-16 Thread Antoon Pardon
Op 2006-01-14, Mike Meyer schreef <[EMAIL PROTECTED]>:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>>> If you
>>> want to argue that the builtin sets should do that, you can - but
>>> that's unrelated to the question of how the comparison operators
>>> behave for the rest of the bulitin types.
>> What I argue is that there is no single order for a specific type.
>
> I think that depends on your definition of type, but let it go.
>
>> There can be an order that is most usefull in general but which order
>> is usefull at a specific point depends on the context.
>
> Yes. So what? Does this fact suggest some change to Python that would
> improve it? If so, you need to mention it. If not, why bring it up at
> all?

I did mention it, you even asked a use case and I gave it. What more
do you want?

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


Arithmetic sequences in Python

2006-01-16 Thread Gregory Petrosyan
Please visit http://www.python.org/peps/pep-0204.html first.

As you can see, PEP 204 was rejected, mostly because of not-so-obvious
syntax. But IMO the idea behind this pep is very nice. So, maybe
there's a reason to adopt slightly modified Haskell's syntax? Something
like

[1,3..10]  -->  [1,3,5,7,9]
(1,3..10)  -->  same values as above, but return generator instead of
list
[1..10] -->  [1,2,3,4,5,6,7,8,9,10]
(1 ..)-->  'infinite' generator that yield 1,2,3 and so on
(-3,-5 ..)   -->  'infinite' generator that yield -3,-5,-7 and so on

So,
1) "[]" means list, "()" means generator
2) the "start" is required, "step" and "end" are optional.

Also, this can be nicely integrated with enumerations (if they will
appear in python). Haskell is also example of such integration.

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


Re: instance attributes not inherited?

2006-01-16 Thread Xavier Morel
John M. Gabriele wrote:
> I'm having a hard time finding the documentation to the super() function.
> I checked the language reference ( http://docs.python.org/ref/ref.html )
> but didn't find it. Can someone please point me to the relevant docs on
> super?
> 
> help( super ) doesn't give much info at all, except that super is actually
> a class, and calling it the way we are here returns a "bound super object",
> but I don't yet see what that means (though I know what bound methods are).
> 

Super is a bit magic, quite complicated, and some people don't like it 
(basically, super is mainly to be used in complex inheritance case with 
diamond shape hierarchies and such, to automate the method resolution 
order).

If you want to give a try at understanding "super", you should read 
Guido's `Unifying types and classes in Python 2.2`, chapters on MRO, 
super and cooperative methods 
(http://www.python.org/2.2.3/descrintro.html#mro) (nb: you may also read 
the rest of the document, it lists all the magic introduced in the 
language with 2.2).
-- 
http://mail.python.org/mailman/listinfo/python-list


FrOSCon 2006 - Call for Papers

2006-01-16 Thread M.-A. Lemburg
I'm sending this on behalf of Sebastian Bergmann, one of the
organizers of FrOSCon:

 Hello,

 The first Free and Open Source Conference "FrOSCon" takes place on 24th
 and 25th June 2006 in St. Augustin, near Bonn, Germany, Organized by a
 committed team, it aims to become a significant event for free software
 in the Rhineland. The conference is hosted by the faculty of computer
 science of the University of Applied Sciences Bonn-Rhein-Sieg in
 collaboration with the student body and the Linux/Unix User Group St.
 Augustin.

 In a Call for Papers [1], the organizers ask for submission of
 contributions. A broad variety of topics concerning free and open
 source software is desired. Particularly welcome are contributions about
 programming languages, free software on the desktop, security, systems
 administration and networks. Aspects of free software in busincess and
 industry are also a focus of the conference.

 Contributions can be submitted in English or German and should summarize
 the intended talk concisely and succinctly; talks should range from 45
 to 60 minutes in length. Deadline for submission is 15th March 2006.

 --
 [1] http://www.froscon.org/wiki/CallforPapers
 http://cfp.froscon.org/

-- 
Sebastian Bergmann  http://www.sebastian-bergmann.de/
GnuPG Key: 0xB85B5D69 / 27A7 2B14 09E4 98CD 6277 0E5B 6867 C514 B85B 5D69

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


Re: Getting better traceback info on exec and execfile - introspection?

2006-01-16 Thread R. Bernstein
Fernando Perez <[EMAIL PROTECTED]> writes:
> So any regexp-matching based approach here is likely to be fairly brittle,
> unless you restrict your tool to the standard python interpreter, and you
> get some guarantee that it will always tag interactive code with
> ''.

Meant to mention for what it's worth. Looks like I'm not the first to use the 
filename == '' test. I note this in the stock pdb.py:

# To be overridden in derived debuggers
def defaultFile(self):
"""Produce a reasonable default."""
filename = self.curframe.f_code.co_filename
if filename == '' and self.mainpyfile:
filename = self.mainpyfile
return filename

I'm not sure under what conditions this equality test normally occurs
though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ConfigParser: writes a list but reads a string?

2006-01-16 Thread Fuzzyman
ConfigObj will read and write list values.

You get all sorts of other advantages as well (nested subsections to
any depth), and the resulting code will be much simpler.

from configobj import ConfigObj
cfgfile = "cfgtest.ini"

cfg = ConfigObj(cfgfile)
t1 = range(1,11)
# no *need* to create a subsection
cfg['test'] = {}
cfg['test']['testlist'] = t1
cfg.write()

To read it back in :

from configobj import ConfigObj
cfgfile = "cfgtest.ini"

cfg = ConfigObj(cfgfile)
print cfg['test']['testlist']

http://www.voidspace.org.uk/python/configobj.html

All the best,

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

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Bas
I like the use of the colon as in the PEP better: it is consistant with
the slice notation and also with the colon operator in Matlab.

I like the general idea and I would probably use it a lot if available,
but the functionality is already there with range and irange.

Bas

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


Re: New Python.org website ?

2006-01-16 Thread Tim Parkin
JW wrote:
> On Sun, 15 Jan 2006 22:19:37 +, Tim Parkin wrote:
> 
> 
>>http://pyyaml.org/downloads/masterhtml/
>>
>>Feedback appreciated ... Many thanks
> 
> 
> Again, with FF 1.0.7 (on FC4 Linux BTW), the left column no longer
> violates the right.  However, "View>Page Style>large text" makes the
> button annotation smaller than "View>Page Style>Basic Page Style".
> 
> Please understand, web programming is not my main axe.  I'm in no way
> asserting my observations are meaningful ;).
> 

Yep... I haven't tweaked that one yet :-) good to know it's not breaking
though, many thanks for the feedback.

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


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Antoon Pardon
Op 2006-01-15, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Sun, 15 Jan 2006 12:14:16 +0100, Fredrik Lundh wrote:
>
>>> Do two instances of Empty have the same value, or is the question
>>> meaningless?
>> 
>> Things are a bit mixed up wrt. old-style classes (because they're
>> implemented in terms of true objects), but if you make that
>> 
>> >>> class Empty(object):
>> ... __slots__ = []
>> ...
>> 
>> it should be clear that instances of this class have no value (or if you
>> prefer, the set of values is empty for all instances), and cannot have
>> one either.
>
> But that's the thing, it isn't clear to me at all that they have no value.
> Does the empty string have a value? I would say yes. How about {} and []?
> Again, I would say yes. So why do None and Empty() have no value?
>
> It took mathematicians centuries to stop arguing about whether 0 is a
> number or not, and then they argued whether or not 1 is a number. And
> then when they settled that both 0 and 1 are numbers, they argued
> whether the empty set counted as a set or not. So I'm not surprised that
> we don't see eye-to-eye here.
>
> I think part of the reason is that you are thinking at one abstract level,
> where objects have a type, an identity, and "everything else", and you
> DEFINE that "everything else" as "value". By that definition, if there is
> nothing else, then there is no value. I can understand that, but I also
> think that there is a different sense of "value" for which it makes sense
> to include type and/or identity as part of the value. The alternative, it
> seems to me, is to conclude that empty strings, dicts, lists and tuples
> all are equally valueless, and I don't think that is a good idea.
>
> The downside of my definition of "value" is that it is fuzzy and depends
> on context. Often we want to exclude type (so that 1 and 1.0 have the
> same value),

We don't need to. We could look at == as being an "is equivallent with"
relationship. So 1 and 1.0 are not the same (value) but they are
equivallent (in an arithmetic context).

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


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Antoon Pardon
Op 2006-01-14, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Sat, 14 Jan 2006 14:14:01 +, Antoon Pardon wrote:
>
>> On 2006-01-14, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>>> On Thu, 12 Jan 2006 16:11:53 -0800, rurpy wrote:
>>>
 It would help if you or someone would answer these
 five questions (with something more than "yes" or "no" :-)
 
 1. Do all objects have values?
>>>
>>> All objects ARE values. Some values themselves are complex objects
>>> which in turn contain other values, e.g. if I execute:
>> 
>> I don't agree with this wording. If a mutable object mutates it
>> is still the same object but is's value has changed.
>
> Yes. And this is a problem why?

It is not about problems, it is about precision of language.
You can't state that an object *is* a value if different
values can be associated with the same object.

> Some values are fixed, and some values are
> changeable.

No values are not changeable. Objects (through mutation)
aquiring a new value is not the same as changable values.

>> So I would agree with: objects have values.
>
> I don't believe this is a useful distinction to make.
>
>>> L = [None, 1, "hello"]
>>>
>>> I have created a name 'L' which is bound to ("has the value of") a list
>>> with three items. The first item has the value of ("is the object") None,
>>> the second has the value of ("is the object") 1, and the third is the
>>> string "hello".
>> 
>> But if you execute L.append(False) then L is still the same object
>> but it's value is different.
>
> Yes. Values can change. So what? 

No values don't change. Objects can mutate and thus can aquire a new
value. Yes we often use language that states: The value changes, but
that is just a shortcut, just as we speak of hearing a train instead
of hearing the sound of a train.

If you say an object is a value, that would imply that two lists
with the same value would also be the same list. 

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Paul Rubin
"Gregory Petrosyan" <[EMAIL PROTECTED]> writes:
> As you can see, PEP 204 was rejected, mostly because of not-so-obvious
> syntax. But IMO the idea behind this pep is very nice. So, maybe
> there's a reason to adopt slightly modified Haskell's syntax? 

I like this with some issues: Python loops tend to be 0-based, so
while it's convenient to express the sequence [1..n], what you usually
want is [0..(n-1)] which is uglier.

If you want to count down from f(n) to zero, in Haskell you might say

  [b, b-1 .. 0] where b=f(n)

There's no "where" in Python, so what do you do?

  [f(n)-1, f(n)-2 .. 0]

evaluates f twice (and might not even get the same result both times),
while the traditional

  xrange(f(n)-1, -1, -1)

only evaluates it once but is IMO repulsive.

Anyway I've never liked having to use range or xrange to control
Python loops.  It's just kludgy and confusing.  So I think your idea
has potential but there's issues that have to be worked out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread Gregory Petrosyan
_Consistentsy_ is what BDFL rejects, if I understand pep right. As for
me, it's not too god to have similar syntax for really different tasks.
And [1:10] is really not obvious, while [1..10] is.

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


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Antoon Pardon
Op 2006-01-14, Mike Meyer schreef <[EMAIL PROTECTED]>:
> Paul Rubin  writes:
>> Mike Meyer <[EMAIL PROTECTED]> writes:
>>> > Whether the '==' operation conforms to your idea of what equality
>>> > means is unclear.
>>> Care to say what it does mean, then?
>> I'd say a==b doesn't necessarily mean a and b have the same value.
>
> Care to say what it does mean (as opposed to what it doesn't mean), then?

I would say: "is equivallent with".

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


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Antoon Pardon
Op 2006-01-14, Mike Meyer schreef <[EMAIL PROTECTED]>:
> "Donn Cave" <[EMAIL PROTECTED]> writes:
>> |> 3. If two objects are equal with "==", does that
>> |>   mean their values are the same?
>> Yes.
>> | >>> 3.0 == 3
>> | True
>> Evidently the value of 3.0 is the same as the value of 3.
>
> And they do. They are two different representations of the same
> value. More in another thread.

I would say they are two different values that are equivallent
in a lot of ways.

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


OT: excellent book on information theory

2006-01-16 Thread Paul Rubin
I came across this while looking up some data compression info today.

David J.C. MacKay
Information Theory, Inference, and Learning Algorithms

Full text online:
http://www.inference.phy.cam.ac.uk/mackay/itila/

It's a really excellent book, on the level of SICP but about
information theory, probability, error correcting codes, etc.  Very
readable, and geeky (in a good way) at the same time.  The writing
style is perhaps along the lines of "Numerical Recipes", though the
format is more conventional.

The whole text is online as a pdf, which is very nice.  The printed
version is somewhat expensive, but according to the following analysis
it's a better bargain than "Harry Potter and the Philosopher's Stone":

http://www.inference.phy.cam.ac.uk/mackay/itila/Potter.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML Writer in wxPython

2006-01-16 Thread Marco Meoni
Could you post an example please?
Thanks!

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


how to handle jpg images with Tkinter

2006-01-16 Thread K Satish
Hi,     I am not able to load jpg images in photoimage widget. That is showing different different errors. can I find any examples on internet.      Thanks,  SatishSend instant messages to your online friends http://in.messenger.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: [ANN] pysqlite 2.1.0 released

2006-01-16 Thread Gerhard Häring
Alex Martelli wrote:
> Gerhard Häring <[EMAIL PROTECTED]> wrote:
>...
> 
>>An optimized shortcut has been enabled to retrieve Unicode strings for
>>non-ASCII data, but bytestrings for non-ASCII text:
>>
>>con.text_factory = sqlite.OptimizedUnicode
> 
> 
> I assume you mean "ASCII text" rather than "non-ASCII text" here?

You're right. I stole this idea from APSW, another SQLite wrapper, which 
does this by default in order to reduce memory usage and increase 
performance a little bit for the common use case of ASCII text.

You might argue that that this is premature optimization, but things 
like this do make a difference if you process a lot of text.

Using this feature should be pretty compatible to the default of always 
using Unicode, because `unicode` and `str` have pretty much the same 
interface. But I wasn't 100 % sure, so I kept the old pysqlite default 
of Unicode only and made the optimized case using OptimizedUnicode an 
option.

> At any rate, my compliments for a new release (which looks great!) of a
> most excellent module!

Thanks :-)

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


Re: proposal: another file iterator

2006-01-16 Thread Bengt Richter
On 15 Jan 2006 18:58:53 -0800, Paul Rubin  wrote:

>Jean-Paul Calderone <[EMAIL PROTECTED]> writes:
>> Which is only very slightly longer than your version.  I would like
>> it even more if iter() had been written with the impending doom of
>> lambda in mind, so that this would work:
>> 
>> for chunk in iter('', f.read, blocksize):
>> ...
>> 
>> But it's a bit late now.
>
>Well, iter could be extended to take *args and **kwargs parameters, so
>you'd say
>
>for chunk in iter(f.read, '', (blocksize,)): ...
>
Whatever "Which" refers to got snipped or may be in a post that hasn't
become visible for me yet, but I assume Jean-Paul was referring to lambda use
as in e.g. (untested):

 for chunk in iter(lambda frd=open('yerf', 'rb').read:frd(blocksize), ''): 
...

Does it not do what you want?

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


Class __init__ trouble

2006-01-16 Thread SkyRanger
I create class:

  FOClassName:= PyString_FromString(ClasName);
  FClass:= PyClass_New(nil, FDict, FOClassName);
  PyDict_SetItemString(FDict, ClasName, FClass);
  Py_DECREF(FOClassName);
  Py_DECREF(FDict);
  Py_DECREF(FClass);

Add methods for it:

  MyFunc:=PyCFunction_New(MyMethod, nil);
  MyMeth:=PyMethod_New(MyFunc, nil, FClass);
PyDict_SetItemString(FDict, AMethodName, MyMeth);
  Py_DECREF(MyFunc);
  Py_DECREF(MyMeth);

I place all it in my Delphi class and then create 1 class:


pyGL_Class:=TPythonClass.Create(Python.PyScript.GetPyDict,'pySky3D_Window');
  pyGL_Class.AddClassMethod('__init__',pyWindowClassInit,'');
  pyGL_Class.AddClassMethod('_Show',pyWindowShow,'');
  pyGL_Class.AddClassMethod('_Hide',pyWindowHide,'');
  pyGL_Class.AddClassMethod('_OnMouseOver',pyOnMouseOver,'');

  pyGL_Class.AddClassProperty('_Win_id','winid');
  pyGL_Class.AddClassProperty('_Winpos_x',0);
  pyGL_Class.AddClassProperty('_Winpos_y',0);
  pyGL_Class.AddClassProperty('_Win_width',0);
  pyGL_Class.AddClassProperty('_Win_height',0);
  pyGL_Class.AddClassProperty('_Win_header','window header');
  pyGL_Class.AddClassProperty('_Visible',0);
  pyGL_Class.Free;


#Class defining window
class Sky3D_Windows(sky3d.pySky3D_Window):
def test(self):
print "Hello"
def _OnMouseOver(self):
#self._Hide()
pass

MouseCursWin=Sky3D_Windows('CMouseWin','MouseWinFunc',400,300,100,100,'Mouse','font5')

All work fine, but if i add new class same way

{pySky3D_Button}

pyGL_Class:=TPythonClass.Create(Python.PyScript.GetPyDict,'pySky3D_Button');

pyGL_Class.AddClassMethod('pySky3D_Button.__init__',pyButtonClassInit,'');

  pyGL_Class.AddClassProperty('_Btn_id','Button_id');
  pyGL_Class.Free;

it give me error:

Traceback (most recent call last):
File "D:\sky3d\src\script\sky3d.py", line 32, in OnInit

from window import *
File "D:\sky3d\src\script\window.py", line 18, in ?

CoordWin=Sky3D_Windows('CoordWin','CoordWinFunc',15,Sky3D_GetMainWinRec()[1]
- (250),150,200,'Camera','font5')
TypeError
:
unbound method __init__() must be called with pySky3D_Button instance
as first argument (got str instance instead)

I to little know class embeding in Python, but suspect that __init__
become base for all classes??? Or what? In documentation i did not find
info about PyClass_New and other. But it says that i must some how use
instance of class, but i can't understand how i can get instance non
created class...

Full source in https://opensvn.csie.org/sky3d
or here 
https://opensvn.csie.org/traccgi/sky3d

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


Re: instance attributes not inherited?

2006-01-16 Thread Bengt Richter
On Sun, 15 Jan 2006 20:37:36 -0500, "John M. Gabriele" <[EMAIL PROTECTED]> 
wrote:

>David Hirschfield wrote:
>> Nothing's wrong with python's oop inheritance, you just need to know 
>> that the parent class' __init__ is not automatically called from a 
>> subclass' __init__. Just change your code to do that step, and you'll be 
>> fine:
>> 
>> class Parent( object ):
>> def __init__( self ):
>> self.x = 9
>> 
>> 
>> class Child( Parent ):
>> def __init__( self ):
>> super(Child,self).__init__()
Nit: Someone is posting with source using tabs ;-/ The above super should be 
indented from def.
>>print "Inside Child.__init__()"
>> 
>> -David
>> 
>
>How does it help that Parent.__init__ gets called? That call simply
>would create a temporary Parent object, right? I don't see how it
Wrong ;-) Calling __init__ does not create the object, it operates on an
object that has already been created. There is nothing special about
a user-written __init__ method other than the name and that is is automatically
invoked under usual conditions. Child.__new__ is the method that creates the 
instance,
but since Child doesn't have that method, it gets it by inheritance from 
Parent, which
in turn doesn't have one, so it inherits it from its base class (object). 

>should help (even though it *does* indeed work).
>
>Why do we need to pass self along in that call to super()? Shouldn't
>the class name be enough for super() to find the right superclass object?
self is the instance that needs to appear as the argument of the __init__ call,
so it has to come from somewhere. Actually, it would make more sense to leave 
out
the class than to leave out self, since you can get the class from type(self) 
for
typical super usage (see custom simple_super at end below [1])

 >>> class Parent( object ):
 ... def __init__( self ):
 ... self.x = 9
 ... print 'Inside Parent.__init__()'
 ...
 >>> class Child( Parent ):
 ... def __init__( self ):
 ... sup = super(Child,self)
 ... sup.__init__()
 ... self.sup = sup
 ... print "Inside Child.__init__()"
 ...
 >>> c = Child()
 Inside Parent.__init__()
 Inside Child.__init__()
 >>> c.sup
 , >

sup is an object that will present an attribute namespace that it implements
by looking for attributes in the inheritance hierarchy of the instance argument 
(child)
but starting one step beyond the normal first place to look, which is the 
instance's class
that was passed to super. For a normal method such as __init__, it will form 
the bound method
when you evaluate the __init__ attribute of the super object:

 >>> c.sup.__init__
 >

a bound method has the first argument bound in, and when you call the bound 
method
without an argument, the underlying function gets called with the actual first 
argument (self).

 >>> c.sup.__init__()
 Inside Parent.__init__()

The method resolution order lists the base classes of a particular class in the 
order they
will be searched for a method. super skips the current class, since it is 
shadowing the rest.
The whole list:

 >>> type(c).mro()
 [, , ]

Skipping to where super will start looking:
 >>> type(c).mro()[1]
 

If you get the __init__ attribute from the class, as opposed to as an
attribute of the instance, you get an UNbound method:

 >>> type(c).mro()[1].__init__
 

which can be called with the instance as the first argument:

 >>> type(c).mro()[1].__init__(c)
 Inside Parent.__init__()

If you want to, you can access the actual function behind the unbound method:

 >>> type(c).mro()[1].__init__.im_func
 

And form a bound method:

 >>> type(c).mro()[1].__init__.im_func.__get__(c, type(c))
 >

Which you can then call, just like we did sup.__init__ above:

 >>> type(c).mro()[1].__init__.im_func.__get__(c, type(c))()
 Inside Parent.__init__()


Another way to spell this is:

 >>> Parent.__init__.im_func
 
 >>> Parent.__init__.im_func.__get__(c, type(c))
 >
 >>> Parent.__init__.im_func.__get__(c, type(c))()
 Inside Parent.__init__()

Or without forming the unbound method and using im_func to
get the function (looking instead for the __init__ function per se in the 
Parent class dict):

 >>> Parent.__dict__['__init__']
 
 >>> Parent.__dict__['__init__'].__get__(c, type(c))
 >
 >>> Parent.__dict__['__init__'].__get__(c, type(c))()
 Inside Parent.__init__()

An attribute with a __get__ method (which any normal function has) is a
descriptor, and depending on various logic will have its __get__ method
called with the object whose attribute is apparently being accessed.
Much of python's magic is implemented via descriptors, so you may want
to read about it ;-)

[1] If we wanted to, we could write our own simple_super. E.g.,

 >>> class simple_super(object):
 ... def __init__(self, inst): self.inst = inst
 ... def __getattribute__(self, attr):
 ... inst = object.__getattribute__(self, 'inst')
 ... try: return getattr(type(inst).mro()[1], attr).im_func.__get__(
 ...  

strange (and orrible) behavior in gtk.CellRendererCombo using pygtk

2006-01-16 Thread _v_tiziano
Hi folks!

I notice a strange (and orrible) behavior in gtk.CellRendererCombo.

My code work trapping the 'edited' signal to store in a temporary
buffer before the "save all" operation (by clicking a save-button).
The is that gtk.CellRendererCombo (unlike gtk.CellRendererEntry, and
others...) dont emit the 'edited' signal when the user click on a
widget outside the gtk.TreeView, but only clicking on another cell in
same TreeView.

It's possible? There's a good reason?

thak's a lot
tiziano
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing class methods from being defined

2006-01-16 Thread Steven D'Aprano
On Sun, 15 Jan 2006 18:41:02 -0800, David Hirschfield wrote:

> Here's a strange concept that I don't really know how to implement, but 
> I suspect can be implemented via descriptors or metaclasses somehow:
> 
> I want a class that, when instantiated, only defines certain methods if 
> a global indicates it is okay to have those methods.

Others have already made suggestions, here is a third:


class A:
def foo(self):
print "Foo!"
def bar(self):
print "Bar!"
def baz(self):
print "Baz!"
__all__ = [x.__name__ for x in (foo, bar, baz)]
def __null(self, name="", *args, **kwargs):
raise NameError("Method '%s' was disabled at init time." % name)
def __init__(self, data=None):
global permitted # not strictly needed, but I prefer it 
for method in self.__all__:
if method not in permitted:
# if you are clever, use currying to bind the name of 
# the method to the first arg of __null so it gives a 
# more useful error message
setattr(self, method, self.__null)
# local initialisation
self.x = data


The main disadvantage of this I can see is that dir(A()) still reports
methods foo, bar, baz even if they have been disabled. But maybe that's
better behaviour than just making them disappear (principle of least
surprise: better to explicitly report that something is disabled than to
just have it magically appear and disappear).


-- 
Steven.

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


Posting examples with tabs

2006-01-16 Thread Duncan Booth
Bengt Richter wrote:

> Nit: Someone is posting with source using tabs

Which reminds me: can anyone tell me how to configure idle so that the 
shell has tabs disabled by default?

The editor defaults to not using tabs, and I can toggle the setting from 
the options dialog, but the shell has tab use turned on and so far as I can 
see it is hardwired (it can be toggled at runtime, or I can edit PyShell.py 
but I feel there ought to be a configuration setting to turn tabs off 
only I can't find one).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Bengt Richter
On 15 Jan 2006 13:50:14 -0800, Paul Rubin  wrote:

>Mike Meyer <[EMAIL PROTECTED]> writes:
>> > I'd say a==b doesn't necessarily mean a and b have the same value.
>> Care to say what it does mean (as opposed to what it doesn't mean), then?
>
>a==b simply means that a.__eq__(b) returns True.  
That's one possibility, but I guess __eq__ might not necessarily
even have to be defined (too lazy to set up the new-style class test ;-):

 >>> class A:
 ... def __getattr__(self, attr): print 'A().%s'%attr; raise AttributeError
 ...
 >>> class B:
 ... def __getattr__(self, attr): print 'B().%s'%attr; raise AttributeError
 ...
 >>> A()==B()
 A().__eq__
 B().__eq__
 B().__eq__
 A().__eq__
 A().__coerce__
 B().__coerce__
 A().__cmp__
 B().__cmp__
 False

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


Re: More than you ever wanted to know about objects

2006-01-16 Thread Boris Borcic
Mike Meyer wrote :
> 
> For even more fun, consider 1.0 == 1 == decimal.Decimal('1.0').
> 

Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
 >>> import decimal
 >>> 1 == 1.0 == decimal.Decimal('1.0')
False
 >>> decimal.Decimal('1.0') == 1 == 1.0
True

MM, painful
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread Steven D'Aprano
On Mon, 16 Jan 2006 01:01:39 -0800, Gregory Petrosyan wrote:

> Please visit http://www.python.org/peps/pep-0204.html first.
> 
> As you can see, PEP 204 was rejected, mostly because of not-so-obvious
> syntax. But IMO the idea behind this pep is very nice. So, maybe
> there's a reason to adopt slightly modified Haskell's syntax? Something
> like
> 
> [1,3..10]  -->  [1,3,5,7,9]

-1 on the introduction of new syntax. Any new syntax.

(I reserve the right to change my mind if somebody comes up with syntax
that I like, but in general, I'm *very* negative on adding to Python's
clean syntax.)

For finite sequences, your proposal adds nothing new to existing
solutions like range and xrange. The only added feature this proposal
introduces is infinite iterators, and they aren't particularly hard to
make:

def arithmetic_sequence(start, step=1):
yield start
while 1:
start += step
yield start

The equivalent generator for a geometric sequence is left as an exercise
for the reader.

If your proposal included support for ranges of characters, I'd be more
interested.



-- 
Steven.

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


Re: Is 'everything' a refrence or isn't it?

2006-01-16 Thread Steven D'Aprano
On Mon, 16 Jan 2006 10:34:40 +, Bengt Richter wrote:

>  >>> class A:
>  ... def __getattr__(self, attr): print 'A().%s'%attr; raise 
> AttributeError
>  ...
>  >>> class B:
>  ... def __getattr__(self, attr): print 'B().%s'%attr; raise 
> AttributeError
>  ...
>  >>> A()==B()
>  A().__eq__
>  B().__eq__
>  B().__eq__
>  A().__eq__
>  A().__coerce__
>  B().__coerce__
>  A().__cmp__
>  B().__cmp__
>  False

Why are A().__eq__ and B().__eq__ both being called twice?


-- 
Steven.

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> For finite sequences, your proposal adds nothing new to existing
> solutions like range and xrange.

Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).

> The only added feature this proposal
> introduces is infinite iterators, and they aren't particularly hard to
> make:
> 
> def arithmetic_sequence(start, step=1):
> yield start
> while 1:
> start += step
> yield start

Well, that would be itertools.count(start, step) but in general a simple
expression is nicer than 5 lines of code.

> If your proposal included support for ranges of characters, I'd be more
> interested.

There's something to be said for that.  Should ['a'..'z'] be a list or
a string?
-- 
http://mail.python.org/mailman/listinfo/python-list


Socket Programming HOWTO example

2006-01-16 Thread Marco Meoni
Hi. I read the Gordon McMillan's "Socket Programming Howto".
I tried to use the example in this howto but this doesn't work.
The code is class mysocket:
'''classe solamente dimostrativa
  - codificata per chiarezza, non per efficenza'''
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(host, port):
self.sock.connect((host, port))
def mysend(msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError, \\
"connessione socket interrotta"
totalsent = totalsent + sent
def myreceive():
msg = ''
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError, \\
"connessione socket interrotta"
msg = msg + chunk
return msg
 
How can i use this?
Thanks all!
Marco

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


Linking to Python for Windows CE

2006-01-16 Thread Martin Evans
I've just been tasked with porting our desktop embedded Python support 
onto our existing CE offering. I've managed to compile the Python 
sources and have produced an armdbg420\python23.lib file.

When I come to link to the Python library though from our one of our 
DLLs, I am getting the following unresolved externals:

---
embedded.obj : error LNK2019: unresolved external symbol
"__declspec(dllimport) int __cdecl WinCE_fclose(void *)"
(__imp_?WinCE_fclose@@[EMAIL PROTECTED]) referenced in function "unsigned long
__cdecl PythonThread(void *)" (?PythonThread@@[EMAIL PROTECTED])

embedded.obj : error LNK2019: unresolved external symbol __imp_LoadLibraryU
referenced in function "unsigned long __cdecl PythonThread(void *)"
(?PythonThread@@[EMAIL PROTECTED])

embedded.obj : error LNK2019: unresolved external symbol
"__declspec(dllimport) void * __cdecl WinCE_fopen(char const *,char const
*)" (__imp_?WinCE_fopen@@[EMAIL PROTECTED]) referenced in function "void * 
__cdecl
OpenScriptFile(unsigned short *)" (?OpenScriptFile@@[EMAIL PROTECTED])

---

python23.lib does have entries for WinCE_fopen (part of 
wince-compatibility.c) when looking at the lib file using dumpbin (all 
are undecorated). Have I missed some vital step in producing it?


Just to clarify my environment, I am producing a PocketPC 2003 
application that embeds Python, scripts are launched within our 
application with script output displayed in our own output window. We 
also provide our own Python extension library. All works on ok on the 
desktop version.

Any help would gratefully appreciated. Thanks.

Martin

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


Re: More than you ever wanted to know about objects [was: Is everything a refrence or isn't it]

2006-01-16 Thread Boris Borcic
Tim Peters a écrit :
> [Alex Martelli]
> ...
>>> In mathematics, 1 is not "the same" as 1.0 -- there exists a natural
>>> morphism of integers into reals that _maps_ 1 to 1.0, but they're still
>>> NOT "the same" thing.  And similarly for the real-vs-complex case.

- but does there exists any sense of "mathematics object identity" 
that's not built out of similar maps ? IOW, if - abstracting from your 
example - I admit as a rule that is sufficient to deny identity, to 
point out that two objects are "merely" related by a natural map, isn't 
it then the case that I can display an infinite quantity of *distinct* 
clones of any mathematical object or structure that I can think of ?

Smallscale python illustration :

 >>> 2<<100
2535301200456458802993406410752L
 >>> 2<<100 is 2<<100
False

> [Xavier Morel]
>> I disagree here, 1 and 1.0 are the same mathematical object e.g. 1 (and
>> the same as "1+0i"), the difference due to notation only makes sense in
>> computer science where integers, real and complex ensembles are disjoin.
>> In mathematics, Z is included in IR which is included in C (note: this
>> is not mathspeak, but I have no idea how to say it in english), and this
>> notation -- at best -- merely determines the ensemble you're currently
>> considering.
>>
>> There is no "natural morphism" of integers into reals because there is
>> no mathematical difference between integers and reals, the real ensemble
>> is merely a superset of the integers one.

Well, how do you know there should be a difference between
(a) "(there exists) a natural morphism from A to B"
(b) "A is a subset of B"
? To paraphrase you : "the 'natural morphism' ensemble is merely a 
superset of the 'subset/superset' one"

More to the point, where you view really breaks is when two incompatible 
extensions of the number tower are possible, like what happens with 
complex numbers and surreal numbers, which are both rich extensions of 
real numbers. Or real numbers and transfinite cardinals, viewed both as 
extending natural numbers.

>>
>> Or so it was last time i got a math course.
> 
> This all depends on which math course you last took ;-)

I often wonder whether young and adventurous minds could be more 
efficiently seduced to mathematics by enlisting them to interstellar travel.

The idea goes thus. First note that by adjusting (natural) language 
courses one may end up with home-grown pupils equivalent to pupils taken 
from another continent; for instance you may teach arab to young 
americans and obtain something more in the likeness of an arab.

Then argue that by adjusting the mathematics curriculum, one may obtain 
similar effects, but with displacements on the scale of interstellar 
travel rather than intercontinental travel !

[Tim Peters]
> You have more a physicist's view here.  The simplest case is real versus 
> complex,
> where even a physicist  can accept that a complex number,
> formally, is an ordered pair of real numbers.

Well, I suppose you've heard of Paul Erdoes's notion of a "Supreme 
Fascist" dictator of mathematics who owns a Book of All the Best Proofs ?

It's easy to extend Him with a -WarpDrive- method of the form "Any 
teacher teaching A before B shall be sentenced to death".

The spacedrive effect would be obtained by an appropriate choices of A 
and B divergent from our current habits. Of course one could expect many 
choices to lead nowhere - or at least to rough rides. But, I surmise 
that a promising and most fascinating pick would be A=real, B=complex.

...
> in a computer all numerics suck,

Sets suck.

Cheers, BB
--
666 ?? -- 666 ~ .666 ~ 2/3 ~  1 - 1/3  ~ tertium non datur
   ~ the excluded middle
   ~ "either with us, or against us" !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing class methods from being defined

2006-01-16 Thread Dan Sommers
On Mon, 16 Jan 2006 21:25:50 +1100,
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Sun, 15 Jan 2006 18:41:02 -0800, David Hirschfield wrote:
>> Here's a strange concept that I don't really know how to implement, but 
>> I suspect can be implemented via descriptors or metaclasses somehow:
>> 
>> I want a class that, when instantiated, only defines certain methods if 
>> a global indicates it is okay to have those methods.

> Others have already made suggestions, here is a third:


> class A:
> def foo(self):
> print "Foo!"
> def bar(self):
> print "Bar!"
> def baz(self):
> print "Baz!"
> __all__ = [x.__name__ for x in (foo, bar, baz)]
> def __null(self, name="", *args, **kwargs):
> raise NameError("Method '%s' was disabled at init time." % name)
> def __init__(self, data=None):
> global permitted # not strictly needed, but I prefer it 
> for method in self.__all__:
> if method not in permitted:
> # if you are clever, use currying to bind the name of 
> # the method to the first arg of __null so it gives a 
> # more useful error message
> setattr(self, method, self.__null)
> # local initialisation
> self.x = data


> The main disadvantage of this I can see is that dir(A()) still reports
> methods foo, bar, baz even if they have been disabled. But maybe
> that's better behaviour than just making them disappear (principle of
> least surprise: better to explicitly report that something is disabled
> than to just have it magically appear and disappear).

By the principle of least surprise, if dir(some_sobject) contains foo,
then some_object.foo should *not* raise a NameError.

All of the posted solutions to the OP's problem could easily be extended
to do something noisy with the (dis-)allowed methods.

Regards,
Dan

-- 
Dan Sommers

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Xavier Morel
Paul Rubin wrote:
> There's something to be said for that.  Should ['a'..'z'] be a list or
> a string?
To me, the most obvious result would be either a range object as a 
result, or always a list/generator of objects (to stay perfectly 
consistent). If a range of numbers translate into a list of numbers, 
then a range of characters should likewise translate to a list of 
characters, and a join would be required to get a regular string. This 
also adds more consistency between the two proposals of the initial post 
(e.g. list-based range and generator-based range), for while the 
list-based range could be expanded into a string a generator-based one 
couldn't/shouldn't, and the abstraction breaks (because two constructs 
that should be more or less equivalent become extremely different and 
can't be swapped transparently).

This would also be consistent with other languages providing a native 
"range" object such as Ruby or or Ada ranges.

The only thing that bothers me about the initial proposal is that there 
would not, in fact, be any "range object", but merely a syntactic sugar 
for list/generator creation. Not that I really mind it, but, well, 
syntactic sugar for the purpose of syntactic sugar really doesn't bring 
much to the table.

For those who'd need the (0..n-1) behavior, Ruby features something that 
I find quite elegant (if not perfectly obvious at first), (first..last) 
provides a range from first to last with both boundaries included, but 
(first...last) (notice the 3 periods) excludes the end object of the 
range definition ('a'..'z') is the range from 'a' to 'z' while 
('a'...'z') only ranges from 'a' to 'y').
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing a substring from a string

2006-01-16 Thread Peter Hansen
ankit wrote:
> I am using mainstr.replace(substr, "") but it gives me additional
> carriage returns which leads to empty spaces as follows:

The .replace() method does *not* introduce additional carriage returns 
(nor newlines/linefeeds, which is probably what you meant).  If you 
think it does, your tests are flawed or you are misinterpreting what is 
happening.

Maybe start with a simpler test case, and make use of repr() on your 
output to let you compare the input and output more accurately.

If you still think newlines are being introduced, please post the 
*actual code* you are using.  Do not just retype it: cut and paste it so 
we know it's reliable.

(I tried with what you posted, and after correcting for the missing 
quotation mark when you defined substr, I get the results you wanted, 
not what you showed.)

-Peter

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


Re: Linking to Python for Windows CE

2006-01-16 Thread Martin Evans
Sorry, false alarm.  It turned out one of my own files was using 
fopen/fclose and this was upseting things. After removing those it 
linked fine.

Martin Evans wrote:

> I've just been tasked with porting our desktop embedded Python support 
> onto our existing CE offering. I've managed to compile the Python 
> sources and have produced an armdbg420\python23.lib file.
> 
> When I come to link to the Python library though from our one of our 
> DLLs, I am getting the following unresolved externals:
> 
> ---
> embedded.obj : error LNK2019: unresolved external symbol
> "__declspec(dllimport) int __cdecl WinCE_fclose(void *)"
> (__imp_?WinCE_fclose@@[EMAIL PROTECTED]) referenced in function "unsigned long
> __cdecl PythonThread(void *)" (?PythonThread@@[EMAIL PROTECTED])
> 
> embedded.obj : error LNK2019: unresolved external symbol __imp_LoadLibraryU
> referenced in function "unsigned long __cdecl PythonThread(void *)"
> (?PythonThread@@[EMAIL PROTECTED])
> 
> embedded.obj : error LNK2019: unresolved external symbol
> "__declspec(dllimport) void * __cdecl WinCE_fopen(char const *,char const
> *)" (__imp_?WinCE_fopen@@[EMAIL PROTECTED]) referenced in function "void * 
> __cdecl
> OpenScriptFile(unsigned short *)" (?OpenScriptFile@@[EMAIL PROTECTED])
> 
> ---
> 
> python23.lib does have entries for WinCE_fopen (part of 
> wince-compatibility.c) when looking at the lib file using dumpbin (all 
> are undecorated). Have I missed some vital step in producing it?
> 
> 
> Just to clarify my environment, I am producing a PocketPC 2003 
> application that embeds Python, scripts are launched within our 
> application with script output displayed in our own output window. We 
> also provide our own Python extension library. All works on ok on the 
> desktop version.
> 
> Any help would gratefully appreciated. Thanks.
> 
> Martin
> 

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


Re: ConfigParser: writes a list but reads a string?

2006-01-16 Thread Frithiof Andreas Jensen

"Terry Carroll" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> It looks like ConfigParser will accept a list to be writing to the
> *.ini file; but when reading it back in, it treats it as a string.

ConfigParser is nasty because it does not really support type conversions
but still permits writing incompatible types to the configuration - i.e. the
conversions are generally one-way. It probably will croak on Floats in the
same way. The "string interpolation" works in mysterious ways too.

If you need ConfigParser to work then let every config item be strings and
convert manually as necessary.

> Is there a pythonic way to read in a list from a .INI file with
> ConfigParser?  Is this expected behavior for ConfigParser?

Not in the way we normally use "expected" - but with ConfigParser it is to
be expected ;-)

> I would
> not expect this conversion; rather, an exception when trying to write
> the list if the list is not supported.
>

If you want both text format config files and types that work then use
"ZConfig" instead.

PS:

ZConfig has no built-in way of writing a configuration - but this is not a
severe limitation: If the configuration is split into a "static-", which get
updated before a run and a "state-" set of files with things that are
changed by the application it is easier to keep the configuration consistent
anyway (it is not so hard to dump a dict into a ZConfig format).


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


Re: Linking to Python for Windows CE

2006-01-16 Thread Fuzzyman
There are modified Python sources for Windows CE via the sourceforge
site :

http://sourceforge.net/projects/pythonce

There is now a rudimentary website :

http://pythonce.sf.net

It seems like this project now has traction again. The source has to be
'hacked' quite a bit to compile for Windows CE and there was concern
about moving the macros required to do this into the main source, which
is why it is a separate project.

The current latest version is 2.3.5 - but this may change soon.

All the best,

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

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


Re: ConfigParser: writes a list but reads a string?

2006-01-16 Thread Fuzzyman
Note that ConfigObj also supports type conversion via the ``validate``
module which comes with it. This validates a config file against an
(optional) ``configspec`` which you supply, and does all the
conversion. It reports any errors it encounters.

Syntax for reading and writing is a standard 'ini-like' format with an
extended syntax for nested sections. The major differences are that you
can have values in the root section, and you should use '=' as the
``keyword = value`` divider.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/configobj.html

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


Re: Linking to Python for Windows CE

2006-01-16 Thread Fuzzyman
Hmmm... looks like you're already using this. Sorry.

All the best,

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

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


boost.python on Debian

2006-01-16 Thread Joe bloggs
Can anyone tell me how to get boost.python to work on Debian Sarge?
When I try to build the tutorial hello world example bjam reports:

/usr/share/doc/libboost-doc/examples/libs/python/example/boost-build.jam
attempted to load the build system by invoking

'boost-build ../../../tools/build/v1 ;'

but we were unable to find "bootstrap.jam" in the specified directory or
in BOOST_BUILD_PATH (searching 
/usr/share/doc/libboost-doc/examples/libs/python/example/../../../tools/build/v1,
/usr/share/boost-build).

I have looked for 'bootstrap.jam' but it doesn't exist on my system. 
I suppose that the Debian boost package doesn't have the same structure as
the official one, and is missing some files. 
Can anyone tell me how to fix this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Trying to generate a list of the subclasses of C

2006-01-16 Thread Charles Krug
List:

I have this:

# classC.py

class C(object): pass

class D(C): pass

class E(C): pass

def CSubclasses():
for name in dir(): pass

I'm trying to create a list of all of C's subclasses:

import classC

print C
aList = []
for name in dir(classC):
print name,
try:
if issubclass(classC.__dict__[name], C):
print classC.__dict__[name]
else:
print
except TypeError:
print

Which gives me this:


C
CSubclasses
D
E
__builtins__
__doc__
__file__
__name__

However when I do this from the command line:

>>> issubclass(D,C)
True

but

>>> issubclass(classC.__dict__['D'], C)
False

So my approach is flawed.

The end result I'm after is an automatically generated dictionary
containing instaces of the subclasses keyed by the subclass names:

{'D':D(), 'E':E(), . . . }

I can see the information I need in the module's __dict__ and by using
the dir() method, but I'm not having much success extracting it.



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


Re: Socket Programming HOWTO example

2006-01-16 Thread Steve Holden
Marco Meoni wrote:
> Hi. I read the Gordon McMillan's "Socket Programming Howto".
> I tried to use the example in this howto but this doesn't work.
> The code is class mysocket:
> '''classe solamente dimostrativa
>   - codificata per chiarezza, non per efficenza'''
> def __init__(self, sock=None):
> if sock is None:
> self.sock = socket.socket(
> socket.AF_INET, socket.SOCK_STREAM)
> else:
> self.sock = sock
> def connect(host, port):
> self.sock.connect((host, port))
> def mysend(msg):
> totalsent = 0
> while totalsent < MSGLEN:
> sent = self.sock.send(msg[totalsent:])
> if sent == 0:
> raise RuntimeError, \\
> "connessione socket interrotta"
> totalsent = totalsent + sent
> def myreceive():
> msg = ''
> while len(msg) < MSGLEN:
> chunk = self.sock.recv(MSGLEN-len(msg))
> if chunk == '':
> raise RuntimeError, \\
> "connessione socket interrotta"
> msg = msg + chunk
> return msg
>  
> How can i use this?

Well, a lot depends on what you mean by "doesn't work".

I can see you have changed the example a little (because I know that 
Gordon's original didn't have comments in Italian). Did the program 
produce a syntax error, a traceback or what? It would have been helpful 
if you had included a link to Gordon's tutorial -- I presume you mean 
the one at

   http://www.amk.ca/python/howto/sockets/

What are you trying to do, and why do you think this particular chunk of 
code might help you? Did you actually try to create and use any 
instances of this class?

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

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


Re: Trying to generate a list of the subclasses of C

2006-01-16 Thread Diez B. Roggisch
> The end result I'm after is an automatically generated dictionary
> containing instaces of the subclasses keyed by the subclass names:
> 
> {'D':D(), 'E':E(), . . . }
> 
> I can see the information I need in the module's __dict__ and by using
> the dir() method, but I'm not having much success extracting it.

Use a metaclass:


subclassesofc = []

class SubclassCollector(type):

def __new__(cls, name, bases, dict):
subclassesofc.append(name)
return type.__new__(cls, name, bases, dict)

class C(object):
__metaclass__ = SubclassCollector



class A(C):
pass

print subclassesofc



Regards,

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


Python and Word

2006-01-16 Thread rodmc
Is there a way to write Word plug-ins in Python?  I am using Python
2.3.5 and Word 2000, and need to be able to write a small network
application with a basic GUI which can run inside Word. 

cheers,

rod

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


Re: New Python.org website ?

2006-01-16 Thread Tim Chase
> The nav styles have crept back in sync with the rest of the
> site.. ;-) can you check again and tell me if it looks ok (and
> if not get me another screenie?)

Sorry it took so long to get back to you.  It looked fine from 
home, but the originals were snapped back at work (where my 
configuration is diff.)

With the regular style, they don't overlap, but they look cramped:

http://tim.thechases.com/pythonbeta/pythonbeta3moz.gif

With the "large text" page style, the original problem returns:

http://tim.thechases.com/pythonbeta/pythonbeta3mozLP.gif

Both shots are from Mozilla Suite 1.7, but they look about the
same in FF.


It seems to be a font-size issue.  When I crank the font rather
small (using ctrl+plus and ctrl+minus), the overlap becomes
pretty bad.  When I crank the font-size up larger, it seems to
make the problem go away (except for the fact I end up with fonts
that can be read across the room ;)  This symptom is worse in FF
than in MozSuite, though I might not have fonts set the same way
(one may have a minimum-allowed font size, while the other may
not, or something like that).

Using the dev tools in Mozilla suite, it looks like you've got a
 section (id="body-main") with a fixed margin-left property
of 15em (coming from the styles/styles.css file).  Thus,
depending on your font-size, the body-main element will be
further left or right.

Hope this helps you figure out what's goin' on.

-tim





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


Re: Python and Word

2006-01-16 Thread Tim N. van der Leeuw

rodmc wrote:
> Is there a way to write Word plug-ins in Python?  I am using Python
> 2.3.5 and Word 2000, and need to be able to write a small network
> application with a basic GUI which can run inside Word.
>
> cheers,
>
> rod

Hi Rod,

Does it really need to be an application which runs inside Word? Or is
it OK if it's an external application (with or without GUI) which does
manipulations with MS Word documents using COM objects?

(I frequently do the latter, but don't know about doing the former)

cheers,

--Tim

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


Re: Python and Word

2006-01-16 Thread rodmc
Hi Tim,

Thanks for replying.

It needs to be a small application/plug-in which can visualise data
that is either within Word already or which is sent to it via a server
on the localhost. The actual GUI will be very simple, for example and
image and some buttons.

What it actually has to do should be quite simple, but I have never
programmed Word plug-ins before, and am also new to Python.

cheers,

rod

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


recursively removing files and directories

2006-01-16 Thread rbt
What is the most efficient way to recursively remove files and directories?

Currently, I'm using os.walk() to unlink any files present, then I call 
os.walk() again with the topdown=False option and get rid of diretories 
with rmdir. This works well, but it seems that there should be a more 
efficient way. Here are my function definitions:

def remove_files(target_dir):
 # This attempts to remove _all_ files from a directory.
 # Use with caution on directories that store temporary files.

 for root, dirs, files in os.walk(target_dir):
 for f in files:

 try:
 # Make attributes normal so file can be deleted.
 win32api.SetFileAttributes(os.path.join(root, f), 
win32con.FILE_ATTRIBUTE_NORMAL)
 except:
 pass

 try:
 # Try to delete the file.
 os.unlink(os.path.join(root, f))
 except:
 pass

def remove_dirs(target_dir):
 # This attempts to remove _all_ sub directories from a directory.
 # Use with caution on directories that store temporary information.

 for root, dirs, files in os.walk(target_dir, topdown=False):
 for d in dirs:

 try:
 # Make attributes normal so dir can be deleted.
 win32api.SetFileAttributes(os.path.join(root, d), 
win32con.FILE_ATTRIBUTE_NORMAL)
 except:
 pass

 try:
 # Try to delete the directory.
 os.rmdir(os.path.join(root, d))
 except:
 pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Word

2006-01-16 Thread Tim N. van der Leeuw
Hi Rod,

If you download and install the 'Python Win' extensions, which I think
are linked from from the Python download page for windows, you have a
set of COM classes for Python which allow you to do everything you can
do in Word from a Python program.

It allows a lot of interactive exploration at the command prompt,
although not everything is very obvious (in part due to the way the
word object model is structured).

BTW, if you are new to Python, why not use VBA for the program?

cheers,

--Tim

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


Re: recursively removing files and directories

2006-01-16 Thread Fuzzyman
shutil.rmtree

You might need an ``onerror`` handler to sort out permissions.

There is one for just this in pathutils :

http://www.voidspace.org.uk/python/pathutils.html

All the best,

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

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


Re: recursively removing files and directories

2006-01-16 Thread Richie Hindle

[rbt]
> What is the most efficient way to recursively remove files and directories?

shutil.rmtree: http://docs.python.org/lib/module-shutil.html#l2h-2356

-- 
Richie Hindle
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursively removing files and directories

2006-01-16 Thread Tim N. van der Leeuw
Wasn't this the example given in the Python manuals? Recursively
deleting files and directories?

cheers,

--Tim

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


Re: Python and Word

2006-01-16 Thread rodmc
Hi Tim.

Thanks for the tips.

As for VBA, well I am looking at that as well. Although for
architectural reasons elsewhere in the project Python or C++ are the
only options. While  I could use several languages I am trying where
possible to stick to one or at most two. 

cheers,

rod

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


Re: boost.python on Debian

2006-01-16 Thread Pierre Barbier de Reuille
Joe bloggs a écrit :
> Can anyone tell me how to get boost.python to work on Debian Sarge?
> When I try to build the tutorial hello world example bjam reports:
> 
> /usr/share/doc/libboost-doc/examples/libs/python/example/boost-build.jam
> attempted to load the build system by invoking
> 
> 'boost-build ../../../tools/build/v1 ;'
> 
> but we were unable to find "bootstrap.jam" in the specified directory or
> in BOOST_BUILD_PATH (searching 
> /usr/share/doc/libboost-doc/examples/libs/python/example/../../../tools/build/v1,
> /usr/share/boost-build).
> 
> I have looked for 'bootstrap.jam' but it doesn't exist on my system. 
> I suppose that the Debian boost package doesn't have the same structure as
> the official one, and is missing some files. 
> Can anyone tell me how to fix this?

Well, is :

$ apt-get install libboost-python-dev

a valid answer ? Because the Boost project itself maintains the debian
packages, they are always very up-to-date ...

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


Re: Trying to generate a list of the subclasses of C

2006-01-16 Thread Pierre Barbier de Reuille
Charles Krug a écrit :
> List:
> 
> I have this:
> 
> # classC.py
> 
> class C(object): pass
> 
> class D(C): pass
> 
> class E(C): pass
> 
> def CSubclasses():
> for name in dir(): pass
> 
> I'm trying to create a list of all of C's subclasses:
> 
> import classC
> 
> print C
> aList = []
> for name in dir(classC):
> print name,
> try:
> if issubclass(classC.__dict__[name], C):
> print classC.__dict__[name]
> else:
> print
> except TypeError:
> print
> 

Where is C defined ?

>>> import classC

does not define the name C in the current scope ... thus, you should write :

for name in dir(classC):
print name,
try:
if issubclass(classC.__dict__[name], classC.C):
print classC.__dict__[name]
else:
print
except TypeError:
print

and it gives :

C 
CSubclasses
D 
E 
__builtins__
__doc__
__file__
__name__

... which is exactly what you want !

Pierre

> Which gives me this:
> 
> 
> C
> CSubclasses
> D
> E
> __builtins__
> __doc__
> __file__
> __name__
> 
> However when I do this from the command line:
> 
> 
issubclass(D,C)
> 
> True
> 
> but
> 
> 
issubclass(classC.__dict__['D'], C)
> 
> False
> 
> So my approach is flawed.
> 
> The end result I'm after is an automatically generated dictionary
> containing instaces of the subclasses keyed by the subclass names:
> 
> {'D':D(), 'E':E(), . . . }
> 
> I can see the information I need in the module's __dict__ and by using
> the dir() method, but I'm not having much success extracting it.
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Extracting results from a large hotshot profile

2006-01-16 Thread Brian Cole
I'm profiling some code that screens a large database. The algorithm
efficiency is heavily variable, based upon the different records in
the database. In order to get a sense of the best place to start
optimizing the code I did a hotshot profile. To make this profile took
about a day. However, I've been trying to extract results from the
profile for the past two days. It's eating up all the memory (2G
memory) on the machine and is slowing sucking up the swap space
(another 2G).

I'm hesitant to kill it for I might get results out of it some day
(even if I may have to bequeath them to my grand-children), but is
there a better way to do this?

I'm using the following script to print my results:
import sys
import hotshot.stats
stats = hotshot.stats.load(sys.argv[1])
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(20)

The profile is 355 MB large. Is there anything I can do to extract that data?

Thanks in advance,
Brian Cole
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Word

2006-01-16 Thread Diez B. Roggisch
rodmc wrote:

> Hi Tim.
> 
> Thanks for the tips.
> 
> As for VBA, well I am looking at that as well. Although for
> architectural reasons elsewhere in the project Python or C++ are the
> only options. While  I could use several languages I am trying where
> possible to stick to one or at most two.

I guess you will be way easier off writing the GUI-Parts that are embedded
in word in VBA. Actually I have difficulties imaging who not to do so. 

But of course you can write your server in python, and expose its
functionality using COM, so that easy access from VBA is granted.

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


Re: recursively removing files and directories

2006-01-16 Thread rbt
Tim N. van der Leeuw wrote:
> Wasn't this the example given in the Python manuals? Recursively
> deleting files and directories?

I don't know... I wrote it without consulting anything. Hope I'm not 
infringing on a patent :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursively removing files and directories

2006-01-16 Thread rbt
Fuzzyman wrote:
> shutil.rmtree

Many thanks. I'll give that a go!

> 
> You might need an ``onerror`` handler to sort out permissions.
> 
> There is one for just this in pathutils :
> 
> http://www.voidspace.org.uk/python/pathutils.html
> 
> All the best,
> 
> Fuzzyman
> http://www.voidspace.org.uk/python/index.shtml
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arithmetic sequences in Python

2006-01-16 Thread bearophileHUGS
Ranges of letters are quite useful, they are used a lot in Delphi/Ada
languages:
"a", "b", "c", "d", "e"...

I like the syntax [1..n], it looks natural enough to me, but I think
the Ruby syntax with ... isn't much natural.
To avoid bugs the following two lines must have the same meaning:
[1..n-1]
[1..(n-1)]

If you don't want to change the Python syntax then maybe the
range/xrange can be extended for chars too:

xrange("a", "z")
range("z", "a", -1)

But for char ranges I think people usually don't want to stop to "y"
(what if you want to go to "z" too? This is much more common than
wanting to stop to "y"), so another possibility is to create a new
function like xrange that generates the last element too:

interval("a", "c") equals to iter("abc")
interval(1, 3) equals to iter([1,2,3])
interval(2, 0, -1) equals to iter([2,1,0])

I have created such interval function, and I use it now and then.

Bye,
bearophile

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


Re: OT: excellent book on information theory

2006-01-16 Thread Grant Edwards
On 2006-01-16, Paul Rubin <> wrote:
> I came across this while looking up some data compression info today.
>
> David J.C. MacKay
> Information Theory, Inference, and Learning Algorithms
>
> Full text online:
> http://www.inference.phy.cam.ac.uk/mackay/itila/
>
> It's a really excellent book, on the level of SICP but about
> information theory, probability, error correcting codes, etc.  Very
> readable, and geeky (in a good way) at the same time.  The writing
> style is perhaps along the lines of "Numerical Recipes", though the
> format is more conventional.
>
> The whole text is online as a pdf, which is very nice.  The printed
> version is somewhat expensive, but according to the following analysis
> it's a better bargain than "Harry Potter and the Philosopher's Stone":
>
> http://www.inference.phy.cam.ac.uk/mackay/itila/Potter.html

That made me smile on a Monday morning (not an insignificant
accomplishment).  I noticed in the one footnote that the H.P.
book had been "translated into American".  I've always wondered
about that.  I noticed several spots in the H.P. books where
the dialog seemed "wrong": the kids were using American rather
than British English.  I thought it rather jarring.

-- 
Grant Edwards   grante Yow!  Don't SANFORIZE me!!
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing a substring from a string

2006-01-16 Thread Paul Watson
ankit wrote:
> Hi All,
> I want to remove a substring from a string without any additional
> tabs/returns in the output string. Is there any method availaible or
> how can I do it. For the ease, I am giving an example:
> 
> [code]
> mainstr ="""
> ${if:isLeaf}
>   Dont include this isLeaf=True
> ${/if:isLeaf}
> 
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>include this isLeaf=False
> ${/if:!isLeaf}
> """
> [/code]
> 
> Now if I want to remove :
> [code]
> substr = ""
> ${if:isLeaf}
>   Dont include this isLeaf=True
> ${/if:isLeaf}
> """
> [/code]
> 
> Expected output is :
> [code]
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>include this isLeaf=False
> ${/if:!isLeaf}
> [/code]
> 
> I am using mainstr.replace(substr, "") but it gives me additional
> carriage returns which leads to empty spaces as follows:
> 
> Actual Output:
> [code]
> 
> 
> 
> 
> 
> ${if:isStatic}
>   include this isStatic=True
> ${/if:isStatic}
> 
> ${if:!isLeaf}
>include this isLeaf=False
> ${/if:!isLeaf}
> [/code]
> 
> Note: See additional newlines before isStatic tag
> 
> 
> Any Suggestions ?

Are you using 'print' to get the output?  Please see the following code 
and note what the 'print' lines which have a comma at the end produce. 
The 'print' statement is not always suitable for producing closely 
controlled output.  Consider constructing the exact string you want and 
using a 'write' method.

$ cat ./jjj.py
#!/usr/bin/python

s = 'now'
print s
print s,
print s

x = s.replace('now', '')
print '%s' % x,
print 'then'
09:34 pwatson [ ruth:/home/pwatson ] 431
$ ./jjj.py
now
now now
  then
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On Numbers

2006-01-16 Thread Terry Hancock
On 15 Jan 2006 21:14:33 -0800
"Dan Bishop" <[EMAIL PROTECTED]> wrote:
> although I personally would prefer
> 
>(number)
>/   \
> (realnumber)   complex
>   |   |   |
> int float |
>   |
> Decimal

Mathematically, "real numbers" are a subset of "complex
numbers", though, so the set hierarchy would look like this:

"number"
  |
complex
  |
"real"
  |
"rational"
  |
  +-,
  | |
float  decimal
  | |
  +-'
  | 
 int

Noting of course that "real" and "number" are only 
abstract concepts -- they can't truly be represented
on the computer. AFAIK, there is no general purpose
"rational" type in Python, but there could be.

I'm bothered by the fact that "int" can be coerced into
either "decimal" or "float". In practice, you should
have to choose one or the other.  Practically speaking,
it probably makes more sense to do this:

"number"
  |
complex
  |
"real"
  |
float
  |
decimal
  | 
 int

Because, in general, it is safer (no info loss) to
convert "int" to "decimal" where possible.

OTOH, for scientific or other performance-critical
applications, the exactitude of 'decimal' is less
desireable than the known precision and higher speed
of float implementations.

I suspect this is the sort of decision that was viewed
as "too tricky".

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

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


Re: New Python.org website ?

2006-01-16 Thread Tim Parkin
Tim Chase wrote:
>> The nav styles have crept back in sync with the rest of the
>> site.. ;-) can you check again and tell me if it looks ok (and
>> if not get me another screenie?)
> 
> 
> Sorry it took so long to get back to you.  It looked fine from home, but
> the originals were snapped back at work (where my configuration is diff.)
> 
> With the regular style, they don't overlap, but they look cramped:
> 
> http://tim.thechases.com/pythonbeta/pythonbeta3moz.gif
> 
> With the "large text" page style, the original problem returns:
> 
> http://tim.thechases.com/pythonbeta/pythonbeta3mozLP.gif
> 
> Both shots are from Mozilla Suite 1.7, but they look about the
> same in FF.
> 
Thanks Tim!! If it works with the regular styles then we're onto a
winner (I'd not changed the large styles one... one step at a time at
the moment).

> It seems to be a font-size issue.  When I crank the font rather
> small (using ctrl+plus and ctrl+minus), the overlap becomes
> pretty bad.  When I crank the font-size up larger, it seems to
> make the problem go away (except for the fact I end up with fonts
> that can be read across the room ;)  This symptom is worse in FF
> than in MozSuite, though I might not have fonts set the same way
> (one may have a minimum-allowed font size, while the other may
> not, or something like that).
Yeah, the min font size is causing the problems.. the basefont size of
the body is larger than the basefont size of the menu. Hence the min
font size affects the menu first (which means they don't match).

I'll post again when I've updated the main site.

Cheers!!

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


Re: Python and Word

2006-01-16 Thread BartlebyScrivener
How to automate Word

http://www.faqts.com/knowledge_base/view.phtml/aid/37034/fid/244

rpd

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


Re: Extracting results from a large hotshot profile

2006-01-16 Thread Mike C. Fletcher
Brian Cole wrote:
...

>I did a hotshot profile. To make this profile took
>about a day. However, I've been trying to extract results from the
>profile for the past two days. It's eating up all the memory (2G
>memory) on the machine and is slowing sucking up the swap space
>(another 2G).
>
>I'm hesitant to kill it for I might get results out of it some day
>(even if I may have to bequeath them to my grand-children), but is
>there a better way to do this?
>  
>
...

>The profile is 355 MB large. Is there anything I can do to extract that data?
>  
>
You might want to try my RunSnakeRun utility:

http://www.vrplumber.com/programming/runsnakerun/

It's designed to load large hotspot runs.  I've never had a 355 MB one, 
but I regularly load 140+MB ones on a desktop 1GB machine.  It does an 
incremental load, so you start to see results as soon as it starts 
running and continues loading the data-set in the background (it can 
take quite a while for the full data-set to load, but I don't *think* it 
should run out of RAM).

In case you don't want the GUI, the package includes the core 
hotshotreader module that actually does the incremental loading, you 
could use that to produce a view by writing code to display the results 
statically.

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: Widget that displays a directory tree?

2006-01-16 Thread Christos Georgiou
On Thu, 12 Jan 2006 11:55:46 -0500, rumours say that "Edward C. Jones"
<[EMAIL PROTECTED]> might have written:

>Do any of the Python GUIs have a super-high-level widget that displays a 
>directory tree? Most file managers or editors have this type of window.

If you have idle installed, you can check the PathBrowser.py file in your
idlelib directory.  (Run idle; click File -> Path Browser to see it in
action, and click File -> Open Module -> PathBrowser -> OK to see/edit the
source).
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Space left on device

2006-01-16 Thread sir_alex
Is there any function to see how much space is left on a device (such
as a usb key)? I'm trying to fill in an mp3 reader in a little script,
and this information could be very useful! Thanks!

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


Space left on device

2006-01-16 Thread sir_alex
Is there any function to see how much space is left on a device (such
as a usb key)? I'm trying to fill in an mp3 reader in a little script,
and this information could be very useful! Thanks!

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Steven D'Aprano
On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote:

> For those who'd need the (0..n-1) behavior, Ruby features something that 
> I find quite elegant (if not perfectly obvious at first), (first..last) 
> provides a range from first to last with both boundaries included, but 
> (first...last) (notice the 3 periods) 

No, no I didn't.

Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately
uses a simple, consistent system of indexing from the start to one past
the end specifically to help prevent signpost errors, and now some folks
want to undermine that.

*shakes head in amazement*


-- 
Steven.

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


Re: Python and Word

2006-01-16 Thread Diez B. Roggisch
> I guess you will be way easier off writing the GUI-Parts that are embedded
> in word in VBA. Actually I have difficulties imaging who not to do so.
   ^^^

Gosh, must be permutation day. That was supposed to be "how".

Diez

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


Re: On Numbers

2006-01-16 Thread Alex Martelli
Terry Hancock <[EMAIL PROTECTED]> wrote:
   ...
> I'm bothered by the fact that "int" can be coerced into
> either "decimal" or "float". In practice, you should
> have to choose one or the other.  Practically speaking,

Why ever?!  You're indicating "is a subset of", and int IS a subset of
both (net of floats' issues with maximum sizes, of course) -- why should
you have to choose?

> it probably makes more sense to do this:
> 
> "number"
>   |
> complex
>   |
> "real"
>   |
> float
>   |
> decimal
>   | 
>  int
> 
> Because, in general, it is safer (no info loss) to
> convert "int" to "decimal" where possible.

But decimal is NOTHING LIKE a subset of float; it's a SUPERSET (since 2
is a factor of 10, but not viceversa).

> I suspect this is the sort of decision that was viewed
> as "too tricky".

So _my_ preference would be to have abstract empty classes 'basenumber'
and 'baseinteger', with everything inheriting directly from 'basenumber'
except that 'int' (and if we want to keep it around 'long') inherits
from 'baseinteger'.

The main reason for existence of baseinteger is simple: a list (or other
sequence) should accept as index any baseinteger (so a package such as
gmpy can easily have instances of gmpy.mpz "be integers", directly
acceptable as list indices, w/o having to carry around uselessly an
instance of int... inheritance from non-abstract classes is NOT just a
question of subsets and supesets, it has implications in implementation
terms, too).  It's a rather specific use case, I won't cry much if
'baseinteger' goes away.

The case for 'basenumber' is much stronger, and I'm making it on
python-dev (where I already made it in the past, in the last few years);
look for [basenumber site:python.org] and you'll find the few but
informative posts that went around, mostly about 3 years ago.

My main worry is that in the quest for a "perfect hierarchy" that keeps
proving too tricky, something with real-life usefulness such as
basenumber may fall by the wayside...


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


Re: Widget that displays a directory tree?

2006-01-16 Thread Claudio Grondi
Christos Georgiou wrote:
> On Thu, 12 Jan 2006 11:55:46 -0500, rumours say that "Edward C. Jones"
> <[EMAIL PROTECTED]> might have written:
> 
> 
>>Do any of the Python GUIs have a super-high-level widget that displays a 
>>directory tree? Most file managers or editors have this type of window.
> 
> 
> If you have idle installed, you can check the PathBrowser.py file in your
> idlelib directory.  (Run idle; click File -> Path Browser to see it in
> action, and click File -> Open Module -> PathBrowser -> OK to see/edit the
> source).

C:\>C:\Python24\python.exe
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on 
win32
C:\>C:\Python24\Lib\idlelib\PathBrowser.py
Traceback (most recent call last):
   File "C:\Python24\Lib\idlelib\PathBrowser.py", line 95, in ?
 main()
   File "C:\Python24\Lib\idlelib\PathBrowser.py", line 90, in main
 PathBrowser(PyShell.flist)
AttributeError: 'module' object has no attribute 'flist'

Strange ...

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Alex Martelli
Paul Rubin  wrote:
   ...
> while the traditional
> 
>   xrange(f(n)-1, -1, -1)
> 
> only evaluates it once but is IMO repulsive.

Yep, reversed(range(f(n))) is MUCH better.


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


Re: Arithmetic sequences in Python

2006-01-16 Thread Alex Martelli
Paul Rubin  wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > For finite sequences, your proposal adds nothing new to existing
> > solutions like range and xrange.
> 
> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).

But not easier than reversed(range(6)) [[the 5 in one of the two
expressions in your sentence has to be an offbyone;-)]]


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


Re: Indentation/whitespace

2006-01-16 Thread thakadu
>It just has to be consistent within a *single* block.

Correct, and therein lies the problem I am describing.
If someone has used two spaces and you paste into
the SAME block where you are using four spaces
you will break your code.

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


Re: Trying to generate a list of the subclasses of C

2006-01-16 Thread Alex Martelli
Charles Krug <[EMAIL PROTECTED]> wrote:
   ...
> I'm trying to create a list of all of C's subclasses:

There's a class method for that very purpose:

>>> class C(object): pass
... 
>>> class D(C): pass
... 
>>> class E(C): pass
... 
>>> C.__subclasses__()
[, ]
>>> 


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


Re: Widget that displays a directory tree?

2006-01-16 Thread Fredrik Lundh
Claudio Grondi wrote:

> Christos Georgiou wrote:
> > On Thu, 12 Jan 2006 11:55:46 -0500, rumours say that "Edward C. Jones"
> > <[EMAIL PROTECTED]> might have written:
> >
> >
> >>Do any of the Python GUIs have a super-high-level widget that displays a
> >>directory tree? Most file managers or editors have this type of window.
> >
> >
> > If you have idle installed, you can check the PathBrowser.py file in your
> > idlelib directory.  (Run idle; click File -> Path Browser to see it in
> > action, and click File -> Open Module -> PathBrowser -> OK to see/edit the
> > source).
>
> C:\>C:\Python24\python.exe
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on
> win32
> C:\>C:\Python24\Lib\idlelib\PathBrowser.py
> Traceback (most recent call last):
>File "C:\Python24\Lib\idlelib\PathBrowser.py", line 95, in ?
>  main()
>File "C:\Python24\Lib\idlelib\PathBrowser.py", line 90, in main
>  PathBrowser(PyShell.flist)
> AttributeError: 'module' object has no attribute 'flist'
>
> Strange ...

in what way?

the instructions you didn't read told you to run idle, and select the
browser via the menu system to see it in action.





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


Re: Space left on device

2006-01-16 Thread rbt
sir_alex wrote:
> Is there any function to see how much space is left on a device (such
> as a usb key)? I'm trying to fill in an mp3 reader in a little script,
> and this information could be very useful! Thanks!
> 

On windows with the win32 extensions, you might try this:

# Get hard drive info from Windows.
drive = win32api.GetDiskFreeSpace('c:')
print drive[0], "sectors per cluster."
print drive[1], "bytes per sector."
print drive[2], "free clusters."
print drive[3], "total clusters."

You could use wmi to discover where the device has been mounted:
for item in c.Win32_DiskDrive():
 print item

instance of Win32_DiskDrive
{
 BytesPerSector = 512;
 Capabilities = {3, 4, 7};
 Caption = "M-SysT5 Dell Memory Key USB Device";
 ConfigManagerErrorCode = 0;
 ConfigManagerUserConfig = FALSE;
 CreationClassName = "Win32_DiskDrive";
 Description = "Disk drive";
 DeviceID = ".\\PHYSICALDRIVE1";
 Index = 1;
 InterfaceType = "USB";
 Manufacturer = "(Standard disk drives)";
 MediaLoaded = TRUE;
 MediaType = "Removable media other than\tfloppy";
 Model = "M-SysT5 Dell Memory Key USB Device";
 Name = ".\\PHYSICALDRIVE1";
 Partitions = 1;
 PNPDeviceID =
"USBSTOR\\DISK&VEN_M-SYST5&PROD_DELL_MEMORY_KEY&REV_5.00\\09809350C300C9D7&0";
 SectorsPerTrack = 63;
 Signature = 2865277640;
 Size = "254983680";
 Status = "OK";
...
-- 
http://mail.python.org/mailman/listinfo/python-list


zipfile decompress problems

2006-01-16 Thread Waguy
Hi all,

I am new to python and want to create a process to unzip large numbers of
zip files I get from a SOAP application.  The files all have a ZIP extention
and can be unzipped using WinZip.

However when I try opening the files using zlib or zipfile modules I get the
following error:

Traceback (most recent call last):
  File "", line 1, in -toplevel-
file = zipfile.ZipFile("c:\\chessy.zip", "r")
  File "C:\Python24\lib\zipfile.py", line 210, in __init__
self._GetContents()
  File "C:\Python24\lib\zipfile.py", line 230, in _GetContents
self._RealGetContents()
  File "C:\Python24\lib\zipfile.py", line 242, in _RealGetContents
raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file

The code I used in python was:

import zipfile
file = zipfile.ZipFile("c:\\chessy.zip", "r")

I tried to do the same with a zip file I created using WinZip and it worked
fine.  I have been searching the web for about two days and haven't found
anything helpful.

Can anyone help with this?  I have the zip I can send, however I tried to 
send this message with it attached and it didn't get posted.

Cheers,




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


Re: Arithmetic sequences in Python

2006-01-16 Thread Alex Martelli
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote:
> 
> > For those who'd need the (0..n-1) behavior, Ruby features something that
> > I find quite elegant (if not perfectly obvious at first), (first..last)
> > provides a range from first to last with both boundaries included, but
> > (first...last) (notice the 3 periods) 
> 
> No, no I didn't.
> 
> Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately
> uses a simple, consistent system of indexing from the start to one past
> the end specifically to help prevent signpost errors, and now some folks
> want to undermine that.
> 
> *shakes head in amazement*

Agreed.  *IF* we truly needed an occasional "up to X *INCLUDED*"
sequence, it should be in a syntax that can't FAIL to be noticed, such
as range(X, endincluded=True).


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


Re: Pythonic wrappers for SQL?

2006-01-16 Thread Stian Soiland
On 1/14/06, EleSSaR^ <[EMAIL PROTECTED]> wrote:
> Kenneth McDonald si è profuso/a a scrivere su comp.lang.python tutte queste
> elucubrazioni:
>
> > there any good libraries out there that let one write (basic) queries
> > in a Pythonic syntax, rather than directly in SQL?
>
> You need an ORM. Beyond SQLAlchemy (I don't have experience with it) i
> would suggest you try out SQLObject and PyDO.
>
> Just a clue: although they prevent you from writing SQL, you'll have to
> learn SQL basics anyway, or you won't understand the docs.
>
> If you simply want to forget SQL, you can try out Axiom:

Or - as a word play in this case - try my module ForgetSQL [1]

(Also available in a new and backwards-incompatible beta version [2]
which should be easier to get started with, has more extensive unit
tests, but has only been tested with MySQL and SQLite)

[1] http://soiland.no/software/forgetsql/
[2] http://soiland.no/i/src/forgetsql2/

Example code from [2]

import MySQLdb, forgetsql2
# Connect to MySQLdb using keyword parameters
db = forgetsql2.generate(MySQLdb, {db='fish'})

# Iterate through generated class from the table "postal"
for postal in db.Postal:
# Print normal fields
print postal.postal_no, postal.postal_name, postal.municipal_id
# Follow the foreign key municipal_id to retrieve the entry
# from the Municipal class
municipal = postal.get_municipal()
print municipal.municipal_name

# Retrieve by primary key
rogaland = db.County(county_id=11)
# Iterate over municipals that have foreign keys to rogaland
for municipal in rogaland.get_municipals():
print municipal.municipal_name

# Load by primary key, change, and save
postal = db.Postal(postal_id=4042)
postal.postal_name = "Fish land"
postal.save()


--
Stian Søiland   In theory there is no difference between theory
Birmingham, UK  and practice. In practice there is. [Berra]
http://soiland.no/
 =/\=
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preventing class methods from being defined

2006-01-16 Thread Steven D'Aprano
On Mon, 16 Jan 2006 06:39:48 -0500, Dan Sommers wrote:

> By the principle of least surprise, if dir(some_sobject) contains foo,
> then some_object.foo should *not* raise a NameError.

Good thinking. Yes, it should raise a different exception.

-- 
Steven.

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


Re: Widget that displays a directory tree?

2006-01-16 Thread Claudio Grondi
Fredrik Lundh wrote:
> Claudio Grondi wrote:
> 
> 
>>Christos Georgiou wrote:
>>
>>>On Thu, 12 Jan 2006 11:55:46 -0500, rumours say that "Edward C. Jones"
>>><[EMAIL PROTECTED]> might have written:
>>>
>>>
>>>
Do any of the Python GUIs have a super-high-level widget that displays a
directory tree? Most file managers or editors have this type of window.
>>>
>>>
>>>If you have idle installed, you can check the PathBrowser.py file in your
>>>idlelib directory.  (Run idle; click File -> Path Browser to see it in
>>>action, and click File -> Open Module -> PathBrowser -> OK to see/edit the
>>>source).
>>
>>C:\>C:\Python24\python.exe
>>Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on
>>win32
>>C:\>C:\Python24\Lib\idlelib\PathBrowser.py
>>Traceback (most recent call last):
>>   File "C:\Python24\Lib\idlelib\PathBrowser.py", line 95, in ?
>> main()
>>   File "C:\Python24\Lib\idlelib\PathBrowser.py", line 90, in main
>> PathBrowser(PyShell.flist)
>>AttributeError: 'module' object has no attribute 'flist'
>>
>>Strange ...
> 
> 
> in what way?
> 
> the instructions you didn't read told you to run idle, and select the
> browser via the menu system to see it in action.
> 
> 
Yes, you are right. The section
def main():
 import PyShell
 PathBrowser(PyShell.flist)
 if sys.stdin is sys.__stdin__:
 mainloop()
in PathBrowser.py suggested (apparent falsely), that it should run also 
standalone - that was my problem.
Thank you.

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


Re: Extracting results from a large hotshot profile

2006-01-16 Thread Brian Cole
Thanks for the tip. I got the following error message when trying to
run your profiler.

Traceback (most recent call last):
  File "c:\Documents and Settings\coleb2\My Documents\software\Python24\lib\site
-packages\wx-2.6-msw-ansi\wx\_core.py", line 13469, in 
lambda event: event.callable(*event.args, **event.kw) )
  File "runsnake.py", line 106, in load
for count, files, functions in hotshotreader.loadHotshot( filename, 2 ):
  File "c:\Documents and Settings\coleb2\My Documents\software\Python24\Lib\site
-packages\runsnakerun\hotshotreader.py", line 95, in loadHotshot
localDeltas[depth] = 0
IndexError: index out of bounds

I don't know much about Numeric, or NumPy, or whatever it's called
now. I'm quite confused by the whole matter in fact.

As the traceback shows I'm running this on Windows. I'm gonna go
wrestle with installing wxPython and Numeric on my Linux box and see
if that makes a difference.

Thanks,
Brian

On 1/16/06, Mike C. Fletcher <[EMAIL PROTECTED]> wrote:
> Brian Cole wrote:
> ...
>
> >I did a hotshot profile. To make this profile took
> >about a day. However, I've been trying to extract results from the
> >profile for the past two days. It's eating up all the memory (2G
> >memory) on the machine and is slowing sucking up the swap space
> >(another 2G).
> >
> >I'm hesitant to kill it for I might get results out of it some day
> >(even if I may have to bequeath them to my grand-children), but is
> >there a better way to do this?
> >
> >
> ...
>
> >The profile is 355 MB large. Is there anything I can do to extract that data?
> >
> >
> You might want to try my RunSnakeRun utility:
>
> http://www.vrplumber.com/programming/runsnakerun/
>
> It's designed to load large hotspot runs.  I've never had a 355 MB one,
> but I regularly load 140+MB ones on a desktop 1GB machine.  It does an
> incremental load, so you start to see results as soon as it starts
> running and continues loading the data-set in the background (it can
> take quite a while for the full data-set to load, but I don't *think* it
> should run out of RAM).
>
> In case you don't want the GUI, the package includes the core
> hotshotreader module that actually does the incremental loading, you
> could use that to produce a view by writing code to display the results
> statically.
>
> HTH,
> Mike
>
> --
> 
>   Mike C. Fletcher
>   Designer, VR Plumber, Coder
>   http://www.vrplumber.com
>   http://blog.vrplumber.com
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Space left on device

2006-01-16 Thread Jean-Paul Calderone
On 16 Jan 2006 07:52:46 -0800, sir_alex <[EMAIL PROTECTED]> wrote:
>Is there any function to see how much space is left on a device (such
>as a usb key)? I'm trying to fill in an mp3 reader in a little script,
>and this information could be very useful! Thanks!

If you are on a platform with statvfs(2):

>>> import os
>>> s = os.statvfs('/')
>>> s.f_bavail * s.f_bsize
59866619904L
>>> 

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


Re: Trying to generate a list of the subclasses of C

2006-01-16 Thread Duncan Booth
Charles Krug wrote:

> The end result I'm after is an automatically generated dictionary
> containing instaces of the subclasses keyed by the subclass names:
> 
> {'D':D(), 'E':E(), . . . }
> 
> I can see the information I need in the module's __dict__ and by using
> the dir() method, but I'm not having much success extracting it.

Try this:

class C(object): pass

class D(C): pass

class E(C): pass

def CSubclasses():
return dict((cls.__name__, cls) for cls in C.__subclasses__())

print CSubclasses()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indentation/whitespace

2006-01-16 Thread Diez B. Roggisch
thakadu wrote:

>>It just has to be consistent within a *single* block.
> 
> Correct, and therein lies the problem I am describing.
> If someone has used two spaces and you paste into
> the SAME block where you are using four spaces
> you will break your code.

And then you invoke your "in/dedent block" function of your editor, and
things work. Similar to hitting "Format Source" in eclipse for JAVA.

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Steven D'Aprano
On Mon, 16 Jan 2006 02:58:39 -0800, Paul Rubin wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> For finite sequences, your proposal adds nothing new to existing
>> solutions like range and xrange.
> 
> Oh come on, [5,4,..0] is much easier to read than range(5,-1,-1).

Only in isolation, and arguably not even then. Or do you think that Perl
is much easier to read than Python simply because you can write your
programs in fewer characters?

It looks too much like the list [5,4,0], and is easy to make typos:
[5,4,.0] gives you no syntax error but very different results.

The meaning isn't particular clear: is it supposed to be [start, stop,
step] (the natural expectation for those used to Python slices and ranges)
or [start, next, stop]? It is actually the second, but go back to the
original post by Gregory: after giving examples, he still wrongly
described his proposal as having a "step" parameter. There is no step
parameter -- the step is implied, by subtracting start from next. Such
confusion doesn't bode well.

Python indexing deliberately goes to one-past-the-end counting for a
reason: it helps prevent off-by-one signpost errors. This syntax goes
against that decision, and adds one more thing to memorise about Python:
the end index is not included in the list, except for arithmetic
sequences, where it is, sometimes but not necessarily. In [5,6,10] the end
index 10 is included; in [5,7,10] it isn't.

You've picked the most awkward example of range, I admit. But let's look
at a few others:

[0,..9] versus range(10)
[55, ...73] versus range(55, 74)
[1, 3, ..len(mystr)] versus range(1, len(mystr)+1, 2) 
[55, 65, 295] versus range(55, 296, 10)

How often do you find yourself knowing the first two terms of a sequence
but not the step size anyway? Is that a common use case?



>> The only added feature this proposal
>> introduces is infinite iterators, and they aren't particularly hard to
>> make:
>> 
>> def arithmetic_sequence(start, step=1):
>> yield start
>> while 1:
>> start += step
>> yield start
> 
> Well, that would be itertools.count(start, step) but in general a simple
> expression is nicer than 5 lines of code.

I didn't say that my generator was the only way to produce the required
result, I was pointing out how simple it is. Yes, itertools is the way to
go for this sort of thing.


>> If your proposal included support for ranges of characters, I'd be more
>> interested.
> 
> There's something to be said for that.  Should ['a'..'z'] be a list or a
> string?

It uses [ something ] syntax, so for consistency with lists and list
comprehensions it should be a list.

But a string would be more practical, since list(['a'..'z']) is easier and
more intuitive than ''.join(['a'..'z']). But I'm not sure that it is
*that* much more practical to deserve breaking the reader's expectation.

So I think the best thing would be to create itertools.chars('a', 'z') or
similar, not new syntax.


-- 
Steven.

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


Re: Extracting results from a large hotshot profile

2006-01-16 Thread Mike C. Fletcher
Brian Cole wrote:

>Thanks for the tip. I got the following error message when trying to
>run your profiler.
>  
>
...

>  File "c:\Documents and Settings\coleb2\My 
> Documents\software\Python24\Lib\site
>-packages\runsnakerun\hotshotreader.py", line 95, in loadHotshot
>localDeltas[depth] = 0
>IndexError: index out of bounds
>  
>
...

>As the traceback shows I'm running this on Windows. I'm gonna go
>wrestle with installing wxPython and Numeric on my Linux box and see
>if that makes a difference.
>  
>
Not likely.  The hotshotreader module is creating an array of 
sys.getrecursionlimit() long integers to store the accumulated local 
times.  It does the same to track the number of frames.  Most likely 
your main program is setting sys.getrecursionlimit explicitly and as a 
result it winds up with a larger possible stack.  You can try replacing 
the sys.getrecursionlimit() calls with some big number (say 40,000, or 
just multiply the recursion limit by 10 or 20 if you like) and see if 
that solves the problem.  Probably should allow for setting the value on 
the command-line I guess.  I suppose there may also be cases where a 
recursive call to the interpreter gets a whole separate stack... or 
maybe there's something going on with threads intermixing to create 
greater depth.

Let me know if that helps,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: Extracting results from a large hotshot profile

2006-01-16 Thread Brian Cole
Tried replacing sys.getrecursionlimit() with 40,000. Choked with the
same error, just took longer to get there.

It looks like depth is not reset to zero after the yield:
if (not i%yieldCount) and i:
yield i, files, functions

Should it be?


On 1/16/06, Mike C. Fletcher <[EMAIL PROTECTED]> wrote:
> Brian Cole wrote:
>
> >Thanks for the tip. I got the following error message when trying to
> >run your profiler.
> >
> >
> ...
>
> >  File "c:\Documents and Settings\coleb2\My 
> > Documents\software\Python24\Lib\site
> >-packages\runsnakerun\hotshotreader.py", line 95, in loadHotshot
> >localDeltas[depth] = 0
> >IndexError: index out of bounds
> >
> >
> ...
>
> >As the traceback shows I'm running this on Windows. I'm gonna go
> >wrestle with installing wxPython and Numeric on my Linux box and see
> >if that makes a difference.
> >
> >
> Not likely.  The hotshotreader module is creating an array of
> sys.getrecursionlimit() long integers to store the accumulated local
> times.  It does the same to track the number of frames.  Most likely
> your main program is setting sys.getrecursionlimit explicitly and as a
> result it winds up with a larger possible stack.  You can try replacing
> the sys.getrecursionlimit() calls with some big number (say 40,000, or
> just multiply the recursion limit by 10 or 20 if you like) and see if
> that solves the problem.  Probably should allow for setting the value on
> the command-line I guess.  I suppose there may also be cases where a
> recursive call to the interpreter gets a whole separate stack... or
> maybe there's something going on with threads intermixing to create
> greater depth.
>
> Let me know if that helps,
> Mike
>
> --
> 
>   Mike C. Fletcher
>   Designer, VR Plumber, Coder
>   http://www.vrplumber.com
>   http://blog.vrplumber.com
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Shrinky-dink Python (also, non-Unicode Python build is broken)

2006-01-16 Thread Larry Hastings
I'm an indie shareware Windows game developer.  In indie shareware
game development, download size is terribly important; conventional
wisdom holds that--even today--your download should be 5MB or less.

I'd like to use Python in my games.  However, python24.dll is 1.86MB,
and zips down to 877k.  I can't afford to devote 1/6 of my download
to just the scripting interpreter; I've got music, and textures, and
my own crappy code to ship.

Following a friend's suggestion, as an experiment I downloaded the
Python 2.4.2 source, then set about stripping out everything I could.
I removed:
 * Unicode support, including the CJK codecs
 * All doc strings
 * *Every* module written in C
Now when I build, python24.dll is 570k, and zips down to about 260k.
But I learned some things on the way.


First and foremost: turning off Py_USING_UNICODE *breaks the build*
on Windows.  The following list of breakages were all fixed with
judicious applications of #ifdef Py_USING_UNICODE:
* The implementation of "multi-byte codecs" (CJK codecs) implicitly
  assumes that they can use all the Unicode facilities.  So all the
  files in "Modules/cjkcodecs" fail to build.
* Obviously, the Unicode string object depends on Unicode support,
  so Objects/unicode* doesn't build.
* There are several spots in the code that need to handle Unicode
  strings in some slightly special way, and assume Unicode is turned
  on.  E.g.:
* Modules/posixmodule.c, posix__getfullpathname(), line 1745
* same file, posix_open(), starting on line 5201
* Objects/fileobject.c, open_the_file(), starting on line 158
* _winreg.c, Py2Reg(), starting on lines 724 and 777

In addition, there was one slightly more complicated problem: _winreg.c
assumes it should call PyUnicode_DecodeMBCS() to turn strings pulled
from the registry into Unicode strings.  I'm not sure what the correct
thing to do here is; I went with changing the calls from
PyUnicode_DecodeMBCS() to PyString_FromStringAndSize() for non-Unicode
builds.

Of course, it's not the most important thing in the world--after all,
I'm the first person to even *notice*, right?  But it seems a shame
that
one can break the build so easily.  If it pleases the stewards of
Python, I would be happy to submit patches that fix the non-"using
Unicode" build.


Second of all, the dumb-as-a-bag-of-rocks Windows linker (at least
the one used by VC++ under MSVS .Net 2003) *links in unused static
symbols*.  If I want to excise the code for a module, it is not
sufficient to comment-out the relevant _inittab line in config.c.
Nor does it help if I comment out the "extern" prototype for the
init function.  As far as I can tell, the only way to *really* get
rid of a module, including all its static functions and static data,
is to actually *remove all the code* (with comments, or #if, or
whatnot).  What a nosebleed, huh?

So in order to build my *really* minimal python24.dll, I have to hack
up the source something fierce.  It would be pleasant if the Python
source code provided an easy facility for turning off modules at
compile-time.  I would be happy to propose something / write a PEP
/ submit patches to do such a thing, if there is a chance that such
a thing could make it into the official Python source.  However, I
realize that this has terribly limited appeal; that, and the fact
that Python releases are infrequent, makes me think it's not a
terrible hardship if I had to re-hack up each new Python release
by hand.


Whatcha think, froods?


/larry/

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


Re: pdb.py - why is this debugger different from all other debuggers?

2006-01-16 Thread skip

Andreas> Am Donnerstag, den 05.01.2006, 15:03 -0800 schrieb
Andreas> [EMAIL PROTECTED]: I know this sounds like brutal, but I've been
Andreas> developing Python code for a decade now, and I've almost never
Andreas> used pdb.py. OTOH I also use gdb only for "bt" from a core
Andreas> file.

In addition, if you are running Python from gdb, when you reach the (gdb)
prompt you can source the Misc/gdbinit file that comes with the Python
distribution to get a user-defined "pystack" command that will display the
current Python stack trace.  The "pystackv" command does that and displays
the values of all the local variables up the stack trace as well.  The "up"
and "down" commands are overridden as well so that they display the current
Python stack frame if the current C stack frame is PyEval_EvalFrameEx (the
main interpreter loop).

I also find pdb fairly unnecessary.  A combination of unittests, inserted
prints and the occasional use of cgitb is generally sufficient for my needs.

Skip

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


Re: Arithmetic sequences in Python

2006-01-16 Thread Roy Smith
Alex Martelli <[EMAIL PROTECTED]> wrote:
>Agreed.  *IF* we truly needed an occasional "up to X *INCLUDED*"
>sequence, it should be in a syntax that can't FAIL to be noticed, such
>as range(X, endincluded=True).

How about...

for i in (0..x]:
blah

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


Re: zipfile decompress problems

2006-01-16 Thread Giovanni Bajo
Waguy wrote:

> import zipfile
> file = zipfile.ZipFile("c:\\chessy.zip", "r")


Use "rb".
-- 
Giovanni Bajo


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


Re: Shrinky-dink Python (also, non-Unicode Python build is broken)

2006-01-16 Thread Steven Bethard
Larry Hastings wrote:
> Of course, it's not the most important thing in the world--after all,
> I'm the first person to even *notice*, right?  But it seems a shame
> that
> one can break the build so easily.  If it pleases the stewards of
> Python, I would be happy to submit patches that fix the non-"using
> Unicode" build.

There was a recent python-dev thread_ suggesting that we drop support 
for --disable-unicode, mainly I think because no one was willing to 
maintain it.  If you're willing to offer patches and some maintenance, 
it probably has a decent chance of acceptance.

.. _thread: 
http://mail.python.org/pipermail/python-dev/2005-October/056897.html

> So in order to build my *really* minimal python24.dll, I have to hack
> up the source something fierce.  It would be pleasant if the Python
> source code provided an easy facility for turning off modules at
> compile-time.  I would be happy to propose something / write a PEP
> / submit patches to do such a thing, if there is a chance that such
> a thing could make it into the official Python source.  However, I
> realize that this has terribly limited appeal; that, and the fact
> that Python releases are infrequent, makes me think it's not a
> terrible hardship if I had to re-hack up each new Python release
> by hand.

My impression is that, for most things like this, python-dev is happy to 
accept the patches *if* someone is willing to commit to maintaining 
them, and they don't make the codebase too much more complex.

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


  1   2   >