ANN: cElementTree 1.0.4 (december 13, 2005)

2005-12-16 Thread Fredrik Lundh
effbot.org proudly presents release 1.0.4 of the cElementTree library,
a fast and very efficient implementation of the ElementTree API, for
Python 2.1 and later.  On typical documents, it's 15-20 times faster
than the Python version of ElementTree, and uses 2-5 times less
memory.

cElementTree 1.0.4 is 1.0.2 plus 2.3.5/2.4.2 compatibility fixes for
copy/deepcopy (previously released as 1.0.3, as binaries only), new
pi and comment targets in XMLParser, plus the ability to link
against pyexpat instead of expat (this requires Python 2.5).

The library is available as C source code, and as Windows installers
for recent Python versions.  Get your copy here:

http://effbot.org/downloads#celementtree

The cElementTree module uses some support functions from the standard
ElementTree library, and will not work properly without it.  If you haven't
installed it already, you can get it from:

http://effbot.org/downloads#elementtree

enjoy /F
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Adding methods to instances

2005-12-16 Thread Antoon Pardon
Op 2005-12-15, Ed Leafe schreef [EMAIL PROTECTED]:
 On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:

  So? Am I nuts? Or is this possible?

 Yes it is, use exec() to turn your string in valid Python code
 and bind the dynamic function as a method of class Test

 xx = def dynamic(self):
 print dynamic, self.testAtt
 

 exec xx

 class Test(object):
  testAtt = sample
  def normalMethod(self):
  print normal, self.testAtt

 t = Test()
 Test.dynamic = dynamic
 t.dynamic()

  Thanks! I knew I had done this before. My mistake was that I was  
 setting the exec'd code to the instance, and not to the class. That  
 works, but makes it a function, which doesn't automatically get sent  
 the 'self' reference.

But this will make the function a method to all instances of the class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.

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


Re: special operator =+

2005-12-16 Thread Steve Holden
Peter Hansen wrote:
 [EMAIL PROTECTED] wrote:
 
kenny NguyenDoes anyone know the operator =+?

It isn't an operator, it's equivalent to = (assignment) only.
 
 
 Though actually it would try to call the __pos__ method on the object 
 prior to binding it to the name on the left side.  (Much as - would call 
 the __neg__ method if it existed.)  :-)
 
Technically one shouldn't really say it, since the sequence can only 
occur in an assignment or a keyword argument specification, and in all 
cases it's actually two symbols, an = followed by a unary + operator.

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: python24.dll and encodings ?

2005-12-16 Thread Thomas Heller
Bugs [EMAIL PROTECTED] writes:

 Thomas Heller wrote:
 [snip]
 A PEP discussing the rationales would *really* be great.

 My whole impetus for this thread was to minimize the size of Python
 executables created with py2exe.  Right now they tend to be rather
 large, even for very small applications, as they include a bunch of
 unutilized Python functionality and/or encodings.

That was what I guessed.

 It would be nice to see a Python environment structure that is more
 desktop-application-friendly for applications that distribute the
 Python environment WITH the application (i.e. using py2exe).  Ideally,
 it would be nice to be able to distribute as minimal amount of the
 Python runtime environment as possible.

Before py2exe had the single-file option, the most common 'complaint'
was the large number of files it generated.  Now, the 'complaint' is
about the size of the executable.  (Historically, the change in
Python2.4 was done by Martin on my request, that was before the
single-file option in py2exe.  Plus, Python2.4 contains much more
encodings than 2.3 had.)

The PEP would probably have to find a balance between the number of
files and the size of a 'typical' py2exe built application.  Personally,
I don't care too much on either the file number and the files sizes
since I use inno setup for distributing the applications.

Technically, as far as py2exe is concerned, it would be nice if the zlib
module was a builtin module because it would be easier to bootstrap the
executable - for obvious reasons the zlib module cannot be loaded from a
(compressed) zipfile.  Unfortunately, this collides with Martin's
current policy to exclude extensions that need third party source code
from the python dll.

To summarize: Before someone requests a change to the builtin modules
list, a PEP would be needed to find the right balance.

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


Re: problem with os.spawnle(os.P_NOWAIT,'C:\info.exe')

2005-12-16 Thread Fredrik Lundh
[EMAIL PROTECTED] write;

 i tried running a exe file info.exe from the spawnle cmd, its running
 fine from the interactive mode, but when i try to run the same info.exe
 file from a python file, its giving me the following error:

 ##
 Traceback (most recent call last):
   File C:\Documents and Settings\shivayogimath_dc\Desktop\network.py,
 line 56,
  in ?

  os.spawnle(os.P_NOWAIT,'C:\info.exe')

   File C:\Python23\Lib\site-packages\wmi.py, line 263, in __getattr__
 raise AttributeError, attribute
 AttributeError: spawnle
 

 Could u please help in removing this error.

if os.spawnle gives you an attribute error in a module that's installed under
site-packages, it's likely that you've overwritten the name os in your code.

as an emergeny fix, add import os to the line just before os.spawnle.

(if you're lucky, this will break the code that overwrote the os name, so
you can fix that...)

/F



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


Re: IsString

2005-12-16 Thread Steve Holden
Steven D'Aprano wrote:
 On Thu, 15 Dec 2005 08:22:37 +, Steve Holden wrote:
 
 
Hear, hear. However you describe it Python is what it is, and this 
interminable discussion about its similarities with and differences from 
various concepts (most lately call by name/call by value) doesn't much 
aid understanding for the majority.

The important question is not what's that Python concept called in 
other languages but do you understand how Python works.
 
 
 Would you have a problem with me describing Python as an untyped
 high-level assembly-language, and then working around the lack of JMP
 using try...exempt?
 
 Of course, I understand that it is no skin off your nose whether I write
 bad code or not, but you might get mighty frustrated with my constant
 questions on the news group How do I write this piece of assembly code in
 Python?.
 
 
I was merely trying to imply that this particular piece of 
interpreter-navel-gazing has gone on way too long to sustain most 
readers' interest.

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: Tuples

2005-12-16 Thread Michael . Coll-Barth

Well, it works for me and x is a list, not a tuple.  Or am I reading too
much into your subject line?

-Original Message-
From:
[EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
n.org]On Behalf Of Tuvas
Sent: Thursday, December 15, 2005 12:20 PM
To: python-list@python.org
Subject: Tuples


Let's say I make a program something like follows:

x=[]
x.append([1,2,3])
x.append([4,5,6])
print x
print x[0]
print x[0][1]
x[0][1]=5

Okay, everything works here as expected except the last line. Why won't
this work? Thanks for the help!


The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure.  If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof.  Thank you.

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


Re: The difference between import package.module and from package import module(about pymol)

2005-12-16 Thread Ben Finney
Xiao Jianfeng [EMAIL PROTECTED] writes:
 In pymol I can use from chempy import Atom but import chempy.Atom
 doesn't work.
 It says,ImportError: No module named Atom. What is going wrong ?

I would trust the error message first, and check your assumption.

Is 'chempy' actually a package, containing an 'Atom' module? Or is
'chempy' actually a module, containing an 'Atom' attribute?

-- 
 \I washed a sock. Then I put it in the dryer. When I took it |
  `\  out, it was gone.  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ActivePython and Amara

2005-12-16 Thread James
Where I go to work, a quote stands etched in a very large font into the
concrete prominently to remind us to be humble.

The greatest obstacle to discovery is not ignorance - it is the
illusion of knowledge.
(Daniel J. Boorstin)

You just have to trust us on this. We are not jumping to conclusions
based on one or two silly posts. It was evident in almost *every* post
you posted so far. *You really are a newbie* and there is nothing wrong
with that. We all have been there. But you must stop being defensive
about it. You just need to be patient and read all the docs before
trying to do what you are trying to do now.

Here is a link to keep you busy.
http://www.awaretek.com/tutorials.html

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


Re: How can I load python script into Html ??

2005-12-16 Thread Tim Roberts
Steve M [EMAIL PROTECTED] wrote:

Man, I don't even know where to start. There is no way this will work
if you don't have a web browser that can interpret Python. I don't know
of one, and I don't think anybody wants one because using a browser
that would execute arbitrary Python code provided by the server would
be an obscene security mistake.

Internet Explorer will happily do so, if you have the Python Windows
extensions installed, and register the active scripting component that cmes
with it.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getsockopt

2005-12-16 Thread Steve Holden
Fabian Deutsch wrote:
 Hello,
 
 my name is fabian and i'm a student from northern germany. right now i
 try to create som kind of decapsulation of esp-udp packets using python.
 
 therefor i need to use the socket.getsockopt (SOL_IP, IP_OPTIONS, 20)
 method. But al i get is some empty value. Nothin.
 
 Does someone know or have an working exmaple of how to use this method??
 
 The lines:
 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)
 s.bind(('',4500))
 while 1:# Run until cancelled
   message, client = s.recvfrom(1400) # =256 byte datagram
 hdr = s.getsockopt (SOL_IP, IP_OPTIONS, 20)
 print Client connected:, client
 print HDR: + binascii.hexlify(hdr)
 
Perhaps you're getting an empty string back because no IP options are 
set in the received packets' headers?

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: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Ben Finney schreef [EMAIL PROTECTED]:
 [quoting private email with permission]

 Antoon Pardon wrote:
 I just downloaded your enum module for python [from the Cheeseshop]
 and played a bit with it. IMO some of the behaviour makes it less
 usefull.

 Feedback is appreciated. I'm hoping to provide a one obvious way to
 do enumerations in Python.

  from enum import Enum
  day = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
  col = Enum('red', 'green', 'blue')
  day.wed == col.blue
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File enum.py, line 100, in __cmp__
 raise EnumValueCompareError(self, other)
 enum.EnumValueCompareError: Not values from the same enumeration:
 (EnumValue(enum.Enum object at 0x4020c30c, 2, 'wed'),
 EnumValue(enum.Enum object at 0x4021a14c, 2, 'blue'))
  type(day.mon) == type(col.red)
 True
  type(day.mon) is type(col.red)
 True
  lst= [day.mon, col.red]
  day.fri in lst

 As can be seen from the above, you raise an exception when one wants
 to compare Enums from different enumarations, but it seems a bit
 strange that different enumerations belong to the same type.

 This does seem a point that could be confusing. Would it be better if
 every Enum instance had its own unique subclass of EnumValue, that was
 used to instantiate values for that enumeration?

If you decide on keeping the current behaviour when comparing
values of different enumerations, I would definitely answer
yes.

 I also think it would be more usefull if enums from different
 enumerations just tested unequal.

 My rationale for this is: The only purpose of an enumeration is to
 have a set of arbitrary unique values within that enumeration. The
 values make no sense in the context of a different enumeration, so I
 see three different comparison results:

  Weekday.mon == Weekday.mon
 True
  Weekday.fri == Weekday.mon
 False
  Colour.blue == Weekday.mon
 [...]
 enum.EnumValueCompareError: Not values from the same enumeration

 However, I'm aware that this is not how other Python types behave:

  23 == 23
 True
  42 == 23
 False
  spam == 23
 False

 Is there a semantic difference between these cases? Is that difference
 enough to want different behaviour?

 Is there some behaviour other than evaluate to False or raise an
 exception, that could indicate not comparable?

This is a difficult question, because AFAIU python doesn't have clear
guidelines for this. I also have the impression that comparisons are
used for two different reasons.

The first is compare things in a mathematical kind of way in which
how things are compared is important.

The second is more an ordering mechanisme. Whether a string is greater
than an int or vice versa, is not imporant what is important is that
this order is consistent and can be used in binary searches, trees
and other structures to organise data.

Now python has only one collection of compare operators which can
cause conflicts. For instance, one could impose an order on sets
to use for such structure but that goes against the normal order
on sets which is based on subsets.

The only advise I have here is look at PEP 3000 that states:

Comparisons other than == and != between disparate types will raise
an exception unless explicitly supported by the type.

Which seem to imply that == and != should not raise an exception
but , =, , = should.

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Ben Finney
Mike Meyer [EMAIL PROTECTED] writes:
 Peter Hansen [EMAIL PROTECTED] writes:
 That is, [perhaps] trying to compare enumerations that should not
 be compared *is* an error (raising an exception) *because* the
 whole point of enumerations is to avoid errors in such cases.

 Except it might not be an error. For instance, if I've got a list of
 enum objects taken from various types (say I've got one set of enums
 for days of the week, another for months of the year, and so on, and
 which I use depends on whether the user wants to select days of the
 week, months of the year, etc), it makes perfect sense to want to know
 if a specific enum value is in the list, and the obvious way to check
 it is with my_value in enum_list. That won't work if you raise an
 exception - it takes a relatively convoluted bit of code to make this
 test.

The 'enum' package in Cheeseshop doesn't do that. Enumerations are
sequences (of unique arbitrary values), that can be iterated and tested
for membership.

What's being discussed here is what happens when comparing the *values*
from the enumeration.

 Python generally uses '==' to mean is the same value.  To do that,
 a simple true/false return is enough. In raising an exception,
 you're making '==' carry an extra meaning (I'm not sure *what* that
 is, though).

The problem with is the same value as an explanation for '==' is
that it doesn't help in cases such as::

 ShirtSize = Enum('small', 'medium', 'large')
 AppleSize = Enum('small', 'large')

What should be the result of this comparison::

 ShirtSize.small == AppleSize.small

Are they the same value? They're both small (and they both coerce
to the same string value, and in this case the same integer value).

If not, is 'False' the right way to indicate that?

Or is it an error to even try comparing them?

 Do any python builtins behave that way? How about anything in the
 python standard library?

No to both; I believe this may be a defining property of
enumerations. Am I wrong?

-- 
 \   Man cannot be uplifted; he must be seduced into virtue.  -- |
  `\   Donald Robert Perry Marquis |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split string saving screened spaces

2005-12-16 Thread Giovanni Bajo
Sergey wrote:

 Which module to use to do such thing:

 -a -b -c '1 2 3' - [-a, -b, -c, '1 2 3']


 import shlex
 shlex.split(-a -b -c '1 2 3')
['-a', '-b', '-c', '1 2 3']

-- 
Giovanni Bajo


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


Re: split string saving screened spaces

2005-12-16 Thread bonono

Sergey wrote:
 Which module to use to do such thing:

 -a -b -c '1 2 3' - [-a, -b, -c, '1 2 3']

 (i have string, need to pass it to getopt)
seems like CSV except that the seperator is space. You may check to see
if the CSV module can take space as delimiter.

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


Python and curses

2005-12-16 Thread linuxfreak
Was wanting to write a text based application in python seems
curses module is the way to go... anyone knows of any good tutorials
apart from the one written by esr

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


Python IDE

2005-12-16 Thread linuxfreak
Which is a better python IDE SPE or WingIDE in terms of features

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


Re: getsockopt

2005-12-16 Thread Fabian Deutsch
 --- Ursprüngliche Nachricht ---
 Von: Steve Holden [EMAIL PROTECTED]
 An: python-list@python.org
 Betreff: Re: getsockopt
 Datum: Fri, 16 Dec 2005 08:29:08 +
 
 Fabian Deutsch wrote:
  Hello,
  
  my name is fabian and i'm a student from northern germany. right now i
  try to create som kind of decapsulation of esp-udp packets using python.
  
  therefor i need to use the socket.getsockopt (SOL_IP, IP_OPTIONS, 20)
  method. But al i get is some empty value. Nothin.
  
  Does someone know or have an working exmaple of how to use this method??
  
  The lines:
  s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)
  s.bind(('',4500))
  while 1:# Run until cancelled
  message, client = s.recvfrom(1400) # =256 byte datagram
  hdr = s.getsockopt (SOL_IP, IP_OPTIONS, 20)
  print Client connected:, client
  print HDR: + binascii.hexlify(hdr)
  
 Perhaps you're getting an empty string back because no IP options are 
 set in the received packets' headers?
 
Hey,
you are right - i just re-read the ip (7) man - i only get the ip options ..

but do you know a way of getting the whole header?

'cause what i'm trying to do is, to remove the udp-header of the packet i
recieved and sendind a new packet without the udp-header.
I want to do this by taking it's payload (incl. esp-hdr) and ip-header and
resending it to my system creating a new packet with the old ip-header and
payload (incl. esp-hdr) i got from the recvd packet.

Before:
++-+--+--- - - 
| IP HDR | UDP HDR |  ESP HDR | PAYLOAD ...
++-+--+--- - - 
After :
++-+--- - - 
| IP HDR | ESP HDR | PAYLOAD ...
++-+--- - - 

regards
fabian

-- 
Fabian Deutsch [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie to python

2005-12-16 Thread Johhny
Hello,

Here is the script then the problem.

cat testing.py

import crypt
import random, string
def getsalt(chars = string.letters + string.digits):
 return random.choice(chars) + random.choice(chars)
username = raw_input('password : ')
print crypt.crypt(username,getsalt())


python testing.py
password : testing
Traceback (most recent call last):
  File testing.py, line 1, in ?
import crypt
  File /home/testing/scripts/crypt.py, line 4, in ?
TypeError: 'module' object is not callable

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


Re: newbie to python

2005-12-16 Thread Peter Otten
Johhny wrote:

 Here is the script then the problem.
 
 cat testing.py
 
 import crypt
 import random, string
 def getsalt(chars = string.letters + string.digits):
  return random.choice(chars) + random.choice(chars)
 username = raw_input('password : ')
 print crypt.crypt(username,getsalt())
 
 
 python testing.py
 password : testing
 Traceback (most recent call last):
   File testing.py, line 1, in ?
 import crypt
   File /home/testing/scripts/crypt.py, line 4, in ?

Read carefully. You have a file /home/testing/scripts/crypt.py which is
imported instead of the crypt module in Python's standard library.
Rename /home/testing/scripts/crypt.py to something else, delete
/home/testing/scripts/crypt.pyc, and all should be well.

Peter


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


Re: getsockopt

2005-12-16 Thread Steve Holden
Fabian Deutsch wrote:
--- Ursprüngliche Nachricht ---
Von: Steve Holden [EMAIL PROTECTED]
An: python-list@python.org
Betreff: Re: getsockopt
Datum: Fri, 16 Dec 2005 08:29:08 +

Fabian Deutsch wrote:

Hello,

my name is fabian and i'm a student from northern germany. right now i
try to create som kind of decapsulation of esp-udp packets using python.

therefor i need to use the socket.getsockopt (SOL_IP, IP_OPTIONS, 20)
method. But al i get is some empty value. Nothin.

Does someone know or have an working exmaple of how to use this method??

The lines:
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)
s.bind(('',4500))
while 1:# Run until cancelled
 message, client = s.recvfrom(1400) # =256 byte datagram
hdr = s.getsockopt (SOL_IP, IP_OPTIONS, 20)
print Client connected:, client
print HDR: + binascii.hexlify(hdr)


Perhaps you're getting an empty string back because no IP options are 
set in the received packets' headers?

 
 Hey,
 you are right - i just re-read the ip (7) man - i only get the ip options ..
 
 but do you know a way of getting the whole header?
 
 'cause what i'm trying to do is, to remove the udp-header of the packet i
 recieved and sendind a new packet without the udp-header.
 I want to do this by taking it's payload (incl. esp-hdr) and ip-header and
 resending it to my system creating a new packet with the old ip-header and
 payload (incl. esp-hdr) i got from the recvd packet.
 
 Before:
 ++-+--+--- - - 
 | IP HDR | UDP HDR |  ESP HDR | PAYLOAD ...
 ++-+--+--- - - 
 After :
 ++-+--- - - 
 | IP HDR | ESP HDR | PAYLOAD ...
 ++-+--- - - 
 
I'm not sure where ESP is going to come into this, or how the traffic 
you will be receiving will be generated. I suspect you may need to 
reconsider your application design a little.

The only way to get hold of the IP headers is to use SOCK_RAW, which 
delivers everything that comes in from the packet driver.

What is it you're actually trying to do? If you perform the 
transformation you outline in the diagrams above then the IP header will 
certainly contain the wrong protocol value for a start.

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: 0 in [True,False] returns True

2005-12-16 Thread Antoon Pardon
Op 2005-12-15, Grant Edwards schreef [EMAIL PROTECTED]:
 On 2005-12-15, Antoon Pardon [EMAIL PROTECTED] wrote:

 Well, in my case, a given name (or return value) is always
 bound to a floating point object. I don't test the type of the
 object and treat it in two different ways depending on what
 type it is.  It's just a float.

 Do you find that difference so important?

 Possibly.  In my case, a float is always a float.  You can
 always do the same set of operations on it.

 As far as I understand
 the gtk identifiers are always positive integers. So I could
 have coded as follows:

   UnConnected = (-1, -2)
   Registered, UnRegistered = UnConnected

 In your case, there isn't a single set of operations that work
 regardles of the value.  You have to _check_ the value in order
 to decide what operations are allowed on that value.  I'm not
 saying the latter is evil but I think the distinction is
 important.

   ...

   if self.cb_src in UnConnected:

 Now all values are integers and I no longer treat an object different
 depending on type but on value. However conceptually nothing changed.
 My code branches depending on set membership of this attribute.

 Could you explain why it should make a (big) difference between
 these two approaches?

 Your examples are still both very different from the NaN
 example.  A NaN is a floating point operation that supports all
 the same operations as all other floating point operations.  In
 your example an integer object of -2 does not support the same
 operations that a real GTK identifier does.  They are two
 different types.

I think the disctinction you are making is based on which level
you look at things. For you floats are something you use, you
see NaN as just a floats because the details of implementation
have been abstracted out for you.

But look at it from the level of someone who has to implement
floating point numbers. He can't just take two floats and put
them into his general add_float algorithm. If he did that
the result of working with a NaN could result in a regular
number. So he has to test for special values like NaN is
his 'code' too.

Of course we tend to forget this because in this case the
abstraction is usually done at the hardware level. But
I don't think that is such an important disctinction here.

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


Re: CherryPy wiki not working

2005-12-16 Thread bill
Yes, it looks like some type of virus has affected my computer.

CherryPy was fine from home using my IMac.

But at work from both Firefox and IE I get this problem and now it has
affected another site.

The URLs at CherryPy look like this :

http://www.cherrypy.org/store/0_1_540744_1_1_index.html

Still, not a Python problem.

Bill

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


Re: getsockopt

2005-12-16 Thread Fabian Deutsch
Stave Holde wrote:
 Fabian Deutsch wrote:
 --- Ursprüngliche Nachricht ---
 Von: Steve Holden [EMAIL PROTECTED]
 An: python-list@python.org
 Betreff: Re: getsockopt
 Datum: Fri, 16 Dec 2005 08:29:08 +
 
 Fabian Deutsch wrote:
 
 Hello,
 
 my name is fabian and i'm a student from northern germany. right now i
 try to create som kind of decapsulation of esp-udp packets using
 python.
 
 therefor i need to use the socket.getsockopt (SOL_IP, IP_OPTIONS, 20)
 method. But al i get is some empty value. Nothin.
 
 Does someone know or have an working exmaple of how to use this
 method??
 
 The lines:
 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)
 s.bind(('',4500))
 while 1:# Run until cancelled
message, client = s.recvfrom(1400) # =256 byte datagram
 hdr = s.getsockopt (SOL_IP, IP_OPTIONS, 20)
 print Client connected:, client
 print HDR: + binascii.hexlify(hdr)
 
 
 Perhaps you're getting an empty string back because no IP options are 
 set in the received packets' headers?
 
  
  Hey,
  you are right - i just re-read the ip (7) man - i only get the ip
 options ..
  
  but do you know a way of getting the whole header?
  
  'cause what i'm trying to do is, to remove the udp-header of the
 packet i
  recieved and sendind a new packet without the udp-header.
  I want to do this by taking it's payload (incl. esp-hdr) and ip-header
 and
  resending it to my system creating a new packet with the old ip-header
 and
  payload (incl. esp-hdr) i got from the recvd packet.
  
  Before:
  ++-+--+--- - - 
  | IP HDR | UDP HDR |  ESP HDR | PAYLOAD ...
  ++-+--+--- - - 
  After :
  ++-+--- - - 
  | IP HDR | ESP HDR | PAYLOAD ...
  ++-+--- - - 
  
 I'm not sure where ESP is going to come into this, or how the traffic 
 you will be receiving will be generated. I suspect you may need to 
 reconsider your application design a little.
 
 The only way to get hold of the IP headers is to use SOCK_RAW, which 
 delivers everything that comes in from the packet driver.
 
 What is it you're actually trying to do? If you perform the 
 transformation you outline in the diagrams above then the IP header will 
 certainly contain the wrong protocol value for a start.
 
Well actually I managed to recieve the encapsulated esp packages,
decapsulate them and send them to my system using 

   sr = socket(AF_INET, SOCK_RAW, IPPROTO_ESP)
   ...
   sr.sendto(message (MY_IP,0))

it does work and my system correctly deciphers the packages (i get an icmo
oing request and my system answers with icmp reply) but the problem is, that
the src_adr of the esp_package is set to my local adr and not the adr of the
original esp-udp_packet sender ... so i try to  use
  sr.send 
to send the message, but then i will have to create the whole header ... but
i dont't want to create it but copy it from the recived packet to the new
one ..

i hope you understand what i am trying to say ..

fabian

-- 
Fabian Deutsch [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Ben Finney schreef [EMAIL PROTECTED]:
 Mike Meyer [EMAIL PROTECTED] writes:
 Peter Hansen [EMAIL PROTECTED] writes:
 That is, [perhaps] trying to compare enumerations that should not
 be compared *is* an error (raising an exception) *because* the
 whole point of enumerations is to avoid errors in such cases.

 Except it might not be an error. For instance, if I've got a list of
 enum objects taken from various types (say I've got one set of enums
 for days of the week, another for months of the year, and so on, and
 which I use depends on whether the user wants to select days of the
 week, months of the year, etc), it makes perfect sense to want to know
 if a specific enum value is in the list, and the obvious way to check
 it is with my_value in enum_list. That won't work if you raise an
 exception - it takes a relatively convoluted bit of code to make this
 test.

 The 'enum' package in Cheeseshop doesn't do that. Enumerations are
 sequences (of unique arbitrary values), that can be iterated and tested
 for membership.

Sure but we do have this:

 from enum import Enum
 day = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
 col = Enum('red', 'green', 'blue')
 lst= [day.mon, col.red]
 col.blue in lst
Traceback (most recent call last):
  File stdin, line 1, in ?
  File enum.py, line 100, in __cmp__
raise EnumValueCompareError(self, other)
enum.EnumValueCompareError: Not values from the same enumeration:
(EnumValue(enum.Enum object at 0x402181ac, 2, 'blue'),
EnumValue(enum.Enum object at 0x4020c36c, 0, 'mon'))

 What's being discussed here is what happens when comparing the *values*
 from the enumeration.

 Python generally uses '==' to mean is the same value.  To do that,
 a simple true/false return is enough. In raising an exception,
 you're making '==' carry an extra meaning (I'm not sure *what* that
 is, though).

 The problem with is the same value as an explanation for '==' is
 that it doesn't help in cases such as::

  ShirtSize = Enum('small', 'medium', 'large')
  AppleSize = Enum('small', 'large')

 What should be the result of this comparison::

  ShirtSize.small == AppleSize.small

 Are they the same value? They're both small (and they both coerce
 to the same string value, and in this case the same integer value).

 If not, is 'False' the right way to indicate that?

I would agree 'False' is the right answer here.

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


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-16 Thread bruno at modulix
Adrian Holovaty wrote:
 bruno at modulix wrote:
 
RoR is not an IDE, it's a web framework. The closest things in Python
are TurboGears (good Ajax/js support via Mochikit), Subway (never
tested), and Django (no Ajax support AFAIK).
 
 
 Note that no Ajax support is misleading. Of course you can use Ajax
 with Django, just as you can use it with *any* Web framework. That's
 because Ajax is a browser-side technology (JavaScript), not a
 server-side technology (Python). Django is just as capable of producing
 JavaScript as it is of producing (X)HTML or whatever else.
 
 Hope that clears things up!

Adrian, what you describe here is *exactly* what I call no Ajax
support: you have to handle the whole thing manually, the framework
doesn't provide anything by itself. Would you say the CGI module offers
support for templating, data persistance and Ajax as well ?-)

And BTW, Ajax is not a client-side techno, it's a combination of client
*and* server-side technos. TurboGears support Ajax (well, a variant of,
since it's based on JSON, not XML) by having a pretty good, JSON aware
javascript lib (mochikit) for the client side *and* an OOTB JSON
serialization on the server side.

Hope that clears things up !-)

(PS : please, let's not start a Django-vs-TurboGears war, the
Ruby-Python pissing context is enough of a PITA)

-- 
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


thread and alarm

2005-12-16 Thread Sergey
How to send alarm to a thread?
I can set alarm in main thread, but how then send exception to another thread 
to wake it if it executes too long?


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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Ben Sizer
Ben Finney wrote:
 The problem with is the same value as an explanation for '==' is
 that it doesn't help in cases such as::

  ShirtSize = Enum('small', 'medium', 'large')
  AppleSize = Enum('small', 'large')

 What should be the result of this comparison::

  ShirtSize.small == AppleSize.small

 Are they the same value? They're both small (and they both coerce
 to the same string value, and in this case the same integer value).

Is it possible to make it have the following sort of behaviour? :

 ShirtSize.small == AppleSize.small
True
 ShirtSize.small is AppleSize.small
False

It works for comparing a boolean (True) vs. an integer (1), so it has
some sort of precedent. (Especially if you make the tenuous assumption
that True,False are language-supported 'enums' for 0 and 1.)

-- 
Ben Sizer

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


text manipulation

2005-12-16 Thread Johhny
Hello,

I am trying to write a script in python (to replace a perl script with
limited functionality). Now I have some issues. Currently I am using
the perl to load the file then regex parse certain lines to remove
characters (uncomment lines and change variables). I would like to take
that into the python script. I have had a look at the module string
and I dont think its what Im looking for.

Here is an example of some text I would like to manipulate

#comment here
#user_defined_variable = no
#

I would like to make that

#comment here
user_defined_variable = yes
#

With perl/sed Its very easy, However Im having issues to do it in
python. Any advice would be great.

Regards,

Johhny.

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Ben Sizer schreef [EMAIL PROTECTED]:
 Ben Finney wrote:
 The problem with is the same value as an explanation for '==' is
 that it doesn't help in cases such as::

  ShirtSize = Enum('small', 'medium', 'large')
  AppleSize = Enum('small', 'large')

 What should be the result of this comparison::

  ShirtSize.small == AppleSize.small

 Are they the same value? They're both small (and they both coerce
 to the same string value, and in this case the same integer value).

 Is it possible to make it have the following sort of behaviour? :

 ShirtSize.small == AppleSize.small
 True
 ShirtSize.small is AppleSize.small
 False

 It works for comparing a boolean (True) vs. an integer (1), so it has
 some sort of precedent. (Especially if you make the tenuous assumption
 that True,False are language-supported 'enums' for 0 and 1.)

I'm against it. I don't like the following returning True:

  ShirtSize.small in [ShirtSize.Medium, AppleSize.small]


I also think it may cause problems with other comparisons.

Supose the following:

  col = Enum('red', 'green', 'blue')
  paint = Enum('violet' , 'blue', 'red')

Then we get the following situation: 

  col.red == paint.red and col.blue == paint.blue

but

  col.red  col.blue and paint.blue  paint.red

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


Re: text manipulation

2005-12-16 Thread Isaac T Alston
Johhny wrote:

 Any advice would be great.


Have you had a look at Python's re module? If you've not, I suggest you do
so - it contains all of Python's regex tools which you'll need. 

Regards,

-- 
Isaac

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


Re: Clearing the Tkinter Window

2005-12-16 Thread Martin Franklin
James Stroud wrote:
 Dustan wrote:
 
I'm a newbie here, especially with Tkinter.  I'm writing a program that
has 3 phases, if you will, in which I would have to clear the window
and insert new widgets. Is this possible, and if so, how?  I'm writing
my application class based on Frame, if that helps at all.

 
 
 Its not obvious what you are asking.
 
 But, if you populate a Frame with widgets, then you can destroy those 
 widgets if you destroy the Frame:
 
 tk = Tk()
 f = Frame(tk)
 
 # fill frame with 10 buttons
 for i in xrange(10):
Button(f, text=str(i)).pack()
 
 # kill the frame and buttons
 f.destroy()   # references to buttons gone too, so they are GC'd
 
 # make a new frame and put it in tk
 f = Frame(tk)
 
 # etc.
 
 You will want to make sure any name assignments are re-assigned, del'd, 
 or go out of scope after you destroy frame, or the button objects won't 
 be garbage collected, even though they are destroyed when the frame is 
 destroyed.
 
 James


destroy is one way to do it... but if you need to access the destroyed
widgets information after they have gone it may cause problems.. another
method to look at is (are) the *_forget methods (pack_forget /
grid_forget) these do not destroy the widgets but rather remove them
from view.  If for example you are writing a 'wizard' type GUI and want
to show the user the 'Next' page simply forget the current page and pack
the next one in it's place.

Another way is to grid each 'page' over the top of each other and simply
change the 'raise' order (with tkraise method) not 100% sure if this
works though, i've not used it directly myself...


Cheers
Martin

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


Re: Robotics and parallel ports

2005-12-16 Thread Isaac T Alston
Thanks for everyone's tips and hints. I WILL MAKE THIS WORK! I think I'll
take your advice and use the serial port instead of the parallel port - I
won't have that much data to send (in comparison with, for example,
industrial level applications). As for on-board chips though, does this
require low level programming!? Or can I have an embedded python
interpreter for the chip? 

Many thanks.

Regards,

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


Re: tkinter: drop-down widget

2005-12-16 Thread Alex Hunsley
James Stroud wrote:
 Alex Hunsley wrote:
 
 Can anyone recommend some code for creating drop-down menus in tkinter?
 To be absolutely clear, here's an example of a drop-down:

 http://www.google.co.uk/preferences?hl=en
 (see the language selection widget)

 I've found the odd bit of code here and there, such as:
 http://infohost.nmt.edu/tcc/cgi/pre.cgi?file=/u/www/docs/tcc/help/lang/python/mapping/dropdown.py
  


 alex
 
 
 Try:
 
 1. Tkinter OptionMenu:
 http://effbot.org/tkinterbook/optionmenu.htm
 
 2. Pmw OptionMenu:
 http://pmw.sourceforge.net/doc/OptionMenu.html
 
 I would opt for these before a roll-your-own version.

Thanks for those! :)
alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and curses

2005-12-16 Thread Eddie Corns
linuxfreak [EMAIL PROTECTED] writes:

Was wanting to write a text based application in python seems
curses module is the way to go... anyone knows of any good tutorials
apart from the one written by esr

There is at least 1 higher level library atop curses.
http://excess.org/urwid/  I've only played with it a little bit but it looks
useful.

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


Re: Python and curses

2005-12-16 Thread Isaac T Alston
linuxfreak wrote:

 Was wanting to write a text based application in python seems
 curses module is the way to go... anyone knows of any good tutorials
 apart from the one written by esr

Not off the top of my head, no. However, you will find that the functions
needed will be very similar to the C functions used. I did this with PHP a
while back and (because there are a lack of tutorials for PHP too) I had to
resort to the man pages for it. So I'd suggest reading that tutorial (by
esr or whoever) and then just reading the man pages for C for more
documentation.

Regards,

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


Re: text manipulation

2005-12-16 Thread Martin Franklin
Johhny wrote:
 Hello,
 
 I am trying to write a script in python (to replace a perl script with
 limited functionality). Now I have some issues. Currently I am using
 the perl to load the file then regex parse certain lines to remove
 characters (uncomment lines and change variables). I would like to take
 that into the python script. I have had a look at the module string
 and I dont think its what Im looking for.
 
 Here is an example of some text I would like to manipulate
 
 #comment here
 #user_defined_variable = no
 #
 
 I would like to make that
 
 #comment here
 user_defined_variable = yes
 #
 
 With perl/sed Its very easy, However Im having issues to do it in
 python. Any advice would be great.
 
 Regards,
 
 Johhny.
 


forget regular expressions for this job... strings have methods in
python so for example:


for line in file:
 if line.startswith(#user_defined_variable = no):
 line.replace(#user_defined_variable = no,
 user_defined_variable = yes)

... continue processing file / writing out stuff as you go


Cheers
Martin

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


Re: tkinter: drop-down widget

2005-12-16 Thread Martin Franklin
James Stroud wrote:
 Alex Hunsley wrote:
 
Can anyone recommend some code for creating drop-down menus in tkinter?
To be absolutely clear, here's an example of a drop-down:

http://www.google.co.uk/preferences?hl=en
(see the language selection widget)

I've found the odd bit of code here and there, such as:
http://infohost.nmt.edu/tcc/cgi/pre.cgi?file=/u/www/docs/tcc/help/lang/python/mapping/dropdown.py
 


alex
 
 
 Try:
 
 1. Tkinter OptionMenu:
  http://effbot.org/tkinterbook/optionmenu.htm
 
 2. Pmw OptionMenu:
  http://pmw.sourceforge.net/doc/OptionMenu.html
 
 I would opt for these before a roll-your-own version.


try searching for a ComboBox I think you will have more hits
I know Pmw has one, it is also quite easy to build your own
with an Entry, Button and Listbox widget + some nifty code ;)

Cheers,
Martin.

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


Re: text manipulation

2005-12-16 Thread Martin Franklin
Martin Franklin wrote:
 Johhny wrote:
 
Hello,

I am trying to write a script in python (to replace a perl script with
limited functionality). Now I have some issues. Currently I am using
the perl to load the file then regex parse certain lines to remove
characters (uncomment lines and change variables). I would like to take
that into the python script. I have had a look at the module string
and I dont think its what Im looking for.

Here is an example of some text I would like to manipulate

#comment here
#user_defined_variable = no
#

I would like to make that

#comment here
user_defined_variable = yes
#

With perl/sed Its very easy, However Im having issues to do it in
python. Any advice would be great.

Regards,

Johhny.

 
 
 
 forget regular expressions for this job... strings have methods in
 python so for example:
 
 
 for line in file:
  if line.startswith(#user_defined_variable = no):
  line.replace(#user_defined_variable = no,
  user_defined_variable = yes)
 
 ... continue processing file / writing out stuff as you go
 
 
 Cheers
 Martin
 




whoops forgot string methods return the new string.

for line in file:
  if line.startswith(#user_defined_variable = no):
  line = line.replace(#user_defined_variable = no,
  user_defined_variable = yes)

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


Re: text manipulation

2005-12-16 Thread Juho Schultz
Johhny wrote:
 Hello,
 
 I am trying to write a script in python (to replace a perl script with
 limited functionality). Now I have some issues. Currently I am using
 the perl to load the file then regex parse certain lines to remove
 characters (uncomment lines and change variables). I would like to take
 that into the python script. I have had a look at the module string
 and I dont think its what Im looking for.
 
 Here is an example of some text I would like to manipulate
 
 #comment here
 #user_defined_variable = no
 #
 
 I would like to make that
 
 #comment here
 user_defined_variable = yes
 #
 
 With perl/sed Its very easy, However Im having issues to do it in
 python. Any advice would be great.
 
 Regards,
 
 Johhny.
 

Have you also looked at the built-in string methods?


The following script is probably something you
could start with - it just uncomments lines
and replaces values of some variables.

# dictionary of the variable names
# contains the replacement values
newvalues = {'userdefinedvar1':'yes',
'userdefinedvar2':'123.654.345.234'}

# read file to input
output = []
for line in input:
 # check if it is a comment with =
 if line.startswith('#') and ('=' in line):
 name, oldvalue = (line.lstrip('#')).split('=')
 # line.lstrip removes leading comments,
 # split('=') finds the assignment
 if newvalues.has_key(name):
 # replace line
 output.append(%s = %s % (name, newvalue[name]))
 else:
 # or just uncomment
 output.append(%s = %s % (name, oldvalue))
 else:
 output.append(line)

# write output to file
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SVG rendering with Python

2005-12-16 Thread [EMAIL PROTECTED]
Matplotlib also has an SVG renderer.  Just save the file with an SVG
extension or choose SVG as your default backend in the rc file
http://matplotlib.sf.net/matplotlibrc.

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


Re: thread and alarm

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Sergey schreef [EMAIL PROTECTED]:
 How to send alarm to a thread?
 I can set alarm in main thread, but how then send exception to another thread 
 to wake it if it executes too long?

The short answer is you can't and you should preferably look for an
other solution. If for example your other thread is simple loop
like:

  while condition:
 ...

You could change this to:

  while not timeout and condition:

timeout is then a variable that could be set by a differnt thread.


If your code doesn't lend itself for this kind of solution you could
consider the following module I once wrote. However some caveats:

1) You need ctypes.

2) It can only interrupt a thread while it is excuting python
   code. No interruptions while in C-extention code.

3) It is not extensivly tested. It was just a proof of concept
   thing.



import os
import ctypes
from time import sleep
from random import randint

class TimeOut(Exception):
  pass

class Alarm(Exception):
  pass

import threading

class Xthread(threading.Thread):


  def start(self):
self.__original_run = self.run
self.run = self.__run 
threading.Thread.start(self)

  def __run(self):
self._thrd_id = threading._get_ident()
try:
  self.__original_run()
finally:
  self.run = self.__original_run

  def raize(self, excpt):

Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self._thrd_id, 
ctypes.py_object(excpt))
#print self.id , Exception Thrown , Nr
while Nr  1:
  #print self.id , Exception Canceled , Nr
  ctypes.pythonapi.PyThreadState_SetAsyncExc(self._thrd_id, None)
  sleep(0.1)
  Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self._thrd_id, 
ctypes.py_object(excpt))
#if Nr == 0:
#  print self.id , Exception Canceled , Nr
#  ctypes.pythonapi.PyThreadState_SetAsyncExc(self._thrd_id, None)

  def alarm(self, tm):

alrm = threading.Timer(tm, self.raize, (TimeOut,))
alrm.start()
return alrm

if __name__ == __main__:

  class Continue(Xthread):
  
def run(self):
  
  self.id = os.getpid()
  print self.id, self._thrd_id, Begin
  i = 0
  try:
for _ in xrange(randint(0,20)):
  for e in xrange(4 * 10):
i = i + e
print self.id, Finished
  except Alarm:
print self.id, Interupted
  
  lst = [Continue() for _ in xrange(10)]
  
  for T in lst:
T.start()
  
  try:
sleep(10)
  finally:
for T in lst:
  T.raize(Alarm)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Lexical Scope

2005-12-16 Thread Bengt Richter
On 15 Dec 2005 18:45:17 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

Well, the the comparison operations are just a special case really.I
don't know about the obfuscation contest. I've attempted to make an
extensible library.
Sorry about obfuscation contest, I just balked at the reduce code, which 
seemed
like premature overgeneralization ;-)

def lt(*fields):
return collect(fields, lambda x, y: x  y)

def gt(*fields):
return collect(fields, lambda x, y: x  y)

def gte(*fields):
 gte(field, ...) - rule

return collect(fields, lambda x, y: x = y)

etc...
DRY ? ;-)


The purpose of writing the collect function was just to be able to
easily apply the logic to whatever function was wanted.

the added ability is to be able to take as many arguments as it wants.

Yes, but does collect(fields, fun) always know that fun takes two args? And that
it makes sense to apply fun pairwise as a boolean relation to reduce to a 
single boolean value?
You could say that by definition it does. In that case, will your future 
library extender need
to add some other kind of collect-like function?

hire_rule = lt('birth_date', 'hire_date', 'fire_date')
cube_rule = eq('height', 'width', 'depth')

I see where the idea of using reduce would occur ;-)


The reason that it's written like this is because I'm attempting to
make things as declarative as possible. I could use classes and
override __special__ operators and things like that but just applying
rules using prefix notation seems to work alright.
Applying or generating? But yeah, prefix should work fine. Or infix.


I've basically got a simple call signature...takes dict returns bool
that plugs into the little validation routine.
Simple is good.

It turns out that envoking the rules is easistly expressed with a
closure, though I might switch to types if it needs that added
complexity.
It's good that you have a syntax that can be implemented either way.


But your assumption is correct, it's for dictionaries of data to be
validated. I haven't decided if I want to take advantage of the dict's
mutability to include formating as well.
You might consider putting formatting in dict subclasses that have appropriate
__str__ and/or __repr__ methods, and doing print Fmtxxx(record_dict) or such?


Here's a bit from my unit test.
Looks nice. And the syntax is regular enough that you can probably
write an optimizing rule generator when/if you need it.


rule = when(all(have('length'), have('width')),
   check(['length', 'width'], lambda x, y: x == y))
assert rule({'length' : '2', 'width' : '2'}) == True
assert rule({'length' : '2', 'width' : '1'}) == False
assert rule({'length' : '1', 'width' : '2'}) == False

But what about when the when clause says the rule does not apply?
Maybe return NotImplemented, (which passes as True in an if test) e.g.,

 assert rule({'length' : '1', 'height' : '2'}) is NotImplemented

I've also got a collectable equality function so that can be shown
as.

box_rule = when(all(have('length'), have('width')), eq('length',
'width'))

Which basically means, if we have both a length and a width, then be
sure they are equal.
either way, I think it would be better to give tests names, i.e., instead
of the lambda, pass a function def eq(x,y): return x==y and then also
change check to have signature def check(testfun, *fields):...
But collectable has the possibility of inline code generation (see below ;-)


Of course, there is a little function that performs a conjunction of a
complete list of rules on a dict and returns the rules that failed.

I've also got a little adapter that translates functions that take a
string and returns bool into one that fits the call signature called
match.

match(is_ssn, 'social-security_number')

Like I said, it may be considered more readable if using operator
overloading so that it uses python's native syntax. Considering the
added complexity, I don't know if it would be worth it. I'd probably
put a simple little declarative language on top of it to translate the
function calls before that.


Note that you could treat your when, all, have, and check as code source 
generators
and compile a rule as the last part of when processing, e.g.,
(fresh off the griddle, only tested as far as you see ;-)

 jslowery.py --
def all(*tests):
return '(' + ' and '.join(tests) +')'
def have(*fields):
return '(' + ' and '.join('%s in record'%field for field in fields) + ')'
def check(tfun, *fields):
return '%s(%s)' % (tfun.func_name, ', '.join('record[%r]'%field for field 
in fields))
def when(cond, test):
g = globals()
d = dict((name, g[name]) for name in __testfuns__)
src = \
def rule(record):
if not (%s): return NotImplemented
return (%s)
 %(cond, test)
print src  # XXX debug
exec src in d
return d['rule']


def eq(*fields): # collectable
return '(' + ' == '.join('record[%r]'%(field,) for field in fields) + ')'

def 

Re: Re: getsockopt

2005-12-16 Thread Fabian Deutsch
Steve Holden wrote:
 Fabian Deutsch wrote:
 --- Ursprüngliche Nachricht ---
 Von: Steve Holden [EMAIL PROTECTED]
 An: python-list@python.org
 Betreff: Re: getsockopt
 Datum: Fri, 16 Dec 2005 08:29:08 +
 
 Fabian Deutsch wrote:
 
 Hello,
 
 my name is fabian and i'm a student from northern germany. right now i
 try to create som kind of decapsulation of esp-udp packets using
 python.
 
 therefor i need to use the socket.getsockopt (SOL_IP, IP_OPTIONS, 20)
 method. But al i get is some empty value. Nothin.
 
 Does someone know or have an working exmaple of how to use this
 method??
 
 The lines:
 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)
 s.bind(('',4500))
 while 1:# Run until cancelled
message, client = s.recvfrom(1400) # =256 byte datagram
 hdr = s.getsockopt (SOL_IP, IP_OPTIONS, 20)
 print Client connected:, client
 print HDR: + binascii.hexlify(hdr)
 
 
 Perhaps you're getting an empty string back because no IP options are 
 set in the received packets' headers?
 
  
  Hey,
  you are right - i just re-read the ip (7) man - i only get the ip
 options ..
  
  but do you know a way of getting the whole header?
  
  'cause what i'm trying to do is, to remove the udp-header of the
 packet i
  recieved and sendind a new packet without the udp-header.
  I want to do this by taking it's payload (incl. esp-hdr) and ip-header
 and
  resending it to my system creating a new packet with the old ip-header
 and
  payload (incl. esp-hdr) i got from the recvd packet.
  
  Before:
  ++-+--+--- - - 
  | IP HDR | UDP HDR |  ESP HDR | PAYLOAD ...
  ++-+--+--- - - 
  After :
  ++-+--- - - 
  | IP HDR | ESP HDR | PAYLOAD ...
  ++-+--- - - 
  
 I'm not sure where ESP is going to come into this, or how the traffic 
 you will be receiving will be generated. I suspect you may need to 
 reconsider your application design a little.
 
 The only way to get hold of the IP headers is to use SOCK_RAW, which 
 delivers everything that comes in from the packet driver.
 
 What is it you're actually trying to do? If you perform the 
 transformation you outline in the diagrams above then the IP header will 
 certainly contain the wrong protocol value for a start.

You just need the ipsec tools to generate the traffic i want to decapsulate.

setkey -c EOF
add HOSTA HOSTB esp-udp 11 -m tunnel -E 3des-cbc 123456789012123456789012
spdadd HOSTA HOSTB any -P in ipsec
  esp/tunnel/HOSTA-HOSTB/use;
EOF

you will get some udp-esp packets when you ping HOSTB from HOSTA.

- fabian

-- 
Fabian Deutsch [EMAIL PROTECTED]
Hinter dem Gartel 26a
D-27711 Osterholz-Scharmbeck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-16 Thread Paul Boddie
bruno at modulix wrote:
 Adrian, what you describe here is *exactly* what I call no Ajax
 support: you have to handle the whole thing manually, the framework
doesn't provide anything by itself.

I'm not going to argue whether Django supports Ajax or not, but I
will agree that for the desired effect applications do need to be able
to provide something usable for the client-side code to work with.
However, all the something usable needs to be, in my opinion, is a
fragment of an existing Web page which is accessible through a
well-defined Web-style API.

 And BTW, Ajax is not a client-side techno, it's a combination of client
 *and* server-side technos. TurboGears support Ajax (well, a variant of,
 since it's based on JSON, not XML) by having a pretty good, JSON aware
 javascript lib (mochikit) for the client side *and* an OOTB JSON
 serialization on the server side.

I personally don't believe very strongly in this server-side
serialisation of various non-displayable formats for potentially large
amounts of client-side code to unpack, process, stuff into different
places, and so on. As I said before, this is like reinventing
client/server all over again but with the deployment of client-side
code and the presentation technology standardised: you still end up
with maintenance issues, keeping the data model consistent at both ends
whilst dealing with different languages and toolkits. I'd rather have
such functionality controlled with mostly declarative constructs, and
with as few moving parts on the client as possible.

Paul

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


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-16 Thread Paul Boddie
bruno at modulix wrote:
 Adrian, what you describe here is *exactly* what I call no Ajax
 support: you have to handle the whole thing manually, the framework
doesn't provide anything by itself.

I'm not going to argue whether Django supports Ajax or not, but I
will agree that for the desired effect applications do need to be able
to provide something usable for the client-side code to work with.
However, all the something usable needs to be, in my opinion, is a
fragment of an existing Web page which is accessible through a
well-defined Web-style API.

 And BTW, Ajax is not a client-side techno, it's a combination of client
 *and* server-side technos. TurboGears support Ajax (well, a variant of,
 since it's based on JSON, not XML) by having a pretty good, JSON aware
 javascript lib (mochikit) for the client side *and* an OOTB JSON
 serialization on the server side.

I personally don't believe very strongly in this server-side
serialisation of various non-displayable formats for potentially large
amounts of client-side code to unpack, process, stuff into different
places, and so on. As I said before, this is like reinventing
client/server all over again but with the deployment of client-side
code and the presentation technology standardised: you still end up
with maintenance issues, keeping the data model consistent at both ends
whilst dealing with different languages and toolkits. I'd rather have
such functionality controlled with mostly declarative constructs, and
with as few moving parts on the client as possible.

Paul

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


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-16 Thread Paul Boddie
bruno at modulix wrote:
 Adrian, what you describe here is *exactly* what I call no Ajax
 support: you have to handle the whole thing manually, the framework
doesn't provide anything by itself.

I'm not going to argue whether Django supports Ajax or not, but I
will agree that for the desired effect applications do need to be able
to provide something usable for the client-side code to work with.
However, all the something usable needs to be, in my opinion, is a
fragment of an existing Web page which is accessible through a
well-defined Web-style API.

 And BTW, Ajax is not a client-side techno, it's a combination of client
 *and* server-side technos. TurboGears support Ajax (well, a variant of,
 since it's based on JSON, not XML) by having a pretty good, JSON aware
 javascript lib (mochikit) for the client side *and* an OOTB JSON
 serialization on the server side.

I personally don't believe very strongly in this server-side
serialisation of various non-displayable formats for potentially large
amounts of client-side code to unpack, process, stuff into different
places, and so on. As I said before, this is like reinventing
client/server all over again but with the deployment of client-side
code and the presentation technology standardised: you still end up
with maintenance issues, keeping the data model consistent at both ends
whilst dealing with different languages and toolkits. I'd rather have
such functionality controlled with mostly declarative constructs, and
with as few moving parts on the client as possible.

Paul

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Ben Finney
Antoon Pardon [EMAIL PROTECTED] writes:
 Ben Finney wrote:
 The 'enum' package in Cheeseshop [defines enumerations as]
 sequences (of unique arbitrary values), that can be iterated and
 tested for membership.

 Sure but we do have this:

 from enum import Enum
 day = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
 col = Enum('red', 'green', 'blue')
 lst= [day.mon, col.red]
 col.blue in lst
 [...]
 enum.EnumValueCompareError: Not values from the same enumeration:

Yes, that looks like a case in favour of allowing at least equal-value
and not-equal-value comparisons.

 The problem with is the same value as an explanation for '==' is
 that it doesn't help in cases such as::

  ShirtSize = Enum('small', 'medium', 'large')
  AppleSize = Enum('small', 'large')

 What should be the result of this comparison::

  ShirtSize.small == AppleSize.small

 Are they the same value? They're both small (and they both coerce
 to the same string value, and in this case the same integer value).

 If not, is 'False' the right way to indicate that?

 I would agree 'False' is the right answer here.

Antoon Pardon wrote:
 Ben Finney wrote:
  Would it be better if every Enum instance had its own unique
  subclass of EnumValue, that was used to instantiate values for
  that enumeration?

 If you decide on keeping the current behaviour when comparing
 values of different enumerations, I would definitely answer
 yes.

If values from different enums were to be compared for equality (and
not raise an exception), would it still be good to have those values
be of different types?

 This is a difficult question, because AFAIU python doesn't have
 clear guidelines for [comparisons between differing types]. I also
 have the impression that comparisons are used for two different
 reasons.

 The first is compare things in a mathematical kind of way in which
 how things are compared is important.

 The second is more an ordering mechanisme. Whether a string is
 greater than an int or vice versa, is not imporant what is important
 is that this order is consistent and can be used in binary searches,
 trees and other structures to organise data.

 Now python has only one collection of compare operators which can
 cause conflicts. For instance, one could impose an order on sets to
 use for such structure but that goes against the normal order on
 sets which is based on subsets.

 The only advise I have here is look at PEP 3000 that states:

 Comparisons other than == and != between disparate types will raise
 an exception unless explicitly supported by the type.

 Which seem to imply that == and != should not raise an exception but
 , =, , = should.

This seems like a good guide for a policy on enumerations.

How about this proposal:

Enumerations (instances of Enum) contain a fixed sequence of unique,
arbitrary values. The values within an enumeration are instances of a
type (subclass of EnumValue), unique to that enumeration.

Values from an enumeration can be compared for equality (__eq__,
__ne__) with any other value, and will only return True for the same
value from the same enumeration, otherwise False. Other comparison
operations can be performed only with values from the same
enumeration, otherwise an exception (EnumValueCompareError, subclass
of ValueError) is raised.

This might result in the following simplistic implementation::

class EnumValue(object):
# ...

def __eq__(self, other):
result = False
if self is other:
result = True
return result

def __cmp__(self, other):
if isinstance(other, EnumValue):
if is_same_enumeration(self, other):
result = cmp(self.index, other.index)
else:
raise EnumValueCompareError(self, other)
return result

This gives meaning to the equal value comparisons, but ensures that
other comparisons are errors.

Comments so far?

-- 
 \  I like to fill my bathtub up with water, then turn the shower |
  `\on and pretend I'm in a submarine that's been hit.  -- Steven |
_o__)   Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie to python

2005-12-16 Thread Johhny
Thankyou, I appreciate your help. I did not realise that python would
behave that way.

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


Re: Python and curses

2005-12-16 Thread Thomas Dickey
linuxfreak [EMAIL PROTECTED] wrote:
 Was wanting to write a text based application in python seems
 curses module is the way to go... anyone knows of any good tutorials
 apart from the one written by esr

It wasn't written by esr.  He only has his name on it, did none of the work.

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Paul Rubin
Ben Finney [EMAIL PROTECTED] writes:
 This gives meaning to the equal value comparisons, but ensures that
 other comparisons are errors.
 
 Comments so far?

What does copy.copy of an enumeration value do?  What happens if you
have a list with some enumeration values inside, and you make a
deepcopy of it?  What happens if you pickle an enum, then unpickle the
pickle and compare what comes out to the other enum?

All in all, comparing by object identity doesn't sound too good.
Maybe you want to have the enum contain its own name internally, and
do a string comparison.
-- 
http://mail.python.org/mailman/listinfo/python-list


distutils: build scripts as native executables?

2005-12-16 Thread Giovanni Bajo
Hello,

am I wrong or isn't there a way in distutils to build (compile/link) a
native executable and install it among the scripts? It looks like that
distutils.CCompiler features a link_executable() method, and build_ext.py
has most of the logic needed to track dependencies, include paths and
whatnot, but nothing is exposed at a higher level.

I was going to subclass build_ext and find a way to piggy-back
link_executable() into it instead of link_shared_object(), but I thought I
asked before doing useless / duplicate work.
-- 
Giovanni Bajo


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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-16 Thread chuck
 I did a fairly thorough investigation of web frameworks that let us
 write Python (we didn't care what the framework was written in; merely
 that it interfaced with Python) for one of the systems I've built this
 year. I wouldn't call the evaluation of web frameworks a problem - we
 met our schedules, and the tool evaluation phase was by *far* the
 shortest phase in the project, taking less than a week. Most of the
 evaluations were easy - read the description of the framework, and
 decide that we're working outside the problem space it's desinged
 for. It certainly wasn't wasted time - I found a tool that I hadn't
 heard of previously that was nearly perfectly suited to the job at
 hand.

As I read through this thread I can't say that I disagree that having
more choices is a 'good thing'.  However in your example here - I
suspect that you are a bit sharper and have a bit more guts than your
average code slinger since you appear to be an independent.  You've got
to remember that your average corporate programmer - which are the
folks driving the popularity of programming languages - isn't that
sharp/confident.  (I don't mean to insult anyone but that just the
facts.)  They don't do things like evaluate frameworks and make smart
choices.  This is why there needs to be obvious and singularly popular
frameworks and IDE's for Python so that people don't have to think that
hard about it.  Take Java for example - for the most part its Eclipse
and Struts.  I know there are many other choices (I've used them), but
even the managers know these terms.  Very, very few people I know in
the IT world know of 'Python', let alone the name of any web framework
or an IDE for Python.

One of the great things about Python is its simplicty/clarity.  Its a
shame that there doesn't also exist a clarity of choice for a web
framework for Python or an IDE for that matter.  Both of these would go
a long way in motivating people to take a look at Python and realizing
what great value it has to offer the IT world in solving problems.

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


Re: why does php have a standard SQL module and Python doesn't !?

2005-12-16 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 This was my point though:  I found the *description* - but no wordon
 WHICH implementation to get WHERE ?

Hmm.
- Browse to http://www.python.org
- click Documentation
- click Database API
- click Database Modules (Database modules that implement the DB-API 
specification.)
- read list, find the database of your choice

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Antoon Pardon
 Antoon Pardon wrote:
 Ben Finney wrote:
  Would it be better if every Enum instance had its own unique
  subclass of EnumValue, that was used to instantiate values for
  that enumeration?

 If you decide on keeping the current behaviour when comparing
 values of different enumerations, I would definitely answer
 yes.

 If values from different enums were to be compared for equality (and
 not raise an exception), would it still be good to have those values
 be of different types?

Yes, because people who would need a quick and dirty ordering
could then use the type of the object as a first key.

 The only advise I have here is look at PEP 3000 that states:

 Comparisons other than == and != between disparate types will raise
 an exception unless explicitly supported by the type.

 Which seem to imply that == and != should not raise an exception but
 , =, , = should.

 This seems like a good guide for a policy on enumerations.

 How about this proposal:

 Enumerations (instances of Enum) contain a fixed sequence of unique,
 arbitrary values. The values within an enumeration are instances of a
 type (subclass of EnumValue), unique to that enumeration.

 Values from an enumeration can be compared for equality (__eq__,
 __ne__) with any other value, and will only return True for the same
 value from the same enumeration, otherwise False. Other comparison
 operations can be performed only with values from the same
 enumeration, otherwise an exception (EnumValueCompareError, subclass
 of ValueError) is raised.

Looks good to me.

 This might result in the following simplistic implementation::

 class EnumValue(object):
 # ...

 def __eq__(self, other):
 result = False
 if self is other:
 result = True
 return result

 def __cmp__(self, other):
 if isinstance(other, EnumValue):
 if is_same_enumeration(self, other):
 result = cmp(self.index, other.index)
 else:
 raise EnumValueCompareError(self, other)
 return result

 This gives meaning to the equal value comparisons, but ensures that
 other comparisons are errors.

 Comments so far?

Isn't there an else missing? I have the impression that if you compare
two enums from a different enumeration __cmp__ will raise UnboundLocalError.

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


Re: Robotics and parallel ports

2005-12-16 Thread malv
Hi,
Thank you for the info.
The dlp usb solution looks like a terrific gadget, especially since
parallel ports have almost disppeared, at least on portables.
In fact, would in linux not any py software capable of dealing with a
usb connection (almost) suffice? Any further comments would be much
appreciated.
malv

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


Re: split string saving screened spaces

2005-12-16 Thread Paul McGuire
Pyparsing has built-in quoted string support.


from pyparsing import OneOrMore,Word,alphanums,quotedString

item = Word('-',alphanums) | quotedString | Word(alphanums)
items = OneOrMore(item)

print items.parseString( -a -b -c '1 2 3' -d 5 -e zork2000 )

gives:
['-a', '-b', '-c', '1 2 3', '-d', '5', '-e', 'zork2000']


Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul

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


Re: text manipulation

2005-12-16 Thread BartlebyScrivener
John,

Martin is right. Always try to solve without regex first. However, for
those situations where you definitely need regex, use this tutorial:

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

It's well-written, succinct, and Python-specific.

rpd

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


Re: Python IDE

2005-12-16 Thread Mustafa Yalcin Acikyildiz
emacs, best ide of all-time ;)

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


Re: Can Python write foreign characters to the console?

2005-12-16 Thread Grant Edwards
On 2005-12-16, Bock [EMAIL PROTECTED] wrote:

 I was just told about Python.  My searching and reading over the net
 I was able to learn that Python can handle foreign characters via
 Unicodes.  

 Can or does Python write unicode to the screen?

Sure.

 For example, in c++ cout  Hello World. would send this
 string to the screen/monitor.  

 I want to find a programming language that can write German
 üßäö as screen output?

All of the languages I've ever used could write unicode to a
console. Whether your console understands Unicode and displays
it properly is another question.

 Most programming languages/operating systems in North America
 limit one to the 127 characters of ascii.

If that's true, then you're using crap for an OS.

-- 
Grant Edwards   grante Yow!  Either CONFESS now or
  at   we go to PEOPLE'S COURT!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing the Tkinter Window

2005-12-16 Thread Dustan
I don't want to destroy the root, I just want to remove the widgets
(the exact opposite of what Martin was saying).  I started working on
James' idea, but it'll be a while before I have it fully implemented to
test.

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


Re: 0 in [True,False] returns True

2005-12-16 Thread Grant Edwards
On 2005-12-16, Antoon Pardon [EMAIL PROTECTED] wrote:

 Your examples are still both very different from the NaN
 example.  A NaN is a floating point operation that supports all
 the same operations as all other floating point operations.  In
 your example an integer object of -2 does not support the same
 operations that a real GTK identifier does.  They are two
 different types.

 I think the disctinction you are making is based on which level
 you look at things.

Of course.  I was looking at things from a Python point of view
since this is c.l.p.

 For you floats are something you use, you see NaN as just a
 floats because the details of implementation have been
 abstracted out for you.

That goes without saying for anything in computer science or
electronics: it's all just quantum physics whose details of
implimentation have been abstracted out for me.

 But look at it from the level of someone who has to implement
 floating point numbers. He can't just take two floats and put
 them into his general add_float algorithm. If he did that the
 result of working with a NaN could result in a regular number.
 So he has to test for special values like NaN is his 'code'
 too.

 Of course we tend to forget this because in this case the
 abstraction is usually done at the hardware level. But I don't
 think that is such an important disctinction here.

The distinction is in regards to readability and
maintainability of _Python_ code.  This is comp.lang.python.

-- 
Grant Edwards   grante Yow!  does your DRESSING
  at   ROOM have enough ASPARAGUS?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with exec

2005-12-16 Thread Antoon Pardon
I have the following little piece of code:

class Cfg:pass
#config = Cfg()

def assign():
  setattr(config, 'Start' , [13, 26, 29, 34])

def foo():
  config = Cfg()
  dct = {'config':config, 'assign':assign}
  exec assign() in dct
  print config.Start

foo()


When I execute this I get the following error:

Traceback (most recent call last):
  File mod1.py, line 13, in ?
foo()
  File mod1.py, line 10, in foo
exec assign() in dct
  File string, line 1, in ?
  File mod1.py, line 5, in assign
setattr(config, 'Start' , [13, 26, 29, 34])
NameError: global name 'config' is not defined

Now I don't understand this. In the documentation I read the following:

  If only the first expression after in is specified, it should be a
  dictionary, which will be used for both the global and the local
  variables.

I provided a dictionary to be used for the global variables and it
contains a 'config' entry, so why doesn't this work?

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Ben Sizer

Antoon Pardon wrote:
 Op 2005-12-16, Ben Sizer schreef [EMAIL PROTECTED]:
  Is it possible to make it have the following sort of behaviour? :
 
  ShirtSize.small == AppleSize.small
  True
  ShirtSize.small is AppleSize.small
  False
 
  It works for comparing a boolean (True) vs. an integer (1), so it has
  some sort of precedent. (Especially if you make the tenuous assumption
  that True,False are language-supported 'enums' for 0 and 1.)

 I'm against it. I don't like the following returning True:

   ShirtSize.small in [ShirtSize.Medium, AppleSize.small]

I agree to an extent. I can see that being unwanted behaviour, although
not really a big one, and no worse than in C++. I think that when you
have a list of alternatives like that, they're either hard-coded by
selectively picking from the enumeration's initialisation list, or by
being generated according to some other criteria. Either way, it would
be hard to end up with the wrong type of value into that list, I think.

 I also think it may cause problems with other comparisons.

 Supose the following:

   col = Enum('red', 'green', 'blue')
   paint = Enum('violet' , 'blue', 'red')

 Then we get the following situation:

   col.red == paint.red and col.blue == paint.blue

 but

   col.red  col.blue and paint.blue  paint.red

I don't think that's a problem - does any other language make any
guarantees on ordering across multiple enumerations? Transitivity
within any single enumeration plus transivity of equivalence across
multiple enumerations, should be enough for most needs, no?

-- 
Ben Sizer

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


Re: Clearing the Tkinter Window

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

I don't want to destroy the root, I just want to remove the widgets
 (the exact opposite of what Martin was saying).  I started working on
 James' idea, but it'll be a while before I have it fully implemented to
 test.

each widget has a children attribute, which contains a dictionary with Tk 
widget
names as keys, and Python widget objects as values.  to destroy all child 
widgets,
you can simply do:

for w in widget.children.values():
w.destroy()

where widget is the widget you want to reset.

/F 



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


Re: Problem with os.path

2005-12-16 Thread Scott David Daniels
Daya Kiran Sunkara wrote:
 ...
 path = 'E:\mktrisk\service\marketdata\da'
You should use:
   path = r'E:\mktrisk\service\marketdata\da'
if you want to use backslashes regularly (for regexps and paths).
You do know you could also use:
   path = 'E:/mktrisk/service/marketdata/da'
even on windows.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE

2005-12-16 Thread Fuzzyman
SPE is very good - I'd use it, and if you need any features Stani is
very quick to add them.

All the best,

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

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


Re: Problem with exec

2005-12-16 Thread Larry Bates
Antoon Pardon wrote:
 I have the following little piece of code:
 
 class Cfg:pass
 #config = Cfg()
 
 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])
 
 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start
 
 foo()
 
 
 When I execute this I get the following error:
 
 Traceback (most recent call last):
   File mod1.py, line 13, in ?
 foo()
   File mod1.py, line 10, in foo
 exec assign() in dct
   File string, line 1, in ?
   File mod1.py, line 5, in assign
 setattr(config, 'Start' , [13, 26, 29, 34])
 NameError: global name 'config' is not defined
 
 Now I don't understand this. In the documentation I read the following:
 
   If only the first expression after in is specified, it should be a
   dictionary, which will be used for both the global and the local
   variables.
 
 I provided a dictionary to be used for the global variables and it
 contains a 'config' entry, so why doesn't this work?
 

Not entirely sure why you want to do what you have outlined
here but this works:

class Cfg:
pass
#config = Cfg()

def assign(config):
setattr(config, 'Start' , [13, 26, 29, 34])

def foo():
config = Cfg()
assign(config)
print config.Start

foo()

You should probably post what you are trying to do.  Maybe we
can make a suggestion about the best approach.

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


Re: Problem with exec

2005-12-16 Thread Peter Otten
Antoon Pardon wrote:

 I have the following little piece of code:
 
 class Cfg:pass
 #config = Cfg()
 
 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])
 
 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start
 
 foo()
 
 
 When I execute this I get the following error:
 
 Traceback (most recent call last):
   File mod1.py, line 13, in ?
 foo()
   File mod1.py, line 10, in foo
 exec assign() in dct
   File string, line 1, in ?
   File mod1.py, line 5, in assign
 setattr(config, 'Start' , [13, 26, 29, 34])
 NameError: global name 'config' is not defined
 
 Now I don't understand this. In the documentation I read the following:
 
   If only the first expression after in is specified, it should be a
   dictionary, which will be used for both the global and the local
   variables.
 
 I provided a dictionary to be used for the global variables and it
 contains a 'config' entry, so why doesn't this work?


If you have a module

v
def f(): return v


and call f in another module

print f()

where no global variable v is defined, would you expect that call to fail?
Of course not, but how can f look up the variable v then? The function
object keeps a reference of the global namespace it was defined in.
For your example that means the assign() function will look up the config
object in the module's globals(), not in the dictionary you provide to exec

One way to fix your problem would be to define the assign() function inside
the exec'd string.

Peter

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


Parser or regex ?

2005-12-16 Thread Fuzzyman
Hello all,

I'm writing a module that takes user input as strings and (effectively)
translates them to function calls with arguments and keyword
arguments.to pass a list I use a sort of 'list constructor' - so the
syntax looks a bit like :

   checkname(arg1, arg 2, 'arg 3', keywarg=value,
keywarg2='value2', default=list(val1, 'val2'))

Worst case anyway :-)

I can handle this with regular expressions but they are becoming truly
horrible. I wonder if anyone has any suggestions on optimising them. I
could hand write a parser - which would be more code, probably slower -
but less error prone. (Regualr expressions are subject to obscure
errors - especially the ones I create).

The trouble is that I have to pull out the separate arguments, then
pull apart the keyword arguments and the list keyword arguments. This
makes it a 'multi-pass' task - and I wondered if there was a better way
to do it.

As I use ``findall`` to pull out all the arguments - so I also have to
use a *very similar* regex to first check that there are no errors (as
findall will just miss out badly formed parts of the input).

My current approach is :

pull out the checkname and *all* the arguments using :

'(.+?)\((.*)\)'

I then have :


_paramstring = r'''
(?:
(
(?:
[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*list\(
(?:
\s*
(?:
(?:.*?)|  # double quotes
(?:'.*?')|  # single quotes
(?:[^',\s\)][^,\)]*?)   # unquoted
)
\s*,\s*
)*
(?:
(?:.*?)|  # double quotes
(?:'.*?')|  # single quotes
(?:[^',\s\)][^,\)]*?)   # unquoted
)?  # last one
\)
)|
(?:
(?:.*?)|  # double quotes
(?:'.*?')|  # single quotes
(?:[^',\s=][^,=]*?)|   # unquoted
(?: # keyword argument
[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*
(?:
(?:.*?)|  # double quotes
(?:'.*?')|  # single quotes
(?:[^',\s=][^,=]*?)   # unquoted
)
)
)
)
(?:
(?:\s*,\s*)|(?:\s*$)# comma
)
)
'''

I can use ``_paramstring`` with findall to pull out all the arguments.
However - as I said, I first need to check that the entrie input is
well formed. So I do a match against :

_matchstring = '^%s*' % _paramstring

Having done a match I can use findall and ``_paramstring``  to pull out
*all* the parameters as a list - and go through each one checking if it
is a single argument, keyword argument or list constructor.

For keyword arguments and lists constructors I use another regular
expression (the appropriate part of _paramstring basically) to pull out
the values from that.

Now this approach works - but it's hardly optimal (for some value of
optimal). I wondered if anyone could suggest a better approach.

All the best,

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

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


Re: Problem with exec

2005-12-16 Thread Fredrik Lundh
Antoon Pardon wrote:

 I have the following little piece of code:

 class Cfg:pass
 #config = Cfg()

 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])

 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start

 foo()

 When I execute this I get the following error:

 Traceback (most recent call last):
   File mod1.py, line 13, in ?
 foo()
   File mod1.py, line 10, in foo
 exec assign() in dct
   File string, line 1, in ?
   File mod1.py, line 5, in assign
 setattr(config, 'Start' , [13, 26, 29, 34])
 NameError: global name 'config' is not defined

 Now I don't understand this.

I thought you were an expert?

Python's lexically scoped, not dynamically scoped.  Using a specific
global context for the statement assign() doesn't mean that code
called by that statement will suddenly get the same global context.

/F 



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


Re: Python IDE

2005-12-16 Thread Scott David Daniels
Martin Miller wrote:
 ... If someone with actual experience using Komodo with Python is
 listening, I'd be very interested in hearing what you think of it
I got a copy of Komodo some time ago, and I love it.  I wanted a
fairly reliable debugging platform for a fairly large server
I was building (the business crumbled nastily), and I wanted to
step through the code to see where we were having problems.  I have
personally not had huge success using Idle for that (although it
doesn't really seem problematic for smaller stuff), and I have been
_very_ happy with Komodo.  Getting the updates w/o extra charge was
a bonus.  I was happy with the deal on the original version, so
these further improvements just make my deal feel better.

I don't regularly use Komodo, but when I do want it, it is invaluable.
My only affiliation with ActiveState is as a customer.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with exec

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Peter Otten schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:

 I have the following little piece of code:
 
 class Cfg:pass
 #config = Cfg()
 
 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])
 
 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start
 
 foo()
 
 
 When I execute this I get the following error:
 
 Traceback (most recent call last):
   File mod1.py, line 13, in ?
 foo()
   File mod1.py, line 10, in foo
 exec assign() in dct
   File string, line 1, in ?
   File mod1.py, line 5, in assign
 setattr(config, 'Start' , [13, 26, 29, 34])
 NameError: global name 'config' is not defined
 
 Now I don't understand this. In the documentation I read the following:
 
   If only the first expression after in is specified, it should be a
   dictionary, which will be used for both the global and the local
   variables.
 
 I provided a dictionary to be used for the global variables and it
 contains a 'config' entry, so why doesn't this work?


 If you have a module

 v = 42
 def f(): return v


 and call f in another module

 print f()

 where no global variable v is defined, would you expect that call to fail?
 Of course not, but how can f look up the variable v then?

But I am not just calling. I'm using exec. And from the documentation
from exec I get the impression you can use it so that a function
will have temporarily a different reference to global namespace.

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-16 Thread A.M. Kuchling
On Thu, 15 Dec 2005 20:15:17 -0800, 
Alex Martelli [EMAIL PROTECTED] wrote:
 If you claim there's a web project that's unfeasible to do in Ruby,
 you'd better come up with a strong example.  If you're making no such
 claim, which would be counter to the claims of the Ruby community, then
 there aren't gonna be any web projects unfeasible with Rails, either.

I believe Rails assumes you're using a relational database, not an
object database like Durus or the ZODB.  It seems to me Django is
similarly focused; are there hooks that would allow replacing an RDBMS
commit with a custom commit callback?

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


Re: Problem with exec

2005-12-16 Thread Antoon Pardon
Op 2005-12-16, Larry Bates schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 I have the following little piece of code:
 
 class Cfg:pass
 #config = Cfg()
 
 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])
 
 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start
 
 foo()

 [ ... ]

 You should probably post what you are trying to do.  Maybe we
 can make a suggestion about the best approach.

I'm using PLY. The assign function is a dumbded down version
of a production function that will be called during the parsing
of a config file. Each time a line of the form:

 var = val

is encounterd I do setattr(config, 'var', val)

The problem is that doing it this way means config needs to be global.
which I'm trying to avoid, in case some leftovers may cause trouble
when I read in a new configuration or should I ever have different
threads parsing files at the same time. 

The other way would be passing the 'config' variable around in the
productions, but this would complicate things.

So what I am trying to do was provide a global namespace to the call
to fool a function using a global name into using a provided local name.

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


Re: Haskell Typeclasses

2005-12-16 Thread Alex Martelli
Kay Schluehr [EMAIL PROTECTED] wrote:
   ...
 work. Or maybe it works and I just have no clue how completely opaque
 call graphs as they appear in functions like this
 
 def f(x):
  h = g(x)
  h()
 
 can be tracked sufficiently in register-time in order to capture
 dependencies. It is not clear what h can be unless g is called and it
 might be as hard as type-inference or completely impossible to figure
 this out without executing g. If otherwise the checker can guarantee
 detection of a few obvious cycles where dependencies can be tracked
 also syntactically, at least in principle like in your example, what
 exactly is ensured by the checker and how can the definition of a
 typeclass be adapted accordingly? 

My preference would be to have the dependency tracker mark explicit
dependencies only; here, if this was in a typeclass with the appropriate
additions of self., I'd mark f as dependent on g only.  No real purpose
is served by allowing dependencies to be specified in a cloaked form,
anyway -- nor in going out of one's way to impede vigorous attempts by a
programmer to shoot himself or herself in the foot.


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


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-16 Thread Adrian Holovaty
bruno at modulix wrote:
 Adrian, what you describe here is *exactly* what I call no Ajax
 support: you have to handle the whole thing manually, the framework
 doesn't provide anything by itself. Would you say the CGI module offers
 support for templating, data persistance and Ajax as well ?-)

Hey Bruno,

Sorry for the misunderstanding. Here's the Django code I use on the
Ajax bit of the chicagocrime.org Find your District page
(http://www.chicagocrime.org/districts/). See the Guess district
button on that page.


def rpc_guess_district(request, longitude, latitude):
try:
b = beats.guess_by_coordinates(float(longitude),
float(latitude))
except beats.BeatDoesNotExist:
return HttpResponse(Looks like you're not centered on a point
in Chicago.  + \
Please move the map to Chicago and try again.)
return HttpResponse(You're centered on %s %
b.get_name_and_district())


My point is, you don't need a huge serialization framework to do Ajax
easily. As long as a server can return snippets of code (or even plain
text), you can do it.

These pages work the same way:
http://www.chicagocrime.org/map/
http://www.chicagocrime.org/wards/
http://www.chicagocrime.org/route/

Hope that clears up my point of view,
Adrian

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


How to use pydoc?

2005-12-16 Thread newsposter
 import pydoc
 import sys
 sys.version
'2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]'
 pydoc sys
SyntaxError: invalid syntax


The documentation for pydoc says:
Run pydoc name to show documentation on something.

What am I missing?

Thanks!
Chris

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread skip

Without downloading and installing your code, can you tell me what the
result of these comparisons would be?

col = Enum('red', 'green', 'blue')
day = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
col.blue == blue
day.tue == 23

If they return False I would expect

col.blue == day.tue

to return False as well, not raise an exception.

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


Re: Python IDE (was: PythonWin troubleshooting)

2005-12-16 Thread Tim Arnold

chuck [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Apparently not too many people use or are interested in PythonWin.  I'm
 giving up on it.  It used to work pretty good.

 I'm lucky that I have found PyScripter (http://www.mmm-experts.com/) a
 python IDE for the windows platform which is much more stable and has
 more features that PythonWin.  If you are doing Python development on
 Windows I'd recommend taking a look at it.

 I'm also evaluating Wing IDE.  I may have another post with comments on
 it for anyone who might be interested.


Here's a plug for SPE, since I haven't heard anyone extolling its virtues.
I use it every day and love it.
--Tim 


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


Re: Problem with exec

2005-12-16 Thread Peter Otten
Antoon Pardon wrote:

 And from the documentation 
 from exec I get the impression you can use it so that a function 
 will have temporarily a different reference to global namespace.

That impression confuses two things:

(1) A function object carries a global namespace with it. That namespace is
fixed when the function definition is executed, not when the function is
called.

(2) You may provide a global namespace to exec. What's in that may be
altered by rebinding operations (=, def, etc.) in the exec't string.
Functions defined here use that namespace as their global namespace while
functions just executed here don't.

If you could provide a function with a different namespace when it's called,
e. g

f() in namespace

would look up its globals in namespace, that might be an interesting concept
but it's not how Python works.

Peter

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


Re: Parser or regex ?

2005-12-16 Thread Tim Arnold

Fuzzyman [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hello all,

 I'm writing a module that takes user input as strings and (effectively)
 translates them to function calls with arguments and keyword
 arguments.to pass a list I use a sort of 'list constructor' - so the
 syntax looks a bit like :

   checkname(arg1, arg 2, 'arg 3', keywarg=value,
 keywarg2='value2', default=list(val1, 'val2'))

 Worst case anyway :-)


pyparsing is great, easy to configure and very powerful--I think it looks 
like a great tool for your inputs.

http://pyparsing.sourceforge.net/


--Tim 


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


Re: to write set of values to a file from python

2005-12-16 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
 hi
 thanks every body for the help.
 Now how can check whtr the row am reading is the last row or not??
 
 for example: ...
 reader = csv.reader(file)
 for row in reader:
   print row
   HERE HOW CAN I CHECK WHTR THIS ROW IS THE LAST ONE IN THE FILE
 
 so that if at all i dint find what am searching for i can write that
 information at the last row, after opening the file in a append mode.

What Steve Holden says is right.  If it turns out you need to know
ahead of time, use a lagged input to determine whether it is last:

 def lagged(source):
 '''produce element,islast for elements in source'''
 generator = iter(source)
 previous = generator.next()
 for element in generator:
 yield previous, False
 yield previous, True

 file = open ('C:\some.csv','r')
 reader = csv.reader(file)
 for row, final in lagged(reader):
 print row
 if final:
 print 'final:', row
 else:
 print 'leads:', row


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with exec

2005-12-16 Thread Peter Otten
Antoon Pardon wrote:

 Op 2005-12-16, Larry Bates schreef [EMAIL PROTECTED]:
 Antoon Pardon wrote:
 I have the following little piece of code:
 
 class Cfg:pass
 #config = Cfg()
 
 def assign():
   setattr(config, 'Start' , [13, 26, 29, 34])
 
 def foo():
   config = Cfg()
   dct = {'config':config, 'assign':assign}
   exec assign() in dct
   print config.Start
 
 foo()
 
 [ ... ]

 You should probably post what you are trying to do.  Maybe we
 can make a suggestion about the best approach.
 
 I'm using PLY. The assign function is a dumbded down version
 of a production function that will be called during the parsing
 of a config file. Each time a line of the form:
 
  var = val
 
 is encounterd I do setattr(config, 'var', val)
 
 The problem is that doing it this way means config needs to be global.
 which I'm trying to avoid, in case some leftovers may cause trouble
 when I read in a new configuration or should I ever have different
 threads parsing files at the same time.
 
 The other way would be passing the 'config' variable around in the
 productions, but this would complicate things.
 
 So what I am trying to do was provide a global namespace to the call
 to fool a function using a global name into using a provided local name.


Maybe you could use a bound method?

class Cfg:
def assign(self):
setattr(self, 'Start' , [13, 26, 29, 34])

def foo():
config = Cfg()
namespace = dict(assign=config.assign)
exec assign() in namespace
print config.Start

Peter

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread skip

 ShirtSize = Enum('small', 'medium', 'large')
 AppleSize = Enum('small', 'large')

Ben What should be the result of this comparison::

 ShirtSize.small == AppleSize.small

False.  They are values from different objects.  Just make __eq__ map to
is.  I think you'll be fine.

Ben Or is it an error to even try comparing them?

As someone else pointed out containment tests become difficult with your
current formulation.

 Do any python builtins behave that way? How about anything in the
 python standard library?

Ben No to both; I believe this may be a defining property of
Ben enumerations. Am I wrong?

I think so. 0.5 wink.  I think you should be able to compare any two
objects.  I think the complex types give you a little wiggle room on the
size comparisons (, =, , =), but I think == and != really ought to work.

Skip

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


Re: access to preallocated block of memory?

2005-12-16 Thread Scott David Daniels

You might want to take a look at the Blocks and Views code I did,
take a look at it and see if you can either use it directly or use
it with any changes you feel like making.
 http://members.dsl-only.net/~daniels/Block.html
-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Python web framework is most like Ruby on Rails?

2005-12-16 Thread Ben Sizer
Mike Meyer wrote:
 Ben Sizer [EMAIL PROTECTED] writes:
  Flexibility is good, but personally I think the problem is that instead
  of useful variety, we have redundant overlap. How many different
  templating systems, sql--object mappings, and URL dispatch schemes do
  we need? And what exactly is the difference between them all, except
  for slightly different syntax?

 Well, they come in at least three major variants: complete publishing
 system (ake zope), templating system (aka psp), and modules (aka
 cgi). Each of these is focused on a different level of the problem,
 and hence is suitable for different things.

I see what you mean, but unfortunately I think there is a lot more
fuzziness than that. If the separate parts were clearly delineated
things would be a lot better. I look to the Database API Specification
as a great example of how this could (should?) be done, allowing for
easy interchangeability while still providing a well-documented
standard, and the opportunity to bundle a basic module with the
standard library without raising the difficulty level for those who
wish to use other frameworks. A PyWebForm API and a PyWebSession API
would be fairly easy to create, for example. Templating maybe less so,
but not much.

 Syntax can be very important, especially for templating
 systems. Typically, those are used in situations where you have a lot
 of X/HTML and want a bit of dynamic content. Ideally, you want to be
 able to treat this just like a static HTML page. If the syntax of a
 templating system makes your standard web tools puke, you probably
 want to avoid it.

I think templating syntax is very important, but with something like
Python I think the future is in modules like HTMLTemplate rather than
the ASP/PHP model. When you're working with a valid XML page in the
first place, all your tools should work adequately.

-- 
Ben Sizer

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


Re: How to use pydoc?

2005-12-16 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 import pydoc
 import sys
 sys.version
 '2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]'
 pydoc sys
 SyntaxError: invalid syntax

 
 The documentation for pydoc says:
 Run pydoc name to show documentation on something.
 
 What am I missing?

In the interpreter, just do

 help(sys)

or

 help(sys)

if you didn't already import the module.

What you tried is what you would do on the command line. I'm not sure it
works on windows, though, but

python -m pydoc sys

Should work on both windows and unix. 

Peter

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


Re: Parser or regex ?

2005-12-16 Thread Fuzzyman

Tim Arnold wrote:
 Fuzzyman [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  Hello all,
 
  I'm writing a module that takes user input as strings and (effectively)
  translates them to function calls with arguments and keyword
  arguments.to pass a list I use a sort of 'list constructor' - so the
  syntax looks a bit like :
 
checkname(arg1, arg 2, 'arg 3', keywarg=value,
  keywarg2='value2', default=list(val1, 'val2'))
 
  Worst case anyway :-)
 

 pyparsing is great, easy to configure and very powerful--I think it looks
 like a great tool for your inputs.


Thanks - I considered it. It's actually quite a small module (about
38k). I don't want to introduce a dependency on an external module.

All the best,

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

 http://pyparsing.sourceforge.net/
 
 
 --Tim

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


Invoking Unix commands from a Python app

2005-12-16 Thread Rob Cowie
Hi all,

An idea popped into my head recently for an app that would track how
much time a user spends in a particular piece of software (or at least,
for how long an application is open).

I'm assuming there is a way to do this via the command line and a unix
app, although I haven't yet invesitgated it.

My question is, can a command line application be invoked by a python
program? If so, how does one pass parameters to it and retrieve its
response?

Cheers and Merry Christmas,

Rob Cowie

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


Re: problem with os.spawnle(os.P_NOWAIT,'C:\info.exe')

2005-12-16 Thread muttu2244
Ya Thanks Fredrik,

i had overwritten the os in my code indeed, now its working fine.

thanks a lot for that
regards

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


SMP, GIL and Threads

2005-12-16 Thread catsup
Hi,

I have an app written under version Python 2.3.5.  The problem I'm
having is that it hangs on one of its threads.  The thread that hangs
does updates to a standard dictionary shared with another thread that
only reads this dictionary.  This app works beautifully on a single
processor boxes in my testing environment, but this problem quickly
occurs when the software runs on a dual cpu SMP blade server with
hyperthreading turned off, Windows 2003 server.

I do not bother using application level locks because I figure the GIL
is going to do the job for me, and because with one thread doing
updates and the other only reading, things remain consistent logically
for the app.  The app will not have a problem if the dictionary changes
just before it does a read.

I have searched this group on this subject and seen one warning against
sharing objects between threads.  I don't recall every writing a
threaded app that didn't share data between threads in some way.  I've
also seen a recomendation in this list against using threads at all
with Python.  I'm hoping that is an extreme view and not general wisdom
here.  Python has never failed me when analysis indicated that it would
be the correct tool for the job.

Thank you for your time and attention.

Randy

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


Re: Enumeration idioms: Values from different enumerations

2005-12-16 Thread Mike Meyer
Ben Finney [EMAIL PROTECTED] writes:
 Mike Meyer [EMAIL PROTECTED] writes:
 Peter Hansen [EMAIL PROTECTED] writes:
 That is, [perhaps] trying to compare enumerations that should not
 be compared *is* an error (raising an exception) *because* the
 whole point of enumerations is to avoid errors in such cases.
 Except it might not be an error. For instance, if I've got a list of
 enum objects taken from various types (say I've got one set of enums
 for days of the week, another for months of the year, and so on, and
 which I use depends on whether the user wants to select days of the
 week, months of the year, etc), it makes perfect sense to want to know
 if a specific enum value is in the list, and the obvious way to check
 it is with my_value in enum_list. That won't work if you raise an
 exception - it takes a relatively convoluted bit of code to make this
 test.
 What's being discussed here is what happens when comparing the *values*
 from the enumeration.

That's what I thought I was discussing, but apparently I wasn't clear
enough. Let me try again.

I think it's perfectly reasonable to store enum values from different
enums in a list, and check for a specific value being in that list. If
comparing two enum values can raise an exception, then doinng this
become problematic, as you may get an exception. According to what you
say below, this isn't true for any builtin type or any type in the
standard library.

 Python generally uses '==' to mean is the same value.  To do that,
 a simple true/false return is enough. In raising an exception,
 you're making '==' carry an extra meaning (I'm not sure *what* that
 is, though).
 The problem with is the same value as an explanation for '==' is
 that it doesn't help in cases such as::
  ShirtSize = Enum('small', 'medium', 'large')
  AppleSize = Enum('small', 'large')

Actually, it provides a very explicit guideline for these cases. The
guidelines is by no means obvious, as witness languages like LISP,
which have multiple equality operators.

 What should be the result of this comparison::
  ShirtSize.small == AppleSize.small
 Are they the same value? They're both small (and they both coerce
 to the same string value, and in this case the same integer value).

That depends on the semantics you want to place on the values of
enums. Reasonable arguments can be made for anything from they're
exactly like small integers to the values are an implementation
detail, and you shouldn't worry about them. That they coerce to the
same string is irreleevant, at least in python, which doesn't coerce
strings to

 Do any python builtins behave that way? How about anything in the
 python standard library?
 No to both; I believe this may be a defining property of
 enumerations. Am I wrong?

There are enum implementations that don't treat comparing enum values
from different enums as an error, so I'd say you're wrong. In Python's
case, comparing two objects for identity never raises an exception for
any type that comes with the language, so I'd say that that was a
defining property of python.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: Invoking Unix commands from a Python app

2005-12-16 Thread Sybren Stuvel
Rob Cowie enlightened us with:
 Ok, I know see that os.spawnl() will suffice. However, how do I
 retrieve the output of the command.

Apparently, os.spawnl() didn't suffice. Check out the popen2 module
and Popen* classes.

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


Re: Adding methods to instances

2005-12-16 Thread Dody Suria Wijaya
To avoid that:
- subclass Test first

class SubclassTest(T):
 pass

- assign the method to SubclassTest's attribute,

SubclassTest.dynamic = dynamic

- then assign the new class to magic variable __class__ :

t.__class__ = SubclassTest

t.dynamic()

Antoon Pardon wrote:
 But this will make the function a method to all instances of the class.
 Is that what you want? From your first post I had the impression you
 only wanted the function to be the method of one particular instance.
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Visual Python : finished ?

2005-12-16 Thread Bill
Do Re Mi chel La Si Do wrote:
 Hi!

 See :
  http://www.activeperl.com/Products/Visual_Perl/?mp=1
 
 
 @+
 
 MCI

Another closed source success story.

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


Re: Adding methods to instances

2005-12-16 Thread Ben Hutchings
Antoon Pardon [EMAIL PROTECTED] wrote:
 Op 2005-12-15, Ed Leafe schreef [EMAIL PROTECTED]:
 On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:

  So? Am I nuts? Or is this possible?

 Yes it is, use exec() to turn your string in valid Python code
 and bind the dynamic function as a method of class Test

 xx = def dynamic(self):
 print dynamic, self.testAtt
 

 exec xx

 class Test(object):
  testAtt = sample
  def normalMethod(self):
  print normal, self.testAtt

 t = Test()
 Test.dynamic = dynamic
 t.dynamic()

  Thanks! I knew I had done this before. My mistake was that I was  
 setting the exec'd code to the instance, and not to the class. That  
 works, but makes it a function, which doesn't automatically get sent  
 the 'self' reference.

 But this will make the function a method to all instances of the class.
 Is that what you want? From your first post I had the impression you
 only wanted the function to be the method of one particular instance.

How about:

def bind(fun, arg):
return lambda *a, **k: fun(arg, *a, **k)

t.dynamic = bind(dynamic, t)

-- 
Ben Hutchings
The world is coming to an end.  Please log off.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Invoking Unix commands from a Python app

2005-12-16 Thread Rob Cowie
Excellent... just the thing I was looking for. Thanks.

Does anyone know of a unix app that could be used to monitor the
duration of processes etc.? 

Would 'top' do the trick?

Rob C

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


Re: Parser or regex ?

2005-12-16 Thread Michael Spencer
Fuzzyman wrote:
 Hello all,
 
 I'm writing a module that takes user input as strings and (effectively)
 translates them to function calls with arguments and keyword
 arguments.to pass a list I use a sort of 'list constructor' - so the
 syntax looks a bit like :
 
checkname(arg1, arg 2, 'arg 3', keywarg=value,
 keywarg2='value2', default=list(val1, 'val2'))
 
 Worst case anyway :-)
 ...

Perhaps you could simply use Python's parser - the syntax appears to be 
Python's.

e.g., a very quick hack using eval, which is easier without the list call, so 
I'm cheating and replacing it with a list literal for now:
  
   source = checkname(arg1, arg 2, 'arg 3', keywarg=value,
  ... keywarg2='value2', default=[val1, 'val2'])
  

We need some way to ensure bare names don't cause NameErrors:
   class lazynames(dict):
  ... def __getitem__(self, key):
  ... if key in self:
  ... return dict.__getitem__(self, key)
  ... return %s % key # if name not found, return it as a str constant
  ...

  def checkname(*args, **kw):
  ... return args, kw
  ...
   d = lazynames(__builtins__ = None, checkname = checkname)
  

With this set up, you can parse in one line!
   eval(source, globals(), d)
  (('arg1', 'arg 2', 'arg 3'), {'default': ['val1', 'val2'], 'keywarg': 
'value', 
'keywarg2': 'value2'})
  

If you don't like the risks of eval, then compiler.parse gives a form of the 
parse output that is fairly easy to deal with

Cheers
Michael



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


Re: SVG rendering with Python

2005-12-16 Thread Chris Lambacher
On Fri, Dec 16, 2005 at 01:58:40PM +1100, richard wrote:
 Andreas Lobinger wrote:
  richard wrote:
  Dennis Benzinger wrote:
 Does anybody know of a SVG rendering library for Python?
  Google python svg
  
  ... to find what?
 
 The answer to the OP's question.

The OP's question is ambiguous.  Does he want to render something to SVG? or
does he want to render an existing SVG file to a raster format.  I would guess
the latter, apparently you think he means the former.  Luckily for the OP we
both posted an answer for what we thought he was asking so he will have an
answer either way :)

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


  1   2   3   >