Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
...
> Ideally, I'd like a whole series of projects where I'm walked through
> how to go about writing real Python. The way I look at it, nobody
> learnt to build a house just from reading about building materials!

Take a look at "Dive Into Python" from Mark Pilgrim, good examples with
comments.

http://diveintopython.org/

Its available as paper-print or as electronic reading.

A+

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread Ravi Teja
> Is this kind of cleverness what is usually known as "magic"?
> I suspect that this has something to do with it, but not completely
> sure...

:-). It must be. Now Django has a "magic removal branch".

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


Re: Zipping files/zipfile module

2006-08-02 Thread Simon Forman
Brian Beck wrote:
> OriginalBrownster wrote:
> > I want to zip all the files within a directory called "temp"
> > and have the zip archive saved in a directory with temp called ziptemp
> >
> > I was trying to read up on how to use the zipfile module python
> > provides, but I cannot seem to find adequate documentation on function
> > itself.
> >
> > Perhaps someone could help me in this task?
>
> Hello,
>
> This isn't completely tested, but perhaps it will help you get started:
>
> from os import listdir, mkdir
> from os.path import join, basename, isfile
> from zipfile import ZipFile
>
> def zip_dir(path, output_path, include_hidden=True):
> files = [join(path, f) for f in listdir(path) if isfile(join(path, f))]
> try:
> mkdir(output_path)
> except OSError, e:
> if e.errno == 17: # Path exists
> pass
> zip_file = ZipFile(join(output_path, 'temp.zip'), 'w')
> for f in files:
> if basename(f).startswith('.') and not include_hidden:
> continue
> print "Adding %s to archive..." % (f,)
> zip_file.write(f)
> zip_file.close()
>
> Use like:
> zip_dir('temp', 'temp/ziptemp')
>
> Note that if you want to add the entire contents of a directory
> (subdirectories, recursively), you should consider using os.walk or
> something similar. This will only add the file contents of the directory.
> I'm not sure if the zipfile module provides any nice ways to write
> directories to the archive, but I'm assuming it just involves writing an
> arcname with a '/' in it (see help(zipfile.ZipFile)).
>
> --
> Brian Beck
> Adventurer of the First Order

To avoid calling os.path.join() twice for each filename when you build
the list of files you could write the list comprehension like so:

[n for n in (join(path, f) for f in listdir(path)) if isfile(n)]

Also, you should use the "symbolic" errors from the errno module rather
than hard-coding a constant:

from errno import EEXIST
...
if e.errno == EEXIST: # Path exists

Finally, if your using a single arg with a string interpolation and you
know it'll never be a tuple you needn't wrap it in a tuple:

print "Adding %s to archive..." % f

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


Re: Finding the name of a class

2006-08-02 Thread Bruno Desthuilliers
Kirk Strauser wrote:
> Bruno Desthuilliers wrote:
> 
>> Kirk Strauser wrote:
> 
>> class foo(object):
>> pass
>>> how can I find its name, such as:
>>>
>> b = foo
> 
>> I suppose you mean b = foo() ?
> 
> Actually, I meant 'b = foo' in this case - I want to find the name of the
> class that b references, 

Ok. Could have been a typo, just wanted to make sure.


>> The name of a class is in the attribute '__name__' of the class. The
>> class of an object is in the attribute '__class__' of the object.
> 
> I swear that didn't work earlier.  Honest.  :-)

Not sure if it works for old-style classes...

> OK, now for the good stuff.  In the code below, how can I find the name of
> the class that 'bar' belongs to:
> 
 class Foo(object):
> ... def bar(self):
> ... pass
> ...
 b = Foo.bar
 dir(b)
> ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', 
> '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', 
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 
> 'im_self']

>>> b.im_class

>>> b.im_class.__name__
'Foo'
>>>


 b.__class__

This will give you the class of b itself. Remember that in Python,
everything and it's sister is an object - including functions, methods,
classes and modules.

In this case, b is a method object - IOW a descriptor that wraps a
function object.


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


Re: Strange Tkinter Grid behaviour Problem

2006-08-02 Thread H J van Rooyen

"Peter Otten" <[EMAIL PROTECTED]> wrote:
|H  J van Rooyen wrote:
|
| > Hi,
| >
| > Still struggling with my GUI exercise -
| >
| > I have the following lines of code in a routine that is bound at
| >  to an instance of Entry :
| >
| > self.disp.Amount_des = Label(self.disp, text = self.dis_string, fg
| > =
| > 'black', bg = 'yellow')
| > self.disp.Amount_des.grid(row = self.rownum, column=0, sticky =
| > 'nesw')
| >
| > self.disp.Amount = Label(self.disp, text = self.retstring, fg =
| > 'black',
| > bg = 'green')
| > self.disp.Amount.grid(row = self.rownum, column=1, sticky =
| > N+S+E+W)
| >
| > The second call to the grid method fails as follows:
| >
| > Exception in Tkinter callback
| > Traceback (most recent call last):
| >   File "E:\PYTHON24\lib\lib-tk\Tkinter.py", line 1345, in __call__
| > return self.func(*args)
| >   File "C:\WINDOWS\DESKTOP\Entry1.py", line 243, in entryend
| > self.disp.Amount.grid(row = self.rownum, column=1, sticky = N+S+E+W)
| > TypeError: cannot concatenate 'str' and 'instance' objects
| >
| > If I change the N+S+E+W to the 'nsew' form, it works no problem...
| >
| > Weird - at other places in the program the form:  sticky = N+S+E+W works
| > without a problem.
| > I found the 'nsew' form by trial and error...
| >
| > self.disp is a window different from the current one - it is used to
| > display a record entry as it is built up field by field. - the code
| > fragment above is what inserts the description of the entry and the
| > entered data in a row in the window used for displaying, when the user
| > hits the enter key.
| >
| > Is this a bug, or am I still doing something wrong?
|
| You have probably defined your own, say, E somewhere in your module:
|
| E = ... # whatever
|
| This can easily be fixed by using another name. But what you are really
| doing wrong is using the
|
| from Tkinter import *
|
| star-import which drastically increases the likelihood of such name clashes.
| I recommend using qualified names, abbreviated if you like:
|
| import Tkinter as tk
|
| ... tk.N + tk.S + tk.E + tk.W ... # a bit longer, but worth the effort
|
| Of course this could still go wrong if you do
|
| tk = 42
|
| somewhere in your module...
|
| Peter

Well spotted that man! the offending line was:

def entryend(self,S):
"""This gets done on carriage return"""

The 'S" is not actually used by me - it was added because the callback passes
Something back and I got an error earlier while I was still using pack...
*grin*

This also explains why it only happens here and not elsewhere...

Problem sorted - False alarm!

- Thanks

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


Re: BCD List to HEX List

2006-08-02 Thread H J van Rooyen

"John Machin" <[EMAIL PROTECTED]> wrote:

| [EMAIL PROTECTED] wrote:
|
| >My version assumes three subroutines: extracting
| > nibbles, shifting, and adding, Those are pretty simple, so I asked
| > if he needed them rather than presenting them.
| > Assuming we have
| > them, the algorithm is three lines long.
|
| Perhaps you could enlighten us by publishing (a) the spec for each of
| the get_nibble(s), shift, and add subroutines (b) the three-line
| algorithm (c) what the algorithm is intended to achieve ...
|
| >
| > He took a while to state the problem, but was clear from the start
| > that he had lists of digits rather than an integer datatype.
|
| Yes, input was a list [prototyping a byte array] of decimal digits. The
| OUTPUT was also a list of something. A few messages later, it became
| clear that the output desired was a list of hexadecimal digits. Until
| he revealed that the input was up to 24 decimal digits,  I was pursuing
| the notion that a solution involving converting decimal to binary (in a
| 32-bit long) then to hexadecimal was the way to go.
|
| What is apparently needed is an algorithm for converting a "large"
| number from a representation of one base-10 digit per storage unit to
| one of a base-16  digit per storage unit,  when the size of the number
| exceeds the size (8, 16, 32, etc bits) of the "registers" available. Is
| that what you have?
|
| Cheers,
| John

I actually read most of this thread as it happened and could not really figure
out what the OP was on about.

If the above is a true statement of the problem, then its more difficult to do
in a high level language, when the results exceed the native size that the
compiler or interpreter writers thought was a reasonable number of bits.

- ten to the 24 is of the order of 80 binary bits ...

So you need a (say) twelve byte result field for the binary... (thats three 32
bit values concatenated)
you clear the result field out to zero.
Then you feed in the decimal digits, from the most significant side, into a
routine that multiplies the result by ten and then adds the digit. (yes you have
to write this twelve byte Ascii/binary thing yourself)
When you have done this for all the digits, you have a binary number, and
getting hex from binary a nibble at a time is easy...

Well its easy in assembler, even on a cripple little 8 bit processor, anyway...
In python I would take a hard look at what I could do with the decimal module -
doing the reverse of the above but dividing by 16 repetitively and using the
remainder or the fraction to give the hex numbers in lsb to msb order, and doing
a lookup (prolly using a dict) to get the hex digits...

just my $0.02...

- Hendrik



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


Re: Finding the name of a class

2006-08-02 Thread Bruno Desthuilliers
Dennis Lee Bieber wrote:
> On Tue, 01 Aug 2006 11:09:57 -0500, Kirk Strauser <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>> Actually, I meant 'b = foo' in this case - I want to find the name of the
>> class that b references, but the name of an instance (which may have zero
>> or many references to it).
>>
>   Pardon... That gives the class object another name, neither of which
> has any precedence over the other.

Not quite exactly. The 'b = foo' statement binds together name b and the
object foo - which in this case happens to be a class. OTOH, class
objects do have a __name__ attribute, which is not impacted by the binding.

> b = Foo.bar
> dir(b)
>> ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', 
>> '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', 
>> '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 
>> 'im_func', 'im_self']
> b.__class__
>> 
> b.__class__.__name__
>> 'instancemethod'
>>
>> I was sort of hoping that it would print 'Foo'.
> 
>   But... you've just pulled the method "out" of the class
> definition... Without supplying an instance, there is no linkage to a
> class.

Yes there is. Method objects have an im_class attribute, that is a
reference to the class they were 'pulled out' from.


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


Re: Finding the name of a class

2006-08-02 Thread Bruno Desthuilliers
Larry Bates wrote:
> Kirk Strauser wrote:
>> Given a class:
>>
> class foo(object):
> pass
>> how can I find its name, such as:
>>
> b = foo
> print something(b)
>> 'foo'
>>
>> I'm writing a trace() decorator for the sake of practice, and am trying to
>> print the name of the class that a traced method belongs to.  This seems
>> like it should be easy, but I think I've been staring at the problem too
>> long.
> 
> print print b.__class__.__name__  gives what you want

Actually it should be b.__name__, since b refers to *class* foo.
b.__class__ is the metaclass (usually 'type' unless there's a custom
metaclass).



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


Re: Hierarchical unit tests

2006-08-02 Thread Peter Otten
Pupeno wrote:

> Having A(unittest.TestCase) and B(A), the unittests framework seems not to
> run A's test when testing B, right ?

Wrong:

$ cat hierarchical_tests.py
import unittest

class A(unittest.TestCase):
def test_a(self):
pass

class B(A):
def test_b(self):
pass

if __name__ == "__main__":
unittest.main()
$ python hierarchical_tests.py -v
test_a (__main__.A) ... ok
test_a (__main__.B) ... ok
test_b (__main__.B) ... ok

--
Ran 3 tests in 0.001s

OK

Peter

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


Re: cleaner way to write this try/except statement?

2006-08-02 Thread Peter Otten
John Salerno wrote:

> The code to look at is the try statement in the NumbersValidator class,
> just a few lines down. Is this a clean way to write it? i.e. is it okay
> to have all those return statements? Is this a good use of try? Etc.
> 
> Thanks.
> 
> 
> 
> import wx
> 
> 
> class NumbersValidator(wx.PyValidator):
> 
>  def __init__(self):
>  wx.PyValidator.__init__(self)
> 
>  def Clone(self):
>  return NumbersValidator()
> 
>  def Validate(self, parent):
>  text_ctrl = self.GetWindow()
>  text = text_ctrl.GetValue()
> 
>  try:
>  if not text or int(text) <= 0:
>  wx.MessageBox('Enter a valid time.', 'Invalid time
> 
>entered', wx.OK | wx.ICON_ERROR)
>  return False
>  else:
>  return True
>  except ValueError, error:
>  wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>wx.OK | wx.ICON_ERROR)
>  return False
> 
>  def TransferToWindow(self):
>  return True
> 
>  def TransferFromWindow(self):
>  return True

Here's how I might do it:

def is_positive_int_str(s):
try:
value = int(s)
except ValueError:
return False
return value > 0

class PositiveIntegerValidator(wx.PyValidator):
# ...
def Validate(self, parent):
text = self.GetWindow().GetValue()
if is_positive_int_str(text):
return True
wx.MessageBox(...)
return False

Two usability notes:
- "Invalid time entered" is a confusing message when you actually want a
positive integer.
- Pop-up messages are a major annoyance. An alternative would be to change
the text color of the control and show a hint as to what input you expect
in a status bar.

Peter

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi all. I've been try to learn ruby for a few months but I'm about
> ready to give up. The available books either assume a programming
> background, or are out of date. Anyway, I think python may suit me more
> due to its 'theres one way to do it' philosophy (hope the quote is
> right)! 

Actually it's :
"There should be one-- and preferably only one --obvious way to do it."

And FWIW, it's followed by:
"Although that way may not be obvious at first unless you're Dutch."

!-)

NB : launch your Python interactive shell and type:

 import this

to get the whole thing.


> Another quote that I liked was:
> 
>  'Clever is not considered a compliment in Python.' (don't know where I
> read that...)

I don't remember having read this, but it probably refers to Brian
Kernighan:
"Debugging is twice as hard as writing the code in the first place.
 Therefore, if you write the code as cleverly as possible, you are,
 by definition, not smart enough to debug it."


> In Ruby, there are many ways to do the same thing and cleverness seems
> to be held in high regard. These attitudes are not too helpful for
> beginners in my experience. Anyway, enough waffle.
> 
> What books and tutorials are recommended to learn Python? 

There are some recommandations on python.org:
http://wiki.python.org/moin/PythonBooks
http://www.python.org/doc/intros/

Mark Lutz's "Programming Python" was a mostly good intermediate book,
but it's a bit outdated now.

> The tutorial
> that comes with Python is great and has given me a good overview but I
> think I'd benefit from some programming projects, now I have a little
> understanding of how Python works.
> 
> Ideally, I'd like a whole series of projects where I'm walked through
> how to go about writing real Python. The way I look at it, nobody
> learnt to build a house just from reading about building materials!

Indeed. But you don't necessarily need to follow a tutorial for this -
just think of some programs you'd like to write, and try to write them.
You can ask for help and submit (at least parts of) your work for review
here. FWIW, examples in books and tutorials are usually meant to help
you graps some points, features, idioms and gotchas, and are seldom as
complex and complete as "real" programs.

> Any other tips for getting up to speed with Python fairly quickly will
> be greatly appreciated.

Lurking here may be a good idea...

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


Re: BCD List to HEX List

2006-08-02 Thread bryanjugglercryptographer

John Machin wrote:
> [EMAIL PROTECTED] wrote:
> > "For each nibble n of x" means to take each 4 bit piece of the BCD
> > integer as a value from zero to sixteen (though only 0 through 9
> > will appear), from most significant to least significant.

> The OP's input, unvaryingly through the whole thread, even surviving to
> his Javacard implementation of add() etc, is a list/array of decimal
> digits (0 <= value <= 9). Extracting a nibble is so simple that
> mentioning a "subroutine" might make the gentle reader wonder whether
> there was something deeper that they had missed.

Yes, it's simple; that was the point. The most complex routine I
assumed is integer addition, and it's not really hard. I'll
present an example below.

> > "Adding"
> > integers and "shifting" binary integers is well-defined
> > terminology.
>
> Yes, but it's the *representation* of those integers that's been the
> problem throughout.

Right. To solve that problem, I give the high-level algorithm and
deal with the representation in the shift and add procedures.

> > I already posted the three-line algorithm. It
> > appeared immediately under the phrase "To turn BCD x to binary
> > integer y," and that is what it is intended to achieve.
>
> Oh, that "algorithm". The good ol' num = num * base + digit is an
> "algorithm"???

You lost me. The algorithm I presented didn't use a multiply
operator. It could have, and of course it would still be an
algorithm.

> The problem with that is that the OP has always maintained that he has
> no facility for handling a binary integer ("num") longer than 16 bits
> -- no 32-bit long, no bignum package that didn't need "long", ...

No problem. Here's an example of an add procedure he might use in
C. It adds modestly-large integers, as base-256 big-endian
sequences of bytes. It doesn't need an int any larger than 8 bits.
Untested:

typedef unsigned char uint8;
#define SIZEOF_BIGINT 16

uint8 add(uint8* result, const uint8* a, const uint8* b)
/* Set result to a+b, returning carry out of MSB. */
{
uint8 carry = 0;
unsigned int i = SIZEOF_BIGINT;
while (i > 0) {
--i;
result[i] = (a[i] + b[i] + carry) & 0xFF;
carry = carry ? result[i] <= a[i] : result[i] < a[i];
}
return carry;
}

> Where I come from, a "normal binary integer" is base 2. It can be
> broken up into chunks of any size greater than 1 bit, but practically
> according to the wordsize of the CPU: 8, 16, 32, 64, ... bits. Since
> when is base 256 "normal" and in what sense of normal?

All the popular CPU's address storage in byte. In C all variable
sizes are in units of char/unsigned char, and unsigned char must
hold zero through 255.

> The OP maintained the line that he has no facility for handling a
> base-256 number longer than 2 base-256 digits.

So he'll have to build what's needed. That's why I showed the
problem broken down to shifts and adds; they're easy to build.

> The dialogue between Dennis and the OP wasn't the epitome of clarity:

Well, I found Dennis clear.

[...]
> I was merely wondering whether you did in fact
> have a method of converting from base b1 (e.g. 10) to base b2 (e.g. 16)
> without assembling the number in some much larger base  b3 (e.g. 256).

I'm not sure what that means.


-- 
--Bryan

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


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

2006-08-02 Thread david_wahler
I'll be out of the office until approximately August 20th. If you have any 
questions, please email [EMAIL PROTECTED]

-- David Wahler


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


Re: Reinstalling Python Problem (Newbie)

2006-08-02 Thread Avell Diroll
beno wrote:
> I intend to do that. However, I think this is the RIGHT list to ask 
> questions pertinent to python...

I didn't intend to be abrupt, ... I was just in an hurry, sorry for 
that. Anyway I still see this problem more as a program not compiling 
correctly on Freebsd than python not compiling correctly on a platform 
... everybody has his own point of view :-)

Anyway I don't have any freebsd box around any more, so there is no way 
for me to reproduce your problem (hence my remark about the place to post).

Another thing, if you just want to use zope, it seems to be included in 
freebsd ports ... so you should not need to compile anything to _run_ 
zope on your system, but maybe you need specific options not included in 
the ports (this is only fully supported on freebsd-stable and 
freebsd-current which are AFAIK respectively 6.1 and 7.).
Ref.:
http://www.freebsd.org/ports/zope.html
http://www.freebsd.org/ports/lang.html#python-2.4.3

Zope is not supported in 5.5 anymore but it is present in the ports archive.
ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/5.5-RELEASE/ports/

To get back to your specific problem :

> 2 tests failed:
>test_mimetools test_urllib2
> 48 tests skipped:
>test_aepack test_al test_applesingle test_asynchat test_bsddb
>test_bsddb3 test_cd test_cl test_codecmaps_cn test_codecmaps_hk
>test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses
>test_doctest test_fork1 test_gdbm test_gl test_imgfile test_imp
>test_linuxaudiodev test_logging test_macfs test_macostools
>test_nis test_normalization test_ossaudiodev test_pep277
>test_plistlib test_queue test_scriptpackages test_socket
>test_socket_ssl test_socketserver test_sunaudiodev test_tcl
>test_thread test_threaded_import test_threadedtempfile
>test_threading test_threading_local test_threadsignals
>test_timeout test_unicode_file test_urllib2net test_urllibnet
>test_winreg test_winsound
> 13 skips unexpected on freebsd5:
>test_threadedtempfile test_imp test_threaded_import test_fork1
>test_threading test_threadsignals test_socket test_thread
>test_queue test_asynchat test_doctest test_threading_local
>test_logging
> *** Error code 1
> 
> What do I do about the problems with mimetools and urllib2?

This is the last report of the 'make test' command and there should be a 
few lines before that stating each test one by one and printing problems 
has they appear, and sometime pointing at a possible source for the 
specific problem. Have you got such a report for test_urllib2 ?

> What is meant by pointing to this folder thus (as the installation 
> instructions instruct):
> ./configure --prefix=/usr/python

The autotools (configure/make/make install) default installation 
directory is /usr/local by using the prefix option, you are indicating 
that you want to install all the python files in /usr/python when you 
will execute the command 'make install' (instead of /usr/local). I don't 
know which installation instructions you are following, but FWIK this is 
not  a standard place for python to be installed (although it is 
recommended in the README for the AtheOS platform ...).

> BTW, the modpython site is down!

It was up when I sent my first mail, and it is up as I send this one.
http://www.modpython.org/

> TIA,
> beno
> 

As I stated before I don't have any freebsd box to play with ...
HTH

Regards

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


Re: how to stop python

2006-08-02 Thread Laurent Pointal
victor a écrit :
> or if u want explicit exit of program then use:
> 
> import sys
> sys.exit(1)
> 
> or
> 
> raise SystemExit, 'message'

There is also the (not recommanded - see docs, but it exists)
os._exit(n)  function.

A+

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


Re: Using Python for my web site

2006-08-02 Thread Cliff Wells
On Tue, 2006-08-01 at 23:26 -0300, Gerhard Fiedler wrote:

> Or is there something in PostgreSQL that makes its users acidic? :)

Well, ACID is popular in PostgreSQL circles.

Cliff
-- 

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread jitya
[EMAIL PROTECTED] wrote:

> Hi all. I've been try to learn ruby for a few months but I'm about
> ready to give up.

Perfection is achieved only on the point of collapse. -- C.N. Parkinson


Welcome to Python , apart from the tutorials whenever time permits do
read this articles .

Why Python :http://www.linuxjournal.com/article/3882
The Python Paradox :http://www.paulgraham.com/pypar.html
Why I Promote Python : http://www.prescod.net/python/why.html

Regards
Jitendra Nair
Ensim India Pvt Ltd ,
Pune , India



 The available books either assume a programming
> background, or are out of date. Anyway, I think python may suit me more
> due to its 'theres one way to do it' philosophy (hope the quote is
> right)! Another quote that I liked was:
>
>  'Clever is not considered a compliment in Python.' (don't know where I
> read that...)
>
> In Ruby, there are many ways to do the same thing and cleverness seems
> to be held in high regard. These attitudes are not too helpful for
> beginners in my experience. Anyway, enough waffle.
>
> What books and tutorials are recommended to learn Python? The tutorial
> that comes with Python is great and has given me a good overview but I
> think I'd benefit from some programming projects, now I have a little
> understanding of how Python works.
>
> Ideally, I'd like a whole series of projects where I'm walked through
> how to go about writing real Python. The way I look at it, nobody
> learnt to build a house just from reading about building materials!
>
> Any other tips for getting up to speed with Python fairly quickly will
> be greatly appreciated.
> 
> If anyone can help, thanks very much

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread Bruno Desthuilliers
Luis M. González wrote:
> Delaney, Timothy (Tim) wrote:
(snip)
>> "Clever" in this context generally means using a trick/hack that is
>> non-obvious (often even after you understand it). "Cleverness" often
>> leads to difficult-to-understand code, which is contrary to the "python
>> philosophy".
>>
>> There are occasionally times when cleverness is useful, but in those
>> cases it should always be commented explaining exactly what it is doing,
>> and why a non-clever solution was not used. Most of the time there's
>> still a better non-clever way to do it, but the coder is not clever
>> enough to find it ;)
>>
> 
> Is this kind of cleverness 

Which one ?-)

> what is usually known as "magic"?
> I suspect that this has something to do with it, but not completely
> sure...

Python's "magic" is mostly about using the more advanced features of the
language (closures, special '__magic__' methods, descriptors,
metaclasses) and take full advantage of Python's object model and
dynamicity to reduce boilerplate and factor out repetition. All this
surely requires a good understanding of Python's object model - and may
look somewhat "magic" to newcomers -, but no particular "cleverness".

The key here is not to use these features for the sake of using them,
but only if and when it really simplifies the rest of the code by
factoring out the existing complexity.

The unpythonic "cleverness" is mostly about trying to stuff as much
operations as possible in a single expression. Which doesn't change
anything to the complexity of the code but makes the whole thing much
more difficult to understand - so it actually *adds* a level of complexity.

You can take a look at my sig for an example of unpythonic 'cleverness':

print '@'.join(['.'.join([w[::-1] \
for w in p.split('.')]) \
for p in '[EMAIL PROTECTED]'.split('@')])


How much time do you need to understand what happens here ? Way too much
anyway. Now look at the dumbiest way to write the same thing:

parts = '[EMAIL PROTECTED]'.split('@')
reversed_parts = []

for part in parts:
  words = part.split('.')
  reversed_words = []

  for word in words:
  # word[::-1] reverse the word,
  # ie "abc"[::-1] == "cba".
  reversed_words.append(word[::-1])

  reversed_parts.append('.'.join(reversed_words))

reversed_sig = "@".join(reversed_parts)
print reversed_sig

It's perhaps a bit longer, perhaps less 'elegant' (for a somewhat
perlish definition of 'elegance'), certainly less "clever", but at least
it's something that doesn't requires any special attention to understand
- except perhaps for the extended slice stuff, but it's explained by a
comment.


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


Re: Need a compelling argument to use Django instead of Rails

2006-08-02 Thread Ben Sizer
Vincent Delporte wrote:
> On 31 Jul 2006 07:05:27 -0700, "Ben Sizer" <[EMAIL PROTECTED]> wrote:
> >Typically you run PHP as a module in your webserver, so there should be
> >no process startup overhead. mod_python provides the same sort of
> >functionality for Python, but is not as popular or widely installed as
> >the PHP Apache module.
>
> So, if mod_python provides the same functionality, it's not the main
> reason why Python developers use application servers while PHP users
> still program with page codes in /htdocs.
>
> Why do PHP users stick to that old way of things? Because they mostly
> use shared hosts, with no way to install their application server?

Yes, one reason is because they can't install anything other than web
pages. Not only can they not install a Python application server, they
can't install mod_python either, and few places will have it
pre-installed. Shared hosting accounts for a massive number of sites so
this is a significant issue.

Another perfectly good reason is that PHP pages are much simpler to
deploy than any given Python application server. Just add the code into
your HTML pages as required and you're done. Python could come close to
this if something like the Python Server Pages implementation in
mod_python was to become widely available and well known, but that
still requires overcoming the first problem.

-- 
Ben Sizer

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


Behavior on non definded name in Cheetah

2006-08-02 Thread Paolo Pantaleo
[I hope I am posting to the right place]

I have a cheetah template something like this:

x is: $x
y is: $y
z is: $z

[Actually more complicated]

If for example $y is not defined I get an exception and  the parsing
of the template stops. Is  there any way to substitute $y with an emty
string and making cheeta going on with parsing?

Thnx
PAolo

-- 
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior on non definded name in Cheetah

2006-08-02 Thread Stephan Diehl
Paolo Pantaleo wrote:
> [I hope I am posting to the right place]
> 
> I have a cheetah template something like this:
> 
> x is: $x
> y is: $y
> z is: $z
> 
> [Actually more complicated]
> 
> If for example $y is not defined I get an exception and  the parsing
> of the template stops. Is  there any way to substitute $y with an emty
> string and making cheeta going on with parsing?
> 
> Thnx
> PAolo
> 

http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Attribute protection the 2nd

2006-08-02 Thread Kay Schluehr
A new recipe for attribute protection which is aligned with Pythons
convention of privacy indication using underscore name mangling.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496930

Regards,
Kay

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


Re: Zipping files/zipfile module

2006-08-02 Thread Yves Lange
Simon Forman a écrit :
> Brian Beck wrote:
>> OriginalBrownster wrote:
>>> I want to zip all the files within a directory called "temp"
>>> and have the zip archive saved in a directory with temp called ziptemp
>>>
>>> I was trying to read up on how to use the zipfile module python
>>> provides, but I cannot seem to find adequate documentation on function
>>> itself.
>>>
>>> Perhaps someone could help me in this task?
>> Hello,
>>
>> This isn't completely tested, but perhaps it will help you get started:
>>
>> from os import listdir, mkdir
>> from os.path import join, basename, isfile
>> from zipfile import ZipFile
>>
>> def zip_dir(path, output_path, include_hidden=True):
>> files = [join(path, f) for f in listdir(path) if isfile(join(path, f))]
>> try:
>> mkdir(output_path)
>> except OSError, e:
>> if e.errno == 17: # Path exists
>> pass
>> zip_file = ZipFile(join(output_path, 'temp.zip'), 'w')
>> for f in files:
>> if basename(f).startswith('.') and not include_hidden:
>> continue
>> print "Adding %s to archive..." % (f,)
>> zip_file.write(f)
>> zip_file.close()
>>
>> Use like:
>> zip_dir('temp', 'temp/ziptemp')
>>
>> Note that if you want to add the entire contents of a directory
>> (subdirectories, recursively), you should consider using os.walk or
>> something similar. This will only add the file contents of the directory.
>> I'm not sure if the zipfile module provides any nice ways to write
>> directories to the archive, but I'm assuming it just involves writing an
>> arcname with a '/' in it (see help(zipfile.ZipFile)).
>>
>> --
>> Brian Beck
>> Adventurer of the First Order
> 
> To avoid calling os.path.join() twice for each filename when you build
> the list of files you could write the list comprehension like so:
> 
> [n for n in (join(path, f) for f in listdir(path)) if isfile(n)]
> 
> Also, you should use the "symbolic" errors from the errno module rather
> than hard-coding a constant:
> 
> from errno import EEXIST
> ...
> if e.errno == EEXIST: # Path exists
> 
> Finally, if your using a single arg with a string interpolation and you
> know it'll never be a tuple you needn't wrap it in a tuple:
> 
> print "Adding %s to archive..." % f
> 
Other solutions:
you can try the rar command line from WinRar but it's not recommended. 
This is a very slow manner to compress file. Or you can try the Bz 
module of python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior on non definded name in Cheetah

2006-08-02 Thread Paolo Pantaleo
2006/8/2, Stephan Diehl <[EMAIL PROTECTED]>:
> Paolo Pantaleo wrote:
> > [I hope I am posting to the right place]
> >
> > I have a cheetah template something like this:
> >
> > x is: $x
> > y is: $y
> > z is: $z
> >
> > [Actually more complicated]
> >
> > If for example $y is not defined I get an exception and  the parsing
> > of the template stops. Is  there any way to substitute $y with an emty
> > string and making cheeta going on with parsing?
> >
> > Thnx
> > PAolo
> >
>
> http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Actually I wanted to keep things simple for who writes the template,
so I am using this workaround: I define a class

class ClassMapper:
def __init__(self,dict={}):
self.__dict=dict
def getValue(self,str):
try:
return self.__dict[str]
except KeyError:
return ""

x=ClassMapper(dict)
Template(definition, searchList=[{"info":x.getValue}])



so the user should do

$info("name")

Maybe I could define a class that implements a dictionary and doesn''t
raise an exception for a key not present... but it seems to
complicated.

PAolo

-- 
if you have a minute to spend please visit my photogrphy site:
http://mypic.co.nr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior on non definded name in Cheetah

2006-08-02 Thread Peter Otten
Paolo Pantaleo wrote:

> 2006/8/2, Stephan Diehl <[EMAIL PROTECTED]>:
>> Paolo Pantaleo wrote:
>> > [I hope I am posting to the right place]
>> >
>> > I have a cheetah template something like this:
>> >
>> > x is: $x
>> > y is: $y
>> > z is: $z
>> >
>> > [Actually more complicated]
>> >
>> > If for example $y is not defined I get an exception and  the parsing
>> > of the template stops. Is  there any way to substitute $y with an emty
>> > string and making cheeta going on with parsing?
>> >
>> > Thnx
>> > PAolo
>> >
>>
>>
http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> Actually I wanted to keep things simple for who writes the template,
> so I am using this workaround: I define a class
> 
> class ClassMapper:
> def __init__(self,dict={}):
> self.__dict=dict
> def getValue(self,str):
> try:
> return self.__dict[str]
> except KeyError:
> return ""
> 
> x=ClassMapper(dict)
> Template(definition, searchList=[{"info":x.getValue}])
> 
> 
> 
> so the user should do
> 
> $info("name")
> 
> Maybe I could define a class that implements a dictionary and doesn''t
> raise an exception for a key not present... but it seems to
> complicated.

You mean something like

from Cheetah.Template import Template

class Dict(dict):
def __getitem__(self, key):
return self.get(key, "")

template = """\
x is $x
y is $y
z is $z
"""
print Template(template, searchList=[Dict(x="x", y="y")])

You can also make a debugging version:

class Dict(dict):
def __getitem__(self, key):
return self.get(key, "#missing key: %r#" % key)

Peter

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


Datetime objects

2006-08-02 Thread Lad
How can I find days and minutes difference between two datetime
objects?
For example If I  have
b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)

Thank you for help
L.

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


Re: Datetime objects

2006-08-02 Thread Diez B. Roggisch
Lad wrote:

> How can I find days and minutes difference between two datetime
> objects?
> For example If I  have
> b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
> a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)

a - b

Lookup datetime.timedelta - all of this is neatly documented.

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


Class definition within function

2006-08-02 Thread Tomi Lindberg
Hi,

With the following function definition, is it possible to 
create an instance of class C outside the function f (and if 
it is, how)? And yes, I think this is one of those times 
when the real question is why :)

 >>> def f():
class C(object):
def __init__(self):
self.a = 'a'
return C()

 >>> x = f()
 >>> x.a
'a'
 >>> y=f.C()

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 y=f.C()
AttributeError: 'function' object has no attribute 'C'
 >>>

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


Re: Class definition within function

2006-08-02 Thread Diez B. Roggisch
Tomi Lindberg wrote:

> Hi,
> 
> With the following function definition, is it possible to
> create an instance of class C outside the function f (and if
> it is, how)? And yes, I think this is one of those times
> when the real question is why :)
> 
>  >>> def f():
> class C(object):
> def __init__(self):
> self.a = 'a'
> return C()
> 
>  >>> x = f()
>  >>> x.a
> 'a'
>  >>> y=f.C()
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  y=f.C()
> AttributeError: 'function' object has no attribute 'C'

No, its not. Only inside of it. And the question really is: why? If you need
a class that can be instantiated regardless of the execution of f, make it
a globally visible class. If it depends on something f computes, make it a
function-local one (if you like)

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


Re: Reinstalling Python Problem (Newbie)

2006-08-02 Thread Avell Diroll
beno wrote:
> Avell Diroll wrote:
>> beno wrote:
>>  

*** tidying a little ***

>>>
>>> What do I do about the problems with mimetools and urllib2?
>>> 
>>
>> This is the last report of the 'make test' command and there should be
>> a few lines before that stating each test one by one and printing
>> problems has they appear, and sometime pointing at a possible source
>> for the specific problem. Have you got such a report for test_urllib2 ?
>>   
> Here it is for both:
> 
> test_mimetools
> test test_mimetools failed -- Traceback (most recent call last):
>  File "/usr/local/zope/py243/Lib/test/test_mimetools.py", line 30, in
> test_boundary
>nb = mimetools.choose_boundary()
>  File "/usr/local/zope/py243/Lib/mimetools.py", line 130, in
> choose_boundary
>hostid = socket.gethostbyname(socket.gethostname())
> gaierror: (8, 'hostname nor servname provided, or not known')
> 
> 
> test_urllib2
> test test_urllib2 failed -- Traceback (most recent call last):
>  File "/usr/local/zope/py243/Lib/test/test_urllib2.py", line 352, in
> test_file
>for url in [
> gaierror: (8, 'hostname nor servname provided, or not known')
> 
> Looks like the same error ;) So, where am I supposed to provide this
> servname?
> 
>>  

*** tidying a little ***

This gethostname() problem in the test suite looks like an old problem.

I believe your problem is related to what Anthony Baxter and Guido van
Rossum where discussing back in 2004 on the python-dev mailing list :
http://mail.python.org/pipermail/python-dev/2003-November/040501.html

To put things short the test suite might fail on any test using
socket.gethostname() on a machine where /etc/hostname and /etc/hosts are
not matching.
If that is the case for your machine, the problem is coming from the
test suite, not your python build.

regards,

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


Re: Class definition within function

2006-08-02 Thread Kay Schluehr

Tomi Lindberg wrote:
> Hi,
>
> With the following function definition, is it possible to
> create an instance of class C outside the function f (and if
> it is, how)?

def f():
class C(object):
def __init__(self):
self.a = 'a'
f.C = C
return C()

>>> f.C


> And yes, I think this is one of those times
> when the real question is why :)

Definitely ;)

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


Re: Class definition within function

2006-08-02 Thread Tomi Lindberg
Diez B. Roggisch wrote:

> No, its not. Only inside of it. And the question really is: why?

Thanks. And no need to worry, the question was intended as 
fully theoretical.

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


Re: Class definition within function

2006-08-02 Thread Peter Otten
Tomi Lindberg wrote:

> With the following function definition, is it possible to 
> create an instance of class C outside the function f (and if 
> it is, how)? And yes, I think this is one of those times 
> when the real question is why :)
> 
>  >>> def f():
> class C(object):
> def __init__(self):
> self.a = 'a'
> return C()
> 
>  >>> x = f()
>  >>> x.a
> 'a'

y = type(x)()

By the way you get an instance of a different class C every time you call f,
so that

isinstance(f(), type(f())

is False.

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


Re: Datetime objects

2006-08-02 Thread Lad

Sybren Stuvel wrote:
> Lad enlightened us with:
> > How can I find days and minutes difference between two datetime
> > objects?
> > For example If I  have
> > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
> > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)
>
> diff = b - a

Ok, I tried

>>> diff=b-a
>>> diff
datetime.timedelta(0, 52662, 922000)
>>> diff.min
datetime.timedelta(-9)


which is not good for me.

So I tried to use toordinal like this
diff=b.toordinal()-a.toordinal()

but I get 
diff=1

Why?
where do I make a mistake?
Thank you for help

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


Re: Class definition within function

2006-08-02 Thread Duncan Booth
Tomi Lindberg wrote:

> With the following function definition, is it possible to 
> create an instance of class C outside the function f (and if 
> it is, how)? And yes, I think this is one of those times 
> when the real question is why :)
> 
> >>> def f():
>  class C(object):
>   def __init__(self):
>self.a = 'a'
>  return C()
> 
> >>> x = f()
> >>> x.a
> 'a'
> >>> y=f.C()
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  y=f.C()
> AttributeError: 'function' object has no attribute 'C'
> >>>
> 

Well, you could use 'type(x)()', or object.__subclasses__() will include C 
for as long as the class actually exists. Choosing the correct C from 
object's subclasses could prove somewhat tricky though: remember you'll get 
a new C class every time you call 'f'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Datetime objects

2006-08-02 Thread Rama
I am a newcomer to python - so not too sure if this method is the correct one.
 
Noticing this,
 
>>> dir(diff)['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__',
 '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__str__', '__sub__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds']

 
it seems 
 
>>> diff.seconds52662
 
should give you what you want. Converting the seconds to hours, minutes, seconds should be easy.
 
Of course, looking at help(diff), I get the impression that in the generic case you should check if diff.days == 0 to decide if you should be usingthat as well.
 
thank,
Rama
 
On 2 Aug 2006 05:16:08 -0700, Lad <[EMAIL PROTECTED]> wrote:
Sybren Stuvel wrote:> Lad enlightened us with:> > How can I find days and minutes difference between two datetime
> > objects?> > For example If I  have> > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)> > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)>> diff = b - a
Ok, I tried>>> diff=b-a>>> diffdatetime.timedelta(0, 52662, 922000)>>> diff.mindatetime.timedelta(-9)which is not good for me.So I tried to use toordinal like this
diff=b.toordinal()-a.toordinal()but I getdiff=1Why?where do I make a mistake?Thank you for help--http://mail.python.org/mailman/listinfo/python-list

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

Re: Class definition within function

2006-08-02 Thread Tomi Lindberg
Peter Otten wrote:

> By the way you get an instance of a different class C every time you call f,
> so that
> 
> isinstance(f(), type(f())
> 
> is False.

That I didn't know. Well, that theory won't be seeing much 
practice I guess.

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


Re: python under earthlink hosting?

2006-08-02 Thread Martin P. Hellwig
mbstevens wrote:
> I keep chatting with the tech support people at Earthlink, asking where
> the location of the Python interpreter is.  They don't seem to know where
> it is.  They don't know if Python is running on my server, either.  I know
> Perl is at /usr/local/bin/perl ...but when I use a similar address for
> Python I get a 500 internal server error.
> 
> Has anyone succeeded in getting Python CGI scripts running on an earthlink
> hosted site?
> 
> 
Maybe they didn't symlink it, try /usr/local/bin/python2.4

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


Re: Need a compelling argument to use Django instead of Rails

2006-08-02 Thread Paul Rubin
"Ben Sizer" <[EMAIL PROTECTED]> writes:
> Another perfectly good reason is that PHP pages are much simpler to
> deploy than any given Python application server. Just add the code into
> your HTML pages as required and you're done. Python could come close to
> this if something like the Python Server Pages implementation in
> mod_python was to become widely available and well known, but that
> still requires overcoming the first problem.

I didn't realize you could do shared hosting with mod_python, because
of the lack of security barriers between Python objects (i.e. someone
else's application could reach into yours).  You really need a
separate interpreter per user.  A typical shared hosting place might
support 1000's of users with ONE apache/php instance (running in a
whole bunch of threads or processes, to be sure).  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class definition within function

2006-08-02 Thread Diez B. Roggisch
Kay Schluehr wrote:

> 
> Tomi Lindberg wrote:
>> Hi,
>>
>> With the following function definition, is it possible to
>> create an instance of class C outside the function f (and if
>> it is, how)?
> 
> def f():
> class C(object):
> def __init__(self):
> self.a = 'a'
> f.C = C
> return C()
> 
 f.C
> 

Not working, unless f has been called at least once. But what I didn't know
(and always wondered) if the classdefinition inside a function can use the
outer scope - and apparently, it can! Cool.


def f(baseclass):
class C(baseclass):
def __init__(self):
self.a = 'a'
f.C = C
def foo(self):
print baseclass
return C()

c = f(object)
print f.C

c.foo()


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


Re: Datetime objects

2006-08-02 Thread John Machin

Lad wrote:
> Sybren Stuvel wrote:
> > Lad enlightened us with:
> > > How can I find days and minutes difference between two datetime
> > > objects?
> > > For example If I  have
> > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
> > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)
> >
> > diff = b - a
>
> Ok, I tried
>
> >>> diff=b-a
> >>> diff
> datetime.timedelta(0, 52662, 922000)
> >>> diff.min
> datetime.timedelta(-9)

Reread the manual:

1. "min" is minIMUM, not minUTES

2. You need:
>>> diff.days
0
>>> diff.seconds
52662
>>> diff.microseconds
922000
>>> minutes = (diff.seconds + diff.microseconds / 100.0) / 60.0
>>> minutes
877.715368
>>>
>
>
> which is not good for me.
>
> So I tried to use toordinal like this
> diff=b.toordinal()-a.toordinal()
>
> but I get
> diff=1
>
> Why?

because toordinal() works only on the date part, ignoring the time
part.

HTH,
John

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


Re: Nested function scope problem

2006-08-02 Thread Antoon Pardon
On 2006-08-02, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 1 Aug 2006 17:44:54 GMT, Antoon Pardon <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> Suppose I write a C-interpreter and then would translate a statement
>> like "c = c + 100" into actions the interpreter would have to take in
>> order to excute that statement. Something like:
>> 
>>   c-addr_p = GetAddress("c");
>>   c-value = *c-addr_p;
>>   sum = c-value + 100;
>>   *c-addr_p = sum;
>>
>   If this is what your interpreter generates/executes for a C-language
> assignment, then the source language is no longer C...

How do you come to that decision?

> After all, Python's most common implementation IS in C.
>
>   In C, the difference between "c" as a pointer, and "*c" as what it
> points to is explicitly exposed to the user... The two views can be
> separately manipulated. "c" as a variable can be manipulated -- c++
> changes c to "point to" an object (of the type of "c") that is presumed
> to follow the existing object -- whether such exists or not.
>
>   Python does not expose that to the user... You have a name and you
> have an object. The name exists, or it doesn't, independent of the
> object. Not in C -- while the object may not exist, the name, to be used
> at all, has to exist and has storage space assigned to it; storage the
> programmer is able to manipulate without an object.

And how is this all relevant in deciding that the source language for
the above interpreter actions isn't C? What the interpreter does is
the following:

  Get the addres of the variable c
  Get the value that is at that address.
  Add 100 to this value
  Store the new value at that address.

Please explain what is wrong in this sequence of actions
for an interpretation of the C statement: "c = c + 100;"

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


Re: Zipping files/zipfile module

2006-08-02 Thread Ant
Enabling directory recursion:

> from os import listdir, mkdir
> from os.path import join, basename, isfile
> from zipfile import ZipFile
>
> def zip_dir(path, output_path, include_hidden=True):
> try:
> mkdir(output_path)
> except OSError, e:
> if e.errno == 17: # Path exists
> pass
> zip_file = ZipFile(join(output_path, 'temp.zip'), 'w')

   for root, dirs, files in os.walk(dir):
   for f in files:
fp = path.join(root, f)
zip_file.write(fp, fp[len(dir):])  # Write to zip as a
path relative to original dir.
> zip_file.close()

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


Re: cleaner way to write this try/except statement?

2006-08-02 Thread John Salerno
Peter Otten wrote:
> John Salerno wrote:
> 
>> The code to look at is the try statement in the NumbersValidator class,
>> just a few lines down. Is this a clean way to write it? i.e. is it okay
>> to have all those return statements? Is this a good use of try? Etc.
>>
>> Thanks.
>>
>> 
>>
>> import wx
>>
>>
>> class NumbersValidator(wx.PyValidator):
>>
>>  def __init__(self):
>>  wx.PyValidator.__init__(self)
>>
>>  def Clone(self):
>>  return NumbersValidator()
>>
>>  def Validate(self, parent):
>>  text_ctrl = self.GetWindow()
>>  text = text_ctrl.GetValue()
>>
>>  try:
>>  if not text or int(text) <= 0:
>>  wx.MessageBox('Enter a valid time.', 'Invalid time
>>
>>entered', wx.OK | wx.ICON_ERROR)
>>  return False
>>  else:
>>  return True
>>  except ValueError, error:
>>  wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>>wx.OK | wx.ICON_ERROR)
>>  return False
>>
>>  def TransferToWindow(self):
>>  return True
>>
>>  def TransferFromWindow(self):
>>  return True
> 
> Here's how I might do it:
> 
> def is_positive_int_str(s):
> try:
> value = int(s)
> except ValueError:
> return False
> return value > 0
> 
> class PositiveIntegerValidator(wx.PyValidator):
> # ...
> def Validate(self, parent):
> text = self.GetWindow().GetValue()
> if is_positive_int_str(text):
> return True
> wx.MessageBox(...)
> return False
> 
> Two usability notes:
> - "Invalid time entered" is a confusing message when you actually want a
> positive integer.
> - Pop-up messages are a major annoyance. An alternative would be to change
> the text color of the control and show a hint as to what input you expect
> in a status bar.
> 
> Peter
> 

Thanks for all the help guys! I'm going to rework it a little and see 
what happens. Luckily, I'm also reading the chapter on exceptions in 
Python in a Nutshell, so maybe that will help solidify my understanding 
of how to construct them in this situation.
-- 
http://mail.python.org/mailman/listinfo/python-list


upgrading python...

2006-08-02 Thread bruce
hi.

i'min a situation where i might need to upgrade python. i have the current
version of python for FC3. i might need to have the version for FC4. i built
the version that's on FC4 from the python source RPM.

however, when i simply try to install the resulting RPM, the app gives me
dependency issues from apps that are dependent on the previous/current
version of python.

i'm trying to figure out if there's a 'best' way to proceed.

do i simply do the install, and force it to overwrite the current version of
python?

is there a way to point 'yum' at my new python RPM, and let yum take care of
dealing with any dependcy issues? and how would yum handle weird dependency
issues with RPMs that don't exist.. does yum have the ability to actually
build required apps from source?

comments/thoughts/etc...

thanks

-bruce


ps. the reason for this is that i'm looking at some of the newer
functionality in the 2.4 version of python over the 2.3


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


VisualStudio2005 supported in distutils

2006-08-02 Thread mg
Hello,

I try to compile Python and several packages (like Numarray) with Visual 
Studio 2005. I downloaded the last version of Python from Subversion, 
and project files are provided for Visual Studio 2005. With some few 
simple corrections, everything compile and Python run correctly.

Unfortunately, distutils does not support VisualStudio2005. I tried to 
modify the file msvccompiler.py without success (this case requires to 
support some changes of the Visual Studio 8 register for both Win32 and 
Win64). So, I wonder if the integration of VisualStudio2005 in distutils 
is scheduled in the Python developments or better, if someone has 
experiences or patch to support VisualStudio2005 in distutils.

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


Re: cleaner way to write this try/except statement?

2006-08-02 Thread John Salerno
Simon Forman wrote:

> Maybe I did miss something:  Are you actually trying to make a static
> method?  Say, to be able to call it elsewhere than just the Validate()
> method?

I don't know if a static method is the best way to do it, but what I was 
trying to do was make a regular function within the validator class, so 
that I could call it whenever I needed to show that error message. I 
suppose I could just use a regular method to do it, too, but it seems 
more like a utility function than a method that requires 'self'.

My identation seems correct to me (and I get no errors about it), but 
it's still not working the way I have it. Maybe I shouldn't mess with 
decorators right now anyway...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows vs. Linux

2006-08-02 Thread Gerhard Fiedler
On 2006-08-02 04:42:31, Sybren Stuvel wrote:

> I never said "I would have known it better". I just said that IMO it
> was a bad design choice ;-)

Well, and I question your qualification to judge that. 

In order to say that, you would have to know the reasoning, would have to
put it in the historical context and would have to be able to explain why
that reasoning was wrong at the time. A design choice is not necessarily a
bad choice just because it turns out that some 30 years later there is a
similar common product whose creators made a different choice, and now
programmers have to cater to both. With the same reasoning one could say
that the Unix creators should have used the VMS (or any other existing)
form.

Gerhard

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


Re: Network Game in Python

2006-08-02 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> Some questions I have are:
> 1. How can I manage network messages among the players. Should
> multicast be used or Actor should send the message to Supervisor and he
> sends to all. ?

Send a message from one client to the supervisor, handle it, then get
the supervisor to send messages back out to notify all clients of the
change. That way, the supervisor always has the correct state, and
knows which clients are aware of it.

> What python modules can be handy in these things.

The socket and select modules are all that you need. Perhaps there's a
higher-level solution somewhere but I don't expect you'd need it.

> 2. How can I manage moves among players. What move a player makes is
> visible to all others in real time, so essentially all players have the
> same consistent view of the game. Only the person with access can
> actually make a move or carry out action. Any suggestion how to carry
> out this thing.

As above: inform the supervisor/server of the move, and the server
informs all others of what is going on. Usually this is just a message
telling the client to update certain values. The client will update
those values and refresh the display. You may find it easiest to send
whole objects using pickle or something like that.

> 3. Shold I use a flat file or some database in mySQL to measure points
> etc ? I want to have a repository which keep tracks of all the mvoes in
> the system and who played what move etc..? Any suggestions on this.

Use whichever is easiest for you. Why do you need to save the data to
disk anyway? If you definitely need to do that, the shelve module is
often a good choice for basic needs. But it depends on what you need to
do with the information after you write it. 

-- 
Ben Sizer

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


Re: Windows vs. Linux

2006-08-02 Thread John Salerno
Gerhard Fiedler wrote:

> A design choice is not necessarily a
> bad choice just because it turns out that some 30 years later there is a
> similar common product whose creators made a different choice, and now
> programmers have to cater to both.

To be fair, this isn't the reason he gave for it being a bad design 
choice. His reason was that MS chose to use the escape character as 
their path separator.

But of course I still agree with you that in either case it's not a 
judgment you can fairly make 30 years after the fact.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a compelling argument to use Django instead of Rails

2006-08-02 Thread Ben Sizer
Paul Rubin wrote:
> "Ben Sizer" <[EMAIL PROTECTED]> writes:
> > Another perfectly good reason is that PHP pages are much simpler to
> > deploy than any given Python application server. Just add the code into
> > your HTML pages as required and you're done. Python could come close to
> > this if something like the Python Server Pages implementation in
> > mod_python was to become widely available and well known, but that
> > still requires overcoming the first problem.
>
> I didn't realize you could do shared hosting with mod_python, because
> of the lack of security barriers between Python objects (i.e. someone
> else's application could reach into yours).  You really need a
> separate interpreter per user.  A typical shared hosting place might
> support 1000's of users with ONE apache/php instance (running in a
> whole bunch of threads or processes, to be sure).

Ah yes, I hadn't considered that. Is this a Python limitation?
Py_Initialize() seems to initialise a global Python object which
obviously makes it awkward to share. Other languages allow you to
create multiple instances (eg. Lua has lua_newstate() which returns a
new Lua state) which would facilitate running multiple interpreters
without the new process overhead. A brief search implies that mod_perl
doesn't have the same problem as mod_python (but has other problems).
It would be a shame if Python is almost alone in having this issue.

-- 
Ben Sizer

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


Re: upgrading python...

2006-08-02 Thread Matthew Miller
On Wed, Aug 02, 2006 at 06:50:11AM -0700, bruce wrote:
> i'min a situation where i might need to upgrade python. i have the current
> version of python for FC3. i might need to have the version for FC4. i built
> the version that's on FC4 from the python source RPM.

Going from Python 2.3 as in FC3 to FC4's Python 2.4 isn't going to be
viable. Too different.

> however, when i simply try to install the resulting RPM, the app gives me
> dependency issues from apps that are dependent on the previous/current
> version of python.

Exactly.


> i'm trying to figure out if there's a 'best' way to proceed.

One option: build a new python RPM that installs Python2.4 into an
alternate path, or skip that complication and just build and install it
into /usr/local, leaving the system python intact.

But I think the *better* solution is to upgrade to Fedora Core 5 or Fedora
Core 6 Test 2. You want new software, go with a collection of new software
tested together.


> do i simply do the install, and force it to overwrite the current version of
> python?

Don't do this. It will break everything. Including yum, which is written in
python.


> is there a way to point 'yum' at my new python RPM, and let yum take care of
> dealing with any dependcy issues? and how would yum handle weird dependency
> issues with RPMs that don't exist.. does yum have the ability to actually
> build required apps from source?

Yum is pretty good, but it's not *that* magical.


-- 
Matthew Miller   [EMAIL PROTECTED]  
Boston University Linux  -->  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cleaner way to write this try/except statement?

2006-08-02 Thread John Salerno
John Salerno wrote:
> The code to look at is the try statement in the NumbersValidator class, 
> just a few lines down. Is this a clean way to write it? i.e. is it okay 
> to have all those return statements? Is this a good use of try? Etc.

Ok, I came up with this. It looks much nicer, I think, though I'm still 
unsure if it's good to have three separate return statements:

def Validate(self, parent):
 text = self.GetWindow().GetValue()

 try:
 if int(text) != 0:
 return True
 else:
 self.error_message()
 return False
 except ValueError:
 self.error_message()
 return False

But instead of a pop-up box for the error, I've decided to take Peter's 
advice and change the status text instead (plus color the input box). 
But here's an ultra OO newbie question: how do I refer to my frame's 
children from within the validator class? :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to mathematical function

2006-08-02 Thread Colin J. Williams
Nick Vatamaniuc wrote:
> Jeremy,
> 
> Which method of extension are you using? For example you can pass the
> function to C++/C directly using weave, without the need to convert to
> Python first. Python has a different syntax than C++. Also I assume you
> want exponentiation in you example "x^2..." and not 'xor', well, in
> Python that would be "x**2" and in C you would have to include math.h
> and then do pow(x,2). In other words there is no easy way to map Python
> expressions to C++ (if it would be, Python could just all be mapped to
> C++ and run at C++ speed!).
> 
> Below is my attempt at using weave (I prefer pyrex myself...). Note:
> this won't work too fast if your function changes on-the-fly because
> each new version will need to be compiled (gcc will be called and so
> on...). So it would only pay off if your function gets compiled ones
> and then takes a __very__ long time to compute.
> 
> Anyway here is my example:
> 
 import weave
 includes="""
>  #include 
>  """
 c_code="""
>  return_val=pow(a,N);
>  """
 a=42
 N=42
 ans=weave.inline(c_code, ['a','N'], support_code=includes)
> file changed
> None
> cc1plus: warning: command line option "-Wstrict-prototypes" is valid
> for Ada/C/ObjC but not for C++
 ans
> 1.5013093754529656e+68
 a**N
> 150130937545296572356771972164254457814047970568738777235893533016064L
 #now call the function again. no compilation this time, the result was 
 cached!
 ans=weave.inline(c_code, ['a','N'], support_code=includes)
 ans
> 1.5013093754529656e+68
> --
> Look up weave for Python (it is a part of scipy) for more examples...
> 
> Hope this helps,
> Nick Vatamaniuc
> 
> 
> jeremito wrote:
>> I am extending python with C++ and need some help.  I would like to
>> convert a string to a mathematical function and then make this a C++
>> function.  My C++ code would then refer to this function to calculate
>> what it needs.  For example I want to tell my function to calculate
>> "x^2 + 3x +2", but later on I may want: "x + 3".  Does anybody know how
>> I can get an arbitrary string in Python (but proper mathematical
>> function) turned into a C++ function?  My one idea (although I don't
>> know how to implement it, I'm still new at this) is to pass to C++ a
>> pointer to a (Python) function.  Will this work?
>> Thanks,
>> Jeremy
> 
Jeremy,

I presume that you have considered and rejected use of Python's eval 
function.

To this nonC++ user, it seems the simpler way.

A someone else pointed out, you would need to import the math module.

Colin W.

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


Re: upgrading python...

2006-08-02 Thread Paul Boddie
bruce wrote:
>
> i'min a situation where i might need to upgrade python. i have the current
> version of python for FC3. i might need to have the version for FC4. i built
> the version that's on FC4 from the python source RPM.

In principle this is a good idea, since you're aiming to manage your
installed software correctly, allowing the package management system to
permit uninstalls and the dependency management system to control
dependencies. (In fact, I go as far as to make Debian/Ubuntu packages
for virtually all Python packages I obtain independently of the
system's package management utilities, just so that I can then use such
utilities to install the software "properly".)

> however, when i simply try to install the resulting RPM, the app gives me
> dependency issues from apps that are dependent on the previous/current
> version of python.

This is one of the main issues with upgrading things upon which large
numbers of other components or applications are dependent. Really, in
order to preserve those applications, there would need to be an upgrade
path for them (and their libraries) based on the newer version of
Python, and I imagine that a lot of dependency management systems might
refuse to offer a bulk upgrade, especially if some of the applications
or libraries weren't available in an updated form.

> i'm trying to figure out if there's a 'best' way to proceed.
>
> do i simply do the install, and force it to overwrite the current version of
> python?

No: you'll probably break various important applications. As you've
seen, you'd need to offer yum all the potentially upgradable packages,
and although various "distribution upgrade" operations are often
possible, it's a major step just to try something out.

> is there a way to point 'yum' at my new python RPM, and let yum take care of
> dealing with any dependcy issues? and how would yum handle weird dependency
> issues with RPMs that don't exist.. does yum have the ability to actually
> build required apps from source?

I don't really recall many details about yum, since its introduction
came at the end of my Red Hat user experience, but yum is surely a
dependency manager that itself doesn't build packages, although I can
imagine it having features that could ask rpm (the package manager) to
do so. As I note above, to get yum to understand the missing packages,
you'd need to tell it about the Fedora Core 4 repository, but this is
probably only done safely via a "distribution upgrade" that would be
quite drastic.

> comments/thoughts/etc...

[...]

> ps. the reason for this is that i'm looking at some of the newer
> functionality in the 2.4 version of python over the 2.3

If I were in your position, I'd either do a "make altinstall" of Python
2.4 which should put Python 2.4 (as python2.4) alongside Python 2.3 (as
python, python2.3) in /usr/bin (where you would give /usr as the
installation prefix when configuring Python). Otherwise, I'd choose a
different installation prefix (by default, Python installs into
/usr/local) and then change your environment variables for affected
users or programs to use Python from this new location in preference to
the system installation of Python.

In other words, you probably want to install an isolated version of
Python for the special purpose of using newer functionality in your own
applications. Anything else may be a lot of work, disruption and a lot
more besides.

Paul

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


Snake is eating itself

2006-08-02 Thread Kay Schluehr
Diez B. Roggisch wrote:
> Kay Schluehr wrote:
>
> >
> > Tomi Lindberg wrote:
> >> Hi,
> >>
> >> With the following function definition, is it possible to
> >> create an instance of class C outside the function f (and if
> >> it is, how)?
> >
> > def f():
> > class C(object):
> > def __init__(self):
> > self.a = 'a'
> > f.C = C
> > return C()
> >
>  f.C
> > 
>
> Not working, unless f has been called at least once.

Right.

> But what I didn't know
> (and always wondered) if the classdefinition inside a function can use the
> outer scope - and apparently, it can! Cool.

Yes, the bytecode simply refers to a global name f in the scope of
__init__. Fortunately the Python compiler is too stupid to guess what f
might be but simply expects that f  exists at runtime. I use this
"snake is eating itself" pattern very often for passing a module as a
reference to another module inside of itself:

- Module M
import B

def eatMe():
 import M
 B.m = M

if __name__ == '__main__':
eatMe()

---

One might consider M as a component which is definig stuff. Once you
select such a component it can be used to configure a framework F of
which B is a part ( B doesn't import M ! ) So F is essentially
parametrized by M. You ere entering the next level when different
parametrizations F(M1), F(M2),... can coexist or even refer to each
other. This isn't just a mental exercise but it's going to be the way
EasyExtend will support multiple extension languages at the same time
in the fist beta version of the program. Yes, I know ... everything is
heavily cyclic and we should do hierarchies instead ;)

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


Re: Windows vs. Linux

2006-08-02 Thread Richard Brodie

"Gerhard Fiedler" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

>With the same reasoning one could say that the Unix creators should have
> used the VMS (or any other existing) form.

Only if they used Guido's time machine. 


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


Can any one help?

2006-08-02 Thread sujith h
Hi am a newbie to pyparsing. But can any one help
me to write small program to implement a small 
parser? Well is it possible to build a small calculator
to do some arithmetic operations. Hope that i may 
get a reply...

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

Re: Zipping files/zipfile module

2006-08-02 Thread Brian Beck
Yves Lange wrote:
> Other solutions:
> you can try the rar command line from WinRar but it's not recommended.
> This is a very slow manner to compress file.

Are you sure? This worked about 4 times faster than the zip command line
utility in Linux, compressing the same files...

-- 
Brian Beck
Adventurer of the First Order
-- 
http://mail.python.org/mailman/listinfo/python-list


ElementTree and Unicode

2006-08-02 Thread Sébastien Boisgérault

I guess I am doing something wrong ... Any clue ?

>>> from elementtree.ElementTree import *
>>> element = Element("string", value=u"\x00")
>>> xml = tostring(element)
>>> XML(xml)
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.4/site-packages/elementtree/ElementTree.py",
line 960, in XML
parser.feed(text)
  File "/usr/lib/python2.4/site-packages/elementtree/ElementTree.py",
line 1242, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1,
column 15

Cheers,

SB

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


Re: ElementTree and Unicode

2006-08-02 Thread Richard Brodie

"Sébastien Boisgérault" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

 element = Element("string", value=u"\x00")

I'm not as familiar with elementtree.ElementTree as I perhaps
should be. However, you appear to be trying to insert a null
character into an XML document. Should you succeed in this
quest, the resulting document will be ill-formed, and any
conforming parser will choke on it. 


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

Re: cleaner way to write this try/except statement?

2006-08-02 Thread Roy Smith
John Salerno  <[EMAIL PROTECTED]> wrote:
> try:
> if int(text) != 0:
> return True
> else:
> self.error_message()
> return False
> except ValueError:
> self.error_message()
> return False

One possible refactoring would be:

try:
  if int(text) != 0:
return True
except:
  pass
self.error_message()
return False

It's two less lines of code, one less return, and eliminates the
duplicate call to error_message().  On the other hand, the "except:
pass" clause is unusual and would make me (as a reader of the code)
stop and think what was going on.  Pick your poison.

If you want to be truly cryptic and obfuscatory, there's always:

try:
  1 / int(text)
  return True
except:
  return False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows vs. Linux

2006-08-02 Thread bryanjugglercryptographer

Sybren Stuvel wrote:
> John Salerno enlightened us with:
> > But of course I still agree with you that in either case it's not a
> > judgment you can fairly make 30 years after the fact.
>
> I don't see Microsoft changing it the next 30 years either... Apple
> moved from \r to \n as EOL character. I'm sure the folks at mickeysoft
> are smart enough to change from \ to /.

They dis-allow '/' in filenames, and many Microsoft products now
respect
'/' as an alternate to '\'.

>From a WinXP command prompt:

C:\>
C:\>cd /windows/system32

C:\WINDOWS\system32>


For a "Windows vs. Linux" thread, this one has been remarkably
rant-free.

-- 
--Bryan

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


Re: Class definition within function

2006-08-02 Thread Rick Zantow
Duncan Booth <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

>> >>> def f():
>>  class C(object):
>>   def __init__(self):
>>self.a = 'a'
>>  return C()
>> 
>> >>> x = f()
>> >>> x.a
>> 'a'
>> >>> y=f.C()
>> 
> 

Of course there's this:

>>> def f():
...  class C(object):
...   def __init__(self):
...self.a = 'a'
...  return C()
...
>>> x = f()
>>> x.a
'a'
>>> y=x.__class__()
>>> y.a
'a'
>>> type(y) == type(x)
True

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


Re: Need a compelling argument to use Django instead of Rails

2006-08-02 Thread Alex Martelli
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
   ...
> >>And of course import hooks.
> > 
> > Python?? Where?
> 
> RTFM:
> http://www.python.org/doc/2.3.5/lib/built-in-funcs.html

Perhaps a better reference is 
.

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


Re: Need a compelling argument to use Django instead of Rails

2006-08-02 Thread Alex Martelli
Ray <[EMAIL PROTECTED]> wrote:

> Damjan wrote:
> > BTW I'd choose TurboGears for it's flexibility, but I guess Django could be
> > nice when more rapid results are needed (and the problem doesn't fall too
> > far from the Django sweet spot).
> 
> Well actually I was thinking of exaclty the same thing, because our
> apps are mostly CRUD apps anyway. However I just learned of one very
> big killer--lack of support for Oracle and MS SQL Server. That pretty
> much shoots Django down from the list, and with it Python.

According to
, with
Rails...:

"""
When connecting rails to Oracle the performance dropped to the extent it
made any production use of the product useless.
   ...
Oracle. I would bet performance degrades dramatically when Rails
connects to Oracle as Rails does not use Bind Variables or cache
prepared statements. Not using bind variables in Oracle is the single
most common mistake. When running the load test connected to Oracle,
does Oracle consume a lot of the CPU?
Its unfortunate, as until Rails handles Oracle correctly, its not really
fit to be used on it, and I was really hoping to use it there!
"""

IOW, if these comments are correct, Rails is also _practically_ unusable
with Oracle.  Meanwhile, Django has experimental Oracle support with a
patch (, latest checkin is
from Jul 31, but it has been around for over a year in some form or
other).  As to what will mature first, Rails/Oracle performance or the
Django/Oracle patch, who knows.  I suspect it won't matter much, because
"buzz" trumps substance (in the short run, at least), and Ruby on Rails
has buzz (according to Tim O'Reilly's reports at OSCON last week, sales
of Ruby books have overtaken sales of Perl books recently -- Python
books, while gaining relative to Perl, are still below).

The one big issue that may preserve Perl, Python and PHP against Ruby's
onslaught is -- acronyms.  Any of the "P" languages can acronymically be
part of a "LAMP" setup, one of the coolest acronyms in years; indeed,
BSD, PostgreSQL and lighttpd may already have been handicapped by the
un-coolness of acronyms such as BLPP.  But Ruby suffers even worse here,
since somebody using Ruby instead of a P-language would be a... LAMR!!!

If I were on the board of the Ruby equivalent of the PSF, I'd be
lobbying hard for the language's name to be changed to PRuby -- with the
P being mute, as in Wodehouse's character Psmith.  _That_ would remove
the acronymical barrier and ensure PRuby's triumph.


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


Re: upgrading python...

2006-08-02 Thread Michael Brandt
> i'min a situation where i might need to upgrade python. i have the current
> version of python for FC3. i might need to have the version for FC4. i built
> the version that's on FC4 from the python source RPM.

You could try the precompiled Python distribution from ActiveState (AS
package (libcpp5*)):
http://activestate.com/Products/Download/Download.plex?id=ActivePython

Install it under /opt or somewhere else, where it doesn't conflict
with your existing python installation.

The drawback is, that you may install other 3rd party python packages
on your own.

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


Re: Finding the name of a class

2006-08-02 Thread Kent Johnson
Kirk Strauser wrote:
> Larry Bates wrote:
> 
>> print print b.__class__.__name__  gives what you want
> 
> That doesn't seem to do it, though.  Here's the result of importing a module
> from my company's internally-developed library:
> 
 from Daycos.TableCopier.copyfro import StateProcessor
 print StateProcessor.__class__.__name__
> type
> 
> I'm looking for something that would print 'StateProcessor' but am not
> having much luck.

It looks like StateProcessor is a class; StateProcessor.__class__ is the 
class of a class, i.e. type. Try
StateProcessor.__name__

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


Re: Get age of a file/dir

2006-08-02 Thread Antoon Pardon
On 2006-08-01, Carl J. Van Arsdall <[EMAIL PROTECTED]> wrote:
> I've been looking around the OS module and I haven't found anything 
> useful yet.  Does anyone know how to get the age of a file or directory 
> in days?  I'm using unix and don't seem to find anything that will help 
> me.  The only function that comes close so far is
>
> os.path.getctime(path)
>
> However this only gets creation time on Windows, on Unix it gets the the 
> time of the last change.  Any ideas?

On unix there is no way to get the age of a file or directory,
there is no information stored somewhere from which you can
calculate that.

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


Re: looking for a regular expression

2006-08-02 Thread �쩳�b�֤����ڡH
※ [EMAIL PROTECTED] (Thomas Nelson)》之銘言:
> How about
> my_string = "We the people of the United States, in order to form a
> more perfect union, establish justice, insure domestic
> tranquility,.."
> print (x for x in my_string.split(",") if "justice" in x).next()
> This isn't a regular expression, but it gives what you're looking for.
> THN

Thanks a lot! I have never thought of that.

But what if there's not only commas, but also periods and semicolons? I
want to find words between 2 near by punctuations. I think it would make
it difficult to use split instead of regular expression.
--
夫兵者不祥之器物或惡之故有道者不處君子居則貴左用兵則貴右兵者不祥之器非君子
之器不得已而用之恬淡為上勝而不美而美之者是樂殺人夫樂殺人者則不可得志於天下
矣吉事尚左凶事尚右偏將軍居左上將軍居右言以喪禮處之殺人之眾以哀悲泣之戰勝以
喪禮處之道常無名樸雖小天下莫能臣侯王若能守之萬物將自賓天地相合以降甘露民莫
之令而自均始制有名名亦既有夫亦將知 59-104-2-142.adsl.dynamic.seed.net.tw海
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Windows vs. Linux

2006-08-02 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

>>From a WinXP command prompt:
> 
> C:\>
> C:\>cd /windows/system32
> 
> C:\WINDOWS\system32>
> 
> 
Not from my Windows XP command prompt it doesn't. Do you have anything 
strange installed on your system?
-- 
http://mail.python.org/mailman/listinfo/python-list


need help of regular expression genius

2006-08-02 Thread GHUM
I need to split a text at every ; (Semikolon), but not at semikolons
which are "escaped" within a pair of $$ or $_$ signs.

My guess was that something along this should happen withing csv.py;
but ... it is done within _csv.c :(

Example: the SQL text should be splitted at "" (of course,
those "split heres" are not there yet :)

set interval 2;

CREATE FUNCTION uoibcachebetrkd(bigint, text, text, text, text, text,
timestamp without time zone, text, text) RETURNS integer
AS $_$
DECLARE
result int4;
BEGIN
update bcachebetrkd set
name=$2, wieoftjds=$3, letztejds=$4, njds=$5,
konzern=$6, letztespeicherung=$7, betreuera=$8, jdsueberkonzern=$9
where id_p=$1;
IF FOUND THEN
result:=-1;
else
   insert into bcachebetrkd (
   id_p, name, wieoftjds, letztejds, njds, konzern,
letztespeicherung, betreuera, jdsueberkonzern
   )
values ($1, $2, $3, $4, $5, $6, $7, $8, $9);
result:=$1;
END IF;
RETURN result;
END;
$_$
LANGUAGE plpgsql;

CREATE FUNCTION set_quarant(mylvlquarant integer) RETURNS integer
AS $$
BEGIN
perform relname from pg_class
where relname = 'quara_tmp'
  and case when has_schema_privilege(relnamespace, 'USAGE')
then pg_table_is_visible(oid) else false end;
if not found then
create temporary table quara_tmp (
lvlquara integer
);
else
   delete from quara_tmp;
end if;

insert into quara_tmp values (mylvlquarant);
  return 0;
  END;
 $$
LANGUAGE plpgsql;


Can anybody hint me in the right direction, how a RE looks for "all ;
but not those ; within $$" ?

Harald

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


Re: Behavior on non definded name in Cheetah

2006-08-02 Thread Paolo Pantaleo
2006/8/2, Peter Otten <[EMAIL PROTECTED]>:
> Paolo Pantaleo wrote:
>
> > 2006/8/2, Stephan Diehl <[EMAIL PROTECTED]>:
> >> Paolo Pantaleo wrote:
> >> > [I hope I am posting to the right place]
> >> >
> >> > I have a cheetah template something like this:
> >> >
> >> > x is: $x
> >> > y is: $y
> >> > z is: $z
> >> >
> >> > [Actually more complicated]
> >> >
> >> > If for example $y is not defined I get an exception and  the parsing
> >> > of the template stops. Is  there any way to substitute $y with an emty
> >> > string and making cheeta going on with parsing?
> >> >
> >> > Thnx
> >> > PAolo
> >> >
> >>
> >>
> http://cheetahtemplate.org/docs/users_guide_html_multipage/language.namemapper.missing.html
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >>
> >
> > Actually I wanted to keep things simple for who writes the template,
> > so I am using this workaround: I define a class
> >
> > class ClassMapper:
> > def __init__(self,dict={}):
> > self.__dict=dict
> > def getValue(self,str):
> > try:
> > return self.__dict[str]
> > except KeyError:
> > return ""
> >
> > x=ClassMapper(dict)
> > Template(definition, searchList=[{"info":x.getValue}])
> >
> >
> >
> > so the user should do
> >
> > $info("name")
> >
> > Maybe I could define a class that implements a dictionary and doesn''t
> > raise an exception for a key not present... but it seems to
> > complicated.
>
> You mean something like
>
> from Cheetah.Template import Template
>
> class Dict(dict):
> def __getitem__(self, key):
> return self.get(key, "")
>
> template = """\
> x is $x
> y is $y
> z is $z
> """
> print Template(template, searchList=[Dict(x="x", y="y")])
>
> You can also make a debugging version:
>
> class Dict(dict):
> def __getitem__(self, key):
> return self.get(key, "#missing key: %r#" % key)
>
> Peter
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
Wonderful, thnx a lot. Well not so complicated if you know how to do :D

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


Re: ElementTree and Unicode

2006-08-02 Thread Sébastien Boisgérault

Richard Brodie wrote:
> "Sébastien Boisgérault" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>
>  element = Element("string", value=u"\x00")
>
> I'm not as familiar with elementtree.ElementTree as I perhaps
> should be. However, you appear to be trying to insert a null
> character into an XML document. Should you succeed in this
> quest, the resulting document will be ill-formed, and any
> conforming parser will choke on it.

I am trying to embed an *arbitrary* (unicode) strings inside
an XML document. Of course I'd like to be able to reconstruct
it later from the xml document ... If the naive way to do it does
not work, can anyone suggest a way to do it ?

SB

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


Re: looking for a regular expression

2006-08-02 Thread Ant
> But what if there's not only commas, but also periods and semicolons? I
> want to find words between 2 near by punctuations. I think it would make
> it difficult to use split instead of regular expression.

You could use re.split(r"\W", text) instead of the string split method
to split on all non-word characters.

Alternatively the regex you are looking for is probably r"\bjustice\b".

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


Re: looking for a regular expression

2006-08-02 Thread Peter Otten
¨ì©³¦b²Ö¤°»ò°Ú¡H wrote:

>> How about
>> my_string = "We the people of the United States, in order to form a
>> more perfect union, establish justice, insure domestic
>> tranquility,.."
>> print (x for x in my_string.split(",") if "justice" in x).next()
>> This isn't a regular expression, but it gives what you're looking for.
>> THN
> 
> Thanks a lot! I have never thought of that.
> 
> But what if there's not only commas, but also periods and semicolons? I
> want to find words between 2 near by punctuations. I think it would make
> it difficult to use split instead of regular expression.

Reenter re. Use

re.split(r"[.;\-,]", my_string)
 
instead of my_string.split(",").

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


RE: Windows vs. Linux

2006-08-02 Thread Tim Golden
| [EMAIL PROTECTED] wrote:
| 
| >>From a WinXP command prompt:
| > 
| > C:\>
| > C:\>cd /windows/system32
| > 
| > C:\WINDOWS\system32>
| > 
| > 
| Not from my Windows XP command prompt it doesn't. Do you have 
| anything 
| strange installed on your system?

FWIW:



Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

c:\temp>cd \

C:\>cd /windows/System32

C:\windows\system32>



TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Windows vs. Linux

2006-08-02 Thread Alex Martelli
Gerhard Fiedler <[EMAIL PROTECTED]> wrote:
   ...

a few fine points of computing history...:

> >> (URLs probably use the slash because the internet protocols have been
> >> developed largely on Unix-type systems for use with Unix-type systems?)
> > 
> > It wasn't designed specifically for Unix-type systems, but for universal
> > access.
> 
> Right... the URI/URL syntax was formalized in the early 90ies, when

The internet *protocols* were typically developed on non-Unix systems --
that's why each line in text-based protocols must be terminated by
\r+\n, not just \n.  The WWW, as you mention, came later (and I believe
it was born on a NEXT cube, i.e., a unix-variant).

> > My point also was that a lot of programming languages use the backslash
> > as escape character. This has been true at least since the sixties. I
> > think it's a bad design choice from the Microsoft team to pick this
> > escape character as a path separator. 
> 
> Maybe... have you been involved in the decision? Or do you know what the
> reasons were? Do you know whether it was even Microsoft's choice?
> (Remember, they wrote DOS for IBM. And there was nobody who had foreseen
> the PC explosion.) 

Microsoft did *NOT* write DOS -- they purchased it from a small Seattle
company, which called it QDOS (Quick and Dirty OS) and had hacked it up
"in desperation" because CP/M did not run on intel 8086 CPUs, so the
small company's main business, selling 8086 boards, languished.  QDOS
was as compatible with CP/M as said small company could make it (rumor
has it that big parts were disassembled from CP/M and reassembled to run
on 8086 rather than 8080).  Part of the CP/M compatibility did include
the use of / as flag-indicator (the use of \r+\n as line ending also
comes from CP/M -- in turn, CP/M had aped these traits from some DEC
minicomputer operating systems).

When MS did write an OS -- DOS 2.0, which introduced a directory tree --
they did put in the OS an undocumented switch to make - the
flag-indicator and / the path separator, rather than / and \
respectively.  However it was never documented and it got removed in
later versions, perhaps because applications coded to the /-and-\
convention could break if the switch was thrown.

> Did you know that most DOS versions accept the / as path separator? That
> DOS was written on Xenix (Posix) systems (using the slash as path
> separator)? That Microsoft was for a long time pretty much a pure Xenix
> shop?

Internally yes (indeed, they developed Xenix, before later selling it to
SCO), but that does not mean that "DOS was written on Xenix" because DOS
was *not* written in Microsoft, as above mentioned.


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


Re: Windows vs. Linux

2006-08-02 Thread Alex Martelli
jean-michel bain-cornu <[EMAIL PROTECTED]> wrote:

> Andy Dingley a écrit :
> > I'd never recommend dual-boot for anything!
> Don't agree man, it's good for testing...

It's bothersome for testing: virtualization is much handier in most
cases.


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


Re: need help of regular expression genius

2006-08-02 Thread Ant

GHUM wrote:
> I need to split a text at every ; (Semikolon), but not at semikolons
> which are "escaped" within a pair of $$ or $_$ signs.

Looking at you example SQL code, it probably isn't possible with
regexes. Consider the code:

$$
blah blah
...
$$
blah;

xxx
$$
blah
blah
$$

Regexes aren't clever enough to count the number of backreferences, and
so won't help in the above case. You'd be better off creating a custom
parser using a stack or counter of some sort to decide whether or not
to split the text.

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


Re: Windows vs. Linux

2006-08-02 Thread Tim Chase
> | Not from my Windows XP command prompt it doesn't. Do you have 
> | anything 
> | strange installed on your system?
> 
> FWIW:
> 
> 
> 
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
> 
> c:\temp>cd \
> 
> C:\>cd /windows/System32
> 
> C:\windows\system32>
> 
> 



Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\temp>cd \

C:\>cd /windows/system32

C:\WINDOWS\system32>cd /windows/system32
The system cannot find the path specified.
C:\WINDOWS\system32>cd \

C:\>cd /windows

C:\WINDOWS>cd /system32

C:\WINDOWS\system32> REM wtf?



Nice to see consistancy at work.  Looks like leading slashes are 
stripped and so it trys to find it relative to the current path.

Nothing like predictable, cross-platform implementations there. 
[rolls eyes]

Thank goodness Python brings some brains to the table where 
Windows/Dos is ::ehem:: seriously lacking.

-tkc



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


Re: Datetime objects

2006-08-02 Thread Lad

John Machin wrote:
> Lad wrote:
> > Sybren Stuvel wrote:
> > > Lad enlightened us with:
> > > > How can I find days and minutes difference between two datetime
> > > > objects?
> > > > For example If I  have
> > > > b=datetime.datetime(2006, 8, 2, 8, 57, 28, 687000)
> > > > a=datetime.datetime(2006, 8, 1, 18, 19, 45, 765000)
> > >
> > > diff = b - a
> >
> > Ok, I tried
> >
> > >>> diff=b-a
> > >>> diff
> > datetime.timedelta(0, 52662, 922000)
> > >>> diff.min
> > datetime.timedelta(-9)
>
> Reread the manual:
>
> 1. "min" is minIMUM, not minUTES
>
> 2. You need:
> >>> diff.days
> 0
> >>> diff.seconds
> 52662
> >>> diff.microseconds
> 922000
> >>> minutes = (diff.seconds + diff.microseconds / 100.0) / 60.0
> >>> minutes
> 877.715368
> >>>
> >
> >
> > which is not good for me.
> >
> > So I tried to use toordinal like this
> > diff=b.toordinal()-a.toordinal()
> >
> > but I get
> > diff=1
> >
> > Why?
>
> because toordinal() works only on the date part, ignoring the time
> part.
> 
> HTH,
> John
Thank you for the explanation

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


Re: Newbie Q: Class Privacy (or lack of)

2006-08-02 Thread Antoon Pardon
On 2006-07-28, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> 
>> class MyClass(object):
>> 
>> __slots__ = ('bar',)
>> 
>> def func(self):
>> return 123
>> 
>> x = MyClass()
>> x.instance_var_not_defined_in_the_class = 456
>> ==>
>> AttributeError: 'MyClass' object has no attribute
>> 'instance_var_not_defined_in_the_class'
>> 
>> x.func = 789
>> ==>
>> AttributeError: 'MyClass' object attribute 'func' is read-only
>> 
>> Only the bar-attribute can be set:
>> 
>> x.bar = 'foo'
>
> This avoids the problem but you get others in return.  And it's an abuse
> of `__slots__` which is meant as a way to save memory if you need really
> many objects of that type and not as "protection".

I find that a strange purpose because when you are working on a class,
you don't necessarily know if you will ever know many instance of that
class. So should I use __slots__ in all my classes, just to be sure
for when someone wants many instances of one?

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


Re: Newbie Q: Class Privacy (or lack of)

2006-08-02 Thread Diez B. Roggisch
> I find that a strange purpose because when you are working on a class,
> you don't necessarily know if you will ever know many instance of that
> class. So should I use __slots__ in all my classes, just to be sure
> for when someone wants many instances of one?
 
I find that a strange reasoning because when you are working on a class,
you don't necessarily know if you will ever know if it needs a
__getitem__-method.
So do you use __getitem__ in all your classes, just to be sure
for when someone wants __getitem__ in one?

To my experience programming often means that requirements change - and one
has to adapt. If memory becomes an issue, you might overcome it using
slots. Or a disk cache. Or buy new memory. Does that imply for you that you
buy new disks and memory each time you start coding?

Diez

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


Re: Windows vs. Linux

2006-08-02 Thread John Salerno
Sybren Stuvel wrote:

> Apple
> moved from \r to \n as EOL character.

Interesting. I didn't know that. Although it does seem to make sense to 
use both \r\n as EOL (if you still consider one as a carriage return and 
one as a newline, a la old school typewriters), \n is much nicer and 
cleaner looking. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Q: Class Privacy (or lack of)

2006-08-02 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Antoon Pardon wrote:

> On 2006-07-28, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

>> This avoids the problem but you get others in return.  And it's an
>> abuse of `__slots__` which is meant as a way to save memory if you need
>> really many objects of that type and not as "protection".
> 
> I find that a strange purpose because when you are working on a class,
> you don't necessarily know if you will ever know many instance of that
> class. So should I use __slots__ in all my classes, just to be sure for
> when someone wants many instances of one?

No you should not use it unless you are sure there will be really many
instances of that class.  Putting __slots__ in the mix without a
compelling reason is premature optimization.

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


Is there an obvious way to do this in python?

2006-08-02 Thread H J van Rooyen
Hi,

I want to write a small system that is transaction based.

I want to split the GUI front end data entry away from the file handling and
record keeping.

Now it seems almost trivially easy using the sockets module to communicate
between machines on the same LAN, so that I want to do the record keeping on one
machine.

I want to keep the "server" machine as simple as possible - just doing record
keeping on a stimulus response basis - I would prefer it to do one thing at a
time to completion because this style of operation, though limited in
performance, keeps a lot of hassles out of life - a transaction has either
completed, or it has not - recovery scenarios are relatively easy...

Up to this point, I don't have a problem - my toy system can create a dummy
transaction, and I can echo it from the "server" machine, with more than one
"user" machine running - so I think it is feasible to have several tens of "data
entry terminal" systems running, served by one not very strong machine.

Now what I would really like to do is to differentiate between the 'User"
machines, so that some can do a full range of transactions, and others a limited
range.

And I would like to make this flexible, so that it becomes easy to introduce new
transactions, without having to run around updating the code in all the user
machines, with the concomitant version number hassles.

And I would like to do the whole thing in python - so my question is this - is
it possible to do the equivalent of dynamic linking? - i.e. if I keep a list of
what a user is allowed to do - can I somehow send him just the bits he needs to
do the job, without having to change the static code on his machine? - it seems
to me that the eval() thingy could possibly do this for me, by sending it data
that makes it do import statements followed by calls to whatever... - will this
work, or is there a better way?

Or has all this been done already? - and no I don't want a web server and php
and browsers and Java and html or xml... - I want to write something that works
simply and reliably - its just short message accounting type data...

- Hendrik

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


Re: how to get size of unicode string/string in bytes ?

2006-08-02 Thread Walter Dörwald
Diez B. Roggisch wrote:
>> So then the easiest thing to do is: take the maximum length of a unicode
>> string you could possibly want to store, multiply it by 4 and make that
>> the length of the DB field.
>  
>> However, I'm pretty convinced it is a bad idea to store Python unicode
>> strings directly in a DB, especially as they are not portable. I assume
>> that some DB connectors honour the local platform encoding already, but
>> I'd still say that UTF-8 is your best friend here.
> 
> It was your assumption that the OP wanted to store the "real"
> unicode-strings. A moot point anyway, at it is afaik not possible to get
> their contents in byte form (except from a C-extension).

It is possible:

>>> u"a\xff\u\U0010".encode("unicode-internal")
'a\x00\xff\x00\xff\xff\xff\xdb\xff\xdf'

This encoding is useless though, as you can't use it for reencoding on
another platform. (And it's probably not what the OP intended.)

> And assuming 4 bytes per character is a bit dissipative I'd say - especially
> when you have some > 80% ascii-subset in your text as european and american
> languages have.

That would require UTF-32 as an encoding, which Python currently doesn't
have.

> The solution was given before: chose an encoding (utf-8 is certainly the
> most favorable one), and compute the byte-string length.

Exactly!

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


Re: Convert string to mathematical function

2006-08-02 Thread jeremito
I was unaware of the exec and eval functions in Python.  Without trying
them, they seem to be what I want to do.  I'll play around with it and
see if I can figure it out.  Thanks for the suggestions everyone.
Jeremy

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


Newbie Cygwin Q

2006-08-02 Thread Gerry Blais
I'm trying to install and run, on XP,  a queueing analysis package,
PDQ, which has a{ Python, swig, C library version}.

I'm new to Cygwin (but not to Unix).

After installing Cygwin and Python, there is a Python2.4.exe in /lib.

If I have a file with

#!/lib/Python2.4.exe

Print "hello"

and I do the chmod, and submit  ./hello.py

I get a message "hello.py is currently being printed" and nothing
happens, until I give up and ^C out.

or, now, with no changes I can see, 

Can't find file hello

What am I missing?

Thanks,

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


PyImport_Import() failed

2006-08-02 Thread Yang Fan
Hello,   I'm new to Python.I want to embed Python interpreter into my C++ application powered by Borland C++ Builder 2006.   I have written some C++ code in order to evaluate Python script file, but PyImport_Import() calls 
failed.I really don't know what's wrong with my cpp code.It always return a NULL value.   Any advice is appreciated!int TPython::ExecuteScript(const char * pszFileName){                PyObject *pFileName, *pModule, *pDict, *pFunc;
        PyObject *pArgs, *pValue;                pFileName = PyString_FromString(pszFileName);        /* Error checking of pFileName left out */        if(!pFileName)        {        trace1(("pFileName == NULL "));
    }        pModule = PyImport_Import(pFileName); // always failed, returned NULL:(        Py_DECREF(pFileName);        if (pModule != NULL)        {            
                   }        else        {            PyErr_Print();            trace1(("Failed to load \"%s\"\n", pszFileName));            return 1;        }
                return 0;}
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie Cygwin Q

2006-08-02 Thread Gerry Blais

Sorry - problem solved.

My #!/usr/Pyrthon2.4.exe was inadvertently on line 2...

Gerry

On Wed, 02 Aug 2006 13:04:10 -0400, Gerry Blais
<[EMAIL PROTECTED]> wrote:

>I'm trying to install and run, on XP,  a queueing analysis package,
>PDQ, which has a{ Python, swig, C library version}.
>
>I'm new to Cygwin (but not to Unix).
>
>After installing Cygwin and Python, there is a Python2.4.exe in /lib.
>
>If I have a file with
>
>#!/lib/Python2.4.exe
>
>Print "hello"
>
>and I do the chmod, and submit  ./hello.py
>
>I get a message "hello.py is currently being printed" and nothing
>happens, until I give up and ^C out.
>
>or, now, with no changes I can see, 
>
>Can't find file hello
>
>What am I missing?
>
>Thanks,
>
>Gerry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread simonharrison
thanks very much for all the comments, links to articles and other
help.The Ruby crowd says you guys are no where near as friendly as
them! I was half expecting a nervous breakdown after writing my first
post here.

Cheers again

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


Re: Pickle vs XML for file I/O

2006-08-02 Thread crystalattice
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, crystalattice
> wrote:
>
> >> What are the problems you fear when using `shelve` by the way?
> >>
> > The ideas I got about shelve are mostly due to this thread:
> > http://tinyurl.com/lueok.  There weren't any other threads
> > contradicting the information so I figured it has merit.
>
> Main complaint seemed to be that data might be corrupted when the program
> terminates "abnormal" while writing the data.  You have the very same
> problem with pickle or XML serialization.  If the program gets interrupted
> after only half the data is written to disk you lose information.
>
> > Actually, not many people seem to use shelve very much; pickle is used
> > more often so I decided to give it a try and see how it works for me.
>
> They have a slightly different use case.  `pickle` stores single objects
> and `shelve` is a sort of persistent dictionary that maps strings to
> objects.  So if you want to save a party of characters and load them back
> together than pickle a list with those characters.  If you want a database
> of many characters the player can choose from than you might want to store
> them in a `shelve`.
>
> Ciao,
>   Marc 'BlackJack' Rintsch

Okay, that makes sense.  I was able to figure out how to pickle
yesterday.  It's not as hard as I thought (obviously); my confusion
originally came from thinking I needed to pickle each item of the class
separately but I realized that pickling a class instance worked too.

One other question though (hope it doesn't sound silly/stupid).  Your
suggestion to "pickle a party" using a list has me thinking:  can a
list store class instances?  I imagine it can though I don't know if
there may be bad juju if I tried, like data corruption or errors or
something.  I've only been using classes for a few weeks so I don't
know very much about them.

For example, if I wanted to store a party of characters, rather than
pickling each person separately could I put each character instance in
a list then pickle the list?  Like this:

char1 = Character()
char2 = Character()
char3 = Character()
party = [char1, char2, char3]
file = open("partyfile.dat", "w")
pickle.dump(party, file)

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread BartlebyScrivener

[EMAIL PROTECTED] wrote:

>> The Ruby crowd says you guys are no where
>>  near as friendly as them!

Slander! Defamation!

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


Re: Using Python for my web site

2006-08-02 Thread Bruno Desthuilliers
Conrad a écrit :
> On Mon, 31 Jul 2006 19:14:03 +0200, Bruno Desthuilliers wrote:
> 
> 
>>northband wrote:
>>
>>>Hi, I am interested in re-writing my website in Python vs PHP but have a
>>>few questions. Here are my specs, please advise as to which
>>>configuration would be best:
>>>
>>>1.Dell Poweredge Server, w/IIS, currently Windows but considering
>>>FreeBSD
>>
>>I may be a bit biased, but I would not run a web server under Windows...
>>
> 
> 
> That's not biased

Well, actually, yes it is. Definitively.

To make a long story short, my opinion is that the only sensible thing 
to do with Windows is to wipe it out and install an OS instead. OTHO, 
there are surely strong objective reasons for *not* using Windows - I 
just don't feel like wasting my time finding them !-)

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


Re: Nested function scope problem

2006-08-02 Thread Antoon Pardon
On 2006-08-02, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 2 Aug 2006 13:09:26 GMT, Antoon Pardon <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> 
>> And how is this all relevant in deciding that the source language for
>> the above interpreter actions isn't C? What the interpreter does is
>> the following:
>> 
>>   Get the addres of the variable c
>>   Get the value that is at that address.
>>   Add 100 to this value
>>   Store the new value at that address.
>> 
>> Please explain what is wrong in this sequence of actions
>> for an interpretation of the C statement: "c = c + 100;"
>
>   What interpretation will your hypothetical give for:
>
>   c = &c + 1
>   c++
>
> and
>
>   d = *(1000) #I'll concede this one may be a bit invalid
>   #I don't recall if a cast is needed

Why should I answer this? You stated that my interpreter couldn't
be interpreting the C-language. You did that before you asked these
questions. So it seems your decision for your statement is not
dependend om my answer for these questions. So please clarify
how you came to your decision.

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-02 Thread Tim Chase
> The Ruby crowd says you guys are no where near as friendly as 
> them! I was half expecting a nervous breakdown after writing
> my first post here.

Maybe the Ruby folks have to be friendlier to make up for their 
language of choice... :*)

The python mailing list is your pretty typical technical mailing 
list:  if you do your own homework, state your problem clearly 
(with full error messages, actual data, not writing in 
AOL/133t-speak, etc), and have already tried searching the 
web/docs, then you'll find folks here are quite helpful.  Not 
just helpful, but *fast* in their helpfulness too.

-tkc



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


Re: Using Python for my web site

2006-08-02 Thread Bruno Desthuilliers
Luis M. González a écrit :
(snip).
> I guess that the reason for not having used a framework already is
> laziness...

Strange enough, laziness is my first reason for using frameworks ;-)

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


Re: ElementTree and Unicode

2006-08-02 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Sébastien
Boisgérault wrote:

> I am trying to embed an *arbitrary* (unicode) strings inside
> an XML document. Of course I'd like to be able to reconstruct
> it later from the xml document ... If the naive way to do it does
> not work, can anyone suggest a way to do it ?

Encode it in UTF-8 and then Base64.  AFAIK the only reliable way to put an
arbitrary string into XML and get exactly the same string back again.

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

  1   2   >