Re: [[x,f(x)] for x in list that maximizes f(x)] <--newbie help

2005-12-02 Thread Bengt Richter
On 1 Dec 2005 05:45:54 -0800, "Niels L Ellegaard" <[EMAIL PROTECTED]> wrote:

>I just started learning python and I have been wondering. Is there a
>short pythonic way to find the element, x, of a list, mylist, that
>maximizes an expression f(x).
>
>In other words I am looking for a short version of the following:
>
>pair=[mylist[0],f(mylist[0])]
>for x in mylist[1:]:
> if f(x) > pair[1]:
>   pair=[x,f(x)]
>

Reversing the order of the pair:

 >>> mylist = range(10)
 >>> def f(x): return 10-(x-5)**2
 ...
 >>> [f(x) for x in mylist]
 [-15, -6, 1, 6, 9, 10, 9, 6, 1, -6]

Then one line should do it:

 >>> max((f(x),x) for x in mylist)
 (10, 5)

Ok, be picky ;-)

 >>> pair = list(reversed(max((f(x),x) for x in mylist)))
 >>> pair
 [5, 10]

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


Re: super() and multiple inheritance

2005-12-02 Thread Michele Simionato
Hermy:
> So, for the moment my conclusion is that although Python has some
> syntax for multiple inheritance, it doesn't support it very well, and I should
> probably stick to single inheritance.

This is not much a problem of Python, the problem is that multiple
inheritance is
intrinsically HARD to support. If you can avoid it, avoid it. This will
probably make
your application more maintanable.

I your case, I would go with the keyword argument suggestion.

  Michele Simionato

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


Re: ANN: Louie-1.0b2 - Signal dispatching mechanism

2005-12-02 Thread Thomas Heller
"Pat" <[EMAIL PROTECTED]> writes:

> Thomas Heller wrote:
>>
>> What is the difference between PyDispatcher and Louie?
>> (I'm still using a hacked version of the original cookbook recipe...)
>
> Not too much at this point, but the general differences are listed on
> this page:
>
> http://louie.berlios.de/changes.html
>
> Matt and I plan to experiment with other changes for Nufox, PyQt,
> Schevo and other things that we are working on.

Ok, so I won't need it (yet).

Thanks (and also for the original dispatcher module, of which I'm a very
happy user).

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


Re: [[x,f(x)] for x in list that maximizes f(x)] <--newbie help

2005-12-02 Thread Duncan Booth
[EMAIL PROTECTED] wrote:
> Thanks. In that case, would it be easier to understand(beside the
> original iterative loop) if I use reduce and lambda ?
> 
You could try putting them side by side and seeing which is easiest for 
someone to understand:

reduce(lambda (mv,mx), (v,x): mv > v and (mv,mx) or (v,x), ((f(x), x) for x 
in mylist)))
 
max((f(x),i,x) for i,x in enumerate(mylist))[2]

max_x, max_f = mylist[0], f(mylist[0])
for x in mylist[1:]:
new_f = f(x)
if new_f > max_f:
   max_x, max_f = x, new_f

IMO, the last is clearest (but needs a list rather than an iterator), the 
middle is most concise and not too hard to understand and the first is a 
complete mess. YMMV.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instances behaviour

2005-12-02 Thread Peter Otten
Mr.Rech wrote:

> Suppose I have a bunch of classes that represent slightly (but
> conceptually) different object. The instances of each class must behave
> in very similar manner, so that I've created a common class ancestor
> (let say A) that define a lot of special method (such as __getattr__,
> __setattr__, __len__ and so on), and then I've created all my "real"
> classes inheriting from it:
> 
class A(object):
>  # here define all special and some common methods
> 
 class B(A):
> # this is the first "real" class
> 
 class C(A):
> # and this is the second
> 
> and so on. The problem I'm worried about is that an unaware user may
> create an instance of "A" supposing that it has any real use, while it
> is only a sort of prototype. However, I can't see (from my limited
> point of view) any other way to rearrange things and still get a
> similar behaviour.
> 
> Implementing those special methods directly in class B and then inherit
> from it, doesn't seem the right way, since I'd prefer that instances of
> B weren't in any relation with the instances of C (i.e. I'd prefer not
> to subclass C from B)
> 
> Perhaps some OOP techniques (that I miss at the moment) could be of any
> help. Any suggestion?

How about

class A(object):
"""Provides common functionality for A-like classes, e. g. B and C.

Do not instantiate.
""" 

This is definitely a low-tech approach, but I suppose you don't clutter your
functions with spurious argument type checks, either.
An exception like the one shown by Inyeol Lee is typically raised once
during the development process while my approach bites (only) the
illiterate programmer with a message like

>>> a.foo()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'A' object has no attribute 'foo'

which normally can be tracked down almost as quickly -- and which serves him
well anyway :-)

Peter

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


Re: Is Python string immutable?

2005-12-02 Thread Martin Franklin
Chris Mellon wrote:
> On 11/30/05, could ildg <[EMAIL PROTECTED]> wrote:
> 
>>In java and C# String is immutable, str=str+"some more" will return a new
>>string and leave some gargabe.
>>so in java and C# if there are some frequent string operation,
>>StringBuilder/StringBuffer is recommanded.
>>
>>Will string operation in python also leave some garbage? I implemented a
>>net-spider in python which includes many html string procession. After it
>>running for sometime, the python exe eats up over 300M memory. Is this
>>because the string garbages?
>>
>>If String in python is immutable, what class should I use to avoid too much
>>garbages when processing strings frequently?
> 
> 
> Python strings are immutable. The StringIO class provides a buffer
> that you can manipulate like a file, and then convert to a string and
> is probably most suitable for your purposes.
> 

another recipe is to build up a list with .append then when you need to
convert to a string with  "".join(alist)





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


Re: General question about Python design goals

2005-12-02 Thread Duncan Booth
Alex Martelli wrote:

> Yep -- "time tuples" have also become pseudo-tuples (each element can be
> accessed by name as well as by index) a while ago, and I believe there's
> one more example besides stats and times (but I can't recall which one).

Apart from time and os.stat all the uses seem to be restricted to Unix 
only: pwd, grp and resource modules all use StructSequence, also os.statvfs 
and spwd (new in 2.5). Thats from an svn checkout though so there may be 
fewer uses in released code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there no compression support for large sized strings in Python?

2005-12-02 Thread Claudio Grondi

"Gerald Klix" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Did you consider the mmap library?
> Perhaps it is possible to avoid to hold these big stings in memory.
> BTW: AFAIK it is not possible in 32bit windows for an ordinary programm
> to allocate more than 2 GB. That restriction comes from the jurrasic
> MIPS-Processors, that reserved the upper 2 GB for the OS.
>
> HTH,
> Gerald

>>> objMmap = mmap.mmap(fHdl,os.fstat(fHdl)[6])

Traceback (most recent call last):
  File "", line 1, in -toplevel-
objMmap = mmap.mmap(fHdl,os.fstat(fHdl)[6])
OverflowError: memory mapped size is too large (limited by C int)
>>> os.fstat(fHdl)[6]
4498001104L

Max. allowed value is here 256*256*256*128-1
i.e. 2147483647

'jurrasic' lets greet us also in Python.

The only existing 'workaround' seem to be,
to go for a 64 bit machine with a 64 bit Python version.

No other known way?
Can the Python code not be adjusted, so that C long long is used instead of
C int?

 Claudio


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


Re: Is Python string immutable?

2005-12-02 Thread Steve Holden
could ildg wrote:
> In java and C# String is immutable, str=str+"some more" will return a 
> new string and leave some gargabe.
> so in java and C# if there are some frequent string operation, 
> StringBuilder/StringBuffer is recommanded.
>  
> Will string operation in python also leave some garbage? I implemented a 
> net-spider in python which includes many html string procession. After 
> it running for sometime, the python exe eats up over 300M memory. Is 
> this because the string garbages?
>  
If you create garbage in a Python program it will normally be collected 
and returned to free memory by the garbage collector, which should be 
run when memory is exhausted in preference to allocating more memory. 
Additional memory should therefore only be claimed when garbage 
collection fails to return sufficient free space.

If cyclic data structures are created (structures in which components 
refer to each other even though no external references exist) this could 
cause problems in older versions of Python, but nowadays the garbage 
collector also takes pains to collect unreferenced cyclic structures.

> If String in python is immutable, what class should I use to avoid too 
> much garbages when processing strings frequently?
> 
The fact that your process uses 300MB implies that you are retaining 
references to a large amount of data. Without seeing the code, however, 
it's difficult to suggest how you might improve the situation. Are you, 
for example, holding the HTML for every spidered page?

As a side note, both C# and Java also use garbage collection, so if your 
algorithm exhibits the same problem in all three languages this merely 
confirms that the problem really is your algorithm, and not the language 
in which it is implemented.

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: Instances behaviour

2005-12-02 Thread bruno at modulix
Inyeol Lee wrote:
(snip)

class A(object):
... def __init__(self, foo):
... if self.__class__ is A:
... raise TypeError("A is base class.")   


s/TypeError/NotImplementedError/
s/base class/abstract class/


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


Re: Death to tuples!

2005-12-02 Thread Antoon Pardon
On 2005-12-01, Mike Meyer <[EMAIL PROTECTED]> wrote:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> On 2005-12-01, Mike Meyer <[EMAIL PROTECTED]> wrote:
>>> Antoon Pardon <[EMAIL PROTECTED]> writes:
 I know what happens, I would like to know, why they made this choice.
 One could argue that the expression for the default argument belongs
 to the code for the function and thus should be executed at call time.
 Not at definion time. Just as other expressions in the function are
 not evaluated at definition time.
>>>
>>> The idiom to get a default argument evaluated at call time with the
>>> current behavior is:
>>>
>>> def f(arg = None):
>>> if arg is None:
>>>arg = BuildArg()
>>>
>>> What's the idiom to get a default argument evaluated at definition
>>> time if it were as you suggested?
>>
>> Well there are two possibilities I can think of:
>>
>> 1)
>>   arg_default = ...
>>   def f(arg = arg_default):
>>  ...
>
> Yuch. Mostly because it doesn't work:
>
> arg_default = ...
> def f(arg = arg_default):
> ...
>
> arg_default = ...
> def g(arg = arg_default):
>
> That one looks like an accident waiting to happen.

It's not because accidents can happen, that it doesn't work.
IMO that accidents can happen here is because python
doesn't allow a name to be marked as a constant or unreboundable.

> This may not have been the reason it was done in the first place, but
> this loss of functionality would seem to justify the current behavior.
>
> And, just for fun:
>
> def setdefaults(**defaults):
> def maker(func):
> def called(*args, **kwds):
> defaults.update(kwds)
> func(*args, **defaults)
> return called
> return maker

So it seems that with a decorator there would be no loss of
functionality.

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


Re: Instances behaviour

2005-12-02 Thread Mr.Rech
Thanks for your suggestions. They are very usefull and indeed bypass my
problem. However, I've found a (perhaps) more elegant way to get the
same result using metaclasses. My idea is to define my classes as
follows:

>>> class meta_A(type):
  def __new__(cls, classname, bases, classdict):
 # define here all special methods
 newdict = { #special methods dict}
 classdict.update(newdict) # any suggestion on
automatically build newdict?
 return type.__new__(cls, classname, bases, classdict)

>>> class B(object):
  __metaclass__ = meta_A
  # More methods here

I know metaclasses are a complete different beast, anyway I find this
approach more pythonic. Any comment? Suggestion?

Thanks,
 Andrea.

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


Re: Problem cmpiling M2Crypto

2005-12-02 Thread Thomas G. Apostolou
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Thomas G. Apostolou wrote:
>
> > I still get the error:
> > "SWIG/_m2crypto.c(80) : fatal error C1083: Cannot open include file:
> > 'Python.h': No such file or directory
> > error: command '"C:\Program Files\Microsoft Visual
Studio\VC98\BIN\cl.exe"'
> > failed with exit status 2"
> >
> > witch is -as Heikki Toivonen told- because of lack of Python.h
> > I do not hane this file anywhere in my PC.
> > Could anyone sujest of a package to install that contains Python.h and
that
> > would be of use for me later on?
>
> most standard Python installers come with this file (it's usually in
> ./include relative to the installation directory).
>
> I suggest installing a python.org release:
>
> http://www.python.org/
>
> and using that to build the extensions.
>
> (make sure you get the same version as your Plone uses)
>
> 

So what you say is that the Python installed with Plone doesn't have
Python.h in ./include but Python installers from Python.org do have the
file?
If yes i guess i should install the same version to the same location
(over-writing). Is that so?

Thanks again!



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


Re: Compiling Guppy-PE extension modules

2005-12-02 Thread Sverker Nilsson
"Claudio Grondi" <[EMAIL PROTECTED]> wrote:

> but the problem with sets.c remains:
>
> C:\VisualC++NET2003\Vc7\bin\cl.exe /c /nologo /Ox /MD /W3 /G7 /GX
> /DNDEBUG -IE:\Python24\include -IE:\Python24\PC /Tcsrc/sets/sets.c
> /Fobuild\temp.win32-2.4\Re
> lease\src/sets/sets.obj
> sets.c
> src\sets\sets.c(68) : error C2099: initializer is not a constant
> src\sets\sets.c(68) : warning C4047: 'initializing' : 'PyTypeObject *'
> differs in levels of indirection from 'NyHeapDef_SizeGetter'
> src\sets\sets.c(69) : error C2099: initializer is not a constant
> src\sets\sets.c(69) : warning C4028: formal parameter 1 different from
> declaration
> src\sets\sets.c(70) : error C2099: initializer is not a constant
> src\sets\sets.c(70) : warning C4047: 'initializing' : 'PyTypeObject *'
> differs in levels of indirection from 'int (__cdecl *)(PyObject *)'
> src\sets\sets.c(70) : warning C4028: formal parameter 1 different from
> declaration
> src\sets\sets.c(70) : warning C4028: formal parameter 1 different from
> declaration
> error: command 'E:\VisualC++NET2003\Vc7\bin\cl.exe' failed with exit status
> 2
>
> The MSDN help gives a simple example of code raising compiler error C2099:
> // C2099.c
> int j;
> int *p;
> j = *p;   // C2099, *p is not a constant
>
> The example code shows to me, that there is a good reason  compiler
> generates an error in that case.
> j = *p; leads to an assignment of a random (and therefore maybe leading to a
> non deterministic crash of the executable during runtime) value to a
> variable, what can't be intended in a deterministic program.

This is confusing, because the problem of the example code is not that
*p is not constant but rather that p is undefined aka uninitialized.

Humm..

Compiling the following program:

#include 
int main(void) {
int j;
int *p;
j = *p;
printf("%d\n",j); /* Makes sure the optimizer doesnt remove the
previous code */
return 0;
}

with

gcc -O3 -Wall main.c

gives me:

main.c: In function `main':
main.c:4: warning: `p' might be used uninitialized in this function

(And I get a Segmentation fault from running the executable.)

The -Wall flag enables, umm, as it is saying 'all' warnings
though perhaps not really all, and this flag + others is used
by the compilation command generated by distutils when
building with gcc.

I don't see any warnings when building Guppy.

So there should be no case (as easy to discover) as that in the
example.

So I am confused.

I was beginning to wonder if we were talking about the same file/code.
This code is from sets.c lines 66..71

static NyHeapDef nysets_heapdefs[] = {
{0, &NyMutBitSet_Type, (NyHeapDef_SizeGetter) mutbitset_indisize},
{0, &NyCplBitSet_Type, 0, cplbitset_traverse},
{0, &NyNodeSet_Type, nodeset_indisize,  nodeset_traverse,
nodeset_relate},
{0}
};

I can't see how there can be problems with initializers not being
constants here unless, perhaps if the compiler has a problem since
those functions (mutbitset_indisize etc) and the types that are used
as initializers are in separately compiled files. But gcc -Wall
-pedantic handles it and doesn't warn. I don't have the ANSI standard
but I have the 2nd edition of The C Programming Language by Kernighan
and Ritchie (1988, 'Based on Draft-Proposed ANSI C'), and it is saying

- quotes -

A8.7 Initialization
...

All the expressions in the initializer for a static object or array
must be constant expressions as described in &A7.19
...

A7.19 Constant Expressions

Syntactically, a constant expression is an expression restricted to a
subset of operators...
...

More latitude is permitted for the constant expressions of
initializers...  Initializers must evaluate either to a constant or to
the address of a previously declared external or static object plus or
minus a constant.

- end quotes -

If this means the Microsoft .NET compiler is perhaps not compliant
with standard/ANSI C then since it was from 2003 maybe they have come
out with an update now that fixes this problem. I know, it may not
really help you because it may cost money, I don't know how long one
can get updates without paying. Alternatively, I think GCC is
available for Microsoft Windows although I don't know how it handles
the .NET architecture.

For me, if the case is according to hypothesis, and I would have to
rewrite the code to put all the functions and type objects in a single
file, it would be.. umm.. painful. (Though I could get around
it with #include trickery but it is still painful.)

Sverker

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


Re: Instances behaviour

2005-12-02 Thread Peter Otten
Mr.Rech wrote:

> Thanks for your suggestions. They are very usefull and indeed bypass my
> problem. However, I've found a (perhaps) more elegant way to get the
> same result using metaclasses. My idea is to define my classes as
> follows:
> 
 class meta_A(type):
>   def __new__(cls, classname, bases, classdict):
>  # define here all special methods
>  newdict = { #special methods dict}
>  classdict.update(newdict) # any suggestion on
> automatically build newdict?
>  return type.__new__(cls, classname, bases, classdict)

Are you intentionally defeating inheritance?
 
 class B(object):
>   __metaclass__ = meta_A
>   # More methods here
> 
> I know metaclasses are a complete different beast, anyway I find this
> approach more pythonic. Any comment? Suggestion?

Godawful. 

Don't use classes when functions suffice.
Don't use inheritance when duck-typing suffices.
Don't use metaclasses when inheritance suffices.
Corollary: don't use metaclasses to solve problems you have just made up.

In short, the simplest solution is most likely the most pythonic, even when
some odd corner cases are not covered. 

Simplicity also has a nice side effect: fewer bugs.

Peter

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


Re: Compiling Guppy-PE extension modules

2005-12-02 Thread Claudio Grondi

"Sverker Nilsson" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> "Claudio Grondi" <[EMAIL PROTECTED]> wrote:
>
> > but the problem with sets.c remains:
> >
> > C:\VisualC++NET2003\Vc7\bin\cl.exe /c /nologo /Ox /MD /W3 /G7 /GX
> > /DNDEBUG -IE:\Python24\include -IE:\Python24\PC /Tcsrc/sets/sets.c
> > /Fobuild\temp.win32-2.4\Re
> > lease\src/sets/sets.obj
> > sets.c
> > src\sets\sets.c(68) : error C2099: initializer is not a constant
> > src\sets\sets.c(68) : warning C4047: 'initializing' : 'PyTypeObject *'
> > differs in levels of indirection from 'NyHeapDef_SizeGetter'
> > src\sets\sets.c(69) : error C2099: initializer is not a constant
> > src\sets\sets.c(69) : warning C4028: formal parameter 1 different from
> > declaration
> > src\sets\sets.c(70) : error C2099: initializer is not a constant
> > src\sets\sets.c(70) : warning C4047: 'initializing' : 'PyTypeObject *'
> > differs in levels of indirection from 'int (__cdecl *)(PyObject *)'
> > src\sets\sets.c(70) : warning C4028: formal parameter 1 different from
> > declaration
> > src\sets\sets.c(70) : warning C4028: formal parameter 1 different from
> > declaration
> > error: command 'E:\VisualC++NET2003\Vc7\bin\cl.exe' failed with exit
status
> > 2
> >
> > The MSDN help gives a simple example of code raising compiler error
C2099:
> > // C2099.c
> > int j;
> > int *p;
> > j = *p;   // C2099, *p is not a constant
> >
> > The example code shows to me, that there is a good reason  compiler
> > generates an error in that case.
> > j = *p; leads to an assignment of a random (and therefore maybe leading
to a
> > non deterministic crash of the executable during runtime) value to a
> > variable, what can't be intended in a deterministic program.
>
> This is confusing, because the problem of the example code is not that
> *p is not constant but rather that p is undefined aka uninitialized.
>
> Humm..
>
> Compiling the following program:
>
> #include 
> int main(void) {
> int j;
> int *p;
> j = *p;
> printf("%d\n",j); /* Makes sure the optimizer doesnt remove the
> previous code */
> return 0;
> }
>
> with
>
> gcc -O3 -Wall main.c
>
> gives me:
>
> main.c: In function `main':
> main.c:4: warning: `p' might be used uninitialized in this function
>
> (And I get a Segmentation fault from running the executable.)
>
> The -Wall flag enables, umm, as it is saying 'all' warnings
> though perhaps not really all, and this flag + others is used
> by the compilation command generated by distutils when
> building with gcc.
>
> I don't see any warnings when building Guppy.
>
> So there should be no case (as easy to discover) as that in the
> example.
>
> So I am confused.
>
> I was beginning to wonder if we were talking about the same file/code.
> This code is from sets.c lines 66..71
>
> static NyHeapDef nysets_heapdefs[] = {
> {0, &NyMutBitSet_Type, (NyHeapDef_SizeGetter) mutbitset_indisize},
> {0, &NyCplBitSet_Type, 0, cplbitset_traverse},
> {0, &NyNodeSet_Type, nodeset_indisize,  nodeset_traverse,
> nodeset_relate},
> {0}
> };
The code in my sets.c file is lines 67..72:
static NyHeapDef nysets_heapdefs[] = {
{0, &NyMutBitSet_Type, (NyHeapDef_SizeGetter) mutbitset_indisize},
{0, &NyCplBitSet_Type, 0, cplbitset_traverse},
{0, &NyNodeSet_Type, nodeset_indisize,  nodeset_traverse,
nodeset_relate},
{0}
};

Maybe you can explain what this declaration is good for and where the
identifiers are defined, so that I have a chance to fix it myself?
Currently I have no idea where to start and what is wrong with it.
It seems, that the only one not declared identifier is NyHeapDef_SizeGetter,
but this does not help because if I preceede the code with
extern NyHeapDef_SizeGetter
I get:

src\sets\sets.c(68) : warning C4091: 'extern ' : ignored on left of 'int
(__cdecl *)(PyObject *)' when no variable is declared
src\sets\sets.c(78) : error C2099: initializer is not a constant
src\sets\sets.c(78) : warning C4047: 'initializing' : 'PyTypeObject *'
differs in levels of indirection from 'NyHeapDef_SizeGetter'
src\sets\sets.c(79) : error C2099: initializer is not a constant
src\sets\sets.c(79) : warning C4028: formal parameter 1 different from
declaration
src\sets\sets.c(80) : error C2099: initializer is not a constant
src\sets\sets.c(80) : warning C4047: 'initializing' : 'PyTypeObject *'
differs in levels of indirection from 'int (__cdecl *)(PyObject *)'
src\sets\sets.c(80) : warning C4028: formal parameter 1 different from
declaration
src\sets\sets.c(80) : warning C4028: formal parameter 1 different from
declaration
error: command 'E:\VisualC++NET2003\Vc7\bin\cl.exe' failed with exit status
2

where the code at line 68 is:

extern NyHeapDef_SizeGetter; // line 68
// extern mutbitset_indisize;
// extern NyCplBitSet_Type;
// extern cplbitset_traverse;
// extern NyNodeSet_Type;
// extern nodeset_indisize;
// extern nodeset_traverse;
// extern nodeset_relate;

static NyHeapDef nysets_heapdefs[] = {
{0, &NyMutBitSet_Type, 

Re: Need help on designing a project

2005-12-02 Thread Steve Holden
Mardy wrote:
> Hi all,
>   I'm starting to think the way I've implemented my program
> (http://www.mardy.it/eligante) is all wrong.
> Basically, what I want is a web application, which might run as CGI
> scripts in apache (and this is working) or even as a standalone
> application, in which case it would use it's own internal webserver.
> 
> The question is about this homemade webserver: right now it's a slightly
> modified version of the standard CGIHTTPServer module. Since I know all my
> CGIs are python scripts, I thought that performance would be best if they
> are executed with the execfile command, in the same process as the
> webserver.
> 
> This works, but my problem is that SQL connections (MySQL or sqlite) don't
> get closed when the script execution finishes, and at the next execution
> of a CGI they may lock the database (this is especially true with sqlite,
> but even mysql on Windows gave me these problems).
> 
> I tryed to call atexit.register() from inside the CGI script (in order to
> close the connection) but my atexit function get called only when the
> webserver itself exits.
> 
> 
> So, I'd like to know if there is a quick solution, or if I have to rewrite
> the whole mechanism (maybe using some existing framework? which one?).
> 
> 
> What I care most, is the ease of installation and use of my program (and
> portability). That's why I'm not contented with apache.
> 
> 
The logical solution to your problem appears to be to explicitly close 
the database connections at the end of each CGI script. Is there some 
reason you can't do this?

Note that if you are using execfile()then the best structure for your 
scripts would be something like:

conn = db.open()
try:
 #do CGI stuff
finally:
 conn.close()

to make sure that the connection is always closed. Would this help, do 
you think?

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: Instances behaviour

2005-12-02 Thread bruno at modulix
Mr.Rech wrote:
> Thanks for your suggestions. They are very usefull and indeed bypass my
> problem. However, I've found a (perhaps) more elegant way to get the
> same result using metaclasses. 


(snip code)
> 
> I know metaclasses are a complete different beast, anyway I find this
> approach more pythonic. 

It's not. It's a case of ArbitraryOvercomplexification(tm).

The pythonic way is to use inheritence and make the base class abstract
by raising a NotImplementedError in it's __init__ (cf Inyeol Lee's
answer and my small correction)


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


How to creat a file?

2005-12-02 Thread sandorf
I'm new to python. Have a simple question.

"open" function can only open an existing file and raise a IOerror when
the given file does not exist. How can I creat a new file then?

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


Import path for unit tests

2005-12-02 Thread Ben Finney
Howdy all,

My practice when writing unit tests for a project is to make 'test/'
subdirectories for each directory containing modules I want to test.

project-foo/
+-- lib/
|   +-- test/
+-- data/
+-- gui/
|   +-- test/
+-- server/
+-- test/

This means that I need to use relative paths to import the subject
code into the unit test module.

import unittest

import sys
sys.path.append('..')
import foomodule

class Test_Foo(unittest.TestCase):
# ...

This works, so long as the foomodule is *not* in the path before the
appended '..' directory. When writing unit tests for a development
version of a package that is already installed at an older version in
the Python path, this fails: the unit tests are not importing the
development version of foomodule.

What is the common idiom here? I can conceive of several possible ways
to get around it, all of which seem hackish to some degree.

-- 
 \"It's not what you pay a man, but what he costs you that |
  `\  counts."  -- Will Rogers |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem cmpiling M2Crypto under Plone

2005-12-02 Thread Fredrik Lundh
Thomas G. Apostolou wrote:

> So what you say is that the Python installed with Plone doesn't have
> Python.h in ./include but Python installers from Python.org do have the
> file?

that's likely, given building didn't work for you.

after all, Plone's an application that happens to include a Python interpreter,
not a Python distribution.

> If yes i guess i should install the same version to the same location
> (over-writing). Is that so?

to minimize the risk, I'd grab the corresponding python.org version, install it
in a separate location, use the python.org version to build the extensions, and
finally install them in the Plone tree.

but maybe there's no risk for conflict; maybe someone from the Plone team
can clarify ?

 



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


Re: python speed

2005-12-02 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> DecInt's division algorithm is completely general also. But I would
> never claim that Python code is faster than assembler. I believe that
> careful implementation of a good algorithm is more important than the
> raw speed of the language or efficiency of the compiler. Python makes
> it easy to implement algorithms.

that was of course the point here (and your work with DecInt is an
excellent illustration of this principle).

 



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


Re: How to creat a file?

2005-12-02 Thread Laurent RAHUEL
sandorf wrote:

> I'm new to python. Have a simple question.
> 
> "open" function can only open an existing file and raise a IOerror when
> the given file does not exist. How can I creat a new file then?

fic = open('test.txt', 'w')
fic.write('Hello world')
fic.close()


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


Re: How to creat a file?

2005-12-02 Thread Wolfram Kraus
sandorf wrote:
> I'm new to python. Have a simple question.
> 
> "open" function can only open an existing file and raise a IOerror when
> the given file does not exist. How can I creat a new file then?
> 
open the new file in write mode: open('foo', 'w')
See: help(open)

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


Re: How to creat a file?

2005-12-02 Thread Juho Schultz
sandorf wrote:
> I'm new to python. Have a simple question.
> 
> "open" function can only open an existing file and raise a IOerror when
> the given file does not exist. How can I creat a new file then?
> 

You already have two correct answers. A warning: if you open a existing
file for writing, it is truncated (the old contents of that file
disappear.) For adding new content to the end of an existing file,
you can use:

f = open(filename,'a')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to creat a file?

2005-12-02 Thread Fredrik Lundh
"sandorf" <[EMAIL PROTECTED]> wrote:

> I'm new to python. Have a simple question.
>
> "open" function can only open an existing file and raise a IOerror when
> the given file does not exist. How can I creat a new file then?

reading the documentation might help:

>>> help(open)

class file(object)
 |  file(name[, mode[, buffering]]) -> file object
 |
 |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
 |  writing or appending.  The file will be created if it doesn't exist
 |  when opened for writing or appending; it will be truncated when
 |  opened for writing.  Add a 'b' to the mode for binary files.
 |  Add a '+' to the mode to allow simultaneous reading and writing.

/snip/

 |  Note:  open() is an alias for file().

this is also explained in the chapter 7 of the tutorial ("reading and writing 
files"),
as well as the reference manual.

 



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


Re: Death to tuples!

2005-12-02 Thread Antoon Pardon
On 2005-12-02, Bengt Richter <[EMAIL PROTECTED]> wrote:
> On 1 Dec 2005 09:24:30 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>>On 2005-11-30, Duncan Booth <[EMAIL PROTECTED]> wrote:
>>> Antoon Pardon wrote:
>>>
> The left one is equivalent to:
>
> __anon = []
> def Foo(l):
>...
>
> Foo(__anon)
> Foo(__anon)
 
 So, why shouldn't: 
 
res = []
for i in range(10):
   res.append(i*i)
 
 be equivallent to:
 
   __anon = list()
   ...
 
res = __anon
for i in range(10):
   res.append(i*i)
>>>
>>> Because the empty list expression '[]' is evaluated when the expression 
>>> containing it is executed.
>>
>>This doesn't follow. It is not because this is how it is now, that that
>>is the way it should be.
>>
>>I think one could argue that since '[]' is normally evaluated when
>>the expression containing it is excuted, it should also be executed
>>when a function is called, where '[]' is contained in the expression
>  ^^^[1] ^
>>determining the default value.
>  ^^^[2]
> Ok, but "[]" (without the quotes) is just one possible expression, so
> presumably you have to follow your rules for all default value expressions.
> Plain [] evaluates to a fresh new empty list whenever it is evaluated,

Yes, one of the questions I have is why python people whould consider
it a problem if it wasn't.

Personnaly I expect the following pieces of code

  a = 
  b = 

to be equivallent with

  a = 
  b = a

But that isn't the case when the const expression is a list.

A person looking at:

  a = [1 , 2]

sees something resembling

  a = (1 , 2)

Yet the two are treated very differently. As far as I understand the
first is translated into somekind of list((1,2)) statement while
the second is build at compile time and just bound.

This seems to go against the pythonic spirit of explicit is
better than implicit.

It also seems to go against the way default arguments are treated.

> but that's independent of scope. An expression in general may depend on
> names that have to be looked up, which requires not only a place to look
> for them, but also persistence of the name bindings. so def 
> foo(arg=PI*func(x)): ...
> means that at call-time you would have to find 'PI', 'func', and 'x' 
> somewhere.
> Where & how?
> 1) If they should be re-evaluated in the enclosing scope, as default arg 
> expressions
> are now, you can just write foo(PI*func(x)) as your call.

I may be a bit pedantic. (Read that as I probably am)

But you can't necesarry write foo(PI*func(x)) as your call, because PI
and func maybe not within scope where the call is made.

> So you would be asking
> for foo() to be an abbreviation of that. Which would give you a fresh list if
> foo was defined def foo(arg=[]): ...

This was my first thought.

> Of course, if you wanted just the expression value as now at def time, you 
> could write
> def foo(...):...; foo.__default0=PI*fun(x) and later call 
> foo(foo.__default0), which is
> what foo() effectively does now.
>
> 2) Or did you want the def code to look up the bindings at def time and save 
> them
> in, say, a tuple __deftup0=(PI, func, x) that captures the def-time bindings 
> in the scope
> enclosing the def, so that when foo is called, it can do arg = 
> _deftup0[0]*_deftup0[1](_deftup0[2])
> to initialize arg and maybe trigger some side effects at call time.

This is tricky, I think it would depend on how foo(arg=[]) would be
translated. 

   2a) _deftup0=([]), with a subsequent arg = _deftup0[0]
or 
   2b) _deftup0=(list, ()), with subsequently arg = _deftup0[0](_deftup0[1])


My feeling is that this proposal would create a lot of confusion.

Something like def f(arg = s) might give very different results
depending on s being a list or a tuple.

> 3) Or did you want to save the names themselves, __default0_names=('PI', 
> 'func', 'x')
> and look them up at foo call time, which is tricky as things are now, but 
> could be done?

No, this would make for some kind of dynamic scoping, I don't think it
would mingle with the static scoping python has now.


> The left has one list created outside the body of the function, the
> right one has two lists created outside the body of the function. Why
> on earth should these be the same?
 
 Why on earth should it be the same list, when a function is called
 and is provided with a list as a default argument?
> It's not "provided with a list" -- it's provided with a _reference_ to a list.
> You know this by now, I think. Do you want clone-object-on-new-reference 
> semantics?
> A sort of indirect value semantics? If you do, and you think that ought to be
> default semantics, you don't want Python. OTOH, if you want a specific effect,
> why not look for a way to do it either within python, or as a graceful 
> syntactic
> enhancement to python? E.g., def foo(a

Re: aligning a set of word substrings to sentence

2005-12-02 Thread Fredrik Lundh
Steven Bethard wrote:

>>> I feel like there should be a simpler solution (maybe with the re
>>> module?) but I can't figure one out.  Any suggestions?
>>
>> using the finditer pattern I just posted in another thread:
>>
>> tokens = ['She', "'s", 'gon', 'na', 'write', 'a', 'book', '?']
>> text = '''\
>> She's gonna write
>> a book?'''
>>
>> import re
>>
>> tokens.sort() # lexical order
>> tokens.reverse() # look for longest match first
>> pattern = "|".join(map(re.escape, tokens))
>> pattern = re.compile(pattern)
>>
>> I get
>>
>> print [m.span() for m in pattern.finditer(text)]
>> [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 25)]
>>
>> which seems to match your version pretty well.
>
> That's what I was looking for.  Thanks!

except that I misread your problem statement; the RE solution above allows the
tokens to be specified in arbitrary order.  if they've always ordered, you can 
re-
place the code with something like:

# match tokens plus optional whitespace between each token
pattern = "\s*".join("(" + re.escape(token) + ")" for token in tokens)
m = re.match(pattern, text)
result = (m.span(i+1) for i in range(len(tokens)))

which is 6-7 times faster than the previous solution, on my machine.

 



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


Re: CGI module does not parse data

2005-12-02 Thread Mardy
Le die Thu, 01 Dec 2005 15:08:14 -0800, amfr ha scribite:

> I have included some of the content of that file, I am writing this as
> an extension to my ebserver which is based on BaseHTTPServer.  This
> part of the code was taken directly from the CGIHTTPServer file,
> nothing changed

I did the same, it is working for me. About Mac problems, the only thing I
know is that in the code of CGIHTTPServer itself a comment says that
execfile() is the only way to run a CGI on Mac. But it should work.

Maybe it's just your browser, which doesn't show you the output of the
CGI. Did you try connecting to the webserver by telnet?


-- 
Saluti,
Mardy
http://interlingua.altervista.org

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


Re: Import path for unit tests

2005-12-02 Thread Duncan Booth
Ben Finney wrote:

> This works, so long as the foomodule is *not* in the path before the
> appended '..' directory. When writing unit tests for a development
> version of a package that is already installed at an older version in
> the Python path, this fails: the unit tests are not importing the
> development version of foomodule.

Why not just insert foomodule's directory in front of the other entries in 
sys.path instead of at the end?

> 
> What is the common idiom here? I can conceive of several possible ways
> to get around it, all of which seem hackish to some degree.

I don't know if it is the common idiom, but I tend to write:

TESTDIR = os.path.dirname(os.path.abspath(__file__))
PROJECTDIR = os.path.dirname(TESTDIR)
if not TESTDIR in sys.path:
sys.path.insert(1, TESTDIR)
if not PROJECTDIRDIR in sys.path:
sys.path.insert(1, PROJECTDIR)

That gets put in a framework.py file in the test directory. run_tests.py 
(in the same folder) looks like:

import unittest, os, sys
if __name__ == '__main__':
execfile(os.path.join(sys.path[0], 'framework.py'))

if __name__=='__main__':
suite = unittest.TestSuite()
for testfile in os.listdir(TESTDIR):
if testfile.startswith('test_') and testfile.endswith('.py'):
testfile = os.path.splitext(testfile)[0]

module = __import__(testfile)
suite.addTest(module.suite())

unittest.TextTestRunner(verbosity=2).run(suite)

and all the test files import framework. That way I can run an individual 
test_xxx.py, or use run_tests.py to run all test files, and I can start 
them from the test directory, the project directory, or any other 
directory.
-- 
http://mail.python.org/mailman/listinfo/python-list


why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Adriano Ferreira
Many Python scripts I see start with the shebang line

#!/usr/bin/env python

What is the difference from using just

#!python

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


Re: (newbie) N-uples from list of lists

2005-12-02 Thread Martin Miller
I'd be interested in seeing the one liner using reduce you mentioned --
how it might be done that way isn't obvious to me.

Another aspect of Taschuk's solution I like and think is important is
the fact that it is truly iterative in the sense that calling it
returns a generator which will yield each of the combinations, one at
time.  All the others create and return all the combinations at once
(as I suspect the one liner using reduce you mention does, too).

As you point out, "best" is always in the eyes of the beholder.

"Best" regards, ;-)
-Martin


[EMAIL PROTECTED] wrote:
> Interesting, I found a reduce one liner(just one step further of
> Raymond's) easiest to understand and match my thinking about what the
> problem is about.
>
> That once again tell me that different people think and approach the
> problem differently. It is possible to talk about one "fastest" way,
> but many times there isn't such a thing of one "best" way.
>
> Martin Miller wrote:
> > FWIW, I found Steven Taschuk's solution easiest to understand regarding
> > the question posed in your original post -- namely how to solve the
> > problem non-recursively with generators -- because it was similar to my
> > own thinking about how to do it -- but suspect that Raymond Hettinger's
> > is the likely the "best" (as is usually the case ;-).
> >
> > Best,
> > -Martin
> >
> >
> > [EMAIL PROTECTED] wrote:
> > > great thanks to all.
> > >
> > > actually i have not seen it was a cross product... :) but then there
> > > are already few others ideas from the web, i paste what i have found
> > > below...
> > >
> > > BTW i was unable to choose the best one, speaking about performance
> > > which one should be prefered ?
> > >
> > > ### --
> > >
> > > ### from title: variable X procuct - [(x,y) for x in list1 for y in
> > > list2]
> > > ### by author:  steindl fritz
> > > ### 28 mai 2002
> > > ### reply by:   Jeff Epler
> > >
> > > def cross(l=None, *args):
> > > if l is None:
> > > # The product of no lists is 1 element long,
> > > # it contains an empty list
> > > yield []
> > > return
> > > # Otherwise, the product is made up of each
> > > # element in the first list concatenated with each of the
> > > # products of the remaining items of the list
> > > for i in l:
> > > for j in cross(*args):
> > > yield [i] + j
> > >
> > > ### reply by:   Raymond Hettinger
> > >
> > > def CartesianProduct(*args):
> > > ans = [()]
> > > for arg in args:
> > > ans = [ list(x)+[y] for x in ans for y in arg]
> > > return ans
> > >
> > > """
> > > print CartesianProduct([1,2], list('abc'), 'do re mi'.split())
> > > """
> > >
> > > ### from:
> > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975
> > > ### by: Raymond Hettinger
> > >
> > > def cross(*args):
> > > ans = [[]]
> > > for arg in args:
> > > ans = [x+[y] for x in ans for y in arg]
> > > return ans
> > >
> > > ### from:
> > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/159975
> > > ### by: Steven Taschuk
> > > """
> > > Iterator version, Steven Taschuk, 2003/05/24
> > > """
> > > def cross(*sets):
> > > wheels = map(iter, sets) # wheels like in an odometer
> > > digits = [it.next() for it in wheels]
> > > while True:
> > > yield digits[:]
> > > for i in range(len(digits)-1, -1, -1):
> > > try:
> > > digits[i] = wheels[i].next()
> > > break
> > > except StopIteration:
> > > wheels[i] = iter(sets[i])
> > > digits[i] = wheels[i].next()
> > > else:
> > > break

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


Re: How to creat a file?

2005-12-02 Thread sandorf
Thank to you all, guys. Here's another question:

I'm using the Windows version of Python and IDLE. When I debug my .py
file, my modification to the .py file does not seem to take effect
unless I restart IDLE. Saving the file and re-importing it doesn't help
either. Where's the problem?

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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Klaus Alexander Seistrup
Adriano Ferreira wrote:

> Many Python scripts I see start with the shebang line
>
> #!/usr/bin/env python
>
> What is the difference from using just
>
> #!python

#v+

$ ls -l /tmp/hello.py
-rwxr-xr-x  1 klaus klaus 38 2005-12-02 14:59 /tmp/hello.py
$ cat /tmp/hello.py
#! python
print 'Hello, world!'
# eof
$ /tmp/hello.py
bash: /tmp/hello.py: python: bad interpreter: No such file or directory
$ 

#v-

Cheers,

-- 
Klaus Alexander Seistrup
Copenhagen, Denmark
http://streetkids.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New Ordered Dictionery to Criticise

2005-12-02 Thread Fuzzyman
Hello Bengt,

Bengt Richter wrote:
> On 1 Dec 2005 03:38:37 -0800, "Fuzzyman" <[EMAIL PROTECTED]> wrote:
>
> >
> >Fuzzyman wrote:
> >> Sorry for this hurried message - I've done a new implementation of out
> >> ordered dict. This comes out of the discussion on this newsgroup (see
> >> blog entry for link to archive of discussion).
> >>
> >> See the latest blog entry to get at it :
> >> http://www.voidspace.org.uk/python/weblog/index.shtml
> >>
> >
> >Hello all,
> >
> >I've just done a new "beta 2" version. It has a full version of
> >FancyODict with the custome "callable sequence objects" for keys,
> >values and items. They are almost completely covered by tests.
> >
> >You can download the new(er) version from :
> >http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=odictbeta2.py
> >
> Ran my tests on it: this one may be of interest:
>  __ entrypoint: test_popitem 
> ___
>
>  def test_popitem():
>  d = CandidateDict([(k,i*100) for i,k in enumerate('abcde')])
>  >   assert d.popitem() == ('e', 400)
>
>  [C:\pywk\ut\test\test_odicts.py:228]
>  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
> _ _
>  ...
>  ...
>  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
> _ _
>
>  def __getattr__(self, name):
>  """
>  Implemented so that access to ``sequence`` raises a warning.
>
>  >>> d = OrderedDict()
>  >>> d.sequence
>  []
>  """
>  if name == 'sequence':
>  warn('use of sequence attribute is deprecated. Use keys method '
>  'instead.', DeprecationWarning)
>  # NOTE: Still (currently) returns a direct reference. Need to
>  #   because code that uses sequence will expect to be able to
>  #   mutate it in place.
>  return self._sequence
>  else:
>  # NOTE: strictly unnecessary, but it raises the appropriate error
>  >   getattr(self, name)
>
>  [c:\pywk\clp\odictbeta2.py:309]
>  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
> _ _
>  Recursion detected (same locals & position)
>  
> !!!
>  = tests finished: 19 passed, 9 failed in 1.57 seconds 
> =
>

Yep the line :

getattr(self, name)

is a bug.

I've replaced it now (not yet "published") with
object.__getattr__(self, name)
It could equally just be replaced with a raise AttributeError

You've picked up on another typo in the code, whichis odd because
``popitem`` is tested.

Oh well - works now.

[snip..]
> >You can currently alter the order (of keys, values *and* items) by
> >passing an iterable into those methods.
> I'm playing this game, but I wonder how much of it really makes sense ;-)
>

Can you explain what you mean ?


> >
> >Someone has suggested that this "smells bad" - and it ought to be
> >done through separate `setkeys``, ``setvalues``, and ``setitems``
> >methods.
> >
> >I'm *inclined* to agree, but I don't feel strongly about it. Anyone
> >else got any opinions ?
> I don't see a big difference. What's important, if you ask me, is
> whether you get an idea of what will happen when you pass the iterable as
> an argument. OTTOMH that suggests that keys/values/items[slice] = iterable
> have more expectation-generating precedent, and in fact perhaps should define
> what is to happen if no other constraints are violated.

Don't completely follow.

Are you saying that

d = OrderedDict(some_iterable)
d.keys[slice] = iterable

is more *understandable*  ("expectation-generating precedent" WTF) ?

The alternative being : d.keys(iterable)

In which case I'm inclined to agree. *However* - having custom objects
for items/keys/values is undoubtably less efficient.

Therefore I'm supplying two classes OrderedDict and FancyODict (name
not yet fixed).

OrderedDict needs a way of changing the keys - so it needs either

d.keys(iterable)

*or*

d.setkeys(iterable)

Which is preferable, is my question.

I think you're saying you don't care :-)
In which case I will leave it as it presently is.

> >
> >* ``repr`` ought to return a value that ``eval`` could use to turn back
> >into an OrderedDict.
> >
> >I have actually done an implementation of this, but it would mean
> >that *all* the doctests need to be changed. I *will* do this at some
> >point.
> Point in favor of py.test's separation of test/tested I guess.
>

Probably. :-)

doctest is part of the standard library - which is a point in it's
favour.


> >
> >* Slice assignment.
> >
> >The semantics for slice assignment are fiddly.
> >
> >For example, what do you do if in a slice assignment a key collides
> >with an existing key ?
> IMO, a slice defines the sliced-out as well as the untouched, and I think
> it is an error to collide with the unouched part, since it requires eit

Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Adriano Ferreira
On 12/2/05, Klaus Alexander Seistrup <[EMAIL PROTECTED]> wrote:
> #v+
>
> $ ls -l /tmp/hello.py
> -rwxr-xr-x  1 klaus klaus 38 2005-12-02 14:59 /tmp/hello.py
> $ cat /tmp/hello.py
> #! python
> print 'Hello, world!'
> # eof
> $ /tmp/hello.py
> bash: /tmp/hello.py: python: bad interpreter: No such file or directory
> $
>
> #v-

Hey, that's not fair. In your illustration above, does 'python' can be
found in the PATH? That is,

$ python /tmp/hello.py

works? If it does, probably

#!/usr/bin/python
#!/usr/bin/env python
#!python

would also work if
(1) 'python' is at '/usr/bin/python' (but that's inflexible)
(2) 'python' can be found in the environment variable path (if 'env'
is at '/usr/bin/env')
(3) 'python' can be found in the environment variable path (no need
for 'env' utility)

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


Re: why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Fredrik Lundh
Adriano Ferreira wrote:

> Many Python scripts I see start with the shebang line
>
> #!/usr/bin/env python
>
> What is the difference from using just
>
> #!python

$ more test.py
#!python
print "hello"
$ chmod +x test.py
$ ./test.py
-bash: ./test.py: python: bad interpreter: No such file or directory

 



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


Re: XML and namespaces

2005-12-02 Thread uche . ogbuji
Quoting Andrew Kuchling:
"""
> >>> element = document.createElementNS("DAV:", "href")

This call is incorrect; the signature is createElementNS(namespaceURI,
qualifiedName).
"""

Not at all, Andrew.  "href" is a valid qname, as is "foo:href".  The
prefix is optional in a QName.  Here is the correct behavior, taken
from a non-broken DOM library (4Suite's Domlette)

>>> from Ft.Xml import Domlette
>>> document = Domlette.implementation.createDocument(None, None, None)
>>> element = document.createElementNS("DAV:", "href")
>>> document.appendChild(element)

>>> Domlette.Print(document)

>>>

"""
If you call .createElementNS('whatever', 'DAV:href'),
the output is the expected:

"""

Oh, no.  That is not at all expected.  The output should be:



"""
It doesn't look like there's any code in minidom that will
automatically create an 'xmlns:DAV="whatever"' attribute for you.  Is
this automatic creation an expected behaviour?
"""

Of course.  Minidom implements level 2 (thus the "NS" at the end of the
method name), which means that its APIs should all be namespace aware.
The bug is that writexml() and thus toxml() are not so.

"""
(I assume not.  Section 1.3.3 of the DOM Level 3 says "Similarly,
creating a node with a namespace prefix and namespace URI, or changing
the namespace prefix of a node, does not result in any addition,
removal, or modification of any special attributes for declaring the
appropriate XML namespaces."  So the DOM can create XML documents that
aren't well-formed w.r.t. namespaces, I think.)
"""

Oh no.  That only means that namespace declaration attributes are not
created in the DOM data structure.  However, output has to fix up
namespaces in .namespaceURI properties as well as directly asserted
"xmlns" attributes.  It would be silly for DOM to produce malformed
XML+XMLNS, and of course it is not meant to.  The minidom behavior
needs fixing, badly.

--
Uche Ogbuji   Fourthought, Inc.
http://uche.ogbuji.nethttp://fourthought.com
http://copia.ogbuji.net   http://4Suite.org
Articles: http://uche.ogbuji.net/tech/publications/

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


Why my modification of source file doesn't take effect when debugging?

2005-12-02 Thread sandorf
I'm using the Windows version of Python and IDLE. When I debug my .py
file, my modification to the .py file does not seem to take effect
unless I restart IDLE. Saving the file and re-importing it doesn't help

either. Where's the problem? 

Thanks.

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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Klaus Alexander Seistrup
Adriano Ferreira skrev:

>> #v+
>>
>> $ ls -l /tmp/hello.py
>> -rwxr-xr-x  1 klaus klaus 38 2005-12-02 14:59 /tmp/hello.py
>> $ cat /tmp/hello.py
>> #! python
>> print 'Hello, world!'
>> # eof
>> $ /tmp/hello.py
>> bash: /tmp/hello.py: python: bad interpreter: No such file or directory
>> $
>>
>> #v-
>
> Hey, that's not fair. In your illustration above, does 'python' can be
> found in the PATH? That is,
>
> $ python /tmp/hello.py
>
> works? If it does, probably
>
> #!/usr/bin/python
> #!/usr/bin/env python
> #!python
>
> would also work if
> (1) 'python' is at '/usr/bin/python' (but that's inflexible)
> (2) 'python' can be found in the environment variable path (if 'env'
> is at '/usr/bin/env')
> (3) 'python' can be found in the environment variable path (no need
> for 'env' utility)

Sure, I wasn't fair.  But look here:

#v+

$ python /tmp/hello.py
Hello, world!
$ which python
/usr/bin/python
$ 

#v-

I do not know the syntax of the shebang-line, but perhaps an absolute 
path is required?

PS: The "Mail-Copies-To: nobody" header line means that I do not wish 
to receive mail replies - please follow-up to group only.

Cheers,

-- 
Klaus Alexander Seistrup
Copenhagen, Denmark
http://streetkids.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Instances behaviour

2005-12-02 Thread Mr.Rech
I see your point. Looking again at my metaclass implementation and
comparing it with your abstract class + inheritance approach it turns
out that the latter is definetively more straightforward, easier to
maintain and all in all more pythonic.

Sorry, but being an OOP newbie put me in the position of
overcomplexifing(tm) things a little bit. I'll be back soon with other
(I hope less silly) questions. ;-p

Thanks for all your suggestions,
 Andrea

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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Carsten Haese
On Fri, 2005-12-02 at 09:12, Adriano Ferreira wrote:
> On 12/2/05, Klaus Alexander Seistrup <[EMAIL PROTECTED]> wrote:
> > #v+
> >
> > $ ls -l /tmp/hello.py
> > -rwxr-xr-x  1 klaus klaus 38 2005-12-02 14:59 /tmp/hello.py
> > $ cat /tmp/hello.py
> > #! python
> > print 'Hello, world!'
> > # eof
> > $ /tmp/hello.py
> > bash: /tmp/hello.py: python: bad interpreter: No such file or directory
> > $
> >
> > #v-
> 
> Hey, that's not fair. In your illustration above, does 'python' can be
> found in the PATH? That is,
> 
> $ python /tmp/hello.py
> 
> works? If it does, probably
> 
> #!/usr/bin/python
> #!/usr/bin/env python
> #!python
> 
> would also work if
> (1) 'python' is at '/usr/bin/python' (but that's inflexible)
> (2) 'python' can be found in the environment variable path (if 'env'
> is at '/usr/bin/env')
> (3) 'python' can be found in the environment variable path (no need
> for 'env' utility)

(3) assumes that whatever shell the user is running looks up the shebang
executable in the path, which bash, just to name one example, does not
do.

(2) and (1) require that you know where env and python live,
respectively, that's true, but env is likely to be found in an
OS-dependent standard location than python, so (2) is preferable.

HTH,

Carsten.


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


Re: Eclipse best/good or bad IDE for Python?

2005-12-02 Thread Jean-François Doyon
I'm a big fan of Eclipse and reocmmend it to anyone who asks :)

No one can say any one is the *best*, since it's a matter of taste,
but it's pretty darn good.

The main benefit IMO is it's felibility ... Eclipse is a *framework*, 
that can handle lots things quite well, like HTML (If you're coding 
python for the web), C/C++ (If you're building extensions), XML if 
you're using that, and so on ... All from within one application, all 
with common paradigms.

The handling of RCS' is also common ...

I use Eclipse + PyDev + Subclipse everyday!

Of course I never could get into Emacs ... It's incredibly powerful too 
though ... Why move away from it?  Is it missing something you need?

+1 on eclipse from me!

J.F.

[EMAIL PROTECTED] wrote:
> I'm trying to move beyond Emacs/Vim/Kate
> and was wondering if Eclipse is better and if it is the *best*
> IDE for Python.
> 
> Should I leave Emacs and do Python coding in Eclipse?
> 
> Chris
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why my modification of source file doesn't take effect when debugging?

2005-12-02 Thread Jeremy Jones
sandorf wrote:

>I'm using the Windows version of Python and IDLE. When I debug my .py
>file, my modification to the .py file does not seem to take effect
>unless I restart IDLE. Saving the file and re-importing it doesn't help
>
>either. Where's the problem? 
>
>Thanks.
>
>  
>
No problem.  Just reload() it.


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


Setting PYTHONPATH from Makefile

2005-12-02 Thread [EMAIL PROTECTED]
I have a Makefile target that uses a python script, like:

%.abc: %.def
python myscript.py

The problem is that myscript.py and some modules that myscript.py
imports are not in the current directory, but in another place in the
filesystem, say, /path/to/stuff. If this was a tcsh script, I would
just do:

   setenv PYTHONPATH /path/to/stuff
   python myscript.py

but this cannot be done from a Makefile. So what do I do? Is there
another way to set the PYTHONPATH? Like giving an option to "python"
itself? Or?

/David

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


Re: Eclipse best/good or bad IDE for Python?

2005-12-02 Thread Fabio Zadrozny
Hi Chris,

I think that you should try it yourself... being the *best ide*  is 
usually a subjective matter, so, you should decide yourself if it is the 
best IDE for the task you want it to.

I must also warn you that I'm its current maintainer, and it is *my* 
favorite IDE :-)

Also, I use it for large projects (2569 .py files on my python 
installation and about 1800 .py files in my project), and, altough I 
agree with the general idea that you need a fast computer to use it at 
optimal performance, I found that using an athlon 1600+ with 512mb RAM 
was enough for me when using eclipse with pydev (also, the features 
provided by eclipse are more than worth the loss of speed when editing 
some things when compared to editors such as vi or emacs, altough the 
learning curve for that might not be so light, in the long run, I'm 
pretty sure that it is worth it -- altough I really miss a faster 
machine for compiling c++).

But in the end, as I said, it is a subjective matter, so, you'll have to 
decide it for yourself.

Cheers,

Fabio

[EMAIL PROTECTED] wrote:

>I'm trying to move beyond Emacs/Vim/Kate
>and was wondering if Eclipse is better and if it is the *best*
>IDE for Python.
>
>Should I leave Emacs and do Python coding in Eclipse?
>
>Chris
>
>  
>


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


Re: (newbie) N-uples from list of lists

2005-12-02 Thread bonono

Martin Miller wrote:
> I'd be interested in seeing the one liner using reduce you mentioned --
> how it might be done that way isn't obvious to me.
>
> Another aspect of Taschuk's solution I like and think is important is
> the fact that it is truly iterative in the sense that calling it
> returns a generator which will yield each of the combinations, one at
> time.  All the others create and return all the combinations at once
> (as I suspect the one liner using reduce you mention does, too).
>
> As you point out, "best" is always in the eyes of the beholder.
>
> "Best" regards, ;-)

def combine_lol(seq): return reduce(lambda x,y: (a+(b,) for a in x for
b in y), seq, [()])

I use generator expression but being a reduce, it will still goes all
the way till the last sequence before you can have any output. That is
the nature of the problem anyway. You can use scanl equivalent to have
intermediate result if the problem allows but I don't that is true in
this case.

The python community is quite against this kind of thing and treat
map/filter/reduce as plague, it is described as ugly/messy :-)

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


Re: an intriguing wifi http server mystery...please help

2005-12-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Could the above server-speed assymetry that i spoke of above be caused
> by this reverse dns lookup?

I think so. You stated that you use "a fairly simple HTTP server",
although that's not exactly specific enough to diagnose the problem,
but if that were the standard library's BaseHTTPServer then reverse DNS
lookups could well be an issue: that particular server attempts to log
addresses, and in the address_string method there's a call to
socket.getfqdn which could invoke such reverse lookups.

Paul

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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Adriano Ferreira
On 12/2/05, Carsten Haese <[EMAIL PROTECTED]> wrote:
> (3) assumes that whatever shell the user is running looks up the shebang
> executable in the path, which bash, just to name one example, does not
> do.

I think that was the answer I was looking for. So that "#!/usr/bin/env
python" is more portable than "#! python" and that's probably why it
worked for me with cygwin/bash but not for Klaus on whatever platform
he used.

> (2) and (1) require that you know where env and python live,
> respectively, that's true, but env is likely to be found in an
> OS-dependent standard location than python, so (2) is preferable.

I agree. Only a very strange Unix-like installation would not have
'env' at '/usr/bin/env'.

Many thanks to Klaus and Carsten for helping me find out why this
convention is helpful/useful.

Best regards,
Adriano
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Klaus Alexander Seistrup
Adriano Ferreira wrote:

> So that "#!/usr/bin/env python" is more portable than "#! python" 
> and that's probably why it worked for me with cygwin/bash but not 
> for Klaus on whatever platform he used.

/me is using bash on linux.

> I agree. Only a very strange Unix-like installation would not have
> 'env' at '/usr/bin/env'.

According to :

  »However, env(1) is not /usr/bin/env but /bin/env at least on 
   Unicos 9.0.2, OpenServer 5.0.6 and IIRC on at least one older 
   Linux distribution. Free-, Net- and OpenBSD in turn only come 
   with /usr/bin/env. So the env-mechanism is increasing conven-
   ience, but not strictly assuring portability.«

Cheers,

-- 
Klaus Alexander Seistrup
PNX · http://pnx.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ruby on Rails Job Site -- Is there a Python equivalent?

2005-12-02 Thread Paul Boddie
Adrian Holovaty wrote:
> http://code.djangoproject.com/wiki/DevelopersForHire
>
> See the "Django-powered jobs" section. We could definitely advertise
> this page more, as it's a bit hidden at the moment on the Django wiki.

Don't forget the Python Job Board:

http://www.python.org/Jobs.html

Yes, it's a bit more general than just "Django-powered jobs", but I'm
sure you could persuade the webmaster to link to specific, maintained,
Python-related employment resources.

Paul

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


Re: [[x,f(x)] for x in list that maximizes f(x)] <--newbie help

2005-12-02 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:
   ...
> As while DSU is a very smart way to guard the max compare thing, it is
> still being introduced as a way that is not related to the original
> problem, i.e. I just want to compare f(x)

And that's why in 2.5 you'll just code max(mylist, key=f) to express
this intent exactly -- that's precisely what 'key=' means.


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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Adriano Ferreira
On 12/2/05, Klaus Alexander Seistrup <[EMAIL PROTECTED]> wrote:
> /me is using bash on linux.

I think that was not a bash issue in my case, but a Cygwin/Win32
issue. Windows has some monstruous oddities in order to assure broken
behavior of yesterday is here today in the name of compatibility.
Examples of these everlasting broken behaviors in Windows are looking
at current directory and path no matter what you say. Cygwin isn't
immune to this.

> According to :
>
>   »However, env(1) is not /usr/bin/env but /bin/env at least on
>Unicos 9.0.2, OpenServer 5.0.6 and IIRC on at least one older
>Linux distribution. Free-, Net- and OpenBSD in turn only come
>with /usr/bin/env. So the env-mechanism is increasing conven-
>ience, but not strictly assuring portability.«

That is to the point. Thanks.

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


How do you create a custom QCursor in Python Qt?

2005-12-02 Thread Steegg
I am a newcomer to using Python and Qt and the main problem that I have
is the dearth of any example code or books describing the use of Python
and Qt together.

My current problem is that I want to create a custom cursor, from my
understanding of it I need to create two "QBitmap"s, one of which will
be the mask and then using these to create a "QCursor".
I don't mine whether the "QBitmap"s are hardcoded in the source code or
come from image files, just as long as I can create a new cursor:

I have searched all the available code sources I can find:
www.koders.com
Eric
Veus
Civil
Qomics
for examples of how to create cursors but to no avail. So if amyone can
tell me what I'm doing wrong, it would be much appreciated, here's my
code:


#
# InlineBitmapCursor.py
# environment:  Mac OS X 10.4.2  -  Python 2.4.1  -  Qt 3.3.5
# status:   does not produce any error messages but also does not
change
#   the cursor.
# standalone file

import sys, os
from qt import *

class MainWindow(QMainWindow):

def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.setCaption("Custom Cursor")
self.grid=QGrid(2, self)
self.setCentralWidget(self.grid)

self.grid.setFrameShape(QFrame.StyledPanel)

self.button1=QPushButton("Arrow Cursor", self.grid)

self.button2=QPushButton("Bitmap Cursor", self.grid)

self.arrowCursor = QCursor(Qt.ArrowCursor)
self.setCursor(self.arrowCursor)

self.connect(self.button1, SIGNAL("clicked()"), self.arrow)
self.connect(self.button2, SIGNAL("clicked()"), self.bitmap)

# 8 * 8 bitmap - two random bit maps
#self.bitmap2 = QBitmap(8, 8,
"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a")
self.bitmap2 = QBitmap(8, 8,
"\x89\x55\x55\x55\x0d\x0a\x1a\x0a")
self.bitmap3 = QBitmap(8, 8,
"\x88\x67\x34\xaa\x23\x60\x84\xbb")
print "bitmap2 " + repr(self.bitmap2)
print "bitmap3 " + repr(self.bitmap3)

self.inlineBitmapCursor = QCursor(self.bitmap2, self.bitmap3)
print "before setCursor"
self.setCursor(self.inlineBitmapCursor)
print "after setCursor"



def arrow(self):
self.setCursor(self.arrowCursor)


def bitmap(self):
self.setCursor(self.inlineBitmapCursor)


def main(args):
app=QApplication(args)
win=MainWindow()
win.show()
app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")
)
app.exec_loop()


if __name__=="__main__":
main(sys.argv)




This is what happen when it executes:

[~] steve% "/usr/local/bin/pythonw"
"/Users/steve/PythonDev/qt3.3.5/CursorExamples/InlineBitmapCursor.py"
&& echo Exit status: $? && exit 1
bitmap2 
bitmap3 
before setCursor
after setCursor


thanks,
Steve Greenwood

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


Re: aligning a set of word substrings to sentence

2005-12-02 Thread Steven Bethard
Fredrik Lundh wrote:
> Steven Bethard wrote:
> 
> 
I feel like there should be a simpler solution (maybe with the re
module?) but I can't figure one out.  Any suggestions?
>>>
>>>using the finditer pattern I just posted in another thread:
>>>
>>>tokens = ['She', "'s", 'gon', 'na', 'write', 'a', 'book', '?']
>>>text = '''\
>>>She's gonna write
>>>a book?'''
>>>
>>>import re
>>>
>>>tokens.sort() # lexical order
>>>tokens.reverse() # look for longest match first
>>>pattern = "|".join(map(re.escape, tokens))
>>>pattern = re.compile(pattern)
>>>
>>>I get
>>>
>>>print [m.span() for m in pattern.finditer(text)]
>>>[(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 25)]
>>>
>>>which seems to match your version pretty well.
>>
>>That's what I was looking for.  Thanks!
> 
> 
> except that I misread your problem statement; the RE solution above allows the
> tokens to be specified in arbitrary order.  if they've always ordered, you 
> can re-
> place the code with something like:
> 
> # match tokens plus optional whitespace between each token
> pattern = "\s*".join("(" + re.escape(token) + ")" for token in tokens)
> m = re.match(pattern, text)
> result = (m.span(i+1) for i in range(len(tokens)))
> 
> which is 6-7 times faster than the previous solution, on my machine.

Ahh yes, that's faster for me too.  Thanks again!

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


Re: aligning a set of word substrings to sentence

2005-12-02 Thread Steven Bethard
Michael Spencer wrote:
> Steven Bethard wrote:
> 
>> I've got a list of word substrings (the "tokens") which I need to 
>> align to a string of text (the "sentence").  The sentence is basically 
>> the concatenation of the token list, with spaces sometimes inserted 
>> beetween tokens.  I need to determine the start and end offsets of 
>> each token in the sentence.  For example::
>>
>> py> tokens = ['She', "'s", 'gon', 'na', 'write', 'a', 'book', '?']
>> py> text = '''\
>> ... She's gonna write
>> ... a book?'''
>> py> list(offsets(tokens, text))
>> [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 25)]
>>
>
[snip]
>
> and then, for an entry in the wacky category, a difflib solution:
>
>  >>> def offsets(tokens, text):
>  ... from difflib import SequenceMatcher
>  ... s = SequenceMatcher(None, text, "\t".join(tokens))
>  ... for start, _, length in s.get_matching_blocks():
>  ... if length:
>  ... yield start, start + length
>  ...
>  >>> list(offsets(tokens, text))
>  [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 25)]

That's cool, I've never seen that before.  If you pass in str.isspace, 
you can even drop the "if length:" line::

py> def offsets(tokens, text):
... s = SequenceMatcher(str.isspace, text, '\t'.join(tokens))
... for start, _, length in s.get_matching_blocks():
... yield start, start + length
...
py> list(offsets(tokens, text))
[(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 
25), (25, 25)]

I think I'm going to have to take a closer look at 
difflib.SequenceMatcher; I have to do things similar to this pretty often...

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


Detect TKinter window being closed?

2005-12-02 Thread Glen
Is it possible to to detect a Tkinter top-level window being closed with the
close icon/button (top right), for example to call a function before the
window actually closes?

Python 2.4 / Linux (2.6 kernel) if that makes any difference.
Any info would be greatly appreciated.
Thanks
Glen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you create a custom QCursor in Python Qt?

2005-12-02 Thread Phil Thompson
On Friday 02 December 2005 3:31 pm, [EMAIL PROTECTED] wrote:
> I am a newcomer to using Python and Qt and the main problem that I have
> is the dearth of any example code or books describing the use of Python
> and Qt together.
>
> My current problem is that I want to create a custom cursor, from my
> understanding of it I need to create two "QBitmap"s, one of which will
> be the mask and then using these to create a "QCursor".
> I don't mine whether the "QBitmap"s are hardcoded in the source code or
> come from image files, just as long as I can create a new cursor:
>
> I have searched all the available code sources I can find:
> www.koders.com
> Eric
> Veus
> Civil
> Qomics
> for examples of how to create cursors but to no avail. So if amyone can
> tell me what I'm doing wrong, it would be much appreciated, here's my
> code:

How about looking at the cursor.py example that comes with PyQt? It 
demonstrates the standard cursors and implements a custom cursor.

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


Re: Detect TKinter window being closed?

2005-12-02 Thread Adonis
Glen wrote:
> Is it possible to to detect a Tkinter top-level window being closed with the
> close icon/button (top right), for example to call a function before the
> window actually closes?
> 
> Python 2.4 / Linux (2.6 kernel) if that makes any difference.
> Any info would be greatly appreciated.
> Thanks
> Glen

Here is an example code taken from:
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
(located at very end)

Example 7-2. Capturing destroy events

# File: protocol1.py

from Tkinter import *
import tkMessageBox

def callback():
 if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
 root.destroy()

root = Tk()
root.protocol("WM_DELETE_WINDOW", callback)

root.mainloop()

Hope this helps.

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


Re: Eclipse best/good or bad IDE for Python?

2005-12-02 Thread Aaron Bingham
[EMAIL PROTECTED] wrote:

>I'm trying to move beyond Emacs/Vim/Kate
>and was wondering if Eclipse is better and if it is the *best*
>IDE for Python.
>
>Should I leave Emacs and do Python coding in Eclipse?
>  
>
I've been a heavy Emacs user for several years, but recently switched to 
Eclipse for Python development.  I was skeptical at first, but I gave it 
a chance for a few days and was convinced.

The killer PyDev feature for me is pylint integration.  Being informed 
immediately when you mistype a variable name is a big timesaver.  Also 
nice is the refactoring support (although this it is possible to 
integrate BicycleRepairMan! with Emacs, I found it easier to use in 
Eclipse).  I still find the Eclipse editor awkward for some things that 
are easy in Emacs (Emacs is in my fingers), so I occasionally switch 
back to Emacs for a quick edit.

Eclipse performance is not a problem for me, but I have a beefy box.

Enjoy,

Aaron Bingham

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


Re: Detect TKinter window being closed?

2005-12-02 Thread Fredrik Lundh
Glen wrote:

> Is it possible to to detect a Tkinter top-level window being closed with the
> close icon/button (top right), for example to call a function before the
> window actually closes?

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols

 



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


Re: aligning a set of word substrings to sentence

2005-12-02 Thread Steven Bethard
Steven Bethard wrote:
> Michael Spencer wrote:
> 
>> Steven Bethard wrote:
>>
>>> I've got a list of word substrings (the "tokens") which I need to 
>>> align to a string of text (the "sentence").  The sentence is 
>>> basically the concatenation of the token list, with spaces sometimes 
>>> inserted beetween tokens.  I need to determine the start and end 
>>> offsets of each token in the sentence.  For example::
>>>
>>> py> tokens = ['She', "'s", 'gon', 'na', 'write', 'a', 'book', '?']
>>> py> text = '''\
>>> ... She's gonna write
>>> ... a book?'''
>>> py> list(offsets(tokens, text))
>>> [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 
>>> 25)]
>>>
>>
> [snip]
> 
>>
>> and then, for an entry in the wacky category, a difflib solution:
>>
>>  >>> def offsets(tokens, text):
>>  ... from difflib import SequenceMatcher
>>  ... s = SequenceMatcher(None, text, "\t".join(tokens))
>>  ... for start, _, length in s.get_matching_blocks():
>>  ... if length:
>>  ... yield start, start + length
>>  ...
>>  >>> list(offsets(tokens, text))
>>  [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 
>> 25)]
> 
> 
> That's cool, I've never seen that before.  If you pass in str.isspace, 
> you can even drop the "if length:" line::
> 
> py> def offsets(tokens, text):
> ... s = SequenceMatcher(str.isspace, text, '\t'.join(tokens))
> ... for start, _, length in s.get_matching_blocks():
> ... yield start, start + length
> ...
> py> list(offsets(tokens, text))
> [(0, 3), (3, 5), (6, 9), (9, 11), (12, 17), (18, 19), (20, 24), (24, 
> 25), (25, 25)]

Sorry, that should have been::
 list(offsets(tokens, text))[:-1]
since the last item is always the zero-length one.  Which means you 
don't really need str.isspace either.

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


Re: Is there no compression support for large sized strings in Python?

2005-12-02 Thread Christopher Subich
Fredrik Lundh wrote:
> Harald Karner wrote:

>>>python -c "print len('m' * ((2048*1024*1024)-1))"
>>
>>2147483647
> 
> 
> the string type uses the ob_size field to hold the string length, and
> ob_size is an integer:
> 
> $ more Include/object.h
> ...
> int ob_size; /* Number of items in variable part */
> ...
> 
> anyone out there with an ILP64 system?

I have access to an itanium system with a metric ton of memory.  I 
-think- that the Python version is still only a 32-bit python, though 
(any easy way of checking?).  Old version of Python, but I'm not the 
sysadmin and "I want to play around with python" isn't a good enough 
reason for an upgrade. :)


Python 2.2.3 (#1, Nov 12 2004, 13:02:04)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> str = 'm'*2047*1024*1024 + 'n'*2047*1024*1024
 >>> len(str)
-2097152

Yes, that's a negative length.  And I don't really care about rebinding 
str for this demo. :)

 >>> str[0]
Traceback (most recent call last):
   File "", line 1, in ?
IndexError: string index out of range
 >>> str[1]
Traceback (most recent call last):
   File "", line 1, in ?
IndexError: string index out of range
 >>> str[-1]
Traceback (most recent call last):
   File "", line 1, in ?
SystemError: error return without exception set
 >>> len(str[:])
-2097152
 >>> l = list(str)
 >>> len(l)
0
 >>> l
[]

The string is actually created -- top reports 4.0GB of memory usage.

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


Re: Why my modification of source file doesn't take effect when debugging?

2005-12-02 Thread infidel
> I'm using the Windows version of Python and IDLE. When I debug my .py
> file, my modification to the .py file does not seem to take effect
> unless I restart IDLE. Saving the file and re-importing it doesn't help
> either. Where's the problem?

"import" only reads the file the first time it's called.  Every import
call after that looks up the module in memory.  This is to prevent
circular dependencies between modules from creating infinite loops.
You need to use the reload() function:

>>> import foo

#change the contents of foo

>>> foo = reload(foo)

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


Re: Why my modification of source file doesn't take effect when debugging?

2005-12-02 Thread Christophe
infidel a écrit :
>>I'm using the Windows version of Python and IDLE. When I debug my .py
>>file, my modification to the .py file does not seem to take effect
>>unless I restart IDLE. Saving the file and re-importing it doesn't help
>>either. Where's the problem?
> 
> 
> "import" only reads the file the first time it's called.  Every import
> call after that looks up the module in memory.  This is to prevent
> circular dependencies between modules from creating infinite loops.
> You need to use the reload() function:

As a matter of fact, it would help a lot if that stupid behaviour of 
Idle was dropped. I'm sure I'm not the only one who lost lots of time 
because of that bug. Yes I call it a bug.
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Dec 2)

2005-12-02 Thread Cameron Laird
QOTW:  "Python makes it easy to implement algorithms." - casevh

"Most of the discussion of immutables here seems to be caused by
newcomers wanting to copy an idiom from another language which doesn't
have immutable variables. Their real problem is usually with binding,
not immutability." - Mike Meyer


Among the treasures available in The Wiki is the current
copy of "the Sorting min-howto":
http://www.amk.ca/python/howto/sorting/sorting.html

Dabo is way cool--at least as of release 0.5:

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

Tim Golden illustrates that wmi is *not* the only way to
access win32 functionality, and in fact that Python can
mimic VisualBasicScript quite handily.  It's only mimicry,
though; VBS remains better suited for this specific class
of tasks:

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

Claudio Grondi explains ActiveX componentry--OCXs, the
registry, apartments, ...--for a Python audience:

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

Dao is a novel high-level language which advertises strong
multi-threading, Unicode, and particularly comfortable C++ 
interfacing.  Limin Fu provides details:

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

Donn Cave leads at least a score of others in comparing
lists and tuples:
http://groups.google.com/group/comp.lang.python/msg/dd6ba8df451d57e0?


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

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

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

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

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

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

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

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

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

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

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

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

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
The old Python "To-Do List" now lives principally in a
SourceForge reincarnation.
http://sourc

Re: Detect TKinter window being closed?

2005-12-02 Thread Glen
Thanks Fredrik and Adonis that's just what I needed, plus a bit more to
learn about.

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


Re: Death to tuples!

2005-12-02 Thread Mike Meyer
Antoon Pardon <[EMAIL PROTECTED]> writes:
>>> Well there are two possibilities I can think of:
>>>
>>> 1)
>>>   arg_default = ...
>>>   def f(arg = arg_default):
>>>  ...
>>
>> Yuch. Mostly because it doesn't work:
>>
>> arg_default = ...
>> def f(arg = arg_default):
>> ...
>>
>> arg_default = ...
>> def g(arg = arg_default):
>>
>> That one looks like an accident waiting to happen.
> It's not because accidents can happen, that it doesn't work.
> IMO that accidents can happen here is because python
> doesn't allow a name to be marked as a constant or unreboundable.

Loets of "accidents" could be fixed if Python marked names in various
ways: with a type, or as only being visible to certain other types, or
whatever. A change that requires such a construct in order to be
usable probably needs rethinking.

Even if that weren't a problem, this would still require introducting
a new variable into the global namespace for every such
argument. Unlike other similar constructs, you *can't* clean them up,
because the whole point is that they be around later.

The decorator was an indication of a possible solution. I know it
fails in some cases, and it probably fails in others as well.

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


Re: Why use #!/usr/bin/env python rather than #!python?

2005-12-02 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Adriano Ferreira <[EMAIL PROTECTED]> wrote:

> Hey, that's not fair. In your illustration above, does 'python' can be
> found in the PATH? That is,
> 
> $ python /tmp/hello.py
> 
> works? If it does, probably
> 
> #!/usr/bin/python
> #!/usr/bin/env python
> #!python
> 
> would also work if
> (1) 'python' is at '/usr/bin/python' (but that's inflexible)
> (2) 'python' can be found in the environment variable path (if 'env'
> is at '/usr/bin/env')
> (3) 'python' can be found in the environment variable path (no need
> for 'env' utility)

Contrary to popular belief, #! is not intended for the shell,
but rather for the execve(2) system call of the UNIX operating
system.  These two characters form the 16 bit "magic number"
of interpreter files.  Any executable file must start with a
16 bit field that identifies it so the operating system will
know how to execute it.

In the case of a #! interpreter file, the operating system
expects the rest of that line to be the path to the file.
PATH is not searched, and is irrelevant.  The only way
#!python can work, is if it's in the current working directory.

Just to help make it confusing, when this mechanism fails
and execve(2) returns an error, most shells will go on to
try to execute the file themselves, regardless of whether
there's a #! or not.  csh (the shell language that doesn't
look anything like C, Bill Joy's attempt at language design
before he started over with Java) does that only if the first
line is "#"; otherwise it invokes the Bourne shell.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem cmpiling M2Crypto under Plone

2005-12-02 Thread Thomas G. Apostolou

"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Thomas G. Apostolou wrote:
>
> > So what you say is that the Python installed with Plone doesn't have
> > Python.h in ./include but Python installers from Python.org do have the
> > file?
>
> that's likely, given building didn't work for you.
>
> after all, Plone's an application that happens to include a Python
interpreter,
> not a Python distribution.
>
> > If yes i guess i should install the same version to the same location
> > (over-writing). Is that so?
>
> to minimize the risk, I'd grab the corresponding python.org version,
install it
> in a separate location, use the python.org version to build the
extensions, and
> finally install them in the Plone tree.
>
> but maybe there's no risk for conflict; maybe someone from the Plone team
> can clarify ?

The above sudgestion is right. Unfortunatelly i found out the problem the
bad way...
After installing the full package of python 2.3.3 on top of the
plone's(2.0.5) python installation, the build and install of m2crypto went
ok but the zope server service was refusing to start...
I thought ok the installation kept a BACKUP directory so i can allways roll
back...
I did unistall it and there was realy a rollback option there witch i
choosed.
But still the service was refusing to start giving me an error witch i could
read at windows EventViewer/Application that was saying :

"Python could not import the service's module
File "C:\Program Files\Plone 2\Data\bin\zopeservice.py", line 100, in ?
from nt_svcutils.service import Service
File "C:\Program Files\Plone 2\Zope\lib\python\nt_svcutils\service.py", line
18, in ?
import win32serviceutil
exceptions.ImportError: No module named win32serviceutil
Python could not import the service's module
File "C:\Program Files\Plone 2\Data\bin\zopeservice.py", line 100, in ?
from nt_svcutils.service import Service
File "C:\Program Files\Plone 2\Zope\lib\python\nt_svcutils\service.py", line
18, in ?
import win32serviceutil
exceptions.ImportError: No module named win32serviceutil"


Good for me i had backups of everything (External Methods, Script(Python),
and DTML-PT). So i unistalled Plone 2.0.5, reistalled it and restored my
site. Of course i was not stupid enough and the problem was encountered in
my development pc instead of the real site pc
Now everithing is ok as i run python setup.py install and it ran ok...

Time for me to learn about how to apply patches (there is one for python
2.3.3 for Connection.py and on for m2crypto named xmlrpclib.py.patch inside
patches directory of mycrypto)

After that i'll start with trying to use the whole thing compiling all this
time...
Thanks to the people imlementing m2crypto and all of you helping me with the
compilation.

PS: After all that strugling for building on windows i am sure that i am
going to use the whole thing on linux box next time i set it up for someone
else


Thomas G. Apostolou



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


Re: Eclipse best/good or bad IDE for Python?

2005-12-02 Thread gene tani

[EMAIL PROTECTED] wrote:
> I'm trying to move beyond Emacs/Vim/Kate
> and was wondering if Eclipse is better and if it is the *best*
> IDE for Python.
>
> Should I leave Emacs and do Python coding in Eclipse?
>
> Chris

I'm agnostic; lots of IDE's/editors have buzz, you should learn to use
at least a couple well:

- vim, emacs
- Wing, Komodo, Textmate (OS X only)
- jedit, eclipse,
- eric, PythonWin, kate, leo, etc.

Check the wiki:
http://wiki.python.org/moin/DevelopmentTools

then google c.l.py for how your most desired features are supported:
syntax coloring, SVN integrate, auto-complete (if you think it helps),
pylint, threaded debugger, smart tags, object/class/code
folding/browser etc.  This guy spent a lot of time composing this:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/e3a65f2908bb8ba4/12ea5915f8f09546?q=IDE+subversion&rnum=1#12ea5915f8f09546

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


libxml2 and XPath - Iterate through repeating elements?

2005-12-02 Thread nickheppleston
I'm trying to iterate through repeating elements to extract data using
libxml2 but I'm having zero luck - any help would be appreciated.

My XML source is similar to the following - I'm trying to extract the
line number and product code from the repeating line elements:


  
123456
  
  

  1
  PENS


  2
  STAPLER


  3
  RULER

  


With the following code I can get at the non-repeating elements in the
header, and get the lines elements, but cannot extract the
lineno/productcode data via xpath:

XmlDoc = libxml2.parseFile(XmlFile);
XPathDoc = XmlDoc.xpathNewContext();
XPathDoc.xpathRegisterNs('so',"some-ns");


# Extract data from the order header
PurchaseOrderNo =
XPathDoc.xpathEval('//so:order/so:header/so:orderno');

# Extract data from the order lines
for line in XPathDoc.xpathEval('//so:order/so:lines/so:line'):
print line.content;

# Explicitly free Xml document and XPath context
XmlDoc.freeDoc()
XPathDoc.xpathFreeContext()

Ideally, I'd like to select the line data using xpath (similar to an
XSLT query after a 'for-each' - i.e. xpathEval('so:lineno') and
xpathEval('so:productcode') once I've got the line element).

Any suggestions grealty appreciated!

Cheers, Nick.

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


Re: an intriguing wifi http server mystery...please help

2005-12-02 Thread jojoba
Hello again everyone,

First, I want to thank all those who have contributed to the
unravelling of this server-slow-down mystery.
But unfortunately, either:

1) i have not made my point clear about what my question is
2) i do not understand the responses given

So, let me briefly reiterate what the mystery is.
(i am assuming that readers have read most of my first post above).
I have two computers and a server program (written in python).
Both computers are on my home lan (using a linksys wifi router).
HERE IS THE MYSTERY:
The server runs fast when one computer is the server, but slow when the
other computer is the server.
How can this be, given that this asymmetry does not exist when both
computers are wired.

Please let me know if you need any more information,
Thanks again to all who have been helping with this,
jojoba

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


Re: Death to tuples!

2005-12-02 Thread Mike Meyer
Antoon Pardon <[EMAIL PROTECTED]> writes:
> On 2005-12-02, Bengt Richter <[EMAIL PROTECTED]> wrote:
>> On 1 Dec 2005 09:24:30 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>>>On 2005-11-30, Duncan Booth <[EMAIL PROTECTED]> wrote:
 Antoon Pardon wrote:
>>>I think one could argue that since '[]' is normally evaluated when
>>>the expression containing it is excuted, it should also be executed
>>>when a function is called, where '[]' is contained in the expression
>>  ^^^[1] ^
>>>determining the default value.
>>  ^^^[2]
>> Ok, but "[]" (without the quotes) is just one possible expression, so
>> presumably you have to follow your rules for all default value expressions.
>> Plain [] evaluates to a fresh new empty list whenever it is evaluated,
> Yes, one of the questions I have is why python people whould consider
> it a problem if it wasn't.

That would make [] behave differently from [compute_a_value()]. This
doesn't seem like a good idea.

> Personnaly I expect the following pieces of code
>   a = 
>   b = 
> to be equivallent with
>   a = 
>   b = a
> But that isn't the case when the const expression is a list.

It isn't the case when the const expression is a tuple, either:

x = (1, 2)
>>> (1, 2) is x
False
>>> 

or an integer:

>>> a = 1234
>>> a is 1234
False
>>> 

Every value (in the sense of a syntactic element that's a value, and
not a keyword, variable, or other construct) occuring in a program
should represent a different object. If the compiler can prove that an
value can't be changed, it's allowed to use a single instance for all
occurences of that value. Is there *any* language that behaves
differently from this?

> A person looking at:
>   a = [1 , 2]
> sees something resembling
>   a = (1 , 2)
> Yet the two are treated very differently. As far as I understand the
> first is translated into somekind of list((1,2)) statement while
> the second is build at compile time and just bound.

No, that translation doesn't happen. [1, 2] builds a list of
values. (1, 2) builds and binds a constant, which is only possible
because it, unlike [1, 2], *is* a constant. list(1, 2) calls the
function "list" on a pair of values:

>>> def f():
...  a = [1, 2]
...  b = list(1, 2)
...  c = (1, 2)
... 
>>> dis.dis(f)
  2   0 LOAD_CONST   1 (1)
  3 LOAD_CONST   2 (2)
  6 BUILD_LIST   2
  9 STORE_FAST   0 (a)

  3  12 LOAD_GLOBAL  1 (list)
 15 LOAD_CONST   1 (1)
 18 LOAD_CONST   2 (2)
 21 CALL_FUNCTION2
 24 STORE_FAST   2 (b)

  4  27 LOAD_CONST   3 ((1, 2))
 30 STORE_FAST   1 (c)
 33 LOAD_CONST   0 (None)
 36 RETURN_VALUE

> This seems to go against the pythonic spirit of explicit is
> better than implicit.

Even if "[arg]" were just syntactic sugar for "list(arg)", why would
that be "implicit" in some way?

> It also seems to go against the way default arguments are treated.

Only if you don't understand how default arguments are treated.

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


Re: Setting PYTHONPATH from Makefile

2005-12-02 Thread François Pinard
[EMAIL PROTECTED]
> I have a Makefile target that uses a python script, like:

> %.abc: %.def
> python myscript.py

> If this was a tcsh script, I would just do:

>setenv PYTHONPATH /path/to/stuff
>python myscript.py

> but this cannot be done from a Makefile.

Use:

%.abc: %.def
PYTHONPATH=/path/to/stuff python myscript.py

In fact, within Make or outside Make, for any shell command, you may 
write:

VAR1=VALUE1 VAR2=VALUE2 ... COMMAND ARGUMENTS

so temporarily setting VAR1, VAR2... in the environment for the duration 
of COMMAND only.  This is a useful feature of the shell.

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


How to keep Pydoc from listing too much?

2005-12-02 Thread Tony Nelson
How can I tell Pydoc not to list information for some of the base 
classes?  For example, when a class inherits from gtk.Widget, lots of 
GTK stuff gets added that doesn't really need to be there.  Is there 
some option to Pydoc to tell it to skip some classes?  Is there 
something I can put in my source that is a hint to Pydoc?

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread JohnBMudd
Here it is again...  Python bypassed/discounted because, of all things,
scoping by indentation!?!?

This used to surprise me.  Until I hear more and more otherwise
reasonable programmers list this as their number one reason for
shunning Python.

I gauge design defects by how much after market
discussion/documentation a feature generates/requires.   Scoping by
indentation is a whopper of a defect.

Could the PyPy people find some way (I don't how) to eliminate this
stumbling block going forward??  That is, after they eliminate the GIL!

John

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Here it is again...  Python bypassed/discounted because, of all things,
> scoping by indentation!?!?

[...]

> Could the PyPy people find some way (I don't how) to eliminate this
> stumbling block going forward??

No: I believe they could only eliminate it "going backward". ;-)

Paul

P.S. I will admit that the first thing I do when editing someone else's
code (in any language) is to make sure the tab settings are sane in my
editor, but should basic editing skills really be so far beyond the
person/people entrusted with writing the software that runs your
business/organisation/lifestyle? Is Mr Rocket Scientist really
incapable of tying his own shoelaces?

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


Re: How to creat a file?

2005-12-02 Thread [EMAIL PROTECTED]

sandorf wrote:
> Thank to you all, guys. Here's another question:
>
> I'm using the Windows version of Python and IDLE. When I debug my .py
> file, my modification to the .py file does not seem to take effect
> unless I restart IDLE. Saving the file and re-importing it doesn't help
> either. Where's the problem?

>From your edit window, go to the Run menu and select Run Module.

It will prompt you to save the file, it will restart the shell and will
reload
and run the new version all in one operation.

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


Re: libxml2 and XPath - Iterate through repeating elements?

2005-12-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> I'm trying to iterate through repeating elements to extract data using
> libxml2 but I'm having zero luck - any help would be appreciated.

Here's how I attempt to solve the problem using libxml2dom [1] (and I
imagine others will suggest their own favourite modules, too):

import libxml2dom
d = libxml2dom.parseFile(filename)
order_numbers = d.xpath("//so:order/so:header/so:orderno",
namespaces={"so" : "some-ns"})

At this point, you have a list of nodes. (I imagine that whatever
object the libxml2 module API produces probably has those previous and
next attributes to navigate the result list instead.) The nodes in the
list represent the orderno elements in this case, and in libxml2dom you
can choose to invoke the usual DOM methods on such node objects, or
even the toString method if you want the document text. For the line
items...

lines = d.xpath("//so:order/so:lines/so:line", namespaces={"so" :
"some-ns"})
for line in lines:
print line.toString()

I can't remember what the libxml2 module produces for the content
attribute of a node, although the underlying libxml2 API produces a
"text-only" representation of the document text, as opposed to the
actual document text that the toString method produces in the above
example. I imagine that an application working with the line item
information would use additional DOM or XPath processing to get the
line item index and the product code directly.

Anyway, I recommend libxml2dom because if you're already using the
bundled libxml2 module, you should be able to install libxml2dom and
plug into the same infrastructure that the bundled module depends upon.
Moreover, libxml2dom is a "pure Python" package that doesn't require
any extension module compilation, so it should be quite portable to
whatever platform you're using.

Paul

[1] http://www.python.org/pypi/libxml2dom

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Dave Hansen
On 2 Dec 2005 10:08:21 -0800 in comp.lang.python, [EMAIL PROTECTED]
wrote:

>Here it is again...  Python bypassed/discounted because, of all things,
>scoping by indentation!?!?
>
>This used to surprise me.  Until I hear more and more otherwise
>reasonable programmers list this as their number one reason for
>shunning Python.
>
>I gauge design defects by how much after market
>discussion/documentation a feature generates/requires.   Scoping by
>indentation is a whopper of a defect.

FWIW, indentation scoping one one of the features that _attracted_ me
to Python.  

It's far more interesting to me _why_ people think indentation scoping
is a bad thing.  The answer I get back fall into two general
categories: 1) I've heard/read/been told it's a bad thing, and 2) It
causes portability problems.

Of these, only (2) is valid.  And the only reason it's valid is that
Python recognizes the TAB character as valid indentation.  TAB
characters are evil.  They should be banned from Python source code.
The interpreter should stop translation of code and throw an exception
when one is encountered.  Seriously.  At least, I'm serious when I say
that.  I've never seen TAB characters solve more problems than they
cause in any application.

But I suspect I'm a lone voice crying in the wilderness.  Regards,
-=Dave

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


Detect Blank DVD or CD in CDROM Drive

2005-12-02 Thread Gregory Piñero
Hi guys,

I'm thinking it will take a real expert to do this, probably someone
who can use windows API's or directly poll the hardware or some such
thing.  But if you think you know how then please let me
know.  I'm trying to write an automation script that will burn an
ISO file each night.

By the way, I tried this recipe but it doesn't seem to work for blank media:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/180919-- Gregory PiñeroChief Innovation OfficerBlended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: an intriguing wifi http server mystery...please help

2005-12-02 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> The server runs fast when one computer is the server, but slow when the
> other computer is the server.
> How can this be, given that this asymmetry does not exist when both
> computers are wired.

Probably because the way your wireless interfaces are configured may be
different from the way your wired interfaces are configured. Network
problems are hard enough to solve "on site" with full access to all the
necessary information - doing so with substantially less information in
a newsgroup thread is substantially more difficult.

With regard to my point about the "fairly simple HTTP server" that you
are using, if you choose to run whichever server such that you can see
it writing its log - for BaseHTTPServer this is easy since it just
writes its log to the terminal/console - then you might be able to see
where the delay occurs by putting logging statements in your program at
the start and end of its work. If your program seems to write its
finishing logging message and yet a long delay occurs before the server
writes something about where the request came from (and the browser
gets to see the output of your program), then you may well have a
problem with the way the server prepares its logging messages as I
described in my last message.

Paul

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread [EMAIL PROTECTED]
You're not alone.
The first thing I do after installing an IDE or programmers editor is
to change the configuration to use spaces as identantion.

I still don't get why there is still people using real tabs as
indentation.

--
Paulo

Dave Hansen wrote:
> On 2 Dec 2005 10:08:21 -0800 in comp.lang.python, [EMAIL PROTECTED]
> wrote:
>  ... (cutted)
> Of these, only (2) is valid.  And the only reason it's valid is that
> Python recognizes the TAB character as valid indentation.  TAB
> characters are evil.  They should be banned from Python source code.
> The interpreter should stop translation of code and throw an exception
> when one is encountered.  Seriously.  At least, I'm serious when I say
> that.  I've never seen TAB characters solve more problems than they
> cause in any application.
>
> But I suspect I'm a lone voice crying in the wilderness.  Regards,
> -=Dave
> 
> -- 
> Change is inevitable, progress is not.

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


Re: Instances behaviour

2005-12-02 Thread Inyeol Lee
On Fri, Dec 02, 2005 at 10:43:56AM +0100, bruno at modulix wrote:
> Inyeol Lee wrote:
> (snip)
> 
> class A(object):
> ... def __init__(self, foo):
> ... if self.__class__ is A:
> ... raise TypeError("A is base class.")   
> 
> 
> s/TypeError/NotImplementedError/
> s/base class/abstract class/

I prefer TypeError here, NotImplementedError would be OK though.
Here is an example from sets.py in stdlib.


class BaseSet(object):
"""Common base class for mutable and immutable sets."""

__slots__ = ['_data']

# Constructor

def __init__(self):
"""This is an abstract class."""
# Don't call this from a concrete subclass!
if self.__class__ is BaseSet:
raise TypeError, ("BaseSet is an abstract class.  "
  "Use Set or ImmutableSet.")


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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 Dave Hansen <[EMAIL PROTECTED]> wrote:

> On 2 Dec 2005 10:08:21 -0800 in comp.lang.python, [EMAIL PROTECTED]
> wrote:
> 
> >Here it is again...  Python bypassed/discounted because, of all things,
> >scoping by indentation!?!?
> >
> >This used to surprise me.  Until I hear more and more otherwise
> >reasonable programmers list this as their number one reason for
> >shunning Python.
> >
> >I gauge design defects by how much after market
> >discussion/documentation a feature generates/requires.   Scoping by
> >indentation is a whopper of a defect.
> 
> FWIW, indentation scoping one one of the features that _attracted_ me
> to Python.

Me too.  Or rather, Python code is much more readable because every 
nincompoop has to use indentation correctly whether they want to or not, 
and I like readable code.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


LDAP Authentication

2005-12-02 Thread Derek Perriero
Any help would be great on this.  I've been trying to bind a
username and password to the ldap server for authentication, but when I
locally run this script:

#!/usr/bin/python
import ldap

## Connect to LDAP host
try:
    ldapcn = ldap.initialize('ldap://xxx.xxx.xxx.xxx')
    ldapcn.bind('cn=username,o=domain','password',ldap.AUTH_SIMPLE)
    print "Successful."
except ldap.LDAPError, e:
    print e
    print "Declined.\n"

I always get a successful return even if the password or username is
incorrect.  Or, if I even leave the username and password field in
the initialize function blank, I get a successful return.
I need some guidance in the correct direction.

Thanks!
Derek-- Perriero, Derek[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Death to tuples!

2005-12-02 Thread Bengt Richter
On 2 Dec 2005 13:05:43 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:

>On 2005-12-02, Bengt Richter <[EMAIL PROTECTED]> wrote:
>> On 1 Dec 2005 09:24:30 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>>
>>>On 2005-11-30, Duncan Booth <[EMAIL PROTECTED]> wrote:
 Antoon Pardon wrote:

>
>Personnaly I expect the following pieces of code
>
>  a = 
>  b = 
>
>to be equivallent with
>
>  a = 
>  b = a
>
>But that isn't the case when the const expression is a list.
>
ISTM the line above is a symptom of a bug in your mental Python source 
interpreter.
It's a contradiction. A list can't be a "const expression".
We probably can't make real progress until that is debugged ;-)
Note: assert "const expression is a list" should raise a mental exception ;-)

>A person looking at:
>
>  a = [1 , 2]
English: let a refer to a mutable container object initialized to contain
an ordered sequence of specified elements 1 and 2.
>
>sees something resembling
>
>  a = (1 , 2)
English: let a refer to an immutable container object initialized to contain
an ordered sequence of specified elements 1 and 2.
>
>Yet the two are treated very differently. As far as I understand the
>first is translated into somekind of list((1,2)) statement while
They are of course different in that two different kinds of objects
(mutable vs immutable containers) are generated. This can allow an optimization
in the one case, but not generally in the other.

>the second is build at compile time and just bound.
a = (1, 2) is built at compile time, but a = (x, y) would not be, since x and y
can't generally be known a compile time. This is a matter of optimization, not
semantics. a = (1, 2) _could_ be built with the same code as a = (x, y) picking 
up
1 and 2 constants as arguments to a dynamic construction of the tuple, done in 
the
identical way as the construction would be done with x and y. But that is a red 
herring
in this discussion, if we are talking about the language rather than the 
implementation.

>
>This seems to go against the pythonic spirit of explicit is
>better than implicit.
Unless you accept that '[' is explicitly different from '(' ;-)

>
>It also seems to go against the way default arguments are treated.
I suspect another bug ;-)

>

>> but that's independent of scope. An expression in general may depend on
>> names that have to be looked up, which requires not only a place to look
>> for them, but also persistence of the name bindings. so def 
>> foo(arg=PI*func(x)): ...
>> means that at call-time you would have to find 'PI', 'func', and 'x' 
>> somewhere.
>> Where & how?
>> 1) If they should be re-evaluated in the enclosing scope, as default arg 
>> expressions
>> are now, you can just write foo(PI*func(x)) as your call.
>
>I may be a bit pedantic. (Read that as I probably am)
>
>But you can't necesarry write foo(PI*func(x)) as your call, because PI
>and func maybe not within scope where the call is made.
Yes, I was trying to make you notice this ;-)

>
>> So you would be asking
>> for foo() to be an abbreviation of that. Which would give you a fresh list if
>> foo was defined def foo(arg=[]): ...
>
>This was my first thought.
>
[...]
> Why on earth should it be the same list, when a function is called
> and is provided with a list as a default argument?
>> It's not "provided with a list" -- it's provided with a _reference_ to a 
>> list.
>> You know this by now, I think. Do you want clone-object-on-new-reference 
>> semantics?
>> A sort of indirect value semantics? If you do, and you think that ought to be
>> default semantics, you don't want Python. OTOH, if you want a specific 
>> effect,
>> why not look for a way to do it either within python, or as a graceful 
>> syntactic
>> enhancement to python? E.g., def foo(arg{expr}):... could mean evaluate arg 
>> as you would like.
>> Now the ball is in your court to define "as you would like" (exactly and 
>> precisely ;-)
>
>I didn't start my question because I wanted something to change in
>python. It was just something I wondered about. Now I wouldn't
I wonder if this "something" will still exist once you get
assert "const expression is a list" to raise a mental exception ;-)

>mind python to be enhanced at this point, so should the python
>people decide to work on this, I'll give you my proposal. Using your
>syntax.
>
>  def foo(arg{expr}):
> ...
>
>should be translated something like:
>
>  class _def: pass
>
>  def foo(arg = _def):
>if arg is _def:
>  arg = expr
>...
>
>I think this is equivallent with your first proposal and probably
>not worth the trouble, since it is not that difficult to get
>the behaviour one wants.
Again, I'm not "proposing" anything except to help lay out evidence.
The above is just a spelling of typical idiom for mutable default
value initialization.

>
>I think such a proposal would be most advantaged for the newbees
>because the two possibilities for default values would make them
>think about what the differences are between the 

unittest.assertRaise and keyword arguments?

2005-12-02 Thread Bo Peng
Dear list,

The syntax for using assertRaise is

   assertRaise(exception, function, para1, para2,...)

However, I have a long list of arguments (>20) so I would like to test 
some of them using keyword arguments (use default for others). Is there 
a way to do this except for manually try...except?

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


Re: How to list currently defined classes, methods etc

2005-12-02 Thread Deep
I have been looking a bit and am stuck at this point.

Given a string, how do i find what is the string bound to.
Let me give an example.

def deep():
 print "Hello"

now inspect.ismethod(deep) returns true. (As it should).
But if I am trying to make a list of all bound methods), i use
dir(), which is a list of strings. I get the string "deep" from this
list.
How do I obtain the reference to the method it is bound to.
The same problem can be extended to attributes and classes.

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


Re: XML and namespaces

2005-12-02 Thread A.M. Kuchling
On 2 Dec 2005 06:16:29 -0800, 
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Of course.  Minidom implements level 2 (thus the "NS" at the end of the
> method name), which means that its APIs should all be namespace aware.
> The bug is that writexml() and thus toxml() are not so.

Hm, OK.  Filed as bug #1371937 in the Python bug tracker.  Maybe I'll
look at this during the bug day this Sunday.

--amk

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


Re: unittest.assertRaise and keyword arguments?

2005-12-02 Thread Giovanni Bajo
Bo Peng wrote:

> The syntax for using assertRaise is
>
>assertRaise(exception, function, para1, para2,...)
>
> However, I have a long list of arguments (>20) so I would like to test
> some of them using keyword arguments (use default for others). Is there
> a way to do this except for manually try...except?


You can pass keyword arguments to assertRaises without problems:

self.assertRaises(ValueError, myfunc, arg1,arg2, arg3, arg4, abc=0, foo=1,
bar="hello")

Or you can always do something like:

self.assertRaises(ValueError, lambda: myfunc(arg1,arg2, arg3, arg4, abc=0,
foo=1, bar="hello"))
-- 
Giovanni Bajo


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


Volume of CSG (constructive solid geometry) objects

2005-12-02 Thread Charlie
>From python, I need to be able to create CSG objects and calculate their volume
(and from that their mass).

It looks like their are plenty of packages to create and display CSG objects,
however, I can not seem to find any API to get to the object's volume.

If anyone has any ideas/tips/pointers/etc., I would be very grateful.

Thanks,
Charlie

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


Re: CGI module does not parse data

2005-12-02 Thread amfr
I am using execfile, setting stdin and stdout like this:
sys.stdin = self.wfile
sys.stdout = self.rfile
execfile(filename)

Its the same code used in the CGIHTTPServer module.  I know that the
python is executing corretly, a script with this content would work:

print ""
print ""
print ""
print "blah"
print ""
print "
print ""
print "test"
print ""
print ""

but this would not (lets say i submitted a form with the value of test
being "hello world"):

import cgi
form = cgi.FieldStorage()
print form["test"]
print "test"

I would only be able to see "test", not "hello world"
I am sure its not my browser

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Micah Elliott
On Dec 02, Dave Hansen wrote:
> Python recognizes the TAB character as valid indentation.  TAB
> characters are evil.  They should be banned from Python source code.

AGREE!  AGREE!  AGREE! 

> The interpreter should stop translation of code and throw an
> exception when one is encountered.

You could file a "Parser/Compiler" Feature Request for this (Hmm,
sf.net appears to have just renamed "Request For Enhancment" to
"Feature Request").  Seems the present enformencement of
disallowing tab/space mixing is with -t and -tt.  From PEP-8
http://www.python.org/peps/pep-0008.html>:

...
Tabs or Spaces?

Never mix tabs and spaces.  The most popular way of indenting
Python is with spaces only.  ... Code indented with a mixture
of tabs and spaces should be converted to using spaces
exclusively. ... When invoking the python command line
interpreter with the -t option, it issues warnings about code
that illegally mixes tabs and spaces.  When using -tt these
warnings become errors. These options are highly recommended!

For new projects, spaces-only are strongly recommended over
tabs. Most editors have features that make this easy to do.

If your "FR" is approved, -t and -tt could apply to any use of tabs.
+1 from me.

-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unittest.assertRaise and keyword arguments?

2005-12-02 Thread Bo Peng
Giovanni Bajo wrote:
> You can pass keyword arguments to assertRaises without problems:
> 
> self.assertRaises(ValueError, myfunc, arg1,arg2, arg3, arg4, abc=0, foo=1,
> bar="hello")

Well, I though abc=0 would be keyword arguments for assertRaisers and 
never tried it!

> 
> Or you can always do something like:
> 
> self.assertRaises(ValueError, lambda: myfunc(arg1,arg2, arg3, arg4, abc=0,
> foo=1, bar="hello"))

This is also useful.

I now have nothing to complain against assertTaises. :-)

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


Re: How to list currently defined classes, methods etc

2005-12-02 Thread Kent Johnson
Deep wrote:
> I have been looking a bit and am stuck at this point.
> 
> Given a string, how do i find what is the string bound to.
> Let me give an example.
> 
> def deep():
>  print "Hello"
> 
> now inspect.ismethod(deep) returns true. (As it should).
> But if I am trying to make a list of all bound methods), i use
> dir(), which is a list of strings. I get the string "deep" from this
> list.

Look it up in the globals() dict:
 >>> def deep():
 ...   print 'Hello'
 ...
 >>> globals()['deep']


> How do I obtain the reference to the method it is bound to.
> The same problem can be extended to attributes and classes.

Use getattr() to inspect classes and instances:
 >>> class deeper:
 ...   def deepest(self):
 ... print 'goodbye'
 ...
 >>> getattr(deeper, 'deepest')

 >>> d=deeper()
 >>> getattr(d, 'deepest')
>

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


Re: How to list currently defined classes, methods etc

2005-12-02 Thread Colin J. Williams
Deep wrote:
> I have been looking a bit and am stuck at this point.
> 
> Given a string, how do i find what is the string bound to.
> Let me give an example.
> 
> def deep():
>  print "Hello"
> 
> now inspect.ismethod(deep) returns true. (As it should).
> But if I am trying to make a list of all bound methods), i use
> dir(), which is a list of strings. I get the string "deep" from this
> list.
> How do I obtain the reference to the method it is bound to.
> The same problem can be extended to attributes and classes.
> 
 >>> help('deep') in the interactive mode gives part of what you seek.

A prettier way is to use epydoc: 
http://www.answers.com/main/ntquery?s=epydoc&gwp=13

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


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Gerhard Häring
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Micah Elliott wrote:
> On Dec 02, Dave Hansen wrote:
> 
>>Python recognizes the TAB character as valid indentation.  TAB
>>characters are evil.  They should be banned from Python source code.
> 
> AGREE!  AGREE!  AGREE! 
> 
>>The interpreter should stop translation of code and throw an
>>exception when one is encountered.
> 
> 
> You could file a "Parser/Compiler" Feature Request for this [...]

Read PEP 666 first.

- -- Gerhard
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFDkLJWdIO4ozGCH14RAiOyAJ4gNZrf5rjv5Cqk2cj/hFGXRaeCZwCdEL/X
ITGPnj6tXblSY1r04zS5djY=
=z37M
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Dao Language v.0.9.6-beta is release!

2005-12-02 Thread Simon Brunning
On 12/2/05, Dave Hansen <[EMAIL PROTECTED]> wrote:
> FWIW, indentation scoping one one of the features that _attracted_ me
> to Python.

+1 QOTW

OK, it's a bit of a cliche. But it's a cliche because it's *true*.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >