Re: Top 10 Caribbean island destinations

2007-10-11 Thread george . smith78
lol :) another one on baseball : 90% of the game is physical, the
other half is mental.

GS
[EMAIL PROTECTED]

On Oct 11, 7:32 pm, willshak <[EMAIL PROTECTED]> wrote:
> on 10/11/2007 10:14 PM Audio expert said the following:
>
> > Now I know where NOT to go.
> > TOO crowded for me.
>
> No one goes there anymore. It's too crowded.
> Lawrence "Yogi" Berra
>
>
>
> > <[EMAIL PROTECTED]> wrote in message
> >news:[EMAIL PROTECTED]
>
> >> See the most popular Caribbean island destinations
>
> >>http://tropical-destinations.blogspot.com/
>
> --
>
> Bill
> In Hamptonburgh, NY
> To email, remove the double zeroes after @


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


Re: remove header line when reading/writing files

2007-10-11 Thread Marc 'BlackJack' Rintsch
On Thu, 11 Oct 2007 22:52:55 +, RyanL wrote:

> I'm a newbie with a large number of data files in multiple
> directories.  I want to uncompress, read, and copy the contents of
> each file into one master data file.  The code below seems to be doing
> this perfectly.  The problem is each of the data files has a header
> row in the first line, which I do not want in the master file.  How
> can I skip that first line when writing to the master file?  Any help
> is much appreciated.  Thank you.

Untested version with `itertools.islice()`:

import glob
import gzip
import os
from itertools import islice


def main():
zipdir = 'G:/Research/Data/'
outfilename = 'G:/Research/Data/master_data.txt'
out_file = open(outfilename, 'w')
for name in os.listdir(os.curdir):
if os.path.isdir(name):
os.chdir(name)
for zip_name in glob.glob('*.gz'):
in_file = gzip.GzipFile(zip_name, 'r')
out_file.writelines(islice(in_file, 1, None))
in_file.close()
os.chdir(os.pardir)
out_file.close()

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


Need suggestion on a GTalk Webservice

2007-10-11 Thread est
I am writing a GTalkBot which provides a webservice
http://xxx.com/services/sendmessage.html

If someone POST some text to http://xxx.com/services/sendmessage.html
it will transfer the text to some friends on GTalk.

I tried using django's __init__.py function to build this service but
it seemed too stupid, here is the discuss thread:
http://groups.google.com/group/django-users/t/9e652d3ad37338fc

I thought about other solutions, running a GTalk daemon process and
using sockets to interact with django, but it seemed to COMPLEX to me.
Is there a simpler way to do this? a pythonic, simple way?

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


cxfreeze

2007-10-11 Thread luca72
Hello i use under linux cx-freeze
My python program import a small module were i set the encoding to iso
8859-1.
When i make the executable with cxfreeze and i run it i get this
error:
Traceback (most recent call last):
  File "/home/luca72/Desktop/Luca/python/cx_Freeze-3.0.3/initscripts/
Console.py", line 27, in 
exec code in m.__dict__
  File "main.py", line 4, in 
  File "form_pack_impl.py", line 13, in 
  File "sitecustomize.py", line 3, in 
LookupError: unknown encoding: iso-8859-1

Can you help me

Regards

Luca

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


Re: matching a street address with regular expressions

2007-10-11 Thread Paul McGuire
On Oct 11, 11:50 pm, John Nagle <[EMAIL PROTECTED]> wrote:
>
> If anyone has a first-rate address parser in Python that will cover
> most of the developed world, I'd like to talk to them.
>
> John Nagle
> SiteTruth

The pyparsing examples page includes a street address parser (http://
pyparsing.wikispaces.com/space/showimage/streetAddressParser.py) that
will handle these test cases:

100 South Street
123 Main
221B Baker Street
10 Downing St
1600 Pennsylvania Ave
33 1/2 W 42nd St.
454 N 38 1/2
21A Deer Run Drive
256K Memory Lane
12-1/2 Lincoln
23N W Loop South
23 N W Loop South
25 Main St
2500 14th St
12 Bennet Pkwy
Pearl St
Bennet Rd and Main St
19th St

-- Paul


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


Re: the secret life of zombies

2007-10-11 Thread jsnx
Oh, by the way -- I apologize for the poor formatting of this post,
I guess my linewrap setting is wrong for nntp.

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


Re: Fwd: NUCULAR fielded text searchable indexing

2007-10-11 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> http://www.xfeedme.com/nucular/gut.py/go?FREETEXT=w
> (w for "web") we get 6294 entries which takes about 500ms on
> a cold index and about 150ms on a warm index.  This is on a very
> active shared hosting machine.

That's reasonable speed, but is that just to do the set intersections
and return the size of the result set, or does it retrieve the actual
result set?  It only showed 20 results on a page.  I notice that each
book in the result list has an ID number.  Say those are stored fields
in Nucular: how long does it take to add up all the ID numbers for the
results of that query?  I.e. the requirement is to actually access
every single record in order to compute the sum.  This is similar to
what happens with faceting.

> You are right that you might want to
> use more in-process memory for a really smart, multi-faceted relevance
> ordering or whatever, but you have to be willing to pay for it
> in terms of system resources, config/development time, etcetera.
> If you want cheap and easy, nucular might be good enough, afaik.

I used a cave-man approach with solr, which is I have an external
process keeping the indexes warm by simply reading something from each
page a few times an hour.  That is enough to pull 10k or so results a
second from a query.  Without the warming, getting that many results
takes over a minute.  I do think much better approaches are possible
and solr/lucene is by no means the be-all and end-all.  I don't know
if solr is using mmap or actual seek system calls underneath.

> Regarding the 30 million number -- I bet google does
> estimations and culling of some kind (not really looking at all 10M).

Probably.

> I'm not interested in really addressing the "google" size of data set
> at the moment.

Right, me neither, but a few 10's of GB of indexes is not all that
large these days.  

> >  http://www.newegg.com/Product/Product.aspx?Item=N82E16820147021
> holy rusty metal batman! way-cool!

Heh, check out the benchmark graphs:

  
http://www.tomshardware.com/2006/09/20/conventional_hard_drive_obsoletism/page7.html
-- 
http://mail.python.org/mailman/listinfo/python-list


pyserial doesn't recognize virtual serial port

2007-10-11 Thread naveen . sabapathy
Hi,
  I am trying to use virtual serial ports to develop/test my serial
communication program. Running in to trouble...

  I am using com0com to create the virtual ports. The virtual ports
seem to be working fine when I test it with Hyperterminal .

I am using the example program that comes with pyserial, as below.
---
import serial
ser = serial.Serial('CNCA0') #open virtual serial port
print ser.portstr#check which port was realy used
ser.write("Hello")  #write a string
ser.close()  #close port
-

The following is the error message:

--
Traceback (most recent call last):
  File "C:\Python25\Naveen Files\TestSerial", line 2, in 
ser = serial.Serial('CNCA0') #open first serial port
  File "c:\Python25\Lib\site-packages\serial\serialutil.py", line 156,
in __init__
self.open()
  File "c:\Python25\Lib\site-packages\serial\serialwin32.py", line 55,
in open
raise SerialException("could not open port: %s" % msg)
SerialException: could not open port: (2, 'CreateFile', 'The system
cannot find the file specified.')
--

When I try with 'COM3', which comes inbuilt in my laptop, COM3 is
recognized. Few other posts on the web seem to indicate pyserial
should work fine with virtual serial ports. What am I missing? Please
help.

--Thanks
--NS

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


Is this a bug of the lambda function

2007-10-11 Thread Zhu Wayne
Hi,
I have a short code which gives me strange results, the code is as follows:

f = [lambda x: None]*5
for j in range(0, 5):
 f[j] = lambda x: float(j)*x
print "print f[k](1.),"
for k in range(5):
 print f[k](1.),
print "expect 0. 1. 2. 3. 4."
print
print "print f[j](1.),"
for j in range(5):
 print f[j](1.),
print "expect 0. 1. 2. 3. 4."
print
print "print f[0](1.), f[1](1.), ..."
print f[0](1.), f[1](1.), f[2](1.), f[3](1.), f[4](1.)
print "expect 0. 1. 2. 3. 4."

*
The result is very strange:

print f[k](1.),
4.0 4.0 4.0 4.0 4.0 expect 0. 1. 2. 3. 4.

print f[j](1.),
0.0 1.0 2.0 3.0 4.0 expect 0. 1. 2. 3. 4.

print f[0](1.), f[1](1.), ...
4.0 4.0 4.0 4.0 4.0
expect 0. 1. 2. 3. 4.


It seems only when I use the index j (which is declear with the lambda
function), I can get expected answer, otherwise the result is not
unexpected.

Could anybody give me a possible explanation to this? Does python use kind
of pre-complie techinque to treat the lambda function? (like the macro in C
or inline function in C++)

Thanks in advance

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

Re: [Tutor] matching a street address with regular expressions

2007-10-11 Thread John Nagle
Shawn Milochik wrote:
> On 10/4/07, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>> Christopher Spears wrote:
>>> One of the exercises in Core Python Programming is to
>>> create a regular expression that will match a street
>>> address.  Here is one of my attempts.

This is actually quite difficult to do well.  Worse,
regular expressions are the wrong tool for the job,
because addresses are properly parsed in reverse, from the END of
the address.  See the USPS Postal Address Standards at
"http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf";.  Also
worth reading is "Frank's Compulsive Guide to Postal Addresses"
at "http://www.columbia.edu/kermit/postal.html";.

Here's a fun exercise: convert this address parser in Perl
to Python:

http://cpan.uwinnipeg.ca/htdocs/Geo-StreetAddress-US/Geo/StreetAddress/US.pm.html

There are features in those regular expressions that I can't find in three
Perl books or the online documentation.

If anyone has a first-rate address parser in Python that will cover
most of the developed world, I'd like to talk to them.

John Nagle
SiteTruth
-- 
http://mail.python.org/mailman/listinfo/python-list


a good website for softwares,sports,movies and music ,sex etc.

2007-10-11 Thread panguohua
www.space666.com


good

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


Re: Diferent files: GUI (wxpython) Program

2007-10-11 Thread cmpython

On Oct 11, 7:47 pm, marc <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] escribió:> On Oct 11, 5:44 pm, marc <[EMAIL PROTECTED]> 
> wrote:
> >> Hi why I can call an .py GUI (wxpython) from a program and control it?
> >> I'm newbie in python.
>
> > Sorry, could you restate that?  Explain again what you want to do.
>
> I would to call a python file that contains a GUI (with wx) from a file
> program.
> The programs that I've do, contains a GUI and the code to run it in the
> same file, but I when need to modify a GUI file (I use wxglade) I need
> to delete all code lines (except the GUI code lines) and it difficult
> the program.

Marc,

I haven't used wxGlade, but I would be surprised
if you would have to delete all the code lines in
order to modify the GUI part of the program,
but maybe I am misunderstanding something.  You
should ask on some wxGlade list or help file or
such.

I use Boa Constructor to help build GUIs and it
allows you to make a file which will run the main
frame (the GUI itself).  Maybe this is what you are
looking for?  If so, this is one way to do it:

Say you have a main frame which is your GUI.  Here
is the code for that (this is simply a frame with
a panel on it, super simple):

#--MAIN FRAME---
import wx

def create(parent):
   return Frame1(parent)

class Frame1(wx.Frame):

def __init__(self, parent):
wx.Frame.__init__(self, id=-1, parent=parent)

self.panel1 = wx.Panel(id=-1, parent=self)
#-

You can save this as testFrame1.py

Now you have the program which calls this frame, which we can
save as testApp1.py.  The code for that is as follows:

#The app that calls the GUI---
import wx
import testFrame1

class MyApp(wx.App):
def OnInit(self):
self.main = testFrame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True

def main():
application = MyApp(0)
application.MainLoop()

if __name__ == '__main__':
main()
#

Now you can change anything in the file called
testFrame1 and still launch it from the file
called testApp1.  I think that's basically what
you wanted to do if I understood it.

I'd recommend checking out Boa Constructor.  I've
trimmed the auto-generated code from it to make
it simplified for this message, but it is good
once you're used to it, and it is very easy to make
quick changes to the GUI, both by coding or by using
its Designer, which allows you to arrange the GUI
elements visually.

Lastly, it is probably better to ask questions about
wxPython on the wxPython list.

cm


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

Re: CGI and external JavaScript nightmare

2007-10-11 Thread Istvan Albert
On Oct 11, 2:23 am, IamIan <[EMAIL PROTECTED]> wrote:
>
> is a very lengthy garbled js file 
> athttp://pagead2.googlesyndication.com/pagead/show_ads.js
>
> The first piece of JavaScript works fine and the ads display
> correctly, however the second file throws an "unterminated string
> literal" js error.

the javescript code above is fine. you must be making some other
error(s)

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


Re: remove header line when reading/writing files

2007-10-11 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
> ...
> for zipfile in filelist:
> zfiter = iter(gzip.Gzipfile(zipfile,'r'))
> zfiter.next()  # ignore header line
> for i, line in enumerate(fziter):
> outfile.write(line)
Or even:
   writes = outfile.write
   for zipfile in filelist:
   zfiter = iter(gzip.Gzipfile(zipfile,'r'))
   zfiter.next()  # ignore header line
   for line in zfiter:
   writes(line)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Top 10 Caribbean island destinations

2007-10-11 Thread willshak
on 10/11/2007 10:14 PM Audio expert said the following:
> Now I know where NOT to go.
> TOO crowded for me.
>   

No one goes there anymore. It's too crowded.
Lawrence "Yogi" Berra
>
> <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>   
>> See the most popular Caribbean island destinations
>>
>> http://tropical-destinations.blogspot.com/
>>
>> 
>
>
>   


-- 

Bill
In Hamptonburgh, NY
To email, remove the double zeroes after @
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: EasyMock for python ?

2007-10-11 Thread Ben Finney
BlueBird <[EMAIL PROTECTED]> writes:

> Does anybody know where to find a library like EasyMock for python ?

I've had good results with Ian Bicking's 'minimock.py'
http://blog.ianbicking.org/minimock.html>. It uses the existing
'doctest' functionality for its output, and a minimock.Mock will mock
*everything* (using further Mock instances for attributes and methods)
unless explicitly told otherwise.

This means that the Mock object automatically supports any number of
attributes and methods by any reasonable names; the only setup needed
beyond creating the instance is to seed it with anything you *don't*
want returned as a Mock.

-- 
 \   "Laugh and the world laughs with you; snore and you sleep |
  `\ alone."  -- Anonymous |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: howto add a sub-directory to the searchpath / namespace ?

2007-10-11 Thread Scott David Daniels
[david] wrote:
> r" indicates a 'regular expression' string, normally
> called a raw string. It means that \ characters are
> treated using the regex syntax rather than the c syntax.

This is an incredibly creative answer , if not fastidiously
correct.  Raw strings simply disable the special effects of
backslash (\) within the string (except that it cannot be
the final character of a quoted string even if it a raw string
for technical lexer (tokenizer) simplicity reasons).  The regex
syntax is used on the resulting string constant if (and only if)
the string is passed to the regular expression functions as a
regex pattern parameter.

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


Re: Top 10 Caribbean island destinations

2007-10-11 Thread Audio expert
Now I know where NOT to go.
TOO crowded for me.


<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> See the most popular Caribbean island destinations
>
> http://tropical-destinations.blogspot.com/
> 


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


Re: M2Crypto possible intermittent bug

2007-10-11 Thread John Nagle
John Nagle wrote:
> Heikki Toivonen wrote:
>> John Nagle wrote:
>>> Still having trouble reproducing the problem. But somewhere,
>>> something raised that bogus no-error exception three times.
>>> Anything that returns "(0, 'Error')" as exception data is a bug.
>>
>> If you can, build python and m2crypto with debug symbols, and place
>> breakpoints in |case SSL_ERROR_SYSCALL| blocks (from _ssl.i). Then rerun
>> the tests. That would be my first guess as to where these might be
>> coming from.
> 
>I don't have the right compiler to build it on Windows, and it
> doesn't seem to be failing on Linux.  It failed three times during
> one test run and hasn't failed since.  That makes me suspect an
> uninitialized data problem in C code.  I'll try to reproduce the
> problem.
> 
> John Nagle

   I'm unable to reproduce the problem at this time. Even re-installingM2Crypto
doesn't make it recur.  I've been rerunning my regression test
over and over, and it's not repeatable.

   I suspect that for some reason Windows networking was generating
a local error, and the Windows error status to UNIX-like error status
conversion is wrong somewhere.

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


looking for ways to include python in pascal distro

2007-10-11 Thread [EMAIL PROTECTED]
I have found a couple of ways to include python in my pascal program

http://arctrix.com/nas/python/standalone.html

and an example I compiled from the embeded examples and I was wanting
to know if there are more examples or comiled versions I can execute
from my program...  I am getting an error from the embeded and the
standalone would work better with command line support

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


the secret life of zombies

2007-10-11 Thread jsnx
I'd like a program, call it 'pipe-fitter', that connects and
interactive app
to three named pipes. The program will filter out EOF from the input
pipe, to
keep the interactive program alive for multiple commands. When the
interactive
app dies, by receiving 'exit', say, then we are done with it -- pipe-
fitter
bails out.

I've tried writing pipe-fitter in the shell (infinite loop), C (could
not get
off the ground at all with this one) and now Python. After trying a
few
different approaches, I was turned on to the subprocess module by
someone on
IRC. My program is almost right, except for damn zombies. Here is pipe-
fitter:

https://svn.j-s-n.org/public/i-can-has-root/python/pipe-fitter.py

Say we make some fifos in a dir 'pipes'

  mkdir pipes
  mkfifo pipes/i pipes/o pipes/e

Now we call pipe-fitter thusly:

  pipe-fitter.py -d pipes sh -xv

This runs `sh -xv` with stdin, stdout and stderr connected to pipes/i,
pipes/o
and pipes/e respectively. We open three new terminals. In the first
one, we
put:

  echo "ls -l" > pipes/i

and in the second:

  cat pipes/o

and in the third:

  cat pipes/e

Once we enter the final command, the 'echo' returns and the text comes
streaming out in the 2nd and 3rd terminals. Wonderful. Now, let's try
`exit`.

  echo 'exit' > pipes/i

As expected, cat will terminate in the 2nd and 3rd terminals, with the
3rd
terminal displayin:

  + exit
  exit

However, pipe-fitter.py is still running. Why is that? It did not
'poll' at
the right time, it seems. If I try stuffing more input into pipes/i, I
get

  IOError: [Errno 32] Broken pipe

and pipe-fitter.py finally quits. Not exactly what I was hoping for.

Prowling around with PS, I find that the `sh -xv` called from within
pipe-fitter is a zombie for a spell; if pipe-fitter fails to catch it
at the
right time, there is no avoiding the IOError. I'm using
subprocess.Popen.poll() in a loop, to catch the process's termination
-- is
there something else I should be doing?

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


the secret life of zombies

2007-10-11 Thread jsnx
I'd like a program, call it 'pipe-fitter', that connects and
interactive app
to three named pipes. The program will filter out EOF from the input
pipe, to
keep the interactive program alive for multiple commands. When the
interactive
app dies, by receiving 'exit', say, then we are done with it -- pipe-
fitter
bails out.

I've tried writing pipe-fitter in the shell (infinite loop), C (could
not get
off the ground at all with this one) and now Python. After trying a
few
different approaches, I was turned on to the subprocess module by
someone on
IRC. My program is almost right, except for damn zombies. Here is pipe-
fitter:

https://svn.j-s-n.org/public/i-can-has-root/python/pipe-fitter.py

Say we make some fifos in a dir 'pipes'

  mkdir pipes
  mkfifo pipes/i pipes/o pipes/e

Now we call pipe-fitter thusly:

  pipe-fitter.py -d pipes sh -xv

This runs `sh -xv` with stdin, stdout and stderr connected to pipes/i,
pipes/o
and pipes/e respectively. We open three new terminals. In the first
one, we
put:

  echo "ls -l" > pipes/i

and in the second:

  cat pipes/o

and in the third:

  cat pipes/e

Once we enter the final command, the 'echo' returns and the text comes
streaming out in the 2nd and 3rd terminals. Wonderful. Now, let's try
`exit`.

  echo 'exit' > pipes/i

As expected, cat will terminate in the 2nd and 3rd terminals, with the
3rd
terminal displayin:

  + exit
  exit

However, pipe-fitter.py is still running. Why is that? It did not
'poll' at
the right time, it seems. If I try stuffing more input into pipes/i, I
get

  IOError: [Errno 32] Broken pipe

and pipe-fitter.py finally quits. Not exactly what I was hoping for.

Prowling around with PS, I find that the `sh -xv` called from within
pipe-fitter is a zombie for a spell; if pipe-fitter fails to catch it
at the
right time, there is no avoiding the IOError. I'm using
subprocess.Popen.poll() in a loop, to catch the process's termination
-- is
there something else I should be doing?

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


Re: Declarative properties

2007-10-11 Thread George Sakkis
On Oct 11, 7:04 pm, George Sakkis <[EMAIL PROTECTED]> wrote:

> You could take it even further by removing the need to repeat the
> attribute's name twice. Currently this can done only through
> metaclasses but in the future a class decorator would be even
> better:

Replying to myself here, but actually metaclasses is not the only way;
another solution involves a descriptor class:


class Property(object):

# cache the mapping of types to 'private' attribute names
_type2attrname = {}

def __init__(self, format='_%s'):
self._format = format

def __get__(self, obj, type=None):
try: name = self._type2attrname[type(obj)]
except KeyError:
self._type2attrname[type(obj)] = name =
self._get_propname(obj)
return getattr(obj, name)

def __set__(self, obj, value):
try: name = self._type2attrname[type(obj)]
except KeyError:
self._type2attrname[type(obj)] = name =
self._get_propname(obj)
setattr(obj, name, value)

def _get_propname(self, obj):
for cls in type(obj).mro():
for name,value in cls.__dict__.iteritems():
if value is self:
return self._format % name
assert False  # unreachable


# example 

class Person(object):
name = Property()

def __init__(self, name):
self.name = name

p = Person('John')
q = Person('Mike')
print p.name, q.name
print p.__dict__


George

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


Re: remove header line when reading/writing files

2007-10-11 Thread timaranz
On Oct 12, 12:23 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> Forgot the enumerate call of all things
>
> > for zipfile in filelist:
> >for i, line in enumerate(gzip.Gzipfile(zipfile,'r')):
> >if i: outfile.write(line)
>
> Some days, I'm braindead.
>
> -tkc

I would move the 'if' test outside the loop :

for zipfile in filelist:
zfiter = iter(gzip.Gzipfile(zipfile,'r'))
zfiter.next()  # ignore header line
for i, line in enumerate(fziter):
outfile.write(line)

I'm not sure if the iter(...) is required.  This will raise a
StopIteration exception if zipfile is empty.

Cheers
Tim

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


Re: decorating container types (Python 2.4)

2007-10-11 Thread timaranz
On Oct 12, 12:19 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
>
> > I have a container class A and I want to add functionality to it by
> > using a decorator class B, as follows:
>
> > class A(object):
> > def __len__(self):
> > return 5
>
> > class B(object):
> > def __init__(self, a):
> > self._a = a
>
> > def __getattr__(self, attr):
> > return getattr(self._a, attr)
>
> > def other_methods(self):
> > blah blah blah
>
> > I was expecting len(B) to return 5 but I get
> > AttributeError: type object 'B' has no attribute '__len__'
> > instead.
> > I was expecting len() to call B.__len__() which would invoke
> > B.__getattr__ to call A.__len__ but __getattr__ is not being called.
> > I can work around this, but I am curious if anyone knows _why_
> > __getattr__ is not being called in this situation.
>
> > Thanks
> > Tim
>
> The why part is that __len__ is an unbound method of the class, not an
> unbound method of the class's metaclass. Also, your code above makes
> absolutely no association between classes A and B, which is the most
> fundamental reason.
>
> James
>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA  90095
>
> http://www.jamesstroud.com

Just so I'm clear on this: Are you saying that the problem with my
original code is that len() is equivalent to type(x).__len__(x) that
looks for a class attribute rather than an instance attribute as my
code requires?

I don't own class A and they are generated by function calls rather
than instantiated directly, that's why I'm decorating them instead of
inheriting.  The crux of the (academic) question is why does len()
expect '__len__' to be a class attribute instead of an instance
attribute, and why is this a good idea?

Cheers
Tim

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


Re: Advice on long running processes

2007-10-11 Thread commander_coder
Thank you to folks for the replies.

Jim

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


Re: Diferent files: GUI (wxpython) Program

2007-10-11 Thread marc
[EMAIL PROTECTED] escribió:
> On Oct 11, 5:44 pm, marc <[EMAIL PROTECTED]> wrote:
>> Hi why I can call an .py GUI (wxpython) from a program and control it?
>> I'm newbie in python.
> 
> Sorry, could you restate that?  Explain again what you want to do.
> 
I would to call a python file that contains a GUI (with wx) from a file 
program.
The programs that I've do, contains a GUI and the code to run it in the 
same file, but I when need to modify a GUI file (I use wxglade) I need 
to delete all code lines (except the GUI code lines) and it difficult 
the program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Diferent files: GUI (wxpython) Program

2007-10-11 Thread marc
[EMAIL PROTECTED] escribió:
> On Oct 11, 5:44 pm, marc <[EMAIL PROTECTED]> wrote:
>> Hi why I can call an .py GUI (wxpython) from a program and control it?
>> I'm newbie in python.
> 
> Sorry, could you restate that?  Explain again what you want to do.
> 

I would to call a python file that contains a GUI (with wx) from a file 
program.
The programs that I've do, contains a GUI and the code to run it in the 
same file, but I when need to modify a GUI file (I use wxglade) I need 
to delete all code lines (except the GUI code lines) and it difficult 
the program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RMI with Pyro et al

2007-10-11 Thread Irmen de Jong
Diez B. Roggisch wrote:

> Go install cygwin (but not it's included python-interpreter, or at least
> make sure you have your python path properly under control) and then simply
> start the script from the command-line. And hit C-c if you need it to stop,
> and restart it. Only start it as service if it's deployed.

What's cygwin got to do with it?
-irmen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RMI with Pyro et al

2007-10-11 Thread Irmen de Jong
Sells, Fred wrote:
> Diez B. Roggisch wrote 
> . Why do you want that (hot deploy)
>> anyway? Does startuptime of a script really bother you? 
>> shouldn't take 
>> more than a few seconds.
> 
> My primary need is development/debug.  I'm a Pyro newbie and I add a
> feature and then test.  The only way I've found to kill the Pyro server
> on XP is to open the task manager and kill the python task (hopefully
> the right one).
> 
>  
> 

How do you start "the pyro server"?
Are you talking about the Windows Services that you can simply start/stop with:

net start PyroNS
net start PyroES

net stop PyroNS
net stop PyroES

??

Often it is way simpler to just use the pyro-ns.cmd / pyro-es.cmd batch files 
and stop 
the server with a simple ^C in the console window.


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


Re: Diferent files: GUI (wxpython) Program

2007-10-11 Thread cmpython
On Oct 11, 5:44 pm, marc <[EMAIL PROTECTED]> wrote:
> Hi why I can call an .py GUI (wxpython) from a program and control it?
> I'm newbie in python.

Sorry, could you restate that?  Explain again what you want to do.

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


Re: remove header line when reading/writing files

2007-10-11 Thread Tim Chase
Forgot the enumerate call of all things

> for zipfile in filelist:
>   for i, line in enumerate(gzip.Gzipfile(zipfile,'r')):
>   if i: outfile.write(line)


Some days, I'm braindead.

-tkc


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


Re: remove header line when reading/writing files

2007-10-11 Thread Tim Chase
> each file into one master data file.  The code below seems to be doing
> this perfectly.  The problem is each of the data files has a header
> row in the first line, which I do not want in the master file.  How
> can I skip that first line when writing to the master file?  Any help
> is much appreciated.  Thank you.
[snip]
>   for zipfile in filelist:
>   filein = gzip.GzipFile(zipfile,'r')
>   filecontent = filein.read()
>   filein.close()
>   outfile.write(filecontent)

for zipfile in filelist:
for i, line in gzip.Gzipfile(zipfile,'r'):
if i: outfile.write(line)

should do the trick for you.

If you like a little more readable code, you can change that line to

  if i <> 0: outfile.write(line)

or

  if i == 0: continue
  outfile.write(line)

whichever you like.

-tkc



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


Re: decorating container types (Python 2.4)

2007-10-11 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have a container class A and I want to add functionality to it by
> using a decorator class B, as follows:
> 
> class A(object):
> def __len__(self):
> return 5
> 
> class B(object):
> def __init__(self, a):
> self._a = a
> 
> def __getattr__(self, attr):
> return getattr(self._a, attr)
> 
> def other_methods(self):
> blah blah blah
> 
> I was expecting len(B) to return 5 but I get
> AttributeError: type object 'B' has no attribute '__len__'
> instead.
> I was expecting len() to call B.__len__() which would invoke
> B.__getattr__ to call A.__len__ but __getattr__ is not being called.
> I can work around this, but I am curious if anyone knows _why_
> __getattr__ is not being called in this situation.
> 
> Thanks
> Tim
> 

The why part is that __len__ is an unbound method of the class, not an 
unbound method of the class's metaclass. Also, your code above makes 
absolutely no association between classes A and B, which is the most 
fundamental reason.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

http://www.jamesstroud.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Declarative properties

2007-10-11 Thread George Sakkis
On Oct 11, 7:48 am, Artur Siekielski <[EMAIL PROTECTED]>
wrote:

> I know about 'property' function in Python, but it's normal usage
> isn't declarative, because I have to code imperatively getters and
> setters:
>
> class Person(object):
>def __init__(self, name):
>   self._name = name
>def _get_name(self):
>   return self._name
>def _set_name(self, new_name):
>   self._name = new_name
>name = property(_get_name, _set_name)
>
> I would like to have something like that:
>
> class Person(object):
>name = property('_name')

By now you must have been convinced that default getters/setters is
not a very useful idea in Python but this does not mean you can't do
it; it's actually straightforward:

def make_property(attr):
return property(lambda self: getattr(self,attr),
lambda self, value: setattr(self, attr, value))

class Person(object):
   name = make_property('_name')
   def __init__(self, name):
   self.name = name

You could take it even further by removing the need to repeat the
attribute's name twice. Currently this can done only through
metaclasses but in the future a class decorator would be even better:

def PropertyMaker(*names, **kwds):
format = kwds.get('format', '_%s')
def meta(cls,bases,attrdict):
for name in names:
attrdict[name] = make_property(format % name)
return type(cls,bases,attrdict)
return meta

class Person(object):
__metaclass__ = PropertyMaker('name', format='__%s__')

def __init__(self, name):
self.name = name
print self.__name__


George

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


Re: decorating container types (Python 2.4)

2007-10-11 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have a container class A and I want to add functionality to it by
> using a decorator class B, as follows:
> 
> class A(object):
> def __len__(self):
> return 5
> 
> class B(object):
> def __init__(self, a):
> self._a = a
> 
> def __getattr__(self, attr):
> return getattr(self._a, attr)
> 
> def other_methods(self):
> blah blah blah
> 
> I was expecting len(B) to return 5 but I get
> AttributeError: type object 'B' has no attribute '__len__'
> instead.
> I was expecting len() to call B.__len__() which would invoke
> B.__getattr__ to call A.__len__ but __getattr__ is not being called.
> I can work around this, but I am curious if anyone knows _why_
> __getattr__ is not being called in this situation.
> 
> Thanks
> Tim
> 

You will need a metaclass with a __len__ class attribute

class longmeta(type):
   def __len__(cls):
 return 7

class A(object):
   __metaclass__ = longmeta
   pass

py> class longmeta(type):
...   def __len__(cls):
... return 7
...
py> class A(object):
...   __metaclass__ = longmeta
...   pass
...
py> len(A)
7

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA  90095

http://www.jamesstroud.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Django Contractual Position

2007-10-11 Thread [EMAIL PROTECTED]
The Institute of Design of Chicago, IL is seeking an experienced
Django developer to create an in-house contact and mailing web
application. The application manages the contacts for the different
conferences and events at the Institute of Design.

The ideal candidate has experience with at least one completed Django
application, the more the better. Good communication is required as
the applicant will also be involved with design of the application.

Pay is negotiable. This is a contractual position. Local applicants
only. Applicant must be able to attend meetings at the Institute of
Design 350 N. La Salle St. Chicago, IL 60610

please contact [EMAIL PROTECTED] and [EMAIL PROTECTED] if interested.

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


remove header line when reading/writing files

2007-10-11 Thread RyanL
I'm a newbie with a large number of data files in multiple
directories.  I want to uncompress, read, and copy the contents of
each file into one master data file.  The code below seems to be doing
this perfectly.  The problem is each of the data files has a header
row in the first line, which I do not want in the master file.  How
can I skip that first line when writing to the master file?  Any help
is much appreciated.  Thank you.

import os
import sys
import glob
import gzip
zipdir = "G:/Research/Data/"
outfilename = "G:/Research/Data/master_data.txt"
outfile = open(outfilename,'w')
os.chdir(zipdir)
dirlist = os.listdir(os.curdir)
for item in dirlist:
if os.path.isdir(item):
os.chdir(item)
filelist = glob.glob("*.gz")
for zipfile in filelist:
filein = gzip.GzipFile(zipfile,'r')
filecontent = filein.read()
filein.close()
outfile.write(filecontent)
os.chdir(os.pardir)
outfile.close()

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


Re: storing meta data on dictionary keys

2007-10-11 Thread Andreas Kraemer
On Oct 11, 1:42 pm, Erik Jones <[EMAIL PROTECTED]> wrote:
> On Oct 11, 2007, at 2:25 PM, Andreas Kraemer wrote:
>
> > On Oct 11, 10:17 am, Erik Jones <[EMAIL PROTECTED]> wrote:
>
> >> No, duck typing and inheritance are two different things.  Duck
> >> typing is when you implement the same operations as another object or
> >> class, whereas with inheritance you get the same implementation as
> >> that of the parent class.
>
> > Except when you override a method ...
>
> Right.  But, that's specialization which is still part of the
> inheritance model, and not duck typing, since you're also inheriting
> state.  Duck typing is about implementing an interface and has
> nothing to do with state.  Put another way, with inheritance you're
> getting both behaviour and state, with duck typing you're mimicking
> behaviour.
>
>
>
> >> With duck typing, an object "acts like"
> >> another object in specific contexts.
>
> > That's exactly what Str(str) does in the context dictionary look-
> > up ...
>
> No, in that case Str "is-a" str, it doesn't have to act like a str
> because it is one, whereas with my Node example, Node "acts-like" a
> str (or int or any other hashable).  Read the first sentence of the
> Wikipedia article on duck typing:http://en.wikipedia.org/wiki/
> Duck_typing
>
> >> With inheritance, an object is
> >> the same general type as another object.  You don't want string
> >> objects, you want objects that, in a specific case, act like strings
> >> but in others, I'm sure, not.  How does a concept like string
> >> substitution fit with your inherited objects?
>
> > Since Str(str) inherits all methods of str, those methods that return
> > other strings (always new objects since str is immutable) like e.g.
> > replace() will return str and not Str(str), and don't have the meta
> > data copied. Which may be a bug or a feature  ...:-)
>
> > I think the subtle difference here lies between the definition of
> > inheritance and duck-typing, and how both are typically used in
> > practice ...
>
> Right, here you're wanting to implement your Node as a specialization
> of str in order to get only some of it's behaviour.  But the
> abstractions of a graph node and string don't mix with some of str's
> other behaviour.  To me this is obtuse:
>
>  >>> class Node(str): pass
> ...
>  >>> n = Node('funky %s')
>  >>> n.children = [Node('child1'), Node('child2')]
>  >>> print n % 'yes
> funky yes
>
> Duck typing is what you're looking for and is specifically not
> inheritance.
>
> I'd like to note that my entire argument has been based on the
> semantics of inheritance v. duck typing.  I'm not saying what you're
> doing won't work, just that when I see someone inherit from str I
> expect a str-like object in intention, it being hashable should be
> incidental to that.  This example is sufficiently small and simple
> that if you do choose inheritance you're not likely to get bitten.
> But, once you get in the habit of breaking abstractions like this you
> open yourself up for a world of hurt in other scenarios.
>
> Another thing to think about is that the only thing you have to gain
> with piggy backing str like this is saving three lines of typing, 4
> lines to implement __hash__ and __eq__ v. 1 line to inherit from str.

I get your point. And you are right, I certainly won't use this
technique for anything larger than in this example. As I mentioned in
my OP, I was using the networkx graph package (BTW an excellent
library IMHO, https://networkx.lanl.gov/wiki), and in most cases it is
sufficient (as in the examples on the web site) that nodes *are* just
simple strings or integers. Networkx is about the graph (i.e.
relationships between nodes) and does not use any "internal" node
information except for their identity as defined by __hash__ and
__eq__. That's from where I started 

Andreas

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


Re: urllib.ProxyHandler HTTPS issues

2007-10-11 Thread Devraj
Thanks John. Will investigate sending the CONNECT command to handle
proxies.

Do you recommend doing this for HTTP proxies as well or should I just
use the ProxyHandler for HTTP proxies?


On Oct 12, 4:29 am, [EMAIL PROTECTED] (John J. Lee) wrote:
> Devraj <[EMAIL PROTECTED]> writes:
> > Hi everyone,
>
> > I have been reading various documents/posts on the web about handling
> > proxy options in urllib2. Some of them suggest that urllib2 doesn't
> > handle HTTPS and others say it does. I have successfully written code
> > that relays HTTP connections via a proxy but have failed to do the
> > same for HTTPS connections.
>
> urllib2 does not support "HTTPS proxies" (it does not support use of
> the CONNECT method).
>
> > Can anyone confirm if urllib2 can handle HTTPS,
>
> Yes, it can.
>
> John


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


external access to instances

2007-10-11 Thread Ladislav Andel
Hello,
I have an application which is running in a loop(client/server app using 
twisted and reactor) and where are kept list of instances in memory.
Each instance has it's own loop and it periodically sends requests to 
given network endpoints.
I would like to use a tool(module) which accesses this list of instances 
and the access would be quite occasional because it would be based
on committing changes manually.
How could I get to the list of instances since the tool is not running 
in the main loop of the application?
There should be probably something listening in the main loop and if I 
want to commit changes it would access the main loop and add or delete 
an instance from the list. (adding and deleting is against database so I 
just need simply to run the function in the main loop which will do the 
update)

Any ideas with working approach?

Thank you.
Lada

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


Diferent files: GUI (wxpython) Program

2007-10-11 Thread marc
Hi why I can call an .py GUI (wxpython) from a program and control it?
I'm newbie in python.
-- 
http://mail.python.org/mailman/listinfo/python-list


decorating container types (Python 2.4)

2007-10-11 Thread timaranz
Hi,

I have a container class A and I want to add functionality to it by
using a decorator class B, as follows:

class A(object):
def __len__(self):
return 5

class B(object):
def __init__(self, a):
self._a = a

def __getattr__(self, attr):
return getattr(self._a, attr)

def other_methods(self):
blah blah blah

I was expecting len(B) to return 5 but I get
AttributeError: type object 'B' has no attribute '__len__'
instead.
I was expecting len() to call B.__len__() which would invoke
B.__getattr__ to call A.__len__ but __getattr__ is not being called.
I can work around this, but I am curious if anyone knows _why_
__getattr__ is not being called in this situation.

Thanks
Tim

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-10-11 Thread John W. Kennedy
[EMAIL PROTECTED] wrote:
> Do not bluntly contradict me in public.

You are in grave need of professional psychiatric help.

Seek it now, if you do not wish your life to be ended three or four 
years down the line by a police sniper.

-- 
John W. Kennedy
Read the remains of Shakespeare's lost play, now annotated!
http://pws.prserv.net/jwkennedy/Double%20Falshood/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Web Ontology Language (OWL) parsing

2007-10-11 Thread Sean Davis
I would like to parse some OWL files, but I haven't dealt with OWL in
python or any other language for that matter.  Some quick google
searches do not turn up much in the way of possibilities for doing so
in python.  Any suggestions of available code or using existing
libraries for doing so?

Thanks,
Sean

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


Re: Library for crawling forums

2007-10-11 Thread Thomas Wittek
BlueCrux:
> I'm trying to write a utility to crawl forums and strip posts to be
> gone through offline. Just the content, I don't need to get who posted
> or sigs or any identifying info.
> 
> Can anyone suggest a library that is already geared toward this?

Maybe a combination of mechanize [1] and BeautifulSoup [2]?

[1] http://wwwsearch.sourceforge.net/mechanize/
[2] http://www.crummy.com/software/BeautifulSoup/
-- 
Thomas Wittek
Web: http://gedankenkonstrukt.de/
Jabber: [EMAIL PROTECTED]
GPG: 0xF534E231
-- 
http://mail.python.org/mailman/listinfo/python-list


Top 10 Caribbean island destinations

2007-10-11 Thread arturklis4
See the most popular Caribbean island destinations

http://tropical-destinations.blogspot.com/

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


Re: problem with wxPanel derivation class

2007-10-11 Thread Chris Mellon
On 10/11/07, <"@bag.python.org <"none> wrote:
> wxGlade created a simple Frame with a panel a sizer and 3 wxControls ,
> saticText, TextCtrl, and a Button.
>


> It seems as though the complaint is that  a 'wxWindow *' is expected,
> 'Panel' is received
> However, Panel IS a wx.Panel derivative which IS a wx.Window derivative!
> Additionally, the methods in the code of Panel and MyFrameOne seem to be
> identical.
> I can't understand this. Anyone have any thoughts?
>

It's because you didn't call the base class __init__. wxPython is a
SWIG wrapper around the C++ wxWidgets library, and if you don't call
the base class the SWIG infrastructure that maps your class to an
underlying C++ class doesn't happen and you get this error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: storing meta data on dictionary keys

2007-10-11 Thread Erik Jones
On Oct 11, 2007, at 2:25 PM, Andreas Kraemer wrote:

> On Oct 11, 10:17 am, Erik Jones <[EMAIL PROTECTED]> wrote:
>
>> No, duck typing and inheritance are two different things.  Duck
>> typing is when you implement the same operations as another object or
>> class, whereas with inheritance you get the same implementation as
>> that of the parent class.
>
> Except when you override a method ...

Right.  But, that's specialization which is still part of the  
inheritance model, and not duck typing, since you're also inheriting  
state.  Duck typing is about implementing an interface and has  
nothing to do with state.  Put another way, with inheritance you're  
getting both behaviour and state, with duck typing you're mimicking  
behaviour.

>
>> With duck typing, an object "acts like"
>> another object in specific contexts.
>
> That's exactly what Str(str) does in the context dictionary look-
> up ...

No, in that case Str "is-a" str, it doesn't have to act like a str  
because it is one, whereas with my Node example, Node "acts-like" a  
str (or int or any other hashable).  Read the first sentence of the  
Wikipedia article on duck typing: http://en.wikipedia.org/wiki/ 
Duck_typing

>> With inheritance, an object is
>> the same general type as another object.  You don't want string
>> objects, you want objects that, in a specific case, act like strings
>> but in others, I'm sure, not.  How does a concept like string
>> substitution fit with your inherited objects?
>
> Since Str(str) inherits all methods of str, those methods that return
> other strings (always new objects since str is immutable) like e.g.
> replace() will return str and not Str(str), and don't have the meta
> data copied. Which may be a bug or a feature  ...:-)
>
> I think the subtle difference here lies between the definition of
> inheritance and duck-typing, and how both are typically used in
> practice ...

Right, here you're wanting to implement your Node as a specialization  
of str in order to get only some of it's behaviour.  But the  
abstractions of a graph node and string don't mix with some of str's  
other behaviour.  To me this is obtuse:

 >>> class Node(str): pass
...
 >>> n = Node('funky %s')
 >>> n.children = [Node('child1'), Node('child2')]
 >>> print n % 'yes
funky yes

Duck typing is what you're looking for and is specifically not  
inheritance.

I'd like to note that my entire argument has been based on the  
semantics of inheritance v. duck typing.  I'm not saying what you're  
doing won't work, just that when I see someone inherit from str I  
expect a str-like object in intention, it being hashable should be  
incidental to that.  This example is sufficiently small and simple  
that if you do choose inheritance you're not likely to get bitten.   
But, once you get in the habit of breaking abstractions like this you  
open yourself up for a world of hurt in other scenarios.

Another thing to think about is that the only thing you have to gain  
with piggy backing str like this is saving three lines of typing, 4  
lines to implement __hash__ and __eq__ v. 1 line to inherit from str.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com


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


Re: EasyMock for python ?

2007-10-11 Thread Goldfish
I had to get the hang of jMock-style testing through the usage of the
pmock library. But it seems to work out pretty well.

See some of my test cases at
http://springpython.python-hosting.com/browser/trunk/src/springpython/test/databaseCoreTestCases.py.

That should provide a hearty sample of uses for this mock set. It
easily let me throw away the real database and conclude unit testing
much faster.

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


Re: problem with wxPanel derivation class

2007-10-11 Thread kyosohma

You've got calls for properties in other classes and you don't
initialize the panel object. I edited the code somewhat so it'll at
least run. I tried to comment where I changed things, but I may have
missed a few minor points. See below:



 #The commented out code from MyFrame was moved to class Panel \
# and appropriately modified by changing self.panel to self etc

import wx

class MyFrameTwo(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrameTwo.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
##  self.panel = panel(self, -1)
self.panel = Panel(self, -1)
self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrameTwo.__set_properties
self.SetTitle("frame_1")
# end wxGlade

def __do_layout(self):
# begin wxGlade: MyFrameTwo.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.panel, 1, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
sizer_1.SetSizeHints(self)
self.Layout()
# end wxGlade

# end of class MyFrameTwo

class Panel (wx.Panel):
def __init__(self, parent, *args, **kwds):
wx.Panel.__init__(self, parent) # Added line
self.staticbox = wx.StaticBox(self, -1, "StaticBox")
self.label = wx.StaticText(self, -1, "Field Name")
self.textBox = wx.TextCtrl(self, -1, "Field Value")
self.button = wx.Button(self, -1, "Edit")
self.__doLayout() # added self

def __doLayout(self): # added argument
sizer = wx.StaticBoxSizer(self.staticbox,
wx.HORIZONTAL)
sizer.Add(self.label, 0, wx.ALL, 3)
sizer.Add(self.textBox, 0, wx.ALL, 3)
sizer.Add(self.button, 0, wx.ALL, 3)
self.label.SetMinSize((-1, 15)) # moved from Frame

# maybe comment this and uncommennt  frame2's
corresponding line
self.SetAutoLayout(True)

self.SetSizer(sizer)
sizer.Fit(self)
sizer.SetSizeHints(self)

## modified from BoaApp
class App(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = MyFrameTwo(None)
self.main.Show()
self.SetTopWindow(self.main)
return True

def main():
application = App(0)
application.MainLoop()

if __name__ == '__main__':
main()




Larry is correct. You'll get better help from the wxPython group. See
http://wxpython.org/maillist.php

Mike

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


Re: Accessing Function Variables from Sub-functions

2007-10-11 Thread Terry Reedy

"Licheng Fang" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Sorry to dig up this old thread, but I would like to know what's the
| rationale is. Why can't a nested function rebind a variable of an
| outer function?

Because it is debateble whether this is overall a good idea and because it 
was not obvious exactly how to do so.  (There were about 10 different 
proposals.)  I believe an addition is scheduled for 3.0 (and 2.6 I 
suspect). 



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


Re: determining fully qualified package & class name

2007-10-11 Thread Goldfish
import myPackage

f = myPackage.foo()

print f.__module__ + "." + f.__class__.__name__

That should do it!

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread Chris Mellon
On 10/11/07, brad <[EMAIL PROTECTED]> wrote:
> Chris Mellon wrote:
>
> > In case you're doing this for PCI validation, be aware that just the
> > CC number is considered sensitive and you'd get some false negatives
> > if you filter on anything except that.
> >
> > Random strings that match CC checksums are really quite rare and false
> > positives from that alone are unlikely to be a problem. Unless I
> > deployed this and there was a significant false positive rate I
> > wouldn't risk the false negatives, personally.
>
> Yes, it is for PCI. Our rate of false positives is low, very low. I
> wasn't aware that a number alone was a PCI violation. Thank you! On
> another note, we're a university (Virginia Tech) and we're subject to
> FERPA, HIPPA, GLBA, etc... in addition to PCI. So we do these checks for
> U.S. Social Security Numbers too in an effort to prevent or lessen the
> chance of ID theft. Unfortunately, there is no luhn check for SSNs. We
> follow the Social Security Administration verification guideline
> religiously... here's an web front-end to my logic:
>
> http://black.cirt.vt.edu/public/valid_ssn/index.html
>
> but still have many false positives on SSNs, so being able to id *names
> and numbers* in files would still be a be benefit to us.
>
> Brad
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Defining the problem as "given a word, figure out if that word is
likely to be a name", it seems the simplest solution is to get a
corpus of names and then flag them based on edit distance from words
in the name list. Maybe soundex? You're going to need  a *massive*
corpus though, and that might be a problem if you distribute this for
people to run instead of doing it centrally.

As a totally off the wall speculation, you might be able to train a
neural net against a large enough corpus (Say, your student and
faculty member databases) and end up with something that can match a
name algorithmically without needing the table. This is a really hard
problem - maybe you can get your CompSci department to make it part of
someones thesis ;)

Once you've got a way to tell if a word might be a name, and a way to
tell if another word is likely to be a SSN, you just need to match up
hits within the same document, use some sort of distance filter, and
then you'll be "done".

I assume this is intended primary to catch files that people are
storing accidentally, rather that catching intentional identity theft
in action. It'd be trivial to hide from these sort of scans if you
were actively malicious.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multimethods decorator

2007-10-11 Thread Gerardo Herzig
Bruno Desthuilliers wrote:

>[EMAIL PROTECTED] a écrit :
>  
>
>>>Gerardo Herzig a écrit :
>>>  
>>>
Hi all. Im reading the Gido's aproach using decorators at
http://www.artima.com/weblogs/viewpost.jsp?thread=101605

It looks good to me, but the examples shows the functionality using
functions.
Now, when i try to give this decorator into a method, if i try the

class test(object):
   @multimethod(...)
   def met(self, ...):

The multimethod decorator needs the types of the arguments, and, if the
met method requires self as the first argument, the multimethod should
look like
@multimethod(self.__class__, bla, ble) or some like that...

Now i know that im wrong, because i have this error
 >@multimethod(self.__class__)
 >NameError: name 'self' is not defined


>>>Indeed. Neither self (which will only be known at method call time) nor
>>>even the 'test' class (which is not yet defined when the decorator is
>>>executed) are availables.
>>>  
>>>
>
>  
>
>>Doh!
>>
>>
>
>If you're surprised, then you'd better learn way more about Python's 
>internal (execution model && object model mostly) before continuing with 
>multimethods.
>  
>
Is not that, is just...it allways make sense to me AFTER someone tells 
me!! :)

>  
>
So what would be the first argument to @multimethod??


>>>A string ?-)
>>>  
>>>
>
>  
>
>>Ah? And what will that string contains?
>>
>>
>
>What makes sens for you. Don't forget that Python has very strong 
>introspection features. Also note that it's not uncommon to use a 2-pass 
>approach : marking some methods with the decorator, then doing the real 
>processing in the metaclass (which of course implies a custom metaclass) 
>or in the __new__ method (in which case this processing will happen on 
>*each* instanciation).
>  
>
Oh well, now you kill me with that one.

>  
>
>>>FWIW, there's already an implementation of multiple dispacth by Mr. Eby...
>>>  
>>>
>>Oh yes, i found the dispatch version of multimethods, but i have not tried
>>it yet. Do you think is better this version than Guido's?
>>
>>
>
>I think that dispatch is actually used in a few packages, frameworks or 
>applications. Is it the case of Guido's stuff ?
>
>Also, IIRC, Guido's snippet is quite less generic than dispatch (which 
>is based on expression rules, not only on types).
>  
>
Ok. So im giving dispatch version a chance. Its working nice so far. 
Thanks Man!
Gerardo
-- 
http://mail.python.org/mailman/listinfo/python-list


Guitars Masters

2007-10-11 Thread arturklis2
Guitars reviews, lessons, pictures, and more!!!

http://guitars-masters.blogspot.com/

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread brad
Chris Mellon wrote:

> In case you're doing this for PCI validation, be aware that just the
> CC number is considered sensitive and you'd get some false negatives
> if you filter on anything except that.
> 
> Random strings that match CC checksums are really quite rare and false
> positives from that alone are unlikely to be a problem. Unless I
> deployed this and there was a significant false positive rate I
> wouldn't risk the false negatives, personally.

Yes, it is for PCI. Our rate of false positives is low, very low. I 
wasn't aware that a number alone was a PCI violation. Thank you! On 
another note, we're a university (Virginia Tech) and we're subject to 
FERPA, HIPPA, GLBA, etc... in addition to PCI. So we do these checks for 
U.S. Social Security Numbers too in an effort to prevent or lessen the 
chance of ID theft. Unfortunately, there is no luhn check for SSNs. We 
follow the Social Security Administration verification guideline 
religiously... here's an web front-end to my logic:

http://black.cirt.vt.edu/public/valid_ssn/index.html

but still have many false positives on SSNs, so being able to id *names 
and numbers* in files would still be a be benefit to us.

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread Chris Mellon
On 10/11/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Oct 11, 12:49 pm, Matimus <[EMAIL PROTECTED]> wrote:
> > On Oct 11, 9:11 am, brad <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> > > [EMAIL PROTECTED] wrote:
> > > > However...how can you know it is a name...
> >
> > > OK, I admitted in my first post that it was a crazy question, but if one
> > > could find an answer, one would be onto something. Maybe it's not a 100%
> > > answerable question, but I would guess that it is an 80% answerable
> > > question... I just don't know how... yet :)
> >
> > > Besides admitting that it's a crazy question, I should stop and explain
> > > how it would be useful to me at least. Is a credit card number itself
> > > valuable? I would think not. One can easily re and luhn check for credit
> > > card numbers located in files with a great degree of accuracy, but a
> > > number without a name is not very useful to me. So, if one could
> > > associate names to luhn checked numbers automatically, then one would be
> > > onto something. Or at least say, "hey, this file has luhn validated CCs
> > > *AND* it seems to have people's names in it as well." Now then, I'd have
> > > less to review or perhaps as much as I have now, but I could push the
> > > files with numbers and names to the top of the list so that they would
> > > be reviewed first.
> >
> > > Brad
> >
> > What the hell are you doing? Your post sounds to me like you have a
> > huge amount of stolen, or at the very least misapprehended, data. Now
> > you want to search it for credit card numbers and names so that you
> > can use them.
> >
> > I am not cool with this! This is a public forum about a programming
> > language. What makes you think that anybody in this forum will be cool
> > with that. Perhaps you aren't doing anything illegal, but it sure is
> > coming off that way. If you are doing something illegal I hope you get
> > caught.
> >
> > At the very least, you might want to clarify why you are looking for
> > such capability so that you don't get effectively black-listed (well,
> > by me at least).
> >
> > Matt
>
> Go have a beer and calm down a bit :) It's a legitimate purpose,
> although it could (and probably is being used by bad guys right now).
> My intent, as you can see from the links below, is to catch it before
> the bad guys do.
>
> http://filebox.vt.edu/users/rtilley/public/find_ccns/
> http://filebox.vt.edu/users/rtilley/public/find_ssns/
>
> Brad
>

In case you're doing this for PCI validation, be aware that just the
CC number is considered sensitive and you'd get some false negatives
if you filter on anything except that.

Random strings that match CC checksums are really quite rare and false
positives from that alone are unlikely to be a problem. Unless I
deployed this and there was a significant false positive rate I
wouldn't risk the false negatives, personally.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python SVN down?

2007-10-11 Thread Martin v. Löwis
> Are all the real  ( ;-) ) developers using ssh+svn and not noticing
> this?

As Terry said, some noticed. But yes, many use svn+ssh, plus we live
in different time zones, so we may be asleep when it breaks.

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


Re: Library for crawling forums

2007-10-11 Thread James Matthews
Well i know some that do half the job

urllib or urllib2 to download the page
htmlparser or beautifulsoup For html parsing

Enjoy

On 10/11/07, BlueCrux <[EMAIL PROTECTED]> wrote:
>
> I'm trying to write a utility to crawl forums and strip posts to be
> gone through offline. Just the content, I don't need to get who posted
> or sigs or any identifying info.
>
> Can anyone suggest a library that is already geared toward this?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/search.aspx?Search=Cufflinks
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: storing meta data on dictionary keys

2007-10-11 Thread Andreas Kraemer
On Oct 11, 10:17 am, Erik Jones <[EMAIL PROTECTED]> wrote:

> No, duck typing and inheritance are two different things.  Duck
> typing is when you implement the same operations as another object or
> class, whereas with inheritance you get the same implementation as
> that of the parent class.

Except when you override a method ...

> With duck typing, an object "acts like"
> another object in specific contexts.

That's exactly what Str(str) does in the context dictionary look-
up ...

> With inheritance, an object is
> the same general type as another object.  You don't want string
> objects, you want objects that, in a specific case, act like strings
> but in others, I'm sure, not.  How does a concept like string
> substitution fit with your inherited objects?

Since Str(str) inherits all methods of str, those methods that return
other strings (always new objects since str is immutable) like e.g.
replace() will return str and not Str(str), and don't have the meta
data copied. Which may be a bug or a feature  ...:-)

I think the subtle difference here lies between the definition of
inheritance and duck-typing, and how both are typically used in
practice ...

> If you can, get a copy of Beautiful Code (easily had from Amazon or
> the likes).  It contains an chapter on Python's dictionary
> implementation.

Thanks for the pointer. I like to look at beautiful code.

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread John J. Lee
brad <[EMAIL PROTECTED]> writes:

> Crazy question, but has anyone attempted this or seen Python code that
> does? For example, if a text file contained 'Guido' and or 'Robert'
> and or 'Susan', then we should return True, otherwise return False.

A few ideas:

1. If you don't have a list of names, find a list of words that
doesn't contain proper nouns (there are a few word lists out there,
not sure if any exclude people's names, though).  Look for short runs
of two or three "words" (punctuation-separated tokens) in the email
that aren't in the dictionary.  Some of them will be people's names.

2. Send the text through Google translate and look for runs of words
that are unchanged.  Some of them will be people's names.

3. Search the literature and look for fancy algorithms.  Here are some
papers (the last mentions some commercial software to do this):

http://citeseer.ist.psu.edu/bikel99algorithm.html

http://citeseer.ist.psu.edu/618945.html

http://arxiv.org/html/cmp-lg/9706017


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


Re: Python SVN down?

2007-10-11 Thread Terry Reedy

"Anthon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I am trying to get at the python source code, but it seems
| svn.python.org is down, at least on port 80 (http) and 3690 (svn).
| This happened earlier this week and then it came back (at least
| yesterday).
| Are all the real  ( ;-) ) developers using ssh+svn and not noticing
| this?

The down, up, and down again were all noted on pydev.



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


Library for crawling forums

2007-10-11 Thread BlueCrux
I'm trying to write a utility to crawl forums and strip posts to be
gone through offline. Just the content, I don't need to get who posted
or sigs or any identifying info.

Can anyone suggest a library that is already geared toward this?

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


Re: weakrefs and bound methods

2007-10-11 Thread Mathias Panzenboeck
Bruno Desthuilliers wrote:
> Mathias Panzenboeck a écrit :
> 
> About the lost weakref problem: in Python, methods are just tiny
> wrappers around the object, class and function created at lookup time
> (yes, on *each* lookup) (and WWAI, they are by the function object
> itself, which implements the descriptor protocol).
> 
>> When I change the class Wrapper to following, the class Foo works:
>>
>> class Wrapper(object):
>> def __init__(self,x):
>> self.func_name = x.func_name
>> self.x = weakref.ref(x.im_self)
> 
>> def __call__(self,*args,**kwargs):
>> x = self.x()
>> if x is None:
>> print "lost reference"
>> else:
>> return getattr(x,self.func_name)(*args,**kwargs)
> 
> Anyway, the whole thing looks quite baroque to me - and I'm known for my
> immoderate appetite for brain-melting features
> 
> If I understand correctly, you're doing all this to avoid circular
> references while keeping track of a list of methods to call ?
> 
> If yes, then you're thru much pain for nothing. Mostly because there are
>  other much more simpler solutions. The first one is obviously to use
> names and getattr. In it's most naïve implementation, this would look like:
> 
> class Foo(object):
> def __init__(self):
> self._methods = set()
> self._methods.add('_foo')
> 
> def _foo(self):
> print "_foo"
> 
> def callMethods(self):
>  for name in self._methods:
>  meth = getattr(self, name, None)
>  if callable(meth):
>  meth()
> 
> 
> 
> 
> Now if _methods is supposed to have the same content class-wise (which
> is the case in your exemple), no need to have it as an instance method:
> 
> class Foo(object):
> _methods = set('_foo')
> 
> def _foo(self):
> print "_foo"
> 
> def callMethods(self):
>  for name in self._methods:
>  meth = getattr(self, name, None)
>  if callable(meth):
>  meth()
> 
> We could go further, like using a decorator to mark methods to add to
> _methods, and a metaclass to set the whole thing up, but this would
> probably be overkill. Unless there are other requirements, I'd
> personnaly stop here.
> 
> Oh, and yes, while we're at it : Python usually knows how to deal with
> circular references
> 

Well yes and no. It does with the enabled gc but I like refcounting much more 
because
of the predictable behaviour. And when there are no refloops, refcounting makes 
no
problems. However, Alex Martelli already showed a great way to do what I need, 
see:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81253

I need it for a little UI lib. Well lib is too much. Just a small wrapper around
blenders unusable API for building GUIs for your scripts. It's ugly as hell.
I made very few classes to wrap up that crap. Every input widget in my UI lib 
has an
action. You can register action listeners like this:

def actionListener(value):
print "new value:",value

widget.addActionListener(actionListener)

When an widget itself want's to listen for it's action and does this in 
__init__:

self.addActionListener(sefl.__actionListener)

there would be a ref loop. Therefore I do this now:

self.addActionListener(WeakListener(sefl.__actionListener))

And WeakListener I implemented as follows:

class WeakListener(object):
__slots__ = ('__weakref__', '_func','_obj')

def __init__(self,listener):
self._func = listener.im_func
self._obj  = weakref.ref(listener.im_self)

def __call__(self,*args,**kwargs):
obj = self._obj()

if obj is None:
print "*** lost reference to %s's self object ***" % \
self._func.func_name
else:
self._func(obj,*args,**kwargs)


Could be better/more generic, but that's all I need.

To implement the action listener by overloading a action method is IMHO a bad 
idea.
Because that would kill the listener of the base class. Explicitly calling the 
base
classes action method is ugly and error prone. And when I have to register 
action
listeners from "outside" the widget, too.

But thanks for your reply. :)

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


Re: Declarative properties

2007-10-11 Thread Paul Hankin
On Oct 11, 7:42 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> Sorry I don't get it.  If I want to customize the access to a "normal"
> attribute I simply turn it into a property.

I *think* I understand Artur's problem: he wants to be able to add
(for example) clean-up and validation code to public accesses of these
attributes, but he doesn't want this code run internally to the class.
Or another way of saying the same thing: he wants two views of a
variable; one internal to the class, another to the public.

If I understand correctly, his plan is to use 'X._name' internally to
code in his class, but the public uses 'X.name'. Initially, one is an
alias for the other, but later he writes getters and setters to
customise access through the public version.

[I could be totally wrong of course]
--
Paul Hankin

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


Re: problem with wxPanel derivation class

2007-10-11 Thread Larry Bates
none wrote:
> wxGlade created a simple Frame with a panel a sizer and 3 wxControls ,
> saticText, TextCtrl, and a Button.
> 
> The resulting code works fine.
> 
> Now the problem.
> I wish to make a separate class derrived from wxPanel that has the sized
> and controls as above.  It jusst won't work
> 
> 
> 
> #!/usr/bin/env python
> # -*- coding: ISO-8859-1 -*-
> # generated by wxGlade 0.4cvs on Thu Oct 11 13:26:19 2007
> 
> import wx
> 
> class MyFrameOne(wx.Frame):
> def __init__(self, *args, **kwds):
> # begin wxGlade: MyFrameOne.__init__
> kwds["style"] = wx.DEFAULT_FRAME_STYLE
> wx.Frame.__init__(self, *args, **kwds)
> self.panel = wx.Panel(self, -1)
> self.staticbox = wx.StaticBox(self.panel, -1, "StaticBox")
> self.label = wx.StaticText(self.panel, -1, "Field Name")
> self.textBox = wx.TextCtrl(self.panel, -1, "Field Value")
> self.button = wx.Button(self.panel, -1, "Edit")
> 
> self.__set_properties()
> self.__do_layout()
> # end wxGlade
> 
> def __set_properties(self):
> # begin wxGlade: MyFrameOne.__set_properties
> self.SetTitle("frame_1")
> self.label.SetMinSize((-1, 15))
> # end wxGlade
> 
> def __do_layout(self):
> # begin wxGlade: MyFrameOne.__do_layout
> sizer_1 = wx.BoxSizer(wx.VERTICAL)
> sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
> sizer.Add(self.label, 0, wx.ALL, 3)
> sizer.Add(self.textBox, 0, wx.ALL, 3)
> sizer.Add(self.button, 0, wx.ALL, 3)
> self.panel.SetAutoLayout(True)
> self.panel.SetSizer(sizer)
> sizer.Fit(self.panel)
> sizer.SetSizeHints(self.panel)
> sizer_1.Add(self.panel, 1, wx.EXPAND, 0)
> self.SetAutoLayout(True)
> self.SetSizer(sizer_1)
> sizer_1.Fit(self)
> sizer_1.SetSizeHints(self)
> self.Layout()
> # end wxGlade
> 
> # end of class MyFrameOne
> 
> ## modified from BoaApp
> class App(wx.App):
>   def OnInit(self):
>   wx.InitAllImageHandlers()
>   self.main = MyFrameOne(None)
>   self.main.Show()
>   self.SetTopWindow(self.main)
>   return True
> 
> def main():
>   application = App(0)
>   application.MainLoop()
> 
> if __name__ == '__main__':
>   main()
> 
> 
> 
> 
> #!/usr/bin/env python
> # -*- coding: ISO-8859-1 -*-
> #The commented out code from MyFrame was moved to class Panel \
> # and appropriately modified by changing self.panel to self etc
> 
> import wx
> 
> class MyFrameTwo(wx.Frame):
>   def __init__(self, *args, **kwds):
>   # begin wxGlade: MyFrameTwo.__init__
>   kwds["style"] = wx.DEFAULT_FRAME_STYLE
>   wx.Frame.__init__(self, *args, **kwds)
> ##self.panel = panel(self, -1)
>   self.panel = Panel(self, -1)
>   self.__set_properties()
>   self.__do_layout()
>   # end wxGlade
> 
>   def __set_properties(self):
>   # begin wxGlade: MyFrameTwo.__set_properties
>   self.SetTitle("frame_1")
>   self.label.SetMinSize((-1, 15))
>   # end wxGlade
> 
>   def __do_layout(self):
>   # begin wxGlade: MyFrameTwo.__do_layout
>   sizer_1 = wx.BoxSizer(wx.VERTICAL)
> ##sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
> ##sizer.Add(self.label, 0, wx.ALL, 3)
> ##sizer.Add(self.textBox, 0, wx.ALL, 3)
> ##sizer.Add(self.button, 0, wx.ALL, 3)
>   self.panel.SetAutoLayout(True)
> ##self.panel.SetSizer(sizer)
> ##sizer.Fit(self.panel)
> ##sizer.SetSizeHints(self.panel)
>   sizer_1.Add(self.panel, 1, wx.EXPAND, 0)
>   self.SetAutoLayout(True)
>   self.SetSizer(sizer_1)
>   sizer_1.Fit(self)
>   sizer_1.SetSizeHints(self)
>   self.Layout()
>   # end wxGlade
> 
> # end of class MyFrameTwo
> 
> 
> class Panel (wx.Panel):
>   def __init__(self, *args, **kwds):
>   self.staticbox = wx.StaticBox(self, -1, "StaticBox")
>   self.label = wx.StaticText(self, -1, "Field Name")
>   self.textBox = wx.TextCtrl(self, -1, "Field Value")
>   self.button = wx.Button(self, -1, "Edit")
>   __doLayout()
> 
>   def __doLayout():
>   sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
>   sizer.Add(self.label, 0, wx.ALL, 3)
>   sizer.Add(self.textBox, 0, wx.ALL, 3)
>   sizer.Add(self.button, 0, wx.ALL, 3)
>   
>   # maybe comment this and uncommennt  frame2's corresponding line
>   panel.SetAutoLayout(True)
>   
>   self.SetSizer(sizer)
>   sizer.Fit(self.panel)
>   sizer.SetSizeHin

Re: "".join(string_generator()) fails to be magic

2007-10-11 Thread Dan Stromberg
On Thu, 11 Oct 2007 01:26:04 -0500, Matt Mackal wrote:

> I have an application that occassionally is called upon to process
> strings that are a substantial portion of the size of memory. For
> various reasons, the resultant strings must fit completely in RAM.
> Occassionally, I need to join some large strings to build some even
> larger strings.
> 
> Unfortunately, there's no good way of doing this without using 2x the
> amount of memory as the result. You can get most of the way there with
> things like cStringIO or mmap objects, but when you want to actually
> get the result as a Python string, you run into the copy again.
> 
> Thus, it would be nice if there was a way to join the output of a
> string generator so that I didn't need to keep the partial strings in
> memory.  would be the obvious way to do this, but it of
> course converts the generator output to a list first.
> 
> -- 
>  "Love the dolphins," she advised him. "Write by W.A.S.T.E.."

Some options you might evaluate (I'm -not- guaranteeing all of these'll
work "as advertised"):

1) Add some swap space to your machine and use standard python strings

2) Use mmap.  I may be wrong, and I know you mentioned mmap, but I suspect
that mmap won't use up VM equal to the size of an mmap'd file; I suspect
it just caches portions of the data in physical memory when it's
convenient to do so with the primary copy of the data residing on disk in
a file

3) Use ctypes, and stay in ctypes - don't convert them to python str's. 
Of course, then you're basically writing a C program using the python
intrepreter

4) Use temporary files via the usual file API

5) If you can live with alpha code, you might try the python 3 alpha and
use the mutable "bytes" type, and stay in the "bytes" type - don't convert
it to a str


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


Re: Declarative properties

2007-10-11 Thread Paul Hankin
On Oct 11, 12:48 pm, Artur Siekielski <[EMAIL PROTECTED]>
wrote:
> Hi.
>
> I would like to have declarative properties in Python, ie. something
> like slots definitions in defclass in Common Lisp. It seems that even
> Java will have it, using a library (https://bean-properties.dev.java.net/
> ).
>
> I know about 'property' function in Python, but it's normal usage
> isn't declarative, because I have to code imperatively getters and
> setters:
>
> class Person(object):
>def __init__(self, name):
>   self._name = name
>def _get_name(self):
>   return self._name
>def _set_name(self, new_name):
>   self._name = new_name
>name = property(_get_name, _set_name)
>
> I would like to have something like that:
>
> class Person(object):
>name = property('_name')

Here's something that does what I think you want. I think your use
case is quite unusual in that you expect the public accessors to
change (keeping private use the same), and that you know you're going
to have a costly rewrite of your class when that happens.

Attributes that are declared with 'magic_attribute' access the private
attribute '_', unless there's a '_get_' or '_set_'
method in which case those are called instead.

def magic_attribute(_name):
def set(self, value):
try:
getattr(self, '_set' + _name)(value)
except AttributeError:
setattr(self, _name, value)
def get(self):
try:
return getattr(self, '_get' + _name)()
except AttributeError:
return getattr(self, _name)
return property(get, set)

# An example use...
class C(object):
x = magic_attribute('_x')
y = magic_attribute('_y')

# Override the default set method for x
def _set_x(self, value):
self._x = value + ' world'

# Override the default get method for y
def _get_y(self):
return self._y.upper()

# Test it works...
c = C()
c.x = c.y = 'hello'
print c.x
print c.y

# hello world
# HELLO

--
Paul Hankin

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


Re: CGI and external JavaScript nightmare

2007-10-11 Thread IamIan
bump

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


Pyro: ActiveState (wind32) to Unix

2007-10-11 Thread Sells, Fred
I'm using ActiveState python on a windows box to talk to ACtive Directory.  I'm 
running a Pyro Server on the same box.

The client is Linux running std Python 2.4.

It works just fine until the server codes calls some win32com.client api;  then 
I get 


Traceback (most recent call last):
  File "C:\All\projects\AccAdminTools\src\demo002\client\client.py", line 25, 
in ?
unittest()  
  File "C:\All\projects\AccAdminTools\src\demo002\client\client.py", line 21, 
in unittest
properties = ad.getProperties()
  File 
"c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\core.py",
 line 390, in __call__
return self.__send(self.__name, args, kwargs)
  File 
"c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\core.py",
 line 468, in _invokePYRO
return self.adapter.remoteInvocation(name, 
constants.RIF_VarargsAndKeywords, vargs, kargs)
  File 
"c:\all\tools\python24\lib\site-packages\Pyro-3.7-py2.4-win32.egg\Pyro\protocol.py",
 line 416, in remoteInvocation
answer = pickle.loads(answer)
ImportError: No module named pywintypes

the offending code is 
def getProperties(self):
def getProperties(self):
  attr_dict={}
  adobj=win32com.client.GetObject(self.LdapPath)  #<<

problem with wxPanel derivation class

2007-10-11 Thread none
wxGlade created a simple Frame with a panel a sizer and 3 wxControls ,
saticText, TextCtrl, and a Button.

The resulting code works fine.

Now the problem.
I wish to make a separate class derrived from wxPanel that has the sized
and controls as above.  It jusst won't work



#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
# generated by wxGlade 0.4cvs on Thu Oct 11 13:26:19 2007

import wx

class MyFrameOne(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrameOne.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.panel = wx.Panel(self, -1)
self.staticbox = wx.StaticBox(self.panel, -1, "StaticBox")
self.label = wx.StaticText(self.panel, -1, "Field Name")
self.textBox = wx.TextCtrl(self.panel, -1, "Field Value")
self.button = wx.Button(self.panel, -1, "Edit")

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrameOne.__set_properties
self.SetTitle("frame_1")
self.label.SetMinSize((-1, 15))
# end wxGlade

def __do_layout(self):
# begin wxGlade: MyFrameOne.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
sizer.Add(self.label, 0, wx.ALL, 3)
sizer.Add(self.textBox, 0, wx.ALL, 3)
sizer.Add(self.button, 0, wx.ALL, 3)
self.panel.SetAutoLayout(True)
self.panel.SetSizer(sizer)
sizer.Fit(self.panel)
sizer.SetSizeHints(self.panel)
sizer_1.Add(self.panel, 1, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
sizer_1.SetSizeHints(self)
self.Layout()
# end wxGlade

# end of class MyFrameOne

## modified from BoaApp
class App(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = MyFrameOne(None)
self.main.Show()
self.SetTopWindow(self.main)
return True

def main():
application = App(0)
application.MainLoop()

if __name__ == '__main__':
main()




#!/usr/bin/env python
# -*- coding: ISO-8859-1 -*-
#The commented out code from MyFrame was moved to class Panel \
# and appropriately modified by changing self.panel to self etc

import wx

class MyFrameTwo(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrameTwo.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
##  self.panel = panel(self, -1)
self.panel = Panel(self, -1)
self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrameTwo.__set_properties
self.SetTitle("frame_1")
self.label.SetMinSize((-1, 15))
# end wxGlade

def __do_layout(self):
# begin wxGlade: MyFrameTwo.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
##  sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
##  sizer.Add(self.label, 0, wx.ALL, 3)
##  sizer.Add(self.textBox, 0, wx.ALL, 3)
##  sizer.Add(self.button, 0, wx.ALL, 3)
self.panel.SetAutoLayout(True)
##  self.panel.SetSizer(sizer)
##  sizer.Fit(self.panel)
##  sizer.SetSizeHints(self.panel)
sizer_1.Add(self.panel, 1, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
sizer_1.SetSizeHints(self)
self.Layout()
# end wxGlade

# end of class MyFrameTwo


class Panel (wx.Panel):
def __init__(self, *args, **kwds):
self.staticbox = wx.StaticBox(self, -1, "StaticBox")
self.label = wx.StaticText(self, -1, "Field Name")
self.textBox = wx.TextCtrl(self, -1, "Field Value")
self.button = wx.Button(self, -1, "Edit")
__doLayout()

def __doLayout():
sizer = wx.StaticBoxSizer(self.staticbox, wx.HORIZONTAL)
sizer.Add(self.label, 0, wx.ALL, 3)
sizer.Add(self.textBox, 0, wx.ALL, 3)
sizer.Add(self.button, 0, wx.ALL, 3)

# maybe comment this and uncommennt  frame2's corresponding line
panel.SetAutoLayout(True)

self.SetSizer(sizer)
sizer.Fit(self.panel)
sizer.SetSizeHints(self.panel)


## modified from BoaApp
class App(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = MyFrameTwo

Re: Declarative properties

2007-10-11 Thread Marc 'BlackJack' Rintsch
On Thu, 11 Oct 2007 09:58:48 -0700, Dan Stromberg wrote:

> On Thu, 11 Oct 2007 13:46:12 +, Marc 'BlackJack' Rintsch wrote:
> 
>> On Thu, 11 Oct 2007 13:04:53 +, Artur Siekielski wrote:
>> 
>>> 1. If I use instance field 'name' which is accessed directly by other
>>> classes,
>>> and later I decide to implement nonstandard getter, I must refactor
>>> 'Person' class
>>> and in some places change 'name' to '_name' (assuming this is now the
>>> field's name).
>>> The problem is that I cannot automatically change 'name' to '_name'
>>> everywhere, because
>>> in some places I want public property value (eg. validated and
>>> formatted), and in other
>>> places raw property value.
>> 
>> So what?  Otherwise you carry *always* the baggage of a public property
>> and a private attribute whether you need this or not.  At least for me it
>> would be unnecessary in most cases.
> 
> That "baggage" of carrying around "unneeded" methods is something the
> computer carries for you - IE, no big deal in 99.99% of all cases.

It shows twice as much attributes if I inspect the objects and I don't know
which are merely useless default getters and setters.  And it is more and
more complex code.  Code can be cut down a bit by some metaclass magic but
this brings in another complexity.

> The "baggage" of possibly fixing (AKA "generalizing") how your attributes
> are accessed is something you lug around while your deadline looms.

Sorry I don't get it.  If I want to customize the access to a "normal"
attribute I simply turn it into a property.

> Here's some code that defines such methods for you:
> 
> #!/usr/bin/env python
> 
> def gimme_set_get(foo, attribute):
>lst = [ \
>   'def set_%s(self, value):' % attribute, \
>   '  self._%s = value' % attribute, \
>   'def get_%s(self):' % attribute, \
>   '  return self._%s' % attribute, \
>   'foo.set_%s = set_%s' % (attribute, attribute), \
>   'foo.get_%s = get_%s' % (attribute, attribute) \
>   ]
>s = '\n'.join(lst)
>code = compile(s, '', 'exec')
>eval(code)
> 
> class foo:
>def __init__(self, value):
>   self.public_value = value
> gimme_set_get(foo, 'via_accessor_method_only')
> 
> f = foo(1)
> f.set_via_accessor_method_only(1/9.0)
> print f.get_via_accessor_method_only()
> 
> print dir(f)

And the benefit of this evil ``eval`` dance is exactly what!?

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


Re: Is hostmonster any good for hosting python?

2007-10-11 Thread Tim Chase
> I should have mentioned, I am thinking about using a python framework,
> either django, turbogears, or pylons.
> 
> I think these frameworks require a newer version of python, maybe 2.4.

I can't speak for the others, but I know Django can be deployed
with 2.3+ (though they offer some nicities if using 2.4).

> Also, I think some of them require a newer version of Apache - 2.0 or

mod_python requires Apache 2.x so if you're deploying with
mod_python, yes.  However, if you deploy with lighty+fastcgi,
it's moot what version of Apache you have. :)

> better. I also think these python frameworks all work with fastcgi,
> which - I think - is possible with hostmonster. Although fastcgi is
> acceptable, it is generally not the preferred solution.

The preferred Django deployment environments are

 - Apache + mod_python
 - Apache + FastCGI
 - lighttpd + FastCGI

> I do not think you will get reasonable performance with CGI, even if
> factcgi/mod_python/wsgi are not officially required.

No...with plain-ol'-CGI, performance is abysmal...the entire
framework would be reloaded for each request.  Possibly feasible
for development if you're patient and have nothing better, but
CGI is a generally bad idea.

> Also, I doubt you will find mod_python on any "standard" shared
> hosting. 

To get a python-framework environment, you usually have to get a
better hosting service as the need for mod_python or fastcgi
limits you to these hosting services.  That means no
bottom-of-the-barrel priced hosting services (which usually just
offer static pages, basic CGI, or PHP).

If one *must* use python in a CGI environment, I'll plug WebStack
(the author lurks here on c.l.p, IIRC) which does a nice job of
abstracting deployment environments so you can deploy to a
variety of targets with minimal fuss.  I have several projects in
the wild that use WebStack, before I found Django.

-tkc



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


Re: determining fully qualified package & class name

2007-10-11 Thread Marc 'BlackJack' Rintsch
On Thu, 11 Oct 2007 11:18:33 -0700, patrimith wrote:

> I am used to the following with Java:
> 
> import some.package.MyClass;
> name = MyClass.class.getName();
> 
> The value for name will be "some.package.MyClass".
> 
> For Python, I find:
> 
> from some.package.myclass import MyClass
> name = MyClass.__name__
> 
> The value for  name will be "MyClass"
> 
> Is there a comparable way to get the fully qualified name (package, module,
> and class name) in Python?

Take a look at the `__module__` attribute of the class.

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


Re: How do I make urllib2 preserve case in HTTP header names?

2007-10-11 Thread John J. Lee
[EMAIL PROTECTED] writes:

> The HTTP specification, RFC 2616, states that field names in HTTP
> headers are case insensitive.  But I'm trying to use Python 2.5.1's
> urllib2 to interact with a web service offered by Amazon.com, which
> deviates from the HTTP spec in that it requires use of case-sensitive
> header names ReportName, ReportID, and NumberOfReports.  I try to send
> an HTTP header named "NumberOfReports", but it comes out mangled as
> "Numberofreports'.  What is the best way to use Python 2.5.1 on
> Windows Server 2003 to create HTTP or HTTPS requests that do not
> mangle the case of header field names?

httplib


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


Re: urllib.ProxyHandler HTTPS issues

2007-10-11 Thread John J. Lee
Devraj <[EMAIL PROTECTED]> writes:

> Hi everyone,
>
> I have been reading various documents/posts on the web about handling
> proxy options in urllib2. Some of them suggest that urllib2 doesn't
> handle HTTPS and others say it does. I have successfully written code
> that relays HTTP connections via a proxy but have failed to do the
> same for HTTPS connections.

urllib2 does not support "HTTPS proxies" (it does not support use of
the CONNECT method).


> Can anyone confirm if urllib2 can handle HTTPS,

Yes, it can.


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


Re: matching a street address with regular expressions

2007-10-11 Thread Tim Chase
> Don't forget to write test cases. If you have a series of addresses,
> and confirm they are parsed correctly, you are in a good position to
> refine the pattern. You will instantly know if a change in pattern has
> broken another pattern.
> 
> The reason I'm saying this, is because I think your pattern is
> incomplete. I suggest you add a test case for the following street
> address:
> 
> 221B Baker Street

There are a number of weird street names and addresses that one
may need to address.  Having worked with police applications,
they often break it into the BLOCK, DIRECTION, STREET, SUFFIX and
APARTMENT/SUITE.

However, there are complications...

Block can include things like

  1234 1/2 (an actual street format from one of our test cases
where two block numbers were divided to make room)
  221B (though this might be a block + apartment)

Directions can include not only your cardinal N/S/E/W directions
(written out or abbreviated, with or without punctuation), but
can include 8-point directions or more, such as NW, Northwest,
north-west, etc.  It wouldn't even surprise me if locations with
16-point directions exist (NNW).

The Street portion is often whatever is left over when the rest
is unparsed.

The Suffix would be "Rd", "Road", "St", "Ave", "Cir", "Bvd",
"Blvd", "Row", "Hwy", "Highway", etc.  There are about 30 of them
that we used by default, but I'm sure there are some abnormals as
well.

There are wrinkles in even the above, as here in the Dallas area,
we have a "Northwest Highway" where Northwest is the street-name
of the road, not the Direction portion.

I second Goldfish's suggestion for making a suite of both normal
and abnormal addresses along with their expected breakdowns.
Depending on how normalized you want them to be, you may have to
deal with punctuation and spacing abnormalities as well.

-tkc



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


wana watch latest hindi hot videos?

2007-10-11 Thread diprat7
wana watch latest hindi hot videos?
than www.yedil.com is the site you are looking for
have a nice time with www.yedil.com .Log on now

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


determining fully qualified package & class name

2007-10-11 Thread patrimith

Hi List,

I am used to the following with Java:

import some.package.MyClass;
name = MyClass.class.getName();

The value for name will be "some.package.MyClass".

For Python, I find:

from some.package.myclass import MyClass
name = MyClass.__name__

The value for  name will be "MyClass"

Is there a comparable way to get the fully qualified name (package, module,
and class name) in Python?

Thanks,
Patrick Smith
-- 
View this message in context: 
http://www.nabble.com/determining-fully-qualified-package---class-name-tf4609111.html#a13161736
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Is hostmonster any good for hosting python?

2007-10-11 Thread walterbyrd
I should have mentioned, I am thinking about using a python framework,
either django, turbogears, or pylons.

I think these frameworks require a newer version of python, maybe 2.4.
Also, I think some of them require a newer version of Apache - 2.0 or
better. I also think these python frameworks all work with fastcgi,
which - I think - is possible with hostmonster. Although fastcgi is
acceptable, it is generally not the preferred solution.

I do not think you will get reasonable performance with CGI, even if
factcgi/mod_python/wsgi are not officially required.

Also, I doubt you will find mod_python on any "standard" shared
hosting. To get mod_python you will need 1) a host that speciallizes
in python - like webfaction. 2) a virtual host 3) something like
hcoop.net, which may be sort-of like a virtual host. BTW: hccoop.net
has a long-running freeze on new memberships.

Please correct me if I'm wrong about any of this.

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


Re: Building Binary Packages

2007-10-11 Thread kyosohma
On Oct 10, 11:53 am, "Jim B. Wilson" <[EMAIL PROTECTED]> wrote:
> On Wed, 10 Oct 2007 14:35:35 +, kyosohma wrote:
> > I am trying to figure out how to build binaries for Python packages and
> > I've done it with MinGW.
>
> Apparently, you still can:http://tinyurl.com/yb4bps

I had an acquaintance look at that information who has way more
experience in compiling extensions than I do. He says:

"MinGW seems to usually link to msvcrt.dll and the Python
distributions link to msvcr71.dll. It might be possible to convince
MinGW to use msvcr71.dll by editing the specs config file but I think
it will still link to msvcrt.dll in some cases, possibly alongside
msvcr71.dll which makes this quite a mess to debug."

Does anyone know if this is an issue?

Mike

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


Re: Python process automatically restarting itself

2007-10-11 Thread Matimus
On Oct 11, 7:17 am, Adam Atlas <[EMAIL PROTECTED]> wrote:
> What is the best way for a Python process (presumed to be a script run
> by the interpreter binary, not embedded in some other program) to
> restart itself? This is what I've been trying:
>
> import __main__
>
> for path in sys.path:
> path += '/' + __main__.__file__
> if os.access(path, os.F_OK): break
> else:
> raise Exception('WTF?')
>
> #Then, something like...
> os.execl(sys.executable, sys.executable, path, *sys.argv[1:])
>
> BUT! This is a multi-threaded program, and at least on OS X, trying to
> exec*() in a threaded process raises OSError [Errno 45] Operation not
> supported. So I tried having it fork, and having the child process
> wait for the parent process to die (in various ways) and then exec*().
> That seemed to work, sort of, but the child would not be attached to
> the original terminal, which is a must.
>
> Any ideas?

sys.path is the search path that Python uses for finding modules, and
probably isn't what you wanted. Also, it is bad practice to hard code
the file separator. In general you will want to do this:

import os.path
path = os.path.join(path, filename)

which will automatically insert the correct separator for the os you
are using.

That is moot though, since I think this is a better solution:

import os.path, __main__
path = os.path.abspath(__main__.__file__)

That isn't really necessary though. In fact, I think restarting the
process using exec* is the wrong way to go. I would simply encapsulate
my program inside of a function, set a restart flag, return from said
function and restart if the flag was set.

Something like this:

restart = False
def main():
  # do my stuff

  if need_to_restart:
global restart
restart = True

#do clean-up (shut down threads, etc.)
return retval

if __name__ == "__main__":
  retval = main()
  while restart:
restart = False
retval = main()
  sys.exit(retval)

I suppose there are reasons that you might want to restart the
process. Most of the time you are going to want to do something like
what I suggested though. And even in those other cases, you probably
want to use the subprocess module instead of an exec* function.

Matt

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


Re: Declarative properties

2007-10-11 Thread Dan Stromberg
On Thu, 11 Oct 2007 13:46:12 +, Marc 'BlackJack' Rintsch wrote:

> On Thu, 11 Oct 2007 13:04:53 +, Artur Siekielski wrote:
> 
>> On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>>> But why?  Default getters and setters are unnecessary and if you need
>>> something other than the default you need to write it anyway more
>>> explicitly.
>> 
>> I see some problems with your approach:
>> 
>> 1. If I use instance field 'name' which is accessed directly by other
>> classes,
>> and later I decide to implement nonstandard getter, I must refactor
>> 'Person' class
>> and in some places change 'name' to '_name' (assuming this is now the
>> field's name).
>> The problem is that I cannot automatically change 'name' to '_name'
>> everywhere, because
>> in some places I want public property value (eg. validated and
>> formatted), and in other
>> places raw property value.
> 
> So what?  Otherwise you carry *always* the baggage of a public property
> and a private attribute whether you need this or not.  At least for me it
> would be unnecessary in most cases.

That "baggage" of carrying around "unneeded" methods is something the
computer carries for you - IE, no big deal in 99.99% of all cases.

The "baggage" of possibly fixing (AKA "generalizing") how your attributes
are accessed is something you lug around while your deadline looms.

Here's some code that defines such methods for you:

#!/usr/bin/env python

def gimme_set_get(foo, attribute):
   lst = [ \
  'def set_%s(self, value):' % attribute, \
  '  self._%s = value' % attribute, \
  'def get_%s(self):' % attribute, \
  '  return self._%s' % attribute, \
  'foo.set_%s = set_%s' % (attribute, attribute), \
  'foo.get_%s = get_%s' % (attribute, attribute) \
  ]
   s = '\n'.join(lst)
   code = compile(s, '', 'exec')
   eval(code)

class foo:
   def __init__(self, value):
  self.public_value = value
gimme_set_get(foo, 'via_accessor_method_only')

f = foo(1)
f.set_via_accessor_method_only(1/9.0)
print f.get_via_accessor_method_only()

print dir(f)


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


Re: "".join(string_generator()) fails to be magic

2007-10-11 Thread Carl Banks
On Oct 11, 2:26 am, Matt Mackal <[EMAIL PROTECTED]> wrote:
> I have an application that occassionally is called upon to process
> strings that are a substantial portion of the size of memory. For
> various reasons, the resultant strings must fit completely in RAM.
> Occassionally, I need to join some large strings to build some even
> larger strings.

Do you really need a Python string?  Some functions work just fine on
mmap or array objects, for example regular expressions:

>>> import array
>>> import re
>>> a = array.array('c','hello, world')
>>> a
array('c', 'hello, world')
>>> m = re.search('llo',a)
>>> m
<_sre.SRE_Match object at 0x009DCB80>
>>> m.group(0)
array('c', 'llo')

I would look to see if there's a way to use an array or mmap instead.
If you have an upper bound for the total size, then you can reserve
the needed number of bytes.

If you really need a Python string, you might have to resort to a C
solution.


Carl Banks

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


Re: Parsing a commandline from within Python

2007-10-11 Thread Andreas Huesgen

>> Is there any buildin function which mimics the behavior of the
>> standard commandline parser (generating a list of strings
>> "foo bar" and "some text" from the commandline
>> <"foo bar" "some text">)?
> 
> Try the shlex module::
> 
>  >>> import shlex
>  >>> shlex.split('"foo bar" "some text"')
>  ['foo bar', 'some text']
> 

Thanks, that is exactly what i need.


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


Re: Fwd: NUCULAR fielded text searchable indexing

2007-10-11 Thread aaron . watters
regarding http://nucular.sourceforge.net

On Oct 11, 12:32 pm, Paul Rubin  wrote:
>
> How many items did each query return?  When I refer to large result
> sets, I mean you often get queries that return 10k items or more (a
> pretty small number: typing "python" into google gets almost 30
> million hits) and you need to actually examine each item, as opposed
> to displaying ten at a time or something like that (e.g. you want to
> present faceted results).

I can't give a detailed report.  I think 10k result sets were
not unusual or noticably slower.  Of the online demos, looking at

http://www.xfeedme.com/nucular/gut.py/go?FREETEXT=w

(w for "web") we get 6294 entries which takes about 500ms on
a cold index and about 150ms on a warm index.  This is on a very
active shared hosting machine.

You are right that you might want to
use more in-process memory for a really smart, multi-faceted relevance
ordering or whatever, but you have to be willing to pay for it
in terms of system resources, config/development time, etcetera.
If you want cheap and easy, nucular might be good enough, afaik.

Regarding the 30 million number -- I bet google does
estimations and culling of some kind (not really looking at all 10M).
I'm pretty sure of this because in some cases I've looked at all
results available and it turned out to be a lot smaller than the
estimate on the first page.
I'm not interested in really addressing the "google" size of data set
at the moment.

>  http://www.newegg.com/Product/Product.aspx?Item=N82E16820147021

holy rusty metal batman! way-cool!

thanks,  -- Aaron Watters

===
less is more

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread Matimus
On Oct 11, 10:02 am, [EMAIL PROTECTED] wrote:
> On Oct 11, 12:49 pm, Matimus <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 11, 9:11 am, brad <[EMAIL PROTECTED]> wrote:
>
> > > [EMAIL PROTECTED] wrote:
> > > > However...how can you know it is a name...
>
> > > OK, I admitted in my first post that it was a crazy question, but if one
> > > could find an answer, one would be onto something. Maybe it's not a 100%
> > > answerable question, but I would guess that it is an 80% answerable
> > > question... I just don't know how... yet :)
>
> > > Besides admitting that it's a crazy question, I should stop and explain
> > > how it would be useful to me at least. Is a credit card number itself
> > > valuable? I would think not. One can easily re and luhn check for credit
> > > card numbers located in files with a great degree of accuracy, but a
> > > number without a name is not very useful to me. So, if one could
> > > associate names to luhn checked numbers automatically, then one would be
> > > onto something. Or at least say, "hey, this file has luhn validated CCs
> > > *AND* it seems to have people's names in it as well." Now then, I'd have
> > > less to review or perhaps as much as I have now, but I could push the
> > > files with numbers and names to the top of the list so that they would
> > > be reviewed first.
>
> > > Brad
>
> > What the hell are you doing? Your post sounds to me like you have a
> > huge amount of stolen, or at the very least misapprehended, data. Now
> > you want to search it for credit card numbers and names so that you
> > can use them.
>
> > I am not cool with this! This is a public forum about a programming
> > language. What makes you think that anybody in this forum will be cool
> > with that. Perhaps you aren't doing anything illegal, but it sure is
> > coming off that way. If you are doing something illegal I hope you get
> > caught.
>
> > At the very least, you might want to clarify why you are looking for
> > such capability so that you don't get effectively black-listed (well,
> > by me at least).
>
> > Matt
>
> Go have a beer and calm down a bit :) It's a legitimate purpose,
> although it could (and probably is being used by bad guys right now).
> My intent, as you can see from the links below, is to catch it before
> the bad guys do.
>
> http://filebox.vt.edu/users/rtilley/public/find_ccns/http://filebox.vt.edu/users/rtilley/public/find_ssns/
>
> Brad

Its just past 10:00 am where I am... I know customs vary, but
generally beer before lunch is frowned upon :). I know the tone of
posts does not carry well over the web, but I was really just trying
to point out that your previous post sounded very shady, and at the
very least some clarification was in order. I wasn't standing on my
desk frothing at the mouth or anything.

On to my suggestion. I think you are going to have to use statistical
analysis. That is, you won't get something that reliably returns a
boolean, but maybe something that says there is a 75% chance that
there are names in a given file. You can't know that a given string is
or isn't a name, you can only know that it is probably a name based
upon how often it is used in that context. Either way this isn't a
simple problem to solve, and it probably involves creating a database
of words that shows what percentage of the time they are used as
names. How such a database is created... that is the hard part. There
may be tools out there for such analasys, but that isn't an area I
have any experience in.

Matt

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


Re: Parsing a commandline from within Python

2007-10-11 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> Is there any buildin function which mimics the behavior of the
> standard commandline parser (generating a list of strings
> "foo bar" and "some text" from the commandline
> <"foo bar" "some text">)?

Try the shlex module::

 >>> import shlex
 >>> shlex.split('"foo bar" "some text"')
 ['foo bar', 'some text']

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


[Python-SWIG-C++] one question about wrapper interface files

2007-10-11 Thread [EMAIL PROTECTED]
Dear All,

I am new to Python and SWIG, and I tried to search the SWIG
mailinglist for my specific question, but I did not find it. And for a
simple one c++ file, I can handle it successfully.

Now I have a small project including several C files, file1.C file2.C
file3.C file2.h file3.h , file1.C is the main() entry for my project,
and file1.C has the following include statements
#include file2.h
   #include fille3.h

So for using SWIG,  What should I do?

Thanks in advance!

Jiangfan Shi

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


Re: storing meta data on dictionary keys

2007-10-11 Thread Erik Jones

On Oct 11, 2007, at 1:36 AM, Andreas Kraemer wrote:

> On Oct 10, 9:00 pm, Erik Jones <[EMAIL PROTECTED]> wrote:
>> If you're sure that 1.  this use case won't grow and 2. that you'll
>> only be the only person ever using code, then it's your choice of
>> preference.  Both of those points are equally important.  1 is a
>> manageability issue in that you are complicating what could be an
>> easy solution for a small gain in convenience -- one that could just
>> as easily be had by encapsulating the management of both dicts in an
>> explicit class or function/method.  Let me quote lines 2 through 5 of
>> The Zen of Python (PEP20):
>>
>> Explicit is better than implicit.
>> Simple is better than complex.
>> Complex is better than complicated.
>> Flat is better than nested.
>>
>> Using two dicts would be explicit, simple and flat.  Your's is none
>> of those.
>>
>> For point 2, if anyone else needs to work with your code they're most
>> likely going to be confused as the implementation is overly complex.
>> I know when I initially read through it I had to read it a couple
>> times to assure myself of what it was doing because I was thinking
>> that it seems that there's more going on than there is, so there must
>> be.  Remember, the best solutions are those that not only you can
>> understand, but the next guy/girl/?.
>
> You are right, and these are all very valid points. One of the reasons
> I like Python so much is the philosophy behind it. Nevertheless,
> everything is relative, so a pattern that seems complex (or unusual)
> at first may become simple when people get used to it ... I hope, I
> may be excused. In the organization where I work I am mainly
> prototyping (more on the "scientific/algorithm" side) and not required
> to write maintainable code. The engineers will do that (in Java
> anyway, sadly ..).

Excellent.  I'm actually love "hackish" approaches to things when you  
can afford to use them and it seems like you're in that situation.
>
>>> The trivial "class Str(str): pass" in the OP (that already inherits
>>> the correct __hash__ and
>>> __eq__) serves the same purpose as your Node(object) below, ...
>>
>> True, but you're breaking the intended abstraction of inheriting from
>> str, i.e. the reason you can inherit from str is so that you can
>> specialize strings, not get __has__ and __eq__ for free.  You can
>> define those on your own for a reason.
>
> Who says that that's the intended abstraction of inheriting from str?
> I thought that one purpose of inheritance was the reuse of behavior
> (i.e. methods) (and maybe state) of the superclass. So, my class
> Str(str): pass behaves like a string in all aspects, except that you
> can attach some meta data that won't affect that behavior. In fact, I
> use that pattern quite frequently also for other built-in immutable
> types, e.g. floats or ints, which allows me to very easily "tag"
> numerical data (e.g. as an outlier in a stats application or whatever)
> without affecting any subsequent code operating on it as long as it
> only uses its built-in "flavor". This is the power of Python's duck
> typing!

No, duck typing and inheritance are two different things.  Duck  
typing is when you implement the same operations as another object or  
class, whereas with inheritance you get the same implementation as  
that of the parent class.  With duck typing, an object "acts like"  
another object in specific contexts.  With inheritance, an object is  
the same general type as another object.  You don't want string  
objects, you want objects that, in a specific case, act like strings  
but in others, I'm sure, not.  How does a concept like string  
substitution fit with your inherited objects?

>> So, (explicitly:) you want the built-in dict to be a dictionary that
>> also maintains a dictionary of its own key
>
> Without knowing the internals, so I may be wrong. But dict must
> somehow maintain a dictionary of the key objects already. How else
> could it detect collisions of hash values, when it must use __eq__ to
> determine equality of the "query" key object to one of the inserted
> keys having the same hash value? It also needs to do the same check
> when overwriting an existing key.

If you can, get a copy of Beautiful Code (easily had from Amazon or  
the likes).  It contains an chapter on Python's dictionary  
implementation.

>> Not likely to happen.
>> Again, you're asking to have one dictionary act as two and that's
>> just confusing.  I'm not saying that get_key is a bad idea for
>> (possibly) some use cases, just that what you're actually doing is
>> creating a dictionary wherein the same key can return two different
>> object depending on the retrieval method used and that is NOT what
>> the built-in dict is for.  In fact, now that I think of it, get_key
>> is probably a bad name for it, get_other_object_with_this_same_key is
>> probably more apt :)
>
> Or more precise:
> get_key_that_was_used_when_value_was_inserted_into_dictionary :-)

Re: Keeping track of subclasses and instances?

2007-10-11 Thread Bruno Desthuilliers
George Sakkis a écrit :
(snip)

> Anyway, here's something to get you
> started; all a user has to do is derive (directly or indirectly) from
> InstanceTracker and, if a class C defines __init__,
> super(C,self).__init__() should be called explicitly:

Actually, you don't even need that restriction - just move the tracking 
code from __init__ to __new__.

> 
> from collections import deque
> from weakref import WeakKeyDictionary
> 
> class InstanceTracker(object):
   def __new__(cls, *args, **kw):
   try:
all = cls.__dict__['__instances__']
   except KeyError:
cls.__instances__ = all = WeakKeyDictionary()
   self = super(InstanceTracker, self).__new__(cls)
   all[self] = None
   return self

(NB : untested)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Declarative properties

2007-10-11 Thread Bruno Desthuilliers
Artur Siekielski a écrit :
> On Oct 11, 4:21 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> In practice, it turns out to be a lot less work to deal with that
>> occasionally than to always deal with lugging around internal
>> attributes and external properties when they're really not needed.  By
>> writing everything as properties up front you're just creating more
>> work for yourself, and it's generally considered bad practice in
>> Python to have default getters/setters (whether part of a property or
>> not).
> 
> Ok, I appreciate your and Marc's argument. So I see that a pythonic
> way is
> using public attributes, and it works in real life.

Indeed !-)

> Automatic
> "generation" of
> getters/setters is a nice thing when using Java style of properties,
> ie. no
> public fields.

Java doesn't have computed attributes, so you have no other choice if 
you want to keep your design flexible. For languages that have computed 
attributes, this is not a problem to use plain attributes until you 
*really* need to do otherwise.

>>> 2. Properties define (a part of) public interface of a class. When
>>> using fields for public
>>> access, you must tell this explicitly in documentation, or use name
>>> convention.
>> Property vs. attribute doesn't make any difference here: both of them
>> are public, and part of the external interface, unless they're named
>> with a leading underscore.
> 
> Nice thing about properites is that they are defined in more
> declarative way -
> in class body. Attributes are "defined" in a piece of code (which can
> be long
> and can contain loops etc.) by assigning a value to 'self'.

Usually, all there is to know is readable in the initializer. And I've 
rarely seen (good) code that defines public attribute elsewehere (i've 
seen such a thing on a couple occasion, and that's bad coding IMHO).

Anyway, since attributes (including methods, class etc...) can be 
added/replaced/deleted by anyone having access to the object at any 
point of the program, using properties won't help that much here IMHO. 
Not that I don't see your point - I also have a taste for declarative 
APIs and readability - but this is enough to justify the use of 
properties IMHO.

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread byte8bits
On Oct 11, 12:49 pm, Matimus <[EMAIL PROTECTED]> wrote:
> On Oct 11, 9:11 am, brad <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > However...how can you know it is a name...
>
> > OK, I admitted in my first post that it was a crazy question, but if one
> > could find an answer, one would be onto something. Maybe it's not a 100%
> > answerable question, but I would guess that it is an 80% answerable
> > question... I just don't know how... yet :)
>
> > Besides admitting that it's a crazy question, I should stop and explain
> > how it would be useful to me at least. Is a credit card number itself
> > valuable? I would think not. One can easily re and luhn check for credit
> > card numbers located in files with a great degree of accuracy, but a
> > number without a name is not very useful to me. So, if one could
> > associate names to luhn checked numbers automatically, then one would be
> > onto something. Or at least say, "hey, this file has luhn validated CCs
> > *AND* it seems to have people's names in it as well." Now then, I'd have
> > less to review or perhaps as much as I have now, but I could push the
> > files with numbers and names to the top of the list so that they would
> > be reviewed first.
>
> > Brad
>
> What the hell are you doing? Your post sounds to me like you have a
> huge amount of stolen, or at the very least misapprehended, data. Now
> you want to search it for credit card numbers and names so that you
> can use them.
>
> I am not cool with this! This is a public forum about a programming
> language. What makes you think that anybody in this forum will be cool
> with that. Perhaps you aren't doing anything illegal, but it sure is
> coming off that way. If you are doing something illegal I hope you get
> caught.
>
> At the very least, you might want to clarify why you are looking for
> such capability so that you don't get effectively black-listed (well,
> by me at least).
>
> Matt

Go have a beer and calm down a bit :) It's a legitimate purpose,
although it could (and probably is being used by bad guys right now).
My intent, as you can see from the links below, is to catch it before
the bad guys do.

http://filebox.vt.edu/users/rtilley/public/find_ccns/
http://filebox.vt.edu/users/rtilley/public/find_ssns/

Brad



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


Re: Keeping track of subclasses and instances?

2007-10-11 Thread Erik Jones

On Oct 11, 2007, at 12:49 AM, Andreas Kraemer wrote:

> On Oct 10, 6:19 pm, Karlo Lozovina <[EMAIL PROTECTED]> wrote:
>> Larry Bates wrote:
>>> I'm not completely sure I understand the question but here goes.
>>> Instances of
>>> classes are classes can be stored in lists or dictionaries.  In  
>>> lists you
>>> reference them via their index (or iterate over them) and in  
>>> dictionaries
>>> you can give them a name that is used as a key.
>>
>> I wish if it were that simple :).
>>
>> Here is a longer description - I have a function that given input  
>> creates a
>> custom class and returns it back. The user is free to subclass  
>> that (even
>> more, he should do that), and of course he will make instances of  
>> those
>> subclasses. Now, my question is how to keep track of subclasses  
>> and their
>> instances, without the need for user interaction (appending them  
>> to a list,
>> or adding to dictionary)?
>>
>> Thanks,
>>
>> --
>> Karlo Lozovina - Mosorclass Meta(type):
>
> What about the following solution?
>
> class Meta(type):
>   def __new__(mcl,*args,**kw):
> class_ = super(Meta,mcl).__new__(mcl,*args,**kw)
> mcl._classes.append(class_)
> class_._instances = []
> return class_
>   _classes = []
>
> def factory():
>   class Class(object):
> __metaclass__ = Meta
> def __new__(cls,*args,**kw):
>   instance = super(Class,cls).__new__(cls,*args,**kw)
>   cls._instances.append(instance)
>   return instance
>   return Class
>
 A = factory()
 class B(A): pass
> ...
 a = A()
 b = B()
 Meta._classes
> [, ]
 A._instances
> []
 B._instances
> [<__main__.B object at 0xb7dbb0ec>]
>
> So, you see that you can access all classes, their subclasses, and
> instances from Meta.
>
> Of course in a more elaborate version _classes and _instances should
> store weak references, so that classes and instances can actually be
> deleted. I also haven't explored under which circumstances this can
> break ...
>
> I can imagine different use cases for this, (though they certainly are
> non-standard :-)). I once contemplated the (toy-) implementation of a
> frame-based knowledge representation system using Python's object
> model, where one definitely needs classes to keep track of their
> instances ...

Another use case that I've run across is when defining model classes  
using an ORM against a database that uses table inheritance  
extensively with the result that the database has way more tables  
than you'd actually want to manually maintain model classes/files for.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com


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


Parsing a commandline from within Python

2007-10-11 Thread andreas . huesgen
Hello,

I am writing a commandline tool in Python which is often feed with lots of 
commandline arguments. In practice, the commandline already reached a critical 
length which is to long for Windows (some versions of Windows only support 
commandlines of up to 2047 characters). To work around this problem, we thought 
up the idea of bypassing the commandline into a file and then letting Python 
parse the content of the file the same way, the arguments in sys.argv are 
parsed.

Is there any buildin function which mimics the behavior of the standard 
commandline parser (generating a list of strings "foo bar" and "some text" from 
the commandline <"foo bar" "some text">)?

If not, do you have any other ideas how to handle this problem (increasing 
commandline length, xml files might be a way)?


Regards,

Andreas Huesgen

Viel oder wenig? Schnell oder langsam? Unbegrenzt surfen + telefonieren
ohne Zeit- und Volumenbegrenzung? DAS TOP ANGEBOT FÜR ALLE NEUEINSTEIGER
Jetzt bei Arcor: günstig und schnell mit DSL - das All-Inclusive-Paket
für clevere Doppel-Sparer, nur  34,95 €  inkl. DSL- und ISDN-Grundgebühr!
http://www.arcor.de/rd/emf-dsl-2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matching a street address with regular expressions

2007-10-11 Thread Max Erickson
Andy Cheesman <[EMAIL PROTECTED]> wrote:

> Check out kodos http://kodos.sourceforge.net/ for an interactive
> python regexp tester
> 
> Andy
> 

On systems with tkinter installed(So pretty much all Windows and lots 
and lots of Linux systems), the redemo.py script in the Tools/Scripts 
directory of the python installation will be a little quicker to get 
running.


max

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


Re: Declarative properties

2007-10-11 Thread Bruno Desthuilliers
Artur Siekielski a écrit :
> On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> But why?  Default getters and setters are unnecessary and if you need
>> something other than the default you need to write it anyway more
>> explicitly.
> 
> I see some problems with your approach:
> 
> 1. If I use instance field 'name' which is accessed directly by other
> classes,
> and later I decide to implement nonstandard getter, I must refactor
> 'Person' class
> and in some places change 'name' to '_name' (assuming this is now the
> field's name).

Why so ?

class Toto(object):
   def __iinit__(self, name):
 self.name = name
   @apply
   def name():
 def fget(self):
   print "getting %s.name" % self
   return self._name
 def fset(self, val):
   print "setting %s.name to %s" % (self, val)
   self._name = name
   def say_hello(self):
 print "Hello, my name is %s" % self.name

t = Toto('bruno')
t.say_hello()

> The problem is that I cannot automatically change 'name' to '_name'
> everywhere, because
> in some places I want public property value (eg. validated and
> formatted), and in other
> places raw property value.

But then, you do know where you want the raw value, don't you ? And this 
  would be for special cases that didn't exist before this refactoring, 
anyway ?

> 2. Properties define (a part of) public interface of a class.

So do attributes.

> When
> using fields for public
> access, you must tell this explicitly in documentation, or use name
> convention. And public
> fields definition is mixed with private fields, which doesn't happen
> when using properties.

I just don't understand what you're saying here. As long as you did not 
prefix a name with an underscore, it's part of the API. And anyway, 
nothing (except common sens) will prevent anyone to mess with 
implementation attributes.

> 3. Using properties as first-class objects

Which they are already - I don't know of anything that isn't a 
"first-class" object in Python.

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


Re: Finding Peoples' Names in Files

2007-10-11 Thread Dan Stromberg
On Thu, 11 Oct 2007 11:22:50 -0400, brad wrote:

> Crazy question, but has anyone attempted this or seen Python code that 
> does? For example, if a text file contained 'Guido' and or 'Robert' and 
> or 'Susan', then we should return True, otherwise return False.

It'll be hard to handle the Dweezil's and Moon Unit's of the world (I
believe these are Frank Zappa's kids?), but you could compile a list of
reasonably common names by gaining access to a usenet news spool, and
pulling the names from the headers.

But then this is starting to sound dangerously like a spam campaign - in
which case, "Please don't!".


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


Re: Declarative properties

2007-10-11 Thread Bruno Desthuilliers
Artur Siekielski a écrit :
> Hi.
> 
> I would like to have declarative properties in Python, ie. something
> like slots definitions in defclass in Common Lisp. It seems that even
> Java will have it, using a library ( https://bean-properties.dev.java.net/
> ).
> 
> I know about 'property' function

Actually, it's a class.

> in Python, but it's normal usage
> isn't declarative, because I have to code imperatively getters and
> setters:

Indeed. What would be the use of a property (AKA computed attribute) if 
you don't need to do something specific ?

> class Person(object):
>def __init__(self, name):
>   self._name = name
>def _get_name(self):
>   return self._name
>def _set_name(self, new_name):
>   self._name = new_name
>name = property(_get_name, _set_name)

While it's often seen as demonstration code for a property, it's 
actually totally useless. If all you want to do is to get and set an 
attribute (I mean, without any computation anywhere), then just use an 
attribute - you will always be able to turn it into a property if and 
whene the need arises.

> I would like to have something like that:
> 
> class Person(object):
>name = property('_name')
> 
> I assume that this causes "generation" of instance field '_name' and
> default getters and setters.

So far, it's a waste of time. That's exactly what you'd get with a plain 
attribute, with far less complexity and overhead.

> And if I would like to customize (g|
> s)etters, I would write them by hand,

Which bring us back to how properties actually work !-)

> or, better, use more declarative
> approach (like @NotNull annotations in Java version).

> I could probably code a solution to my problem with help of wonderful
> introspection functionalities. But I'm looking for a standard and/or
> proven way of doing this. Maybe some PEP is being prepared for this?

I guess you want to have a look at the descriptor protocol - it's what 
makes properties work, and it allow you to write your own custom 'smart 
attributes'. If you want automatic validation/conversion, you could 
write custom descriptors working with the FormEncode package (I started 
such a thing for Elixir, but had no time to finish it so far). It would 
then looks like:

class Person(object):
   name = StringField(empty=False)

   // etc

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


  1   2   >