Re: PEP 354: Enumerations in Python

2006-02-28 Thread Terry Reedy

"Ben Finney" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Should I amend the PEP to propose "either in the builtins or in the
> collections module"?

Yes, if the idea is accepted, Guido and devs will debate and decide that 
anyway ;-)

> Or should I propose two PEPs and let them compete?

No..

> But the terminology is broken. The term "enumerated" seems to me to
> imply that it does have an order. Can you suggest a term other than
> "enumerated" for what you're describing with the unordered property?

Re flags are not ordered.  Their bug proneness when given to wrong 
functions is a point for your proposal.

tjr



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


Re: type = "instance" instead of "dict"

2006-02-28 Thread Steven D'Aprano
Cruella DeVille wrote:

> This is off topic, but if read the documentation is the answere to
> everything why do we need news groups? 

Because "read the documentation" is NOT the answer to 
everything. However, it was the answer to your question.

> The problem with the
> documentation for Python is that I can't find what I'm looking for (and
> I didn't even know what I was looking for either). 

Is that a problem with the docs or with you? Or perhaps 
a little of both?

In any case, now Jonathan Gardner has kindly pointed 
you at the correct part of the docs, you will be able 
to read up on it and have a better idea of what to do 
next time.

> And since every
> language is well documented... 

That certainly is not true.

 > there's no need for these groups.
 >
> I wouldn't ask here without trying to find the solution on my own
> first.

Good. And now, because people didn't just answer your 
immediate question, but pointed you at the part of the 
docs where you can learn things you should know, you 
may find it easier to solve future problems.



-- 
Steven.

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


PyPornography was: Re: Python vs. Lisp -- please explain

2006-02-28 Thread Christos Georgiou
On Tue, 21 Feb 2006 15:05:40 -0500, rumours say that Steve Holden
<[EMAIL PROTECTED]> might have written:

>Chris Mellon wrote:
>[...]
>> Torstens definition isn't useful for quantifying a difference between
>> interpeted and compiled - it's a rough sort of feel-test. It's like
>> how much of a naked body you can expose before before it changes from
>> art to pornography - it's not something that is easily quantified.
>> 
>[...]

>Possibly, but if your aim is exposing as much flesh as possible without 
>being labeled pornography I think I'd conclude you were in the 
>pornography business from the start, albeit masquerading as an "art dealer".

The difference between art and pornography, as I perceive it, is that you
don't have to think about it when you see pornography.  You can even turn
off the audio in cinematographic/video pornography and still the message
comes through (in the vague lines of "jerk off along").

So, in pornography there's no interpretation step involved; therefore, by
pure logic, all "compiled to machine code" languages should be looked down
upon as pornographic, and Python is art.  QED.


PS You (the READER) are licensed to substitute other "non compiled to
machine code" languages for Python (the PROGRAM) in the previous paragraph,
just do it outside comp.lang.python (the COMPANY).  We don't care what you
do late at night with *your* object of desire, whatever that may be, since
it's not Python.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C++ OpenGL rendering, wxPython GUI?

2006-02-28 Thread John M. Gabriele
[EMAIL PROTECTED] wrote:
> [snip]  Now I'm
> looking to build a GUI in python with the rendering engine as an
> integrated window. I will most likely use wxPython for the GUI and I
> know it has support for adding an OpenGL canvas.
> 
> 

You might look into PyFLTK (which I think was just recently
mentioned on the announce list):

http://pyfltk.sourceforge.net/

I haven't used it. Just something to maybe look into. I think
fltk does indeed have support for OpenGL. And I hear it's a
fast and light toolkit. ;)

---John


-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Indentation Problems

2006-02-28 Thread John M. Gabriele
Renato wrote:
> If you use vi (vim, I hope), then place something like this in your
> .vimrc
> 
> set ts=4
> set sw=4
> set expandtab
> set ai

Or, more verbose:

set tabstop=4
set shiftwidth=4

set autoindent

> There are a lot more tricks for python in vim (and plugins, and
> helpers, and so on), but this is the starting point: tabstops of 4
> places, autoconverted in spaces. Also, when shifting text with < or >
> it moves 4 spaces.
> 

Also possibly useful:

set shiftround

---John


-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


PyGUI 1.6: A Note for MacOSX Users

2006-02-28 Thread greg
A small problem has come to light with PyGUI 1.6
on MacOSX systems.

If you get the following exception:

File "GUI/Generic/BaseAlertFunctions.py", line 5, in ?
ImportError: No module named Alerts

it's probably because you don't have PyObjC installed.

I will fix this to produce a more informative error
message in the next release.

==

What is PyGUI?
--

PyGUI is an experimental highly-Pythonic cross-platform
GUI API. Implementations are currently available for
MacOSX and Gtk. For a full description of the project
goals, see the PyGUI web page at the above address.

The current version is available from:

   http://www.cosc.canterbury.ac.nz/~greg/python_gui/

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


Re: Use empty string for self

2006-02-28 Thread James Stroud
John Salerno wrote:
> Grant Edwards wrote:
> 
>>> A related thing I was wondering about was the use of 'self' in
>>> class methods as the first parameter.
>>
>>
>> It's not a related thing, it's the same thing.
> 
> 
> Oh sorry. I thought the OP was asking about having to use self when 
> qualifying attributes, or even if he was, I didn't realize it was the 
> same principle as my question. And just now I was reading about new 
> style classes, and it also seems like a bit of extra typing to have to 
> subclass object, but I guess that isn't something that can be implied 
> right now either.

"self" is conceptually necessary. Notice the similarities between 
doittoit() and It.doittoit():


py> def doittoit(it):
...   print it.whatzit
...
py> class It:
...   whatzit = 42
...   def doittoit(self):
... print self.whatzit
...
py> anit = It()
py> doittoit(anit)
42
py> It.doittoit(anit)
42
py> anit.doittoit()
42


If you get this example, I'm pretty sure you will understand "self" and 
its necessity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-02-28 Thread John Salerno
Grant Edwards wrote:

>> A related thing I was wondering about was the use of 'self' in
>> class methods as the first parameter.
> 
> It's not a related thing, it's the same thing.

Oh sorry. I thought the OP was asking about having to use self when 
qualifying attributes, or even if he was, I didn't realize it was the 
same principle as my question. And just now I was reading about new 
style classes, and it also seems like a bit of extra typing to have to 
subclass object, but I guess that isn't something that can be implied 
right now either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Make staticmethod objects callable?

2006-02-28 Thread Murali
You have a text-database, each record has some "header info" and some
data (text-blob). e.g.



name = "Tom"
phone = "312-996-"

I last met tom in 1998. He was still single then.
blah
blah

name = "John"
birthday = "1976-Mar-12"

I need to ask him his email when I see him next.
--

I use this format for a file to keep track of tit bits of information.
Lets say the file has several hundred records. I know want to say
generate a birthday list of people and their birthdays. Ofcourse along
with that I also need the "text-blob" (because I dont want to send a
birthday card to a person I dont like). In order to do this I execute a
script

./filter --input=database.txt --condn='similar(name,"tom")'.

The way it is implemented is simple. Have a class which has dict as its
base class. For each record the text between  and  is
executed with the class instance as "locals()". Now that I have a list
of class instances, I just exec the condition and those instances where
it evaluates True comprise the output text file.

To make the user, not have to know too much python, one would like to
define "functions" which can be used. For eg. similar would have the
following definition

@staticmethod
def similar(regexp,str):
   return re.match("(?i)^.*%s.*$" % regexp, str) != None

This way the "locals()" dictionary in the exec'ed environment has
access to the function similar (if similar was callable). At the same
time, I can enclose all these functions in their own name space (as
static methods of a class).

Right now, I declare all these "helper" functions in a different
module, and "attach" the "helper" functions as keys into the
dictionary. If only staticmethods were callable. For some reason (I
dont recall why) the idea of converting the staticmethod into a
callable still did not work, e.g.

class Callable:
   def __init__(self,method):
self.__call__ = method

class Record(dict):

   @staticmethod
   def similar(regexp,string):


   self['similar'] = Callable(similar)

The above did not work. The error message was still related to a
staticmethod not being a callable.

- Murali

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


Re: type = "instance" instead of "dict"

2006-02-28 Thread James Stroud
Mel Wilson wrote:
> James Stroud wrote:
> 
>> Fredrik Lundh wrote:
>>
>>> James Stroud wrote:
>>>
>>>
 Perhaps you did not know that you can inheret directly from dict, which
 is the same as {}. For instance:

 class Dict({}):
   pass
>>
>>
>>
>> I must have been hallucinating. I swear I did this before and it 
>> worked just like class Dict(dict). Since it doesn't read as well, I've 
>> never used it.
>>
>>>
> 
> class D (type({})):
> '''This derivative of dictionary works.'''
> 
> Could that have been it?
> 
> Mel.

This rings a bell. It was a couple of years ago, so the "type" must have 
faded from my already murky memory.

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


Re: Use empty string for self

2006-02-28 Thread Grant Edwards
On 2006-03-01, John Salerno <[EMAIL PROTECTED]> wrote:

>> Yes.  To death.  Executive summary: self is here to stay.
>
> A related thing I was wondering about was the use of 'self' in
> class methods as the first parameter.

It's not a related thing, it's the same thing.

> I understand that right now it is necessary, but is this
> something that the language itself requires,

Yes.  Sort of.  When declaring a function, you have to declare
all of the formal paramters.  For functions that are bound to
class instances as methods, the first formal parameter is the
object instance.  It's common practice to call that parameter
"self", but you can call it something else.

> or just the way it is implemented now?

No.

> It seems like a waste of typing

Typing is free.  At least compared to the costs of the rest of
the life-cycle of a software project.

> to always have to put self as the first parameter in every
> class method.

You could call that first parameter to class methods "s" if you
can't afford the three extra letters (I've got lots of extra
letters, and I can send you some if you like).  If you do call
it something other than self and somebody else ever has to
maintain your code, they'll be annoyed with you.

> Is there no way for it to be implied?

No.

-- 
Grant Edwards
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use empty string for self

2006-02-28 Thread John Salerno
Roy Smith wrote:
> [EMAIL PROTECTED] wrote:
>> Any comments?  Has this been discussed before?
> 
> Yes.  To death.  Executive summary: self is here to stay.

A related thing I was wondering about was the use of 'self' in class 
methods as the first parameter. I understand that right now it is 
necessary, but is this something that the language itself requires, or 
just the way it is implemented now? It seems like a waste of typing to 
always have to put self as the first parameter in every class method. Is 
there no way for it to be implied?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: MySQLdb compile error with AMD64

2006-02-28 Thread Keith Burns
Title: RE: MySQLdb compile error with AMD64






Found it.

Had to change

Extra_compile_args = config(cflags) to the actual list with –march=athlon64

Now just realized that I didn’t download the right RPMs for MySQL for SUSE on AMD64 (so got lib errors I am assuming cos of that).

Will download and update with what I changed in the setup.py once I get this working.

Thanks for the pointers and getting me on the right track!

_
From: Keith Burns [mailto:[EMAIL PROTECTED]]
Sent: Tuesday, February 28, 2006 8:04 PM
To: 'python-list@python.org'
Subject: MySQLdb compile error with AMD64


>> Can anyone offer any assistance on this one?

>

>Look here:

>

>>> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall

>>> -D_FORTIFY_SOURCE=2 -g -fPIC -I/usr/include/mysql

>>> -I/usr/include/python2.4 -c _mysql.c -o

>>> build/temp.linux-x86_64-2.4/_mysql.o -I/usr/include/mysql -g

>>> -march=i586 -mcpu=i686 -fmessage-length=0

>

>specifically at -march=i586. MySQLdb sets CFLAGS which aren't applicable to

>your processor, and as such the compile barfs. You should probably just run

>it with something like

>

>CFLAGS="-march=athlon-64" python setup.py build

>

>I am positive that MySQLdb works on AMD64, I have it running there. Anyway,

>the CFLAGS fix should work.

Hey there!

Appreciate the help but the CFLAGS did not change the gcc –march (I tried it as above and with CFLAGS=”-march=athlon64” which I found in a GCC flag FAQ). 

I realize that the –march is my problem but I can’t work out how to change it.

Any ideas?

Thanks!


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

MySQLdb compile error with AMD64

2006-02-28 Thread Keith Burns
Title: MySQLdb compile error with AMD64







>> Can anyone offer any assistance on this one?

>

>Look here:

>

>>> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall

>>> -D_FORTIFY_SOURCE=2 -g -fPIC -I/usr/include/mysql

>>> -I/usr/include/python2.4 -c _mysql.c -o

>>> build/temp.linux-x86_64-2.4/_mysql.o -I/usr/include/mysql -g

>>> -march=i586 -mcpu=i686 -fmessage-length=0

>

>specifically at -march=i586. MySQLdb sets CFLAGS which aren't applicable to

>your processor, and as such the compile barfs. You should probably just run

>it with something like

>

>CFLAGS="-march=athlon-64" python setup.py build

>

>I am positive that MySQLdb works on AMD64, I have it running there. Anyway,

>the CFLAGS fix should work.

Hey there!

Appreciate the help but the CFLAGS did not change the gcc –march (I tried it as above and with CFLAGS=”-march=athlon64” which I found in a GCC flag FAQ). 

I realize that the –march is my problem but I can’t work out how to change it.

Any ideas?

Thanks!


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

Re: Use empty string for self

2006-02-28 Thread Roy Smith
Terry Hancock <[EMAIL PROTECTED]> wrote:
> However, there is a slightly less onerous method which
> is perfectly legit in present Python -- just use "s"
> for "self":

This is being different for the sake of being different.  Everybody *knows* 
what self means.  If you write your code with s instead of self, it just 
makes it that much harder for other people to understand it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Default Section Values in ConfigParser

2006-02-28 Thread Terry Hancock
On 28 Feb 2006 17:05:32 -0800
"mwt" <[EMAIL PROTECTED]> wrote:
> I want to set default values for a ConfigParser. So far,
> its job is very small, so there is only one section
> heading, ['Main']. Reading the docs, I see that in order
> to set default values in a ConfigParser, you initialize it
> with a dictionary or defaults.

You know, I never noticed that, but there is another way.

I used a multi-line string constant with the same syntax
as the original file, and just fed that in as the first
source (this is particularly easy, so I think it must have
been intended).  Slightly snipped version of my code for
this:

default_cfg = StringIO("""\
[VARIMAGE]
V1_COMPATIBILITY: ON

[SECURITY]
MAX_OPERATORS: 0
""")

# Look for varimage.cfg in 3 possible locations:
config = ConfigParser.ConfigParser()
config.readfp(default_cfg)
config.read(['/etc/varimage.cfg',   
os.path.expandvars('${INSTANCE_HOME}/varimage.cfg'),
   os.path.join(pkghome, 'varimage.cfg') ])


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

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


Re: Use empty string for self

2006-02-28 Thread Terry Hancock
On 28 Feb 2006 15:54:06 -0800
[EMAIL PROTECTED] wrote:
> The issue I have with self. is that is makes the code
> larger and more complicated than it needs to be. 
> Especially in math expressions like: self.position[0] =
> self.startx + len(self.bitlist) * self.bitwidth
> 
> It really makes the code harder to read.  On the other
> hand, eliminating the self. would create other issues
> including readability with regards to which vars are
> instance vars and which come from somewhere else.
> 
> But what if we keep the '.' and leave out the self.  Then
> the example looks like:
> .position[0] = .startx + len(.bitlist) * .bitwidth

I think I'm not the only person who hates this idea. The "."
is just too cryptic, IMHO. The main objection is that it
would require "magic" to make it work, though.

However, there is a slightly less onerous method which
is perfectly legit in present Python -- just use "s"
for "self":

  def mymethod(s):
  # ...
  s.position[0] = s.startx + len(s.bitlist) * s.bitwidth
  # ...

"self" is NOT a keyword, it's just a convention.

While I still generally prefer to see "self", I still
consider the above pretty readable, and it goes more than
halfway towards your goal.

Others have suggested "_" instead of "s". However, IMHO,
it's less visible, takes up the same space as "s", and
requires the shift key, so I'd rather just use "s".

And yes, it's been discussed to death on the list. ;-)

Cheers,
Terry


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

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


Re: Use empty string for self

2006-02-28 Thread Roy Smith
[EMAIL PROTECTED] wrote:
> Any comments?  Has this been discussed before?

Yes.  To death.  Executive summary: self is here to stay.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Roy Smith
Ben Finney <[EMAIL PROTECTED]> wrote:

> > a = enum ('foo', 'bar', 'baz')
> > b = enum ('foo', 'bar', 'baz')
> 
> Two separate enumerations are created

OK, most of the rest follows from that.

> > str (a)
> 
> Not defined in the current specification. Suggestions?

Well, by analogy with

>>> a = set ((1, 2, 3))
>>> print '%s' % a
set([1, 2, 3])

I would think:

enum('foo', 'bar', 'baz')

would make sense.

> > repr (a)
> 
> Not defined in the current specification. Suggestions?

Hmm.  Maybe what I suggested for str() would work for repr() too.  I'm a 
little worried, however, about things that aren't == but print the same.  
It might make more sense for repr() to include the id (in the style of 
'<__main__.x instance at 0x8208f6c>').  Same with the repr() of an enum 
member.

> > hash (a)
> 
> -1210774164  # or some other hash value

I saw some debate about mutable or immutable.  Doesn't making something 
hashable kinda-sorta mean it has to be immutable?

> > You imply that it works from "An enumerated type is created from a
> > sequence of arguments to the type's constructor", but I suspect
> > that's not what you intended.
> 
> That's what I intended; a sequence of arguments. Is there a better way
> to refer to the positional arguments collectively?

I'm not really a language lawyer, so I can't say.  I was mostly trying to 
explore the corners of the envelope.

> > There's been a number of threads recently where people called 
> > regex methods with flags (i.e. re.I) when integers were expected, with 
> > bizarre results.  Making the flags into an enum would solve the problem 
> > while retaining backwards compatibility.
> 
> Yes, this is a prime use case for enums. I tried to cover this in the
> "Motivation"::
> 
> Other examples include error status values and states
> within a defined process.
> 
> Can anyone think of a better way to express this, without necessarily
> referring to any specific set of flags or states or codes or whatever?

Cite the regex thread :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Felipe Almeida Lessa
Em Seg, 2006-02-27 às 17:10 -0800, Paul Rubin escreveu:
> Ben Finney <[EMAIL PROTECTED]> writes:
> > If an enumeration object were to be derived from, I would think it
> > just as likely to want to have *fewer* values in the derived
> > enumeration. Subclassing would not appear to offer a simple way to do
> > that.
> 
> pentium_instructions = enum('add', 'sub', 'mul', ) # etc
> 
> athlon64_instructions = enum('add64', 'sub64', # etc
>  base_enum=pentium_instructions)
> 
> # 386 has no floating point unit
> i386_instructions = enum(base_enum=pentium_instructions,
>  remove=('addf', 'subf', 'mulf',))  # etc

Or maybe just...

i386_instructions = enum('add', 'sub', 'mul', ...)
pentium_instructions = enum(i386_instructions, 'addf', 'subf',
'mulf', ...)
athlon64_instructions = enum(pentium_instructions, 'add64',
'sub64', ...)
myprocessor_instructions = enum('foo', 'bar', 'baz', ...)
all_instructions = enum(athlon64_instructions,
myprocessor_instructions)

...and it could infer from the type that it's another enum to be
included. Also...

(i386_instructions.add == pentium_instructions.add ==
athlon64_instructions.add == all_instructions.add) == True

...and so on.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: PEP 354: Enumerations in Python

2006-02-28 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> These don't seem simple or elegant. I don't see a particular benefit
> to doing it that way, rather than being explicit about manipulating
> the member list::
> 
> pentium_instructions = enum('add', 'sub', 'mul')
> athlon64_instructions = enum(
> *[ str(i) for i in pentium_instructions] + ['add64', 'sub64'] )

I don't know about this.  It makes athlon64_instructions a completely
separate enum from pentium_instructions.  It could be that
athlon64_instructions.add should be the same as pentium_instructions.add .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SyntaxError: can't assign to a function call

2006-02-28 Thread Aahz
In article <[EMAIL PROTECTED]>,
Tim Roberts  <[EMAIL PROTECTED]> wrote:
>
>One thing that can be helpful in situations like this is to remember that
>+= in Python isn't quite as "special" as it is in C.  So,
>
>  f() += [4]
>
>is the same as
>
>  f() = f() + [4]
>
>and I think you can see why that is a problem.

Actually, it's not quite the same as the expansion, either:

>>> a=[1]
>>> b=a
>>> a+=[2]
>>> a is b
1
>>> a = a + [3]
>>> a is b
0
>>> a
[1, 2, 3]
>>> b
[1, 2]
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Ben Finney <[EMAIL PROTECTED]> writes:
> PEP:354
> Title:  Enumerations in Python
> Version:$Revision: 42186 $
> Last-Modified:  $Date: 2006-01-26 11:55:20 +1100 (Thu, 26 Jan 2006) $

Most people seem to be unopposed or in favour of some kind of
enumeration mechanism making it at least as far as the standard
library.

As I understand it, the current outstanding debates are::

  * Builtin types versus stdlib module (maybe 'collections')

  * Ordered sequences versus unordered iterables

  * Immutable versus mutable

  * Bad comparisons: raise exception versus return NotImplemented

  * Terminology for each of these concepts

Any new issues before I make a revised draft?

-- 
 \   "It is seldom that liberty of any kind is lost all at once."  |
  `\ -- David Hume |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Toby Dickenson <[EMAIL PROTECTED]> writes:

> On Monday 27 February 2006 02:49, Ben Finney wrote:
>> Coercing a value from an enumeration to a ``str`` results in the
>> string that was specified for that value when constructing the
>> enumeration::
>
> That sentence seems to assume that all enumeration values will have
> been specified as strings. Thats reasonable, but your description of
> the creation of an enumeration doesnt specify that.

True; I'll need to fix the specification so that it does say that.

>> An enumerated type is created from a sequence of arguments to the
>> type's constructor::
>> 
>> >>> Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
>> >>> Grades = enum('A', 'B', 'C', 'D', 'F')
>
> s/arguments/strings/

s/arguments/string arguments/ :-)

-- 
 \   "Too many pieces of music finish too long after the end."  -- |
  `\  Igor Stravinskey |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Steven Bethard <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
>> This PEP specifies an enumeration data type for Python.
>> An enumeration is an exclusive set of symbolic names bound to
>> arbitrary unique values.  Values within an enumeration can be iterated
>> and compared, but the values have no inherent relationship to values
>> outside the enumeration.
>
> -1 on the proposal as-is.  I don't have many use cases for
> enumerations, and I don't think they merit appearing in the builtins.
> If you put them in the collections module instead, I'd probably be +0.

This seems to be a common distinction.

Should I amend the PEP to propose "either in the builtins or in the
collections module"? Or should I propose two PEPs and let them
compete?

>> This allows the operation to succeed, evaluating to a boolean value::
>> >>> gym_night = Weekdays.wed
>> >>> gym_night < Weekdays.mon
>> False
>> >>> gym_night < Weekdays.wed
>> False
>> >>> gym_night < Weekdays.fri
>> True
>> >>> gym_night < 23
>> False
>> >>> gym_night > 23
>> True
>> >>> gym_night > "wed"
>> True
>> >>> gym_night > Grades.B
>> True
>
> For the few cases of enumerations that I've needed, I've never
> wanted them to be comparable with <, >, etc.  If there were two
> classes, say ``collections.Enum`` and ``collections.OrderedEnum``
> where only the latter made the enumerated items comparable, you
> might even get me as high as +0.5.  (I only care about the
> non-comparable one, but I understand that others may have a need for
> the comparable one.)

Replies to your post indicate this is another popular distinction.

But the terminology is broken. The term "enumerated" seems to me to
imply that it does have an order. Can you suggest a term other than
"enumerated" for what you're describing with the unordered property?

-- 
 \ "For every complex problem, there is a solution that is simple, |
  `\neat, and wrong."  -- Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type = "instance" instead of "dict"

2006-02-28 Thread Mel Wilson
James Stroud wrote:
> Fredrik Lundh wrote:
> 
>> James Stroud wrote:
>>
>>
>>> Perhaps you did not know that you can inheret directly from dict, which
>>> is the same as {}. For instance:
>>>
>>> class Dict({}):
>>>   pass
> 
> 
> I must have been hallucinating. I swear I did this before and it worked 
> just like class Dict(dict). Since it doesn't read as well, I've never 
> used it.
> 
>>

class D (type({})):
 '''This derivative of dictionary works.'''

Could that have been it?

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


Cross compile generation of .pyc from .py files...

2006-02-28 Thread venkatbo
Hi all,

We've managed to cross-compile (from i686 targeting ppc) python (2.4.2)
binaries and
extension modules.

However we cannot figure out how to cross-compile the .py (of
distribution) files and
generate the .pyc files for the target ppc from an i686 system.  Is it
possible to cross
compile .pyc files from .py files?

Some of the errors we get when we run 'python -v' on the target system
include:

# /usr/lib/python2.4/site.pyc has bad magic
import site # from /usr/lib/python2.4/site.py

# /usr/lib/python2.4/types.pyc has bad magic
import types # from /usr/lib/python2.4/types.py
.

Thanks,
/venkat

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


Re: Use empty string for self

2006-02-28 Thread paullanier
Thanks.  I thought for sure it must have been discussed before but for
whatever reason, my googling skills couldn't locate it.

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


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Roy Smith <[EMAIL PROTECTED]> writes:

> A few random questions:
>
> a = enum ('foo', 'bar', 'baz')
> b = enum ('foo', 'bar', 'baz')

Two separate enumerations are created, and bound to the names 'a' and
'b'. Each one has three unique member values, distinct from any
others.

> what's the value of the following:
>
> a == b

False

(the enumeration objects are not the same, and don't contain the same
values)

> a is b

False

(the enumeration objects are not the same)

> a.foo == b.foo

False

(the comparison function returns NotImplemented when comparing values
from different enumerations. The Python interpreter [thanks Alex
Martelli :-)] will evaluate the comparison as False)

> a.foo is b.foo

False

(the members of each enumeration are created as separate values)

> len (a)

3

(enumerations are iterable)

> str (a)

Not defined in the current specification. Suggestions?

> repr (a)

Not defined in the current specification. Suggestions?

> hash (a)

-1210774164  # or some other hash value

(falls back on the 'object' hash function)

> type (a)

  # if included in the language
  # if in the stdlib

> Can you make an enum from a sequence?

The current specification is for an enum constructor to accept its
member names as separate arguments, to allow for the expected common
use case::

foo = enum('bar', 'baz', 'bucket')

> syllables = ['foo', 'bar', 'baz']
> c = enum (syllables)

Can be done with::

c = enum(*syllables)

> You imply that it works from "An enumerated type is created from a
> sequence of arguments to the type's constructor", but I suspect
> that's not what you intended.

That's what I intended; a sequence of arguments. Is there a better way
to refer to the positional arguments collectively?

> BTW, I think this is a great proposal; enums are a badly needed part
> of the language.

Thanks. I hope we can arrive at a consensus view of how enums should
work in Python.

> There's been a number of threads recently where people called 
> regex methods with flags (i.e. re.I) when integers were expected, with 
> bizarre results.  Making the flags into an enum would solve the problem 
> while retaining backwards compatibility.

Yes, this is a prime use case for enums. I tried to cover this in the
"Motivation"::

Other examples include error status values and states
within a defined process.

Can anyone think of a better way to express this, without necessarily
referring to any specific set of flags or states or codes or whatever?

-- 
 \"To be yourself in a world that is constantly trying to make |
  `\ you something else is the greatest accomplishment."  -- Ralph |
_o__)Waldo Emerson |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Default Section Values in ConfigParser

2006-02-28 Thread mwt
I want to set default values for a ConfigParser. So far, its job is
very small, so there is only one section heading, ['Main']. Reading the
docs, I see that in order to set default values in a ConfigParser, you
initialize it with a dictionary or defaults. However, I'm not quite
sure of the syntax to add the section headings in to the dictionary of
defaults. For now, I'm doing it like this:

default_values = {'username' : 'put username here',
'teamnumber': 'team number here',
'update_interval' : 'update interval'}
self.INI = ConfigParser.ConfigParser(default_values)
self.INI.add_section('Main')

This works, but clearly won't last beyond the adding of a second
section. What is the correct way to initialize it with a full
dictionary of defaults, including section names? 

Thanks.

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


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Paul Rubin  writes:
> Do you anticipate having parameters like socket.AF_INET that are
> currently integers, become enumeration members in future releases?

That, and the 're' flags referred to earlier, seems to be a good
application of enumerations.

-- 
 \ "Jealousy: The theory that some other fellow has just as little |
  `\  taste."  -- Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Paul Rubin  writes:

> say that 
>Weekdays = enum('mon', 'tue', ...)
>
> What is the type of Weekdays.mon supposed to be?

The specification doesn't mention that; it should.

I'm calling them EnumValue, but that makes it difficult to talk
about. The term "value" is commonly used to refer to an instance of a
type, so "enumeration value" sounds like an instance of the type
"enumeration", which is confusing.

Perhaps, since "collection" seems the right metaphor for an
enumeration, each of the values in an enumeration should be
EnumMember. On the assumption these might be basic types, though, that
name doesn't read so easily in lowercase ('enummember').

Thoughts?

-- 
 \   "What I resent is that the range of your vision should be the |
  `\  limit of my action."  -- Henry James |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Ben Finney
Paul Rubin  writes:

> Ben Finney <[EMAIL PROTECTED]> writes:
>> If an enumeration object were to be derived from, I would think it
>> just as likely to want to have *fewer* values in the derived
>> enumeration. Subclassing would not appear to offer a simple way to
>> do that.
>
> pentium_instructions = enum('add', 'sub', 'mul', ) # etc
>
> athlon64_instructions = enum('add64', 'sub64', # etc
>  base_enum=pentium_instructions)
>
> # 386 has no floating point unit
> i386_instructions = enum(base_enum=pentium_instructions,
>  remove=('addf', 'subf', 'mulf',))  # etc

These don't seem simple or elegant. I don't see a particular benefit
to doing it that way, rather than being explicit about manipulating
the member list::

pentium_instructions = enum('add', 'sub', 'mul')
athlon64_instructions = enum(
*[ str(i) for i in pentium_instructions] + ['add64', 'sub64'] )
i386_instructions = enum(
*[ str(i) for i in pentium_instructions
if i not in ['addf', 'subf', 'mulf'] ] )

I don't see a benefit to having the enum constructor grow extra
keyword arguments for operating on lists, when a list has its own
methods for doing so.

-- 
 \ "A fine is a tax for doing wrong. A tax is a fine for doing |
  `\  well."  -- Anonymous |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fetching the Return results of a spawned Thread

2006-02-28 Thread Alvin A. Delagon
Thanks a lot for the links that you gave me. I will look into that 
today!  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bsddb3 database file, are there any unexpected file size limits occuring in practice?

2006-02-28 Thread Klaas
> In my current project I expect the total size of the indexes to exceed
> by far the size of the data indexed, but because Berkeley does not
> support multiple indexed columns (i.e. only one key value column as
> index) if I access the database files one after another (not
> simultaneously) it should work without problems with RAM, right?

You can maintain multiple secondary indices on a primary database.  BDB
isn't a "relational" database, though, so speaking of columns confuses
the issue.  But you can have one database with primary key -> value,
then multiple secondary key -> primary key databases (with bdb
transparently providing the secondary key -> value mapping if you
desire).

> Do the data volume required to store the key values have impact on the
> size of the index pages or does the size of the index pages depend only
> on the number of records and kind of the index (btree, hash)?

For btree, it is the size of the keys that matters.  I presume the same
is true for the hashtable, but I'm not certain.

> What is the upper limit of number of records in practice?

Depends on sizes of the keys and values, page size, cache size, and
physical limitations of your machine.

-Mike

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


Re: Py2exe

2006-02-28 Thread D
Thanks Larry - that is exactly what I needed!  I do have the program
written to be a service, and now plan to use py2exe and Inno Setup to
package it up. 

Doug

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


Re: type = "instance" instead of "dict"

2006-02-28 Thread Cruella DeVille
This is off topic, but if read the documentation is the answere to
everything why do we need news groups? The problem with the
documentation for Python is that I can't find what I'm looking for (and
I didn't even know what I was looking for either). And since every
language is well documented... there's no need for these groups.

I wouldn't ask here without trying to find the solution on my own
first.

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


Re: Use empty string for self

2006-02-28 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> It seems that lots of people don't like having to prefix self. in front
...
> But what if we keep the '.' and leave out the self.  
...
> Any comments?  Has this been discussed before?

Yes, at least once (found by group-googling for "removing self" in this 
newsgroup):

http://groups.google.com/group/comp.lang.python/browse_frm/thread/ebcd82c4f3c2d483/ad791fdd4734579c?tvc=1&q=%22removing+self%22#ad791fdd4734579c


-Peter

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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> BTW, are the python-dev guys aware that 10 ** -1 = 0.10001 ?

http://docs.python.org/tut/node16.html





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


Use empty string for self

2006-02-28 Thread paullanier
It seems that lots of people don't like having to prefix self. in front
of instance variables when writing methods in Python.  Of course,
whenever someone suggests doing away with 'self' many people point to
the scoping advantages that self brings.  But I hadn't seen this
proposal when I searched so I thought I'd throw it out there.  Maybe
it's already been thrown out but I like it.

The issue I have with self. is that is makes the code larger and more
complicated than it needs to be.  Especially in math expressions like:
self.position[0] = self.startx + len(self.bitlist) * self.bitwidth

It really makes the code harder to read.  On the other hand,
eliminating the self. would create other issues including readability
with regards to which vars are instance vars and which come from
somewhere else.

But what if we keep the '.' and leave out the self.  Then the example
looks like:
.position[0] = .startx + len(.bitlist) * .bitwidth

The 'self' is implied but the scoping rules don't change and it's still
clear when reading it that they are instance variables.  We can keep
the self in the method header (or not) but that is really a separate
issue.

Any comments?  Has this been discussed before?

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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Grant Edwards
On 2006-02-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I like Fredrik's solution.  If for some reason you are afraid of
> logarithms, you could also do:
>
 x = 4978
 decades = [10 ** n for n in xrange(-1,8)]
 import itertools
 itertools.ifilter(lambda decade: x < decade, decades).next()
> 1
>
> BTW, are the python-dev guys aware that 10 ** -1 = 0.10001 ?

You're joking, right?

-- 
Grant Edwards   grante Yow!  HOORAY, Ronald!! Now
  at   YOU can marry LINDA
   visi.comRONSTADT too!!
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Extended Python debugger 1.14

2006-02-28 Thread R. Bernstein
Download from
http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827

On-line documentation is at
http://bashdb.sourceforge.net/pydb/pydb/lib/index.html

Changes since 1.12
* Add MAN page (from Debian)
* Bump revision to 0.12 to 1.13 to be compatible with Debian pydb package.
* Improve set_trace(), post_mortem(), and pm()
* Document alternative invocation methods and how to call from a program.
* Break out cmds and bdb overrides into a separate module
* add optional count on "where"
* install in our own directory (e.g. site-packages/pydb)
  NOTE: REMOVE OLD PYDB INSTALLATIONS BEFORE INSTALLING THIS PYDB.
* As a result of the above add __init__.py to give package info.
* Don't rely on tabs settings. Remove all tabs in programs and use -t 
  to check that.
* Various bug fixes and documentation corrections
* Fix bugs in configuration management. Make distcheck works again
  (sometimes)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQT: QDialog and QMainWindow interacting with each other

2006-02-28 Thread Fabian Steiner
Hi Kai!

Kai Teuber wrote:
  > Hi Fabian,
> 
> override the accept() method and call self.showListViewItems() there.
> But remember to call QDialog.accept() at the end.
> 
> def accept( self ):
> self.showListViewItems()
> QDialog.accept( self )


Thank you very much, I got it working :-)

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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread johnzenger
I like Fredrik's solution.  If for some reason you are afraid of
logarithms, you could also do:

>>> x = 4978
>>> decades = [10 ** n for n in xrange(-1,8)]
>>> import itertools
>>> itertools.ifilter(lambda decade: x < decade, decades).next()
1

BTW, are the python-dev guys aware that 10 ** -1 = 0.10001 ?

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


Re: Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Steven Bethard wrote:
> Nicolas Fleury wrote:
> 
>> I was wondering if it would make sense to make staticmethod objects 
>> callable, so that the following code would work:
>>
>> class A:
>> @staticmethod
>> def foo(): pass
>> bar = foo()
> 
> Do you have a real-world use case?  I pretty much never use 
> staticmethods (preferring instead to use module-level functions) so I'm 
> having a hard time coming up with some code where this would be really 
> useful.  I'm also a little wary of breaking the parallel between 
> classmethod and staticmethod which are currently *just* descriptors 
> (without any other special functionality).

Well, IMHO, if staticmethod is worth being standard, than calling these 
static methods inside the class definition is worth being supported.  To 
be honest I don't use static methods like you, but users come see me 
asking "Why?" and I find their code logically structured so I conclude 
there's a usability problem here.

> Maybe instead of making just staticmethods callable, both staticmethods 
> and classmethods could gain an 'im_func' attribute like bound and 
> unbound methods have?

I don't like it either (__get__ can be called anyway).  My problem is 
the expectation of the user.  I wonder if it should just work.  Adding a 
few lines of code in staticmethod is worth it if it avoids all these 
questions over and over again, no?

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


Re: Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Felipe Almeida Lessa wrote:
> Em Ter, 2006-02-28 às 15:17 -0500, Nicolas Fleury escreveu:
> 
>>class A:
>> @staticmethod
>> def foo(): pass
>> bar = foo()
> 
> 
> # Why not:
> 
> def foo(): pass
> 
> class A:
>   bar = foo()
>   foo = staticmethod(foo)
> 

Well, you could even do:

class A:
 def foo(): pass
 bar = foo()
 staticmethod(foo)

But it's a bit sad to have a special syntax for decorators then.  It's a 
usability problem, nothing to do with functionality.  There's obvious 
workarounds, but IMHO any user saying "it should just work" is at least 
partly right.

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

Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Grant Edwards
On 2006-02-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Quoting Derek Basch <[EMAIL PROTECTED]>:
>
>> Given a value (x) that is within the range (1e-1, 1e7) how do I round
>> (x) up to the closest exact logarithmic decade? For instance:
>
> How about this:
>
> def roundup(x):
> if x < 1:
> return 1
> else:
> return '1' + ('0' * len(str(int(x

Interesting approach.  You're converting to string at the same
time.  I would guess the OP wanted a float.

-- 
Grant Edwards   grante Yow!  It's OKAY -- I'm an
  at   INTELLECTUAL, too.
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Firebird and Python

2006-02-28 Thread Claudio Grondi
haxier wrote:
> All the info you need is in the kinterbasdb module. I've worked with it
> under windows and Linux and... "it just works". Really well indeed. I'd
> recommend it a lot.
> 
> http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_embedded_using_with
> 
> --
> Asier.
> 
Thanks - you have provided exactly the information I asked for.

Thanks also to Magnus (yes I asked for the in-process feature).

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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Derek Basch
Thanks effbot. I knew their had to be something buried in the math
module that could help. ceil() it is!



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


RE: MySQLdb compile error with AMD64

2006-02-28 Thread Heiko Wundram
[EMAIL PROTECTED] wrote:

> Can anyone offer any assistance on this one?

Look here:

>> gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall
>> -D_FORTIFY_SOURCE=2 -g -fPIC -I/usr/include/mysql
>> -I/usr/include/python2.4 -c _mysql.c -o
>> build/temp.linux-x86_64-2.4/_mysql.o -I/usr/include/mysql -g
>> -march=i586 -mcpu=i686 -fmessage-length=0

specifically at -march=i586. MySQLdb sets CFLAGS which aren't applicable to
your processor, and as such the compile barfs. You should probably just run
it with something like

CFLAGS="-march=athlon-64" python setup.py build

I am positive that MySQLdb works on AMD64, I have it running there. Anyway,
the CFLAGS fix should work.

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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Felipe Almeida Lessa
Em Ter, 2006-02-28 às 17:47 -0500, [EMAIL PROTECTED] escreveu:
> Quoting Derek Basch <[EMAIL PROTECTED]>:
> 
> > Given a value (x) that is within the range (1e-1, 1e7) how do I round
> > (x) up to the closest exact logarithmic decade? For instance:
> 
> How about this:
> 
> def roundup(x):
> if x < 1:
> return 1
> else:
> return '1' + ('0' * len(str(int(x

No dice. First, it returns an int for some cases and a string for the
others. Second, casting from str to int and vice-versa and concatenating
strings won't perform any good. I wouldn't like this hack on my code.

My 2¢,
Felipe.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread jao
Quoting Derek Basch <[EMAIL PROTECTED]>:

> Given a value (x) that is within the range (1e-1, 1e7) how do I round
> (x) up to the closest exact logarithmic decade? For instance:

How about this:

def roundup(x):
if x < 1:
return 1
else:
return '1' + ('0' * len(str(int(x

Jack Orenstein


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


Re: Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Fredrik Lundh
Derek Basch wrote:

> Given a value (x) that is within the range (1e-1, 1e7) how do I round
> (x) up to the closest exact logarithmic decade? For instance:
>
> 10**3 = 1000
> x = 4978
> 10**4 = 1
> x = 1

how about

>>> import math
>>> def roundup(x):
...return 10**math.ceil(math.log10(x))
...
>>> roundup(4978)
1.0

?





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


Rounding up to the nearest exact logarithmic decade

2006-02-28 Thread Derek Basch
Given a value (x) that is within the range (1e-1, 1e7) how do I round
(x) up to the closest exact logarithmic decade? For instance:

10**3 = 1000
x = 4978
10**4 = 1

x = 1

Thanks Everyone!
Derek Basch

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


Re: type = "instance" instead of "dict"

2006-02-28 Thread James Stroud
Fredrik Lundh wrote:
> James Stroud wrote:
> 
> 
>>Perhaps you did not know that you can inheret directly from dict, which
>>is the same as {}. For instance:
>>
>>class Dict({}):
>>   pass

I must have been hallucinating. I swear I did this before and it worked 
just like class Dict(dict). Since it doesn't read as well, I've never 
used it.

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


Re: Get my airlines boarding pass

2006-02-28 Thread James Stroud
rh0dium wrote:
> Hi all,
> 
> Has any of you fine geniuses figured out a nice python script to go to
> the Southwest airlines website and check in, and retrieve your boarding
> pass - automatically 24 hours in advance
> 

Not yet, but I think you are the real genius here. Brilliant idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Make staticmethod objects callable?

2006-02-28 Thread Felipe Almeida Lessa
Em Ter, 2006-02-28 às 15:17 -0500, Nicolas Fleury escreveu:
> class A:
>  @staticmethod
>  def foo(): pass
>  bar = foo()

# Why not:

def foo(): pass

class A:
bar = foo()
foo = staticmethod(foo)

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Make staticmethod objects callable?

2006-02-28 Thread Steven Bethard
Nicolas Fleury wrote:
> I was wondering if it would make sense to make staticmethod objects 
> callable, so that the following code would work:
> 
> class A:
> @staticmethod
> def foo(): pass
> bar = foo()

Do you have a real-world use case?  I pretty much never use 
staticmethods (preferring instead to use module-level functions) so I'm 
having a hard time coming up with some code where this would be really 
useful.  I'm also a little wary of breaking the parallel between 
classmethod and staticmethod which are currently *just* descriptors 
(without any other special functionality).

Maybe instead of making just staticmethods callable, both staticmethods 
and classmethods could gain an 'im_func' attribute like bound and 
unbound methods have?

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


Re: Py2exe

2006-02-28 Thread Larry Bates
D wrote:
> Jay - what I'm not sure of is the syntax to use.  I have downloaded and
> installed py2exe.
> 

First a question:

Have you written the server program as a windows service?  You can't
just run something as a service, it has to be written to be a service.

Your setup files will look something like the ones below.

Client:

from distutils.core import setup
import py2exe
setup(name="client", zipfile=None,
  windows=[{"script":"client.py",
"icon_resources":[(1,"client.ico")]}],
  options={"py2exe": {"compressed": 1,
  "optimize": 2,
  "bundle_files":1}}
 )

Obviously the program here was called client.py.  You will
need an icon to supply to icon_resources.  This creates a
single .EXE file from as much as py2exe can possible put
into it.

Server:

from distutils.core import setup
import py2exe
setup(service=[script:"server.py"], zipfile=None,
  options={"py2exe":{"compressed": 1,
 "optimize": 2,
 "bundle_files":1}}
  )


Of course replace 'server' with the name of your program.

These are merely EXAMPLES.  Your specific needs might be
different depending on specifics of your program.

Hope it helps.

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


Re: Py2exe

2006-02-28 Thread D
Jay - what I'm not sure of is the syntax to use.  I have downloaded and
installed py2exe.

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


Re: Matplotlib logarithmic scatter plot

2006-02-28 Thread Derek Basch
Thanks again. Here is the finished product. Maybe it will help someone
in the future:

from pylab import *

def log_10_product(x, pos):
"""The two args are the value and tick position.
Label ticks with the product of the exponentiation"""
return '%1i' % (x)

ax = subplot(111)
# Axis scale must be set prior to declaring the Formatter
# If it is not the Formatter will use the default log labels for ticks.
ax.set_xscale('log')
ax.set_yscale('log')

formatter = FuncFormatter(log_10_product)
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)

ax.scatter( [3, 5, 70, 700, 900], [4, 8, 120, 160, 200], s=8, c='b',
marker='s', faceted=False)
ax.scatter( [1000, 2000, 3000, 4000, 5000], [2000, 4000, 6000, 8000,
1000], s=8, c='r', marker='s', faceted=False)

ax.set_xlim(1e-1, 1e5)
ax.set_ylim(1e-1, 1e5)
grid(True)
xlabel(r"Result", fontsize = 12)
ylabel(r"Prediction", fontsize = 12)

show()

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


Re: Py2exe

2006-02-28 Thread jay graves
First google.com hit using your title.

http://www.google.com/search?q=py2exe

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


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Terry Hancock
On 28 Feb 2006 09:58:47 -0800
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Add me to the "me, too!" list of people who think
> enumerations would be better off without > or <
> comparison.

+1 on "unordered"

Comparable enums do have use-cases (like the days of the
week), but I can't think of many of them. Also, there is
the point that even the days of the week is not a great
use of the ordering since it varies between locales, as
I think was pointed out in this thread.

The most compelling reason to have some kind of ordering is
just so you can iterate over them -- but dicts are
iterable without being ordered, so I see no reason
why enums couldn't be.

In C, enums are a rather shallow mask pulled over integers,
and as is common practice in C, the mask is routinely
ignored or removed.  I think that enums in Python, if added,
should be "strong enums" without this kind of ambiguous
behavior.

I also think though that the characterization of the
behavior of enumerated value instances is much more
important than the behavior of the enumeration collection
object, which is basically just a set, anyway.

Cheers,
Terry

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

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


OT The Art

2006-02-28 Thread julianlzb87
Illuminated manuscripts, 13 volumes

http://ptlslzb87.blogspot.com/

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


Re: Python Indentation Problems

2006-02-28 Thread Terry Hancock
On 26 Feb 2006 22:21:26 -0800
[EMAIL PROTECTED] wrote:
> I am a newbie to Python. I am mainly using Eric as the IDE
> for coding. Also, using VIM and gedit sometimes.
> 
> I had this wierd problem of indentation. My code was 100%
> right but it wont run because indentation was not right. I
> checked time and again but still no success. I rewrote the
> code over again in VI and it ran.
> 
> Can you please explain whats the trick behind the correct
> indentation.

I'm not sure about Eric, but I found that when using the
Python interpreter through a terminal window, it's often
confusingly fastidious about tabs versus spaces. You would
think that in an interactive context the interpreter would
be smart enough to fix these errors on input (e.g. by
implementing a "convert tabs to spaces" policy by default
-- I've already configured my gvim editor to do that, and
while it's not obviously the right thing to do in an
editor it seems like a no-brainer for an editing mode
whose only purpose is to run Python), but it apparently
doesn't (or didn't anyway -- either I've gotten better
about not mixing them, or it may have been fixed, or else
I'm just lucky to finally have a terminal that agrees with
the interpreter on the width of tabs).

In any case, it's good practice not to mix tabs and spaces.

I actually recommend using just tabs when playing with
the interpreter (it's faster) -- but use spaces in your real
source code files.

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

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


Py2exe

2006-02-28 Thread D
I have a simple client/server file server app that I would like to
convert to a single .exe.  The client is just uses Tkinter and displays
a simple GUI.  The server has no GUI and just listens for and processes
connections.  How can I convert these 2 files to an .exe, while
enabling the server app to register as a Windows service?  Thanks.

Doug

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


Re: minimize a program into an icon on the taskbar.

2006-02-28 Thread Frank Niessink
Larry Bates:
> Its called the system tray and here is a link to some sample code
> for Windows I found via Google:

But, but, but, ... the OP was talking about a wxPython app. 
wx.TaskBarIcon is the wxPython builtin support for making an icon in the 
system tray. Nothing else is needed.

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


Re: Thread Question

2006-02-28 Thread D
Guys - I appreciate the clarification.   So it looks like they used a
class for the ping thread because they were a) running multiple
instances of the thread concurrently and b) needing to keep track of
the state of each instance, correct?  I believe that in my case, since
I will be just running one instance of the thread to ensure that the
remote system is functioning properly, that the single statement should
work just fine.

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


Re: Looking for Pythonic Examples

2006-02-28 Thread Larry Bates
G. Völkl wrote:
> Hello
> I am looking for examples of Pythonic Thinking:
> 
> One example I found:
> 
> Here some lines of the web side of Bruce Eckel:
> http://www.mindview.net/WebLog/log-0053
> 
> How to read a text file:
> for line in file("FileName.txt"):
>  # Process line
> It is a easy and sophisticated thing in python,
> but hard to do or more complicated in other languages like java.
> 
> Does anyone know more examples ?
> 
> Does anyone know books about real good python programming ?
> 
> Best Regards
> 
> Gerhard

Pick up a copy of the Python Cookbook, it is full of examples.

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


Re: minimize a program into an icon on the taskbar.

2006-02-28 Thread Larry Bates
Frank Niessink wrote:
> Rajesh Sathyamoorthy:
>> Hi,
>>
>> I would know how to minimize a program (wxpython app) into an icon on
>> the taskbar on windows (the one at the side near the clock, i can't
>> remember what is it called.)
>>
>> Is it easy to be done? Is there a way to do the same thing on Linux?
> 
> Did you look into wx.TaskBarIcon?
> 
> Cheers, Frank
> 
> 
Its called the system tray and here is a link to some sample code
for Windows I found via Google:

http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html


Here is a link that says it works for KDE:

http://rootprompt.org/article.php3?article=8294

This may help with gnome:

http://www.realistanew.com/2005/04/19/bittorrent-tray-icon/

-Larry Bates




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


Re: Thread Question

2006-02-28 Thread Kent Johnson
D wrote:
> My question is, how would I go
> about creating the thread?  I have seen examples that used classes, and
> other examples that just called one thread start command - when should
> you use one over another?

For simple use it doesn't matter. Use a class when you want to add more 
state or behaviour - for example you might want a flag that tells the 
thread to stop, or a Queue to communicate with the thread. A class might 
be more convenient in these cases.

IOW if you can write it as a single function it doesn't matter much 
which form you use; for more complex usage you may want a class.

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


Re: Thread Question

2006-02-28 Thread Grant Edwards
On 2006-02-28, Felipe Almeida Lessa <[EMAIL PROTECTED]> wrote:

> # He meant calling direct vs. subclassing. In your example you called
>   the Thread class directly, but you could have subclassed it.

Yup.  I should have realized that.

> # In your case, Edwards, I'd prefer subclassing because then you could
> put some states in the class. A (bad) example:

[...]

Good example.

It's probably bad style, but in my programs the "state info"
like that usually ends up being global variables since it's
also "attached" to thinks like GUI buttons and indicators.  I
never have more than one instance of the thread, so I can get
away with it.  If you need multiple instances of stateful
threads, you really do want to subclass Thread.

-- 
Grant Edwards   grante Yow!  I'm in DISGUISE as a
  at   BAGGAGE CHECKERI can
   visi.comwatch the house, if it's
   ORANGE...
-- 
http://mail.python.org/mailman/listinfo/python-list


Long running Script stops responding, CPU usage increases

2006-02-28 Thread Jeff Quandt
Title: Long running Script stops responding, CPU usage increases






This is running Python 2.3 on windows 2003/windows xp.


I have written a script to display and filter the Win32 event log in a scrolling list to the command line (it also does some summary tasks).  It uses the win32evtlog.ReadEventLog to seek or scan the event log based on filter parameters.  It is supposed to run until the user kills it, so there are repeated calls to ReadEventLog.  

The problem is that after the script has run from some time (usually several hours), the call to ReadEventLog seems to hang and the CPU usage increases dramatically (from nil to 30-50%).  The script does not exit this stage, and has to be broken manually with Ctrl-C.  I've tried closing and reopening the event log handle after it has been open for an hour.  I've added explicit calls to the garbage collector.  Neither helped at all.

I realize that this is an API call, so it may not be a python issue.  But I have seen this type of behavior on other scripts (not event loggers), but they were test/debug tools and weren't important enough to track down the issue.

Any help would be appreciated.


code example:


    def OpenLog( self ):

    #

    #open event log

    #

    self.mHandle  = win32evtlog.OpenEventLog( self.mComputer

    , self.mLogType

    )

    if not self.mHandle:

    raise ValueError, "invalid handle"


    self.mLogOpenTmst = time.time()


    def CloseLog( self ):


    win32evtlog.CloseEventLog( self.mHandle )


    def ReadLog( self ):


    self.mFlags = win32evtlog.EVENTLOG_FORWARDS_READ|win32evtlog.EVENTLOG_SEEK_READ

    vEventScon  = win32evtlog.ReadEventLog( self.mHandle

  , self.mFlags

  , self.mLogOffset

  )

    #

    # if not found, try again in 5 seconds

    #

    if not vEventScon:


    #

    # If we've had the log open for more than 1 hour, dump it and reopen

    #

    if ( time.time() > (self.mLogOpenTmst + 3600) ):

    self.CloseLog()

    self.OpenLog()


    time.sleep( 5 )

    return bOk


    #

    # snip...

    # manipulate event records here

    #


#

# main

#

OpenLog

Ok = 1

while Ok:

    Ok = ReadLog()

CloseLog()




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

Re: PEP 354: Enumerations in Python

2006-02-28 Thread Terry Hancock
On Tue, 28 Feb 2006 14:26:49 -0500
"Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Stefan Rank" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > recent examples from this list:
> >
> > 2006-01-03:
> > http://www.nabble.com/Re%3A-Regex-anomaly-p2179421.html
> > 2006-02-20:
> > http://www.nabble.com/Re%3A-Regular-expression-gone-mad-p3029028.html
> 
> If the re flags were implemented as instances of object
> instead of int, then misuse of them as int args would be
> excepted.  I don't know if such a  change would otherwise
> cause a problem.
> 
> I wonder whether a subclass of object (EnumSet?) that
> allowed for  initialization with a better string
> representation and that disabled order  comparisons would
> fill the bill for unordered enum.
> 
> As Steven Bethard also noted, there seem to be a need for
> two Enum  subclasses:
> EnumSet and EnumSeq.

And one other distinction -- mutable versus immutable. A
immutable enum is the usual use case, a mutable one is a
"vocabulary" (i.e. an open set of symbols, which
nevertheless requires controlled access).

The key thing about symbols like enums etc is that they
don't really represent anything (or that which they
represent is inconvenient to bind to the symbols -- perhaps
its even an abstract concept that has no programmatic
representation beyond the enumerated value).

One thing about an enumerated value is that it should know
what enum it belongs to. For example, I'm currently working
on a project that has the following rather unfortunate
near-collision of symbols:

sym.ABSTRACTS  "scope of abstract nouns" in 
   SCOPE vocabulary

sym.ABSTR  "definiteness of abstract noun" in 
   ARTICLE enum

sym.ABST   "number of noun which has no
   count because abstract (not mass)"
   NUMBER enum

It's quite useful that I can ask "sym.ABST" which one of
the above domains it's in:

>>> sym.ABST.domain
NUMBER

or even better:

>>> sym.ABST


Which makes the enumeration values somewhat
self-documenting.  I'm currently trying to figure out how
best to make this instead show (e.g.):

>>> sym.ABST


I can of course, also use this to catch errors by checking
that the pluralization function in my locale module has
been passed a NUMBER or an explicit int, instead of say, a
SCOPE, by accident.

Another feature here is that all of these symbols, though
also defined within their domain collections is also made
into an attribute of the sym object (which is a "trivial
class" or "convenience namespace").

I also raise an error if any domain tries to overwrite a
symbol in sym, so I can avoid accidental collisions.

I'm still tinkering with this, and the above is from memory,
but I do have it working on another machine. I'm currently
subclassing from dict, not set, though I'm unsure if this is
really wise (but I'm more familiar with dict, and I'm
currently making use of the mapping internally, though I'm
not sure I really need to).

I'm not sure this would be a smart way to do this in another
application, but it looks promising for this one (which is
a kind of artificial locale-neutral language
representation).

I'm not sure that the enum described in the PEP would be as
useful to me as this.  So  I'm -0 on it becoming a built-in,
though I'm +0 on it becoming a module (it's not that hard
to type "from enum import Enum").  But I'm not sure it's the
"best" enum, or even that "one size fits all" with enums
(though having fewer implementations might improve clarity
if they are really equivalent).

Cheers,
Terry

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

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


Re: Thread Question

2006-02-28 Thread Felipe Almeida Lessa
Em Ter, 2006-02-28 às 20:38 +, Grant Edwards escreveu:
> On 2006-02-28, D <[EMAIL PROTECTED]> wrote:
> 
> > Thanks, Grant.  I apologize for not being clear on what I
> > meant by using "classes".  This is an example of what I was
> > referring to:
> > http://www.wellho.net/solutions/python-python-threads-a-first-example.html
> 
> Ah, I see.  I had forgotten that people subclass Thread like
> that.  It's mostly just a matter of style.  There aren't any
> practical differences that I can think of.

Within a class you can maintain lots of internal states and make it
easily changable by other threads. Sure, you could archive this with
functions, but IMHO it's not pythonic. But for simple cases both would
suffice.

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: comple list slices

2006-02-28 Thread Fredrik Lundh
[EMAIL PROTECTED]:

> Len(rows) recalculates each time the while loop begins.  Now that I
> think of it, "rows != []" is faster than "len(rows) > 0."

the difference is very small, and "len(rows)" is faster than "rows != []"
(the latter creates a new list for each test).

and as usual, using the correct Python spelling ("rows") is a lot faster
(about three times in 2.4, according to timeit).





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


Re: Thread Question

2006-02-28 Thread Grant Edwards
On 2006-02-28, D <[EMAIL PROTECTED]> wrote:

> Thanks, Grant.  I apologize for not being clear on what I
> meant by using "classes".  This is an example of what I was
> referring to:
> http://www.wellho.net/solutions/python-python-threads-a-first-example.html

Ah, I see.  I had forgotten that people subclass Thread like
that.  It's mostly just a matter of style.  There aren't any
practical differences that I can think of.

-- 
Grant Edwards   grante Yow!  BARBARA STANWYCK
  at   makes me nervous!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comple list slices

2006-02-28 Thread Felipe Almeida Lessa
Em Ter, 2006-02-28 às 09:10 -0800, [EMAIL PROTECTED] escreveu:
> Although I don't know if this is faster or more efficient than your
> current solution, it does look cooler:
[snip]
> print [x for x in grouper]

This is not cool. Do

print list(grouper)

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Firebird and Python

2006-02-28 Thread haxier
All the info you need is in the kinterbasdb module. I've worked with it
under windows and Linux and... "it just works". Really well indeed. I'd
recommend it a lot.

http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_embedded_using_with

--
Asier.

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


Make staticmethod objects callable?

2006-02-28 Thread Nicolas Fleury
Hi everyone,
I was wondering if it would make sense to make staticmethod objects 
callable, so that the following code would work:

class A:
 @staticmethod
 def foo(): pass
 bar = foo()

I understand staticmethod objects don't need to implement __call__ for 
their other use cases, but would it still make sense to implement 
__call__ for that specific use case?  Would it be error-prone in any way?

Thx and regards,
Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thread Question

2006-02-28 Thread D
Thanks, Grant.  I apologize for not being clear on what I meant by
using "classes".  This is an example of what I was referring to:
http://www.wellho.net/solutions/python-python-threads-a-first-example.html

See the second (threaded) example.  

Doug

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


Re: Thread Question

2006-02-28 Thread Felipe Almeida Lessa
Em Ter, 2006-02-28 às 20:24 +, Grant Edwards escreveu:
> > I have seen examples that used classes, and other examples
> > that just called one thread start command - when should you
> > use one over another?
> 
> I'm not sure what you mean by "use classes" vs. "calling a
> thread start command".  My example above uses a class
> (threading.Thread) to create a thread object, and then calls
> its start method.

# He meant calling direct vs. subclassing. In your example you called
the Thread class directly, but you could have subclassed it.

# In your case, Edwards, I'd prefer subclassing because then you could
put some states in the class. A (bad) example:

class Foo(Thread):
def __init__(self):
Thread.__init__(self)
self.alive = False
self.running = True

def run(self):
while self.running:
self.alive = ping('myhost')
sleep(10)

def stop(self):
self.running = False

# Then you could:

a = Foo()
do_something()
print a.alive
do_something_more()
print a.alive
finish_everything()
print a.alive
a.stop()
# quit

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: comple list slices

2006-02-28 Thread johnzenger
You don't need to copy the list; but if you don't, your original list
will be emptied.

Len(rows) recalculates each time the while loop begins.  Now that I
think of it, "rows != []" is faster than "len(rows) > 0."

By the way, you can also do this using (gasp) a control index:

def grouprows(rows):
index = 0
while len(rows) > index:
rowspan = rows[index]["rowspan"]
yield rows[index:rowspan + index]
index += rowspan

...which kind of brings us back to where we started.

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


Re: Thread Question

2006-02-28 Thread Grant Edwards
On 2006-02-28, D <[EMAIL PROTECTED]> wrote:

> I have a client application that I want (behind the scenes) to check
> and make sure a remote host is up (i.e. by ping or TCP connect).  I'm
> assuming that, since I want this to go on "unknowingly" to the user,
> that I would put this in a thread.

Probably.

> My question is, how would I go about creating the thread?

Assuming foo is the function you want to start in a thread:

   threading.Thread(target=foo).start()

> I have seen examples that used classes, and other examples
> that just called one thread start command - when should you
> use one over another?

I'm not sure what you mean by "use classes" vs. "calling a
thread start command".  My example above uses a class
(threading.Thread) to create a thread object, and then calls
its start method.

-- 
Grant Edwards   grante Yow!  HELLO, little boys!
  at   Gimme a MINT TULIP!! Let's
   visi.comdo the BOSSA NOVA!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: escaping quotes

2006-02-28 Thread John Salerno
Fredrik Lundh wrote:

> because the interactive prompt echos the result back to you as
> a Python literal, where possible.  compare

Ah, of course! I forgot it wasn't 'print'ing it.

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


Re: Threading - will threads run in parallel?

2006-02-28 Thread Jarek Zgoda
SolaFide napisał(a):

> The problem is on Windows: when I run c:\python24\myprogram.py, it has
> a command window open up. If I close it, the program ends. So I want it
> to run without opening that window.

Give it .pyw extension or start using pythonw.exe instead of python.exe.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for Pythonic Examples

2006-02-28 Thread Ido Yehieli
This one is from our very own BDFL, behold- wget implemented in 7 lines
of python code:

import sys, urllib
def reporthook(*a): print a
for url in sys.argv[1:]:
 i = url.rfind('/')
 file = url[i+1:]
 print url, "->", file
 urllib.urlretrieve(url, file, reporthook)

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


Re: Threading - will threads run in parallel?

2006-02-28 Thread SolaFide
Thanks!

The problem is on Windows: when I run c:\python24\myprogram.py, it has
a command window open up. If I close it, the program ends. So I want it
to run without opening that window.

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


Re: Threading - will threads run in parallel?

2006-02-28 Thread Rene Pijlman
SolaFide:
>(get() is a function which waits for a ping on a specific port, thus
>stopping the program for a while.)
>
>Will these run together, 

Thread 2 can run while thread 1 is blocked for I/O and v.v.

>Also, is it possible to split off a program for the terminal that
>started it? As in I type in python test.py and test.py runs in the
>background and lets me do other things in that terminal?

Platform? Shell?

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading - will threads run in parallel?

2006-02-28 Thread Ido Yehieli
>> Also, is it possible to split off a program for the terminal that
>> started it? As in I type in python test.py and test.py runs in the
>> background and lets me do other things in that terminal?

try:
python test.py &

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


Thread Question

2006-02-28 Thread D
I have a client application that I want (behind the scenes) to check
and make sure a remote host is up (i.e. by ping or TCP connect).  I'm
assuming that, since I want this to go on "unknowingly" to the user,
that I would put this in a thread.  My question is, how would I go
about creating the thread?  I have seen examples that used classes, and
other examples that just called one thread start command - when should
you use one over another?  Thanks in advance.

Doug

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


Re: telnetlib problems

2006-02-28 Thread vercingetorix52
I just hit upon something that seems to work...

##
import telnetlib
from select import select

tn = telnetlib.Telnet('192.168.100.11')
sock = tn.get_socket()

tn.read_until('login: ', 5)
select([sock], [], [], 5)
tn.write('user\n')

tn.read_until('Password: ', 5)
select([sock], [], [], 5)
tn.write('password\n')

tn.read_until('bash-2.05$ ', 5)
tn.write('ls\n')
select([sock], [], [], 5)
print tn.read_very_eager()
##

If anyone sees any potential problems with this, I would appreciate it.
 TIA

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


Re: PEP 354: Enumerations in Python

2006-02-28 Thread Terry Reedy

"Stefan Rank" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> recent examples from this list:
>
> 2006-01-03: http://www.nabble.com/Re%3A-Regex-anomaly-p2179421.html
> 2006-02-20:
> http://www.nabble.com/Re%3A-Regular-expression-gone-mad-p3029028.html

If the re flags were implemented as instances of object instead of int,
then misuse of them as int args would be excepted.  I don't know if such a 
change would otherwise cause a problem.

I wonder whether a subclass of object (EnumSet?) that allowed for 
initialization with a better string representation and that disabled order 
comparisons would fill the bill for unordered enum.

As Steven Bethard also noted, there seem to be a need for two Enum 
subclasses:
EnumSet and EnumSeq.

Terry Jan Reedy



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


Threading - will threads run in parallel?

2006-02-28 Thread SolaFide
I have 2 threads that I want to run at the same time: for instance:

from threading import Thread

class test(Thread):
 def run(self):
  while True:
  get(asdf)

class test2(Thread):
   def run(self):
 while True:
  get(jkl)
ack=test()
jkl=test2()
ack.start()
jkl.start()

(get() is a function which waits for a ping on a specific port, thus
stopping the program for a while.)

Will these run together, or do I have to find some other way of running
in parallel?

Also, is it possible to split off a program for the terminal that
started it? As in I type in python test.py and test.py runs in the
background and lets me do other things in that terminal?

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


Re: sort one list using the values from another list

2006-02-28 Thread Ron Adam
[EMAIL PROTECTED] wrote:
> Following Ron Adam solution (and using [] instead of list() in the last
> line), this may be a possible solution of the problem, that is often
> quite fast:
> 
> def psort16(s1, s2):
> try:
> d = dict(izip(s2, s1))
> except TypeError:
> _indices = range(len(s1))
> _indices.sort(key=s2.__getitem__)
> s1[:] = map(s1.__getitem__, _indices)
> else:
> if len(d) == len(s1):
> s1[:] = [d[v] for v in sorted(d)]
> else:
> _indices = range(len(s1))
> _indices.sort(key=s2.__getitem__)
> s1[:] = map(s1.__getitem__, _indices)
> 
> Bye,
> bearophile

Looks good, but I think It would be simpler to just do.

def psort17(s1, s2):
 try:
 d = dict(izip(s2, s1))
 assert len(d) != len(s2)
 s1[:] = [d[v] for v in sorted(d)]
 except Exception:
 _indices = range(len(s1))
 _indices.sort(key=s2.__getitem__)
 s1[:] = map(s1.__getitem__, _indices)

We don't need to specify which exception.  Any problems will just get 
raised again on the second try it also fails.

Cheers,
Ron




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


telnetlib problems

2006-02-28 Thread vercingetorix52
I'm trying to use a python script to access an embedded computer
running linux and connected via a crossover ethernet cable using the
following script...

...and I realize the username and password is not realistic... I'm
still in "proof of concept" stage here :)

#
import telnetlib

tn = telnetlib.Telnet('192.168.100.11')

tn.read_until('login: ', 5)

tn.write('user\n')

tn.read_until('Password: ', 5)

tn.write('password\n')

tn.read_until('bash-2.05$ ', 5)

tn.write('ls\n')

print tn.read_very_eager()
#

As a script, this doesn't work.  However, if I execute the same
commands interactively, it works fine.  If I insert some time delays as
follows...

#
import telnetlib
import time

tn = telnetlib.Telnet('192.168.100.11')

tn.read_until('login: ', 5)
time.sleep(2)
tn.write('user\n')

tn.read_until('Password: ', 5)
time.sleep(2)
tn.write('password\n')

tn.read_until('bash-2.05$ ', 5)

tn.write('ls\n')
time.sleep(2)
print tn.read_very_eager()
#

...and it works fine.  Can anyone tell me what's going on here? TIA

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


Re: Numerical solver

2006-02-28 Thread Robert Kern
Laszlo Zsolt Nagy wrote:
>   Hello,
> 
> I would like to use a numerical solver for a specific problem. My 
> problem looks like this:
> 
>1. I have numeric constants, named A,B,C etc.
>2. I have numeric variables, named x,y,z etc.
>3. I have functions, like f1(x), f2(x), f3(x,y), f4(y) etc.
>4. I have constraints like f1(x) < A  f3(x,y) < B etc.
> 
> Fortunately, all of the variables can be limited to a closed finite 
> interval. (E.g.   0 <= x <= 100)
> There is a specific function, called P(x,y,z) that needs to be optimized 
> (need to find its maximum/minimum).

In [7]: scipy.optimize.fmin_cobyla?

Type:   function
Base Class: 
String Form:
Namespace:  Interactive
File:
/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/scipy-
0.4.7.1607-py2.4-macosx-10.4-ppc.egg/scipy/optimize/cobyla.py
Definition: scipy.optimize.fmin_cobyla(func, x0, cons, args=(),
consargs=None, rhobeg=1.0, rhoen
d=0.0001, iprint=1, maxfun=1000)
Docstring:
Minimize a function using the Contrained Optimization BY Linear
Approximation (COBYLA) method

Arguments:

func -- function to minimize. Called as func(x, *args)

x0   -- initial guess to minimum

cons -- a sequence of functions that all must be >=0 (a single function
if only 1 constraint)

args -- extra arguments to pass to function

consargs -- extra arguments to pass to constraints (default of None means
use same extra arguments as those passed to func).
Use () for no extra arguments.

rhobeg --  reasonable initial changes to the variables

rhoend --  final accuracy in the optimization (not precisely guaranteed)

iprint  -- controls the frequency of output: 0 (no output),1,2,3

maxfun  -- maximum number of function evaluations.


Returns:

x -- the minimum

-- 
Robert Kern
[EMAIL PROTECTED]

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

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


Re: escaping quotes

2006-02-28 Thread Fredrik Lundh
John Salerno wrote:

> I'm reading through the tutorial and found this in section 3:
>
>  >>> '"Isn\'t," she said.'
> '"Isn\'t," she said.'
>
> Why doesn't the escape sequence work in this case?

because the interactive prompt echos the result back to you as
a Python literal, where possible.  compare

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

with

>>> print '"Isn\'t," she said.'
"Isn't," she said.

(this is explained a little later in the chapter you're reading)





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


Re: Best python module for Oracle, but portable to other RDBMSes

2006-02-28 Thread Gerhard Häring
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[EMAIL PROTECTED] wrote:
> What would be the next best Oracle database module for Python next to
> cx_oracle? 

That would probably be DCOracle2.

> I'd like to compare two and choose one, just for the sake of
> seeing how two modules doing the same thing operate.
> 
> Also, does installing cx_oracle create registry entries or require
> admin privs on a Windows XP machine? I see that cx_oracle is
> distributed as an EXE.

It's most probably created using distutils and "python setup.py
bdist_wininst". These installers only use the registry to look up the
path Python where is installed. Of course it will need a correctly
working Oracle client to operate.

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

iD8DBQFEBJxBdIO4ozGCH14RAqXCAJ9Vq6L8SLvnhlBCDc4EzwloJYp28ACfVt8J
TNN+XgNxFLmQscu9wpPIK4M=
=txAA
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Numerical solver

2006-02-28 Thread Laszlo Zsolt Nagy

  Hello,

I would like to use a numerical solver for a specific problem. My 
problem looks like this:

   1. I have numeric constants, named A,B,C etc.
   2. I have numeric variables, named x,y,z etc.
   3. I have functions, like f1(x), f2(x), f3(x,y), f4(y) etc.
   4. I have constraints like f1(x) < A  f3(x,y) < B etc.

Fortunately, all of the variables can be limited to a closed finite 
interval. (E.g.   0 <= x <= 100)
There is a specific function, called P(x,y,z) that needs to be optimized 
(need to find its maximum/minimum).

I'm looking for a native Python solution: I would like to define the 
functions and the constraints in Python.
I have looked at the cheeseshop and found LogiLab's constraint:

http://www.logilab.org/projects/constraint/documentation

It is almost perfect for me, but it is working with finite sets.
I'm not sure about SciPy or NumPy. Do you have an idea about what is the 
package I need?
I'll gladly read any documentation or tutorial, just I do not know which 
one is the best to start with.

Thanks,

   Laszlo

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


  1   2   >