Re: High performance binary data

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Fri, 10 Aug 2007 00:26:54 +, Steve wrote:

> I want to ready binary data from a udp socket effeciently as possible
> in python.  I know of the struct package but do people have any tips
> when dealing with binary data in python?  Is there a library or api
> that is faster when dealing with binary data. I am looking for a any
> one with experience or ideas on the subject.  Pointers any one?

I don't know if it is faster, but maybe constructing objects with
the `ctypes` module let you write more readable code as you can treat and
access C ``struct``\s like objects.

For the "fast" part of the question you might consider actually measuring
your program, as the task may be I/O bound i.e. Python may be faster than
the data comes in regardless of which module, `struct` or `ctypes`, you
use to tear apart and access the data.

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


Re: Does PyModule_GetDict return information about class method variables?

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Aug 2007 19:34:37 -0700, MD wrote:

>I have a variable which is defined inside a class method. When I
> call PyModule_GetDict on the module containing this class, the
> dictionary doesn't contain any information about this variable. Is
> this expected behavior? If so, what options do I have to access this
> variable from my Python C extension.

You can't access names in methods because they don't exist until you call
the method.  It's just like local variables in C.  Consider:

void foo(void)
{
int bar = 42;
}

Here `bar` does not exist until you call `foo()` and it disappears as soon
as the function returns.

It's the very same situation in Python:

class A(object):
def foo(self):
bar = 42

The local name `bar` only exists if `foo()` is called on an instance of `A`.

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


Re: beginner whitespace question

2007-08-09 Thread James Stroud
Dan Bishop wrote:
>> Tabs are for tables, hence the name. "Use spaces for space and use tabs
>> for tables" can be a little mnemonic to help you remember the rules. We
>> can make a little song together if you can think of some things that
>> rhyme with "don't" and "use" and "tabs".
> 
> "won't"
> 
> "blues", "booze", "bruise", "choose", "cruise", "fuse", "hues",
> "Jews", "lose", "muse", "news", "snooze", "views", etc.
> 
> "abs", "cabs", "crabs", "dabs", "grabs", "labs", "scabs", "slabs",
> "stabs", etc.
> 


When you want to screw your whitespace--don't!
Take this little pledge and I know you won't:

When I was in school I would take of booze
While my typing teacher said I'm free to use
Space or formfeed or even tabs
And I punched so hard with my pinkie that scabs
Covered my Jake and Elwood tatoos.
(You didn't see that one coming did yous?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deleting objects on the fly

2007-08-09 Thread Michele Simionato
On Aug 10, 2:25 am, Godzilla <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I wish to know whether I should delete objects created on the fly via
> the "del obj" statement. I noticed the RAM usage increased whenever
> the application is being run for a long time. I am creating lots of
> objects (messages) on the fly for communication between threads.
>
> Rather than having python's gc to do the work, does it make a
> difference if I force a deletion?
>
> Thanks.

Probably not, 'del x' just decrements the reference count, but
it is the gc who does the real job. See 
http://docs.python.org/ref/customization.html#l2h-175

Do you have reference cycles in your application? You should
tell us something more.

   Michele Simionato

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


Re: wxPython before MainLoop

2007-08-09 Thread Heikki Toivonen
[david] wrote:
> I'd like to refresh the display before I start the main loop.

We have this kind of situation in Chandler, where we display and update
the splash screen before we enter MainLoop.

1. Create app object
   http://lxr.osafoundation.org/source/chandler/Chandler.py#080

2. During app object creation, in OnInit, put up splash screen and update it

http://lxr.osafoundation.org/source/chandler/application/Application.py#433

3. The splash screen refresh is basically: draw new stuff,
self.Layout(), self.Update(), wx.Yield()
http://lxr.osafoundation.org/source/chandler/application/Application.py#1421

3. Start MainLoop
   http://lxr.osafoundation.org/source/chandler/Chandler.py#086

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


Re: Puzzled by "is"

2007-08-09 Thread Paul Rudin
John K Masters <[EMAIL PROTECTED]> writes:

>
> OK fiddling around with this and reading the docs I tried:-
> a = 'qq' #10 q's
> b = 'qq' #10 q's
> a is b
> true
> c = 'q' * 10
> c
> 'qq' #10 q's
> d = 'q' * 10
> d
> 'qq' #10 q's
> c is d
> false
>
> So from what I've read "==" tests for equivalence, "is" tests for identity but
> that does not explain the behaviour above.
>

There's nothing especially to be explained, other than "that's the way
the compiler does it". Two equal string literals might be the same
object or they might not be. It's a language implementation detail.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded Design Question

2007-08-09 Thread Mark T

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi all!  I'm implementing one of my first multithreaded apps, and have
> gotten to a point where I think I'm going off track from a standard
> idiom.  Wondering if anyone can point me in the right direction.
>
> The script will run as a daemon and watch a given directory for new
> files.  Once it determines that a file has finished moving into the
> watch folder, it will kick off a process on one of the files.  Several
> of these could be running at any given time up to a max number of
> threads.
>
> Here's how I have it designed so far.  The main thread starts a
> Watch(threading.Thread) class that loops and searches a directory for
> files.  It has been passed a Queue.Queue() object (watch_queue), and
> as it finds new files in the watch folder, it adds the file name to
> the queue.
>
> The main thread then grabs an item off the watch_queue, and kicks off
> processing on that file using another class Worker(threading.thread).
>
> My problem is with communicating between the threads as to which files
> are currently processing, or are already present in the watch_queue so
> that the Watch thread does not continuously add unneeded files to the
> watch_queue to be processed.  For example...Watch() finds a file to be
> processed and adds it to the queue.  The main thread sees the file on
> the queue and pops it off and begins processing.  Now the file has
> been removed from the watch_queue, and Watch() thread has no way of
> knowing that the other Worker() thread is processing it, and shouldn't
> pick it up again.  So it will see the file as new and add it to the
> queue again.  PS.. The file is deleted from the watch folder after it
> has finished processing, so that's how i'll know which files to
> process in the long term.
>
> I made definite progress by creating two queues...watch_queue and
> processing_queue, and then used lists within the classes to store the
> state of which files are processing/watched.
>
> I think I could pull it off, but it has got very confusing quickly,
> trying to keep each thread's list and the queue always in sync with
> one another.  The easiset solution I can see is if my threads could
> read an item from the queue without removing it from the queue and
> only remove it when I tell it to.  Then the Watch() thread could then
> just follow what items are on the watch_queue to know what files to
> add, and then the Worker() thread could intentionally remove the item
> from the watch_queue once it has finished processing it.
>
> Now that I'm writing this out, I see a solution by over-riding or
> wrapping Queue.Queue().get() to give me the behavior I mention above.
>
> I've noticed .join() and .task_done(), but I'm not sure of how to use
> them properly.  Any suggestions would be greatly appreciated.
>
> ~Sean
>

Just rename the file.  We've used that technique in a similar application at 
my work for years where a service looks for files of a particular extension 
to appear in a directory.  When the service sees a file, in renames it to a 
different extension and spins off a thread to process the contents.

-Mark T. 

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


Re: accessing static attributes

2007-08-09 Thread Carsten Haese
On Fri, 10 Aug 2007 02:51:44 -, james_027 wrote
> hi,
> 
> for example an request object ... is request.user the same as
> request.__class__.user?

Not in general:

>>> class Request(object):
...user = "somebody"
...
>>> request = Request()
>>> request.user == request.__class__.user
True
>>> request.user = "nobody"
>>> request.user == request.__class__.user
False

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Puzzled by "is"

2007-08-09 Thread Erik Max Francis
Ben Finney wrote:

> It's important to also realise that the language is *deliberately*
> non-committal on whether any given value will have this behaviour;
> that is, it's entirely left to the language implementation which
> optimisation trade-offs to make, and the language user (that's you and
> I) should *not* expect any particular behaviour to hold between
> different implementations.

Right.  In the terminology of language standards, it is implementation 
defined.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Only love is worth the risk
-- Oleta Adams
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beginner whitespace question

2007-08-09 Thread Dan Bishop
On Aug 9, 8:28 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> eggie5 wrote:
> > But this still isn't valid:
>
> > from django.db import models
>
> > class Poll(models.Model):
> >question = models.CharField(max_length=200)
> >pub_date = models.DateTimeField('date published')
>
> > def __unicode__(self):
> >return self.question
>
> > class Choice(models.Model):
> > poll = models.ForeignKey(Poll)
> > choice = models.CharField(max_length=200)
> > votes = models.IntegerField()
>
> > def __unicode__(self):
> >return self.choice
>
> You want this:
>
> from django.db import models
>
> class Poll(models.Model):
> question = models.CharField(max_length=200)
> pub_date = models.DateTimeField('date published')
>
> def __unicode__(self):
> return self.question
>
> class Choice(models.Model):
>  poll = models.ForeignKey(Poll)
>  choice = models.CharField(max_length=200)
>  votes = models.IntegerField()
>
>  def __unicode__(self):
> return self.choice
>
> But this mixes tabs and spaces.
>
> Rules:
>
> 1. Don't use tabs!
> 2. If you are clueless enough to violate (1), then don't mix tabs and
> spaces.
> 3. Don't use tabs!
>
> Tabs are for tables, hence the name. "Use spaces for space and use tabs
> for tables" can be a little mnemonic to help you remember the rules. We
> can make a little song together if you can think of some things that
> rhyme with "don't" and "use" and "tabs".

"won't"

"blues", "booze", "bruise", "choose", "cruise", "fuse", "hues",
"Jews", "lose", "muse", "news", "snooze", "views", etc.

"abs", "cabs", "crabs", "dabs", "grabs", "labs", "scabs", "slabs",
"stabs", etc.

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


accessing static attributes

2007-08-09 Thread james_027
hi,

for example an request object ... is request.user the same as
request.__class__.user?

THanks
james

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


Re: mmm-mode, python-mode and doctest-mode?

2007-08-09 Thread Edward Loper
Edward Loper wrote:
>> Anyone testing on xemacs?  I tried it, and C-c C-c sent xemacs into an
>> infinite loop (apparantly).

I may have tracked down the cause of this problem.  Please download the 
most recent version, and try again.  And when you do, let me know 
whether that fixed it. :)

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


Does PyModule_GetDict return information about class method variables?

2007-08-09 Thread MD
Hi,

   I have a variable which is defined inside a class method. When I
call PyModule_GetDict on the module containing this class, the
dictionary doesn't contain any information about this variable. Is
this expected behavior? If so, what options do I have to access this
variable from my Python C extension.

Thanks and Regards,
-MD

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


Re: beginner whitespace question

2007-08-09 Thread eggie5
On Aug 9, 6:31 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> James Stroud wrote:
> > def __unicode__(self):
That's so goofy.

> > return self.choice


>
> Laughing to hard at the tab & spaces thing to notice the lack of
> indentation here.
>
> 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: wxPython before MainLoop

2007-08-09 Thread Stephen Hansen
On 8/9/07, [david] <[EMAIL PROTECTED]> wrote:
>
> I'm disappointed that I didn't get a wxPython solution.
>
> If the only way to get wxPython to correctly handle
> this simple task is to code around it, I don't think
> wxPython is really ready for Windows.


A thread *is* basically the right answer, though; so why does wxPython need
an "answer"? Python has one.

Alternatively, let the GUI load (and don't do the long-running-task) and
then do the long running task in an idle handler within the GUI. A bit at a
time.

Alternatively, from within the long-running-task, regularly do:

   if myApp.Pending():
   myApp.Dispatch()

That'll handle any pending UI events (so the main UI is responsive). But you
need to call it regularly during your main task-- if you don't want a
separate thread.

Is there a better place to ask?


The wxPython mailing list. http://wxpython.org/maillist.php

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

Re: Threaded Design Question

2007-08-09 Thread Justin T.
On Aug 9, 5:39 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Aug 9, 7:25 pm, [EMAIL PROTECTED] wrote:
>
> > Hi all!  I'm implementing one of my first multithreaded apps, and have
> > gotten to a point where I think I'm going off track from a standard
> > idiom.  Wondering if anyone can point me in the right direction.
>
> > The script will run as a daemon and watch a given directory for new
> > files.  Once it determines that a file has finished moving into the
> > watch folder, it will kick off a process on one of the files.  Several
> > of these could be running at any given time up to a max number of
> > threads.
>
> > Here's how I have it designed so far.  The main thread starts a
> > Watch(threading.Thread) class that loops and searches a directory for
> > files.  It has been passed a Queue.Queue() object (watch_queue), and
> > as it finds new files in the watch folder, it adds the file name to
> > the queue.
>
> > The main thread then grabs an item off the watch_queue, and kicks off
> > processing on that file using another class Worker(threading.thread).
>
> > My problem is with communicating between the threads as to which files
> > are currently processing, or are already present in the watch_queue so
> > that the Watch thread does not continuously add unneeded files to the
> > watch_queue to be processed.  For example...Watch() finds a file to be
> > processed and adds it to the queue.  The main thread sees the file on
> > the queue and pops it off and begins processing.  Now the file has
> > been removed from the watch_queue, and Watch() thread has no way of
> > knowing that the other Worker() thread is processing it, and shouldn't
> > pick it up again.  So it will see the file as new and add it to the
> > queue again.  PS.. The file is deleted from the watch folder after it
> > has finished processing, so that's how i'll know which files to
> > process in the long term.
>
> I would suggest something like the following in the watch thread:
>
> seen_files = {}
>
> while True:
> # look for new files
> for name in os.listdir(folder):
> if name not in seen_files:
> process_queue.add(name)
> seen_files[name] = True
>
> # forget any missing files and mark the others as not seen, ready for
> next time
> seen_files = dict((name, False) for name, seen in seen_files.items()
> if seen)
>
> time.sleep(1)

Hmm, this wouldn't work. It's not thread safe and the last line before
you sleep doesn't make any sense.

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


Re: Threaded Design Question

2007-08-09 Thread Justin T.

> approach.  That sounds the easiest, although I'm still interested in
> any idioms or other proven approaches for this sort of thing.
>
> ~Sean

Idioms certainly have their place, but in the end you want clear,
correct code. In the case of multi-threaded programming,
synchronization adds complexity, both in code and concepts, so
figuring out a clean design that uses message passing tends to be
clearer and more robust. Most idioms are just a pattern to which
somebody found a simple, robust solution, so if you try to think of a
simple, robust solution, you're probably doing it right. Especially in
trivial cases like the one above.

Justin

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


Re: wxPython before MainLoop

2007-08-09 Thread [david]
I'm disappointed that I didn't get a wxPython solution.

If the only way to get wxPython to correctly handle
this simple task is to code around it, I don't think
wxPython is really ready for Windows.

Is there a better place to ask?

Regarding the suggestions:

Bjoern, you're wrong. The GUI needs to be displayed
for the user to analyse. A delay between display and
readiness is much better than a delay before display
or a delay with the GUI half-drawn.

Mike, the screen does display correctly, it's just
that in Windows, screen updates are not processed
while the application is busy.

7Stud, that's a solution. Unless anyone comes up
with a direct solution, I guess I'll have to do that.

[david]


[david] wrote:
> I'd like to refresh the display before I start the main loop.
> 
> I have code like this:
> 
> app = App()
> app.Show()
> app.long_slow_init()
> app.MainLoop()
> 
> 
> The main frame partly loads at Show, but because the mainloop has not 
> started yet, the display does not update until long_slow_init() finishes.
> 
> Alternatively, I could code
> 
> app = App()
> app.long_slow_init()
> app.Show()
> app.MainLoop()
> 
> Which would give me a crisp Show, but there would be a long slow wait 
> before the app showed any activity at all. I would need a splash screen.
> 
> I'd rather not have a splash screen (and I don't know how anyway). I'd 
> like to just make app.Show() finish correctly before running 
> long_slow_init.
> 
> Is there a wx internal method that I can use to give Windows the 
> opportunity to finish painting the frame before I run long_slow_init()?
> 
> Or is there a better idea?
> 
> (david)
-- 
http://mail.python.org/mailman/listinfo/python-list


wxPython - drawing without paint event

2007-08-09 Thread Matt Bitten
I've got a wxPython program that needs to do some drawing on a DC on a
regular basis, whether or not a paint event happens. I know how to
make a ClientDC to do the drawing in, and I know what drawing calls to
make. But how do I make it all happen? After I call MainLoop, none of
my code gets called unless there is an event. And there is no event,
so my code doesn't get called. What do I do?

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


Re: Threaded Design Question

2007-08-09 Thread half . italian
On Aug 9, 12:09 pm, "Justin T." <[EMAIL PROTECTED]> wrote:
> On Aug 9, 11:25 am, [EMAIL PROTECTED] wrote:
>
> > Here's how I have it designed so far.  The main thread starts a
> > Watch(threading.Thread) class that loops and searches a directory for
> > files.  It has been passed a Queue.Queue() object (watch_queue), and
> > as it finds new files in the watch folder, it adds the file name to
> > the queue.
>
> > The main thread then grabs an item off the watch_queue, and kicks off
> > processing on that file using another class Worker(threading.thread).
>
> Sounds good.
>
>
>
> > I made definite progress by creating two queues...watch_queue and
> > processing_queue, and then used lists within the classes to store the
> > state of which files are processing/watched.
>
> This sounds ugly, synchronization is one of those evils of
> multithreaded programming that should be avoided if possible. I see a
> couple of dirt simple solutions:
>
> 1. Have the watch thread move the file into a "Processing" folder that
> it doesn't scan
> 2. Have the watch thread copy the file into a python tempfile object
> and push that onto the queue, then delete the real file. This can be
> done efficiently (well, more efficiently than new.write(old.read())
> with shutil.copyfileobj(old, new)
>
> Both those take very few lines of code, don't require synchronization,
> and don't require extending standard classes.

Thanks foor the ideas Justin.

I started subclassing/extending the Queue.Queue object with two
additional classes.  One to return the first item in the list without
removing it from the queue, and one to return all items of the list
without removing them.  I think this will take me to where I want to
go.  If it doesn't work, I might just use your processing folder
approach.  That sounds the easiest, although I'm still interested in
any idioms or other proven approaches for this sort of thing.

~Sean

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


Re: beginner whitespace question

2007-08-09 Thread James Stroud
James Stroud wrote:
> def __unicode__(self):
> return self.choice

Laughing to hard at the tab & spaces thing to notice the lack of 
indentation here.

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: beginner whitespace question

2007-08-09 Thread James Stroud
eggie5 wrote:
> But this still isn't valid:
> 
> from django.db import models
> 
> class Poll(models.Model):
>   question = models.CharField(max_length=200)
>   pub_date = models.DateTimeField('date published')
> 
> def __unicode__(self):
>   return self.question
> 
> 
> 
> class Choice(models.Model):
> poll = models.ForeignKey(Poll)
> choice = models.CharField(max_length=200)
> votes = models.IntegerField()
> 
> def __unicode__(self):
>   return self.choice


You want this:


from django.db import models

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __unicode__(self):
return self.question



class Choice(models.Model):
 poll = models.ForeignKey(Poll)
 choice = models.CharField(max_length=200)
 votes = models.IntegerField()

 def __unicode__(self):
return self.choice


But this mixes tabs and spaces.

Rules:

1. Don't use tabs!
2. If you are clueless enough to violate (1), then don't mix tabs and 
spaces.
3. Don't use tabs!

Tabs are for tables, hence the name. "Use spaces for space and use tabs 
for tables" can be a little mnemonic to help you remember the rules. We 
can make a little song together if you can think of some things that 
rhyme with "don't" and "use" and "tabs".

You have been warned. Next time I'll piont and laugh as I answer.

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


Emacs PDB Windows

2007-08-09 Thread [EMAIL PROTECTED]
I'm trying to get PDB working on Emacs 2.1.3, Python 2.3, Windows XP.
Whenever I try to run a Python file from the Emacs buffer using the
PDB command I get the following error
"spawning child process: invalid process"
I've tried the exact same command from the command prompt and the
debugger works properly.
If anyone he has any ideas for a completely lost newbie that would be
much appreciated...

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


Re: Puzzled by "is"

2007-08-09 Thread Ben Finney
Grzegorz Słodkowicz <[EMAIL PROTECTED]> writes:

> That's just theorisation but I'd rather expect the interpreter
> simply not to create a second tuple while there already is an
> identical one.

Others have already said that it's an implementation optimisation,
which seems to partly answer your question.

It's important to also realise that the language is *deliberately*
non-committal on whether any given value will have this behaviour;
that is, it's entirely left to the language implementation which
optimisation trade-offs to make, and the language user (that's you and
I) should *not* expect any particular behaviour to hold between
different implementations.

-- 
 \ "Holy priceless collection of Etruscan snoods, Batman!"  -- |
  `\ Robin |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: beginner whitespace question

2007-08-09 Thread eggie5
But this still isn't valid:

from django.db import models

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __unicode__(self):
return self.question



class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()

def __unicode__(self):
return self.choice


On Aug 9, 5:52 pm, Dan Bishop <[EMAIL PROTECTED]> wrote:
> On Aug 9, 7:02 pm, eggie5 <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Aug 9, 4:52 pm, Dan Bishop <[EMAIL PROTECTED]> wrote:
>
> > > On Aug 9, 6:47 pm, eggie5 <[EMAIL PROTECTED]> wrote:
>
> > > > I keep getting an error for line 7, what's wrong with this?
>
> > > > from django.db import models
>
> > > > class Poll(models.Model):
> > > > question = models.CharField(max_length=200)
> > > > pub_date = models.DateTimeField('date published')
>
> > > > def __unicode__(self):
> > > > return self.question
>
> > > The "def" statements have to be at the same indentation level as
> > > what's before it.
>
> > will they still be a part of the classes?
>
> If you indent them twice, it's a syntax error.
> If you indent them once, they'll be methods of the class.
> If you don't indent them at all, they'll be global functions.


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


Re: beginner whitespace question

2007-08-09 Thread Dan Bishop
On Aug 9, 7:02 pm, eggie5 <[EMAIL PROTECTED]> wrote:
> On Aug 9, 4:52 pm, Dan Bishop <[EMAIL PROTECTED]> wrote:
>
> > On Aug 9, 6:47 pm, eggie5 <[EMAIL PROTECTED]> wrote:
>
> > > I keep getting an error for line 7, what's wrong with this?
>
> > > from django.db import models
>
> > > class Poll(models.Model):
> > > question = models.CharField(max_length=200)
> > > pub_date = models.DateTimeField('date published')
>
> > > def __unicode__(self):
> > > return self.question
>
> > The "def" statements have to be at the same indentation level as
> > what's before it.
>
> will they still be a part of the classes?

If you indent them twice, it's a syntax error.
If you indent them once, they'll be methods of the class.
If you don't indent them at all, they'll be global functions.

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


Re: Gotcha I never ran into before

2007-08-09 Thread James Stroud
Brian Cole wrote:
> I've been programming in Python for about 6 years now. One of the
> features I adore the most is the very useful error messages and stack
> traces that make it easy to debug. However, today I ran into a
> difficult to trace bug because the stack trace was reporting the
> problem in the wrong place.
> 
> class Delegator(object):
> def __init__(self, obj):
> self.obj = obj
> def __getattr__(self, attr):
> return getattr(self.obj, attr)
> 
> class SpecializedDelegator(Delegator):
> def get_blah(self):
> return ["Returning Blah"].upper()
> blah = property(fget=get_blah)
> 
> print SpecializedDelegator("Doesn't Matter").blah
> 
> The stack trace is:
> Traceback (most recent call last):
>   File "test.py", line 12, in ?
> print SpecializedDelegator("Doesn't Matter").blah
>   File "test.py", line 5, in __getattr__
> return getattr(self.obj, attr)
> AttributeError: 'str' object has no attribute 'blah'
> 
> Which is correct, but says nothing about the real problem inside the
> get_blah method. Is there a good reason that when a property's fget
> function throws an AttributeError that it should fall back on
> __getattr__? I would think since the attribute was explicitly defined
> as a property the property function should be allowed to fully crash
> and burn.
> 
> Note: This example is broken up into two classes because that is how I
> discovered it. Since both classes were in separate files it added to
> the agony of debugging this. Luckily I was making a small incremental
> change so I could just back up and figure out what went wrong.
> 
> Thanks,
> Brian

Your __getattr__ in in Delegator is circumventing the property in 
SpecializedDelegator:

py> class Delegator(object):
... def __init__(self, obj):
... self.obj = obj
... def __getattr__(self, attr):
... return getattr(self.obj, attr)
...
py> class SpecializedDelegator(Delegator):
... def get_blah(self):
... return ["Returning Blah"].upper()
... blah = property(fget=get_blah)
...
py> print SpecializedDelegator("Doesn't Matter").blah

Traceback (most recent call last):
   File "", line 1, in 
   File "", line 5, in __getattr__
: 'str' object has no attribute 'blah'

py> class Delegator(object):
... def __init__(self, obj):
... self.obj = obj
... def __getattr__(self, attr):
... if hasattr(self.obj, attr):
...   return getattr(self.obj, attr)
... else:
...   return self.__getattribute__(attr)
...
py> class SpecializedDelegator(Delegator):
... def get_blah(self):
... return ["Returning Blah"].upper()
... blah = property(fget=get_blah)
...
py> print SpecializedDelegator("Doesn't Matter").blah

Traceback (most recent call last):
   File "", line 1, in 
   File "", line 8, in __getattr__
   File "", line 3, in get_blah
: 'list' object has no attribute 'upper'


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: Threaded Design Question

2007-08-09 Thread MRAB
On Aug 9, 7:25 pm, [EMAIL PROTECTED] wrote:
> Hi all!  I'm implementing one of my first multithreaded apps, and have
> gotten to a point where I think I'm going off track from a standard
> idiom.  Wondering if anyone can point me in the right direction.
>
> The script will run as a daemon and watch a given directory for new
> files.  Once it determines that a file has finished moving into the
> watch folder, it will kick off a process on one of the files.  Several
> of these could be running at any given time up to a max number of
> threads.
>
> Here's how I have it designed so far.  The main thread starts a
> Watch(threading.Thread) class that loops and searches a directory for
> files.  It has been passed a Queue.Queue() object (watch_queue), and
> as it finds new files in the watch folder, it adds the file name to
> the queue.
>
> The main thread then grabs an item off the watch_queue, and kicks off
> processing on that file using another class Worker(threading.thread).
>
> My problem is with communicating between the threads as to which files
> are currently processing, or are already present in the watch_queue so
> that the Watch thread does not continuously add unneeded files to the
> watch_queue to be processed.  For example...Watch() finds a file to be
> processed and adds it to the queue.  The main thread sees the file on
> the queue and pops it off and begins processing.  Now the file has
> been removed from the watch_queue, and Watch() thread has no way of
> knowing that the other Worker() thread is processing it, and shouldn't
> pick it up again.  So it will see the file as new and add it to the
> queue again.  PS.. The file is deleted from the watch folder after it
> has finished processing, so that's how i'll know which files to
> process in the long term.
>
I would suggest something like the following in the watch thread:

seen_files = {}

while True:
# look for new files
for name in os.listdir(folder):
if name not in seen_files:
process_queue.add(name)
seen_files[name] = True

# forget any missing files and mark the others as not seen, ready for
next time
seen_files = dict((name, False) for name, seen in seen_files.items()
if seen)

time.sleep(1)

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


Re: Misleading wikipedia article on Python 3?

2007-08-09 Thread Ricardo Aráoz
Evan Klitzke wrote:
> On 8/8/07, greg <[EMAIL PROTECTED]> wrote:
>> Istvan Albert wrote:
>>> A solution would be writing the code with a logging function to begin
>>> with, alas many times that is out of one's hand.
>> If the code has been written with calls to a builtin
>> print function, the situation isn't much better. You
>> could monkeypatch the print function, but that's
>> probably worse than swapping sys.stdout.
> 
> You can easily modify print in a safe way. Here's an example, that
> will work in any recent version of Python:
> 
> import sys
> 
> def print_(s):
> print s
> 
> def logger(method):
> def wrapper(s):
> sys.stderr.write('Logging: %s\n' % s)
> method(s)
> return wrapper
> 
> print_ = logger(print_)
> 
> print_('hello')
> 
> 
> Running this code will do a regular print of 'hello', as well as
> "logging" it to stderr. As a function, you can convert print wholesale
> to another logging function, or wrap it transparently like this to
> provide additional logging functionality. What do you find wrong with
> this sort of "monkeypatching"?
> 

foolish question maybe.
Why wouldn't you do it this way ?

def print_(s):
print s

def logger(m):
sys.stderr.write('Logging: %s\n' % m)
method(m)

print_ = logger(print_)

print_('hello')




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


Importing to

2007-08-09 Thread James Stroud
Many thanks to the numerous helpful comments by Paul Rubin, Carsten 
Haese and others in the thread "How to pass a reference to the current 
module".

After digesting these comments, I came up with this way to circumvent 
the problem of attempting to reference modules that import other modules 
  in said imported modules (executed in main):


   # branches ==> dictionary of dictionaries (actually a ConfigObj)
   for (name, branch) in branches.items():
 modname = branch.get('__module__', None)
 if modname is None:
   namespace = globals()
 else:
   namespace = __import__(modname).globals()
 fname = branch.get('__function__', name)
 function = namespace[fname]
 # etc.


I'm wondering if this approach seems problematic to anyone.

Thanks again for all of the help I've received.

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


High performance binary data

2007-08-09 Thread Steve
I want to ready binary data from a udp socket effeciently as possible
in python.  I know of the struct package but do people have any tips
when dealing with binary data in python?  Is there a library or api
that is faster when dealing with binary data. I am looking for a any
one with experience or ideas on the subject.  Pointers any one?

Thanks
Steve

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


Deleting objects on the fly

2007-08-09 Thread Godzilla
Hello,

I wish to know whether I should delete objects created on the fly via
the "del obj" statement. I noticed the RAM usage increased whenever
the application is being run for a long time. I am creating lots of
objects (messages) on the fly for communication between threads.

Rather than having python's gc to do the work, does it make a
difference if I force a deletion?

Thanks.

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


Re: beginner whitespace question

2007-08-09 Thread eggie5
On Aug 9, 4:52 pm, Dan Bishop <[EMAIL PROTECTED]> wrote:
> On Aug 9, 6:47 pm, eggie5 <[EMAIL PROTECTED]> wrote:
>
> > I keep getting an error for line 7, what's wrong with this?
>
> > from django.db import models
>
> > class Poll(models.Model):
> > question = models.CharField(max_length=200)
> > pub_date = models.DateTimeField('date published')
>
> > def __unicode__(self):
> > return self.question
>
> The "def" statements have to be at the same indentation level as
> what's before it.

will they still be a part of the classes?

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


Smoother Lines in Turtle Graphics

2007-08-09 Thread tomy
Hi All
I am a newbie to turtle graphics in python, so sorry if you find this
question too easy.
How can I get smoother lines in turtle graphics?
I am using python on windows.

Thanks in advance

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


Re: beginner whitespace question

2007-08-09 Thread Dan Bishop
On Aug 9, 6:47 pm, eggie5 <[EMAIL PROTECTED]> wrote:
> I keep getting an error for line 7, what's wrong with this?
>
> from django.db import models
>
> class Poll(models.Model):
> question = models.CharField(max_length=200)
> pub_date = models.DateTimeField('date published')
>
> def __unicode__(self):
> return self.question
>

The "def" statements have to be at the same indentation level as
what's before it.

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


beginner whitespace question

2007-08-09 Thread eggie5
I keep getting an error for line 7, what's wrong with this?

from django.db import models

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __unicode__(self):
return self.question

def was_published_today(self):
return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()

def __unicode__(self):
return self.choice

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


Re: programmatically define a new variable on the fly

2007-08-09 Thread Roberto Bonvallet
On Aug 9, 6:11 pm, Lee Sander <[EMAIL PROTECTED]> wrote:
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing.

Use a dictionary.

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


Re: Threaded Design Question

2007-08-09 Thread Jun-geun Park
[EMAIL PROTECTED] wrote:
> Hi all!  I'm implementing one of my first multithreaded apps, and have
> gotten to a point where I think I'm going off track from a standard
> idiom.  Wondering if anyone can point me in the right direction.
> 
> The script will run as a daemon and watch a given directory for new
> files.  Once it determines that a file has finished moving into the
> watch folder, it will kick off a process on one of the files.  Several
> of these could be running at any given time up to a max number of
> threads.
> 
> Here's how I have it designed so far.  The main thread starts a
> Watch(threading.Thread) class that loops and searches a directory for
> files.  It has been passed a Queue.Queue() object (watch_queue), and
> as it finds new files in the watch folder, it adds the file name to
> the queue.
> 
> The main thread then grabs an item off the watch_queue, and kicks off
> processing on that file using another class Worker(threading.thread).
> 
> My problem is with communicating between the threads as to which files
> are currently processing, or are already present in the watch_queue so
> that the Watch thread does not continuously add unneeded files to the
> watch_queue to be processed.  For example...Watch() finds a file to be
> processed and adds it to the queue.  The main thread sees the file on
> the queue and pops it off and begins processing.  Now the file has
> been removed from the watch_queue, and Watch() thread has no way of
> knowing that the other Worker() thread is processing it, and shouldn't
> pick it up again.  So it will see the file as new and add it to the
> queue again.  PS.. The file is deleted from the watch folder after it
> has finished processing, so that's how i'll know which files to
> process in the long term.
> 
> I made definite progress by creating two queues...watch_queue and
> processing_queue, and then used lists within the classes to store the
> state of which files are processing/watched.
> 
> I think I could pull it off, but it has got very confusing quickly,
> trying to keep each thread's list and the queue always in sync with
> one another.  The easiset solution I can see is if my threads could
> read an item from the queue without removing it from the queue and
> only remove it when I tell it to.  Then the Watch() thread could then
> just follow what items are on the watch_queue to know what files to
> add, and then the Worker() thread could intentionally remove the item
> from the watch_queue once it has finished processing it.
> 
> Now that I'm writing this out, I see a solution by over-riding or
> wrapping Queue.Queue().get() to give me the behavior I mention above.
> 
> I've noticed .join() and .task_done(), but I'm not sure of how to use
> them properly.  Any suggestions would be greatly appreciated.
> 
> ~Sean
> 

1) Use a (global) hash table and a mutex on it. Before a worker thread
starts processing a file, have the worker acquire the mutex, add the
filename into a global dictionary as a key, and release the mutex.  Then,
when the watcher thread attempts to read a file, it only has to check
whether the filename is on the table.

If different files may have a same name, you can also use size or some
other signatures. Also, I think basic operations on primitive types on
Python are atomic so you don't actually need mutex, but in threaded
programs, it's always a good habit to use mutexes explicitly.

2) If the watcher thread doesn't spend much time in "recognizing" files 
to process,
simply make the watcher thread reads many(or all) files in the directory,
put them all in the queue, and wait until all items in the queue are 
processed
using .join(). Workers can indicate that the processing of the last 
dequeued item
is done by calling .task_done() (As soon as all items are flaged 
"task_done()", join() will
unblock.) After processing of files on the queue are all done,
watcher can move or remove processed files and read the directory again. 
Of course,
you need to keep track of "recognized" files of that turn.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: programmatically define a new variable on the fly

2007-08-09 Thread Ian Clark
Lee Sander wrote:
> Hi,
> 
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing. So, for example, if I the file
> I'm reading has
> g 99
> on the first line, I want to create a new variable  called "Xg" whose
> length
> is 99.
> I tried eval("Xg=[0]*99") but that did not work.
> 
> any help would be greatly appreciated
> Lee
> 

 >>> Xg
Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'Xg' is not defined
 >>> namespace = globals()
 >>> var_name = 'Xg'
 >>> var_value = [0] * 9
 >>> namespace[var_name] = var_value
 >>> Xg
[0, 0, 0, 0, 0, 0, 0, 0, 0]

Ian

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


Re: programmatically define a new variable on the fly

2007-08-09 Thread Dustan
On Aug 9, 5:30 pm, Dustan <[EMAIL PROTECTED]> wrote:
> given the
> variables data (the dictionary), name (in your example, 'g') and
> *size* (in your example, 99), you can add it  data as shown:

erm... make that:

given the variables data (the dictionary), name (in your example, 'g')
and size (in your example, 99), you can add it to data as shown:

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


Re: programmatically define a new variable on the fly

2007-08-09 Thread Dustan
On Aug 9, 5:11 pm, Lee Sander <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing. So, for example, if I the file
> I'm reading has
> g 99
> on the first line, I want to create a new variable  called "Xg" whose
> length
> is 99.
> I tried eval("Xg=[0]*99") but that did not work.

eval only evaluates expressions. To go about the problem that way, you
would use exec, not eval.

Of course, use of exec generally means you're going about the problem
the wrong way; it looks to me like a better way to do what you're
doing is to create a dictionary to hold your values. So, given the
variables data (the dictionary), name (in your example, 'g') and
*size* (in your example, 99), you can add it  data as shown:

data[name] = [0]
data[name] *= size

Note that by splitting the '[0]*size' code into two lines as shown
above, you don't create an intermediate list object that gets thrown
away right after creation.

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


Re: Querying Graphics Card Name

2007-08-09 Thread Benjamin Goldenberg
On Aug 9, 4:06 pm, Richard Jones <[EMAIL PROTECTED]>
wrote:
> Benjamin Goldenberg wrote:
> > I would like to find out the name of the graphics card of the machine
> > my program is running on. I have looked into the pyopengl module, and
> > using them to query the card, but it seems like there ought to be a
> > simpler way to find this out without setting up a glcontext. Does
> > anyone have any ideas?
>
> You need a context if you're going to ask OpenGL to tell you what the card
> is. To find out any other way would be highly platform-specific, possibly
> though looking in the /proc directory on Linux, and who-knows-where-else on
> other platforms.
>
> Also, have a look at tools/info.py in the pyglet project
> 
>
> Richard

Thanks for the reference, but I was unable to find tools/info.py in
pyglet. What would be the full path to this file?
Thanks.

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


programmatically define a new variable on the fly

2007-08-09 Thread Lee Sander
Hi,

I would like to define a new variable which is not predefined by me.
For example,
I want to create an array called "X%s" where "%s" is to be determined
based on the data I am processing. So, for example, if I the file
I'm reading has
g 99
on the first line, I want to create a new variable  called "Xg" whose
length
is 99.
I tried eval("Xg=[0]*99") but that did not work.

any help would be greatly appreciated
Lee

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


Re: Puzzled by "is"

2007-08-09 Thread Hrvoje Niksic
Grzegorz Słodkowicz <[EMAIL PROTECTED]> writes:

>> Seriously, it's just an optimization by the implementers. There is
>> no need for more than one empty tuple, since tuples can never be
>> modified once created.
>>
>> But they decided not to create (1, ) in advance. They probably knew
>> that hardly anybody would want to create that tuple ;-) [Seriously:
>> if you started trying to predict which tuples would be used you
>> would go insane, but the empty tuple is the most likely candidate].
>>
> That's just theorisation but I'd rather expect the interpreter simply
> not to create a second tuple while there already is an identical
> one.

But then tuple creation would be slowed down by searching for whether
an "identical one" already exists.  In the general case, that is quite
unlikely, so it's not done.  (I suspect that only the requirement to
store the list of all tuples somewhere would outweigh any potential
gains of this strategy; and if the search were implemented as a hash
table lookup, even more space would be wasted.)  It's done for the
empty tuple because no search is necessary, only a size test.

> Admittedly the empty tuple is a special case but then 'Special cases
> aren't special enough to break the rules'.

Except no rule is being broken.  As others have pointed out, since
tuples are immutable, caching them is quite safe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread Steve Holden
Grzegorz Słodkowicz wrote:
>> Why? Because.
>>
>> Seriously, it's just an optimization by the implementers. There is no 
>> need for more than one empty tuple, since tuples can never be modified 
>> once created.
>>
>> But they decided not to create (1, ) in advance. They probably knew that 
>> hardly anybody would want to create that tuple ;-) [Seriously: if you 
>> started trying to predict which tuples would be used you would go 
>> insane, but the empty tuple is the most likely candidate].
>>   
> That's just theorisation but I'd rather expect the interpreter simply 
> not to create a second tuple while there already is an identical one. 
> This could save some memory if the tuple was large (Although by the same 
> token comparison of large tuples can be expensive). Admittedly the empty 
> tuple is a special case but then 'Special cases aren't special enough to 
> break the rules'.
> 
> A bit odd.
> 
It's a trade-off, preferring to optimize time rather than memory usage. 
If tuples were "interned" like some strings then tuple creation would be 
more expensive due to the need to search the cache when creating them 
which, as you rightly point out, could be very expensive for large tuples.

The integers under 100 are also, IIRC, special-cased:

 >>> x = 12
 >>> y = 32676
 >>> x is 12
True
 >>> y is 32676
False
 >>>

I guess if you *make* the rules you can decide when it's reasonable to 
break them!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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

Re: Querying Graphics Card Name

2007-08-09 Thread Richard Jones
Benjamin Goldenberg wrote:
> I would like to find out the name of the graphics card of the machine
> my program is running on. I have looked into the pyopengl module, and
> using them to query the card, but it seems like there ought to be a
> simpler way to find this out without setting up a glcontext. Does
> anyone have any ideas?

You need a context if you're going to ask OpenGL to tell you what the card
is. To find out any other way would be highly platform-specific, possibly
though looking in the /proc directory on Linux, and who-knows-where-else on
other platforms.

Also, have a look at tools/info.py in the pyglet project



Richard

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


Re: Querying Graphics Card Name

2007-08-09 Thread Benjamin Goldenberg
On Aug 9, 3:26 pm, Bjoern Schliessmann  wrote:
> Benjamin Goldenberg wrote:
> > I would like to find out the name of the graphics card of the
> > machine my program is running on. I have looked into the pyopengl
> > module, and using them to query the card, but it seems like there
> > ought to be a simpler way to find this out without setting up a
> > glcontext. Does anyone have any ideas?
>
> You could execute glxinfo and look for the renderer string. If
> that's sharp enough for your purpose. Another option is lspci.

I should have clarified. I would like a cross platform implementation,
Windows and *nix. It doesn't seem as if glxinfo is available under
Windows, at least not without installing X11 under cygwin. If
necessary, I can write the *nix and Windows queries separately.

Thanks,
Benjamin

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


Re: Screenscraping, in python, a web page that requires javascript?

2007-08-09 Thread John J. Lee
Dan Stromberg - Datallegro <[EMAIL PROTECTED]> writes:

> Is there a method, with python, of screenscraping a web page, if that web
> page uses javascript?

Not pure CPython, no.


> I know about BeautifulSoup, but AFAIK at this time, BeautifulSoup is for
> HTML that doesn't have embedded javascript.

It's not that BeautifulSoup is unhappy with JS, it's just that there's
no support for executing the JS.

There are some Java libraries that know how to execute JS embedded in
web pages, which could be used from Jython:

http://www.thefrontside.net/crosscheck

http://htmlunit.sourceforge.net/

http://httpunit.sourceforge.net/


You can also automate a browser, but that still seems to be painful in
one way or another.


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


Re: Stackless Integration

2007-08-09 Thread Aahz
In article <[EMAIL PROTECTED]>,
Neil Cerutti  <[EMAIL PROTECTED]> wrote:
>On 2007-08-09, Justin T. <[EMAIL PROTECTED]> wrote:
>>JP Calderone:
>>>
>>> It's not Pythonic.
>>
>> Ha! I wish there was a way to indicate sarcasm on the net. You
>> almost got people all riled up!
>
>Sorry. There's NO WAY to show sarcasm on the net. ;)

"If sarcasm were posted to the Net, would anybody notice?"  --JDN
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"And if that makes me an elitist...I couldn't be happier."  --JMS
-- 
http://mail.python.org/mailman/listinfo/python-list


Screenscraping, in python, a web page that requires javascript?

2007-08-09 Thread Dan Stromberg - Datallegro

Is there a method, with python, of screenscraping a web page, if that web
page uses javascript?

I know about BeautifulSoup, but AFAIK at this time, BeautifulSoup is for
HTML that doesn't have embedded javascript.

Thanks!

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


Re: Querying Graphics Card Name

2007-08-09 Thread Bjoern Schliessmann
Benjamin Goldenberg wrote:
> I would like to find out the name of the graphics card of the
> machine my program is running on. I have looked into the pyopengl
> module, and using them to query the card, but it seems like there
> ought to be a simpler way to find this out without setting up a
> glcontext. Does anyone have any ideas?

You could execute glxinfo and look for the renderer string. If
that's sharp enough for your purpose. Another option is lspci.

Regards,


Björn

-- 
BOFH excuse #215:

High nuclear activity in your area.

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


Re: Puzzled by "is"

2007-08-09 Thread Erik Max Francis
Grzegorz Słodkowicz wrote:

> That's just theorisation but I'd rather expect the interpreter simply 
> not to create a second tuple while there already is an identical one. 
> This could save some memory if the tuple was large (Although by the same 
> token comparison of large tuples can be expensive). Admittedly the empty 
> tuple is a special case but then 'Special cases aren't special enough to 
> break the rules'.
> 
> A bit odd.

It doesn't save time if you have to check through all the existing 
tuples for matches ...

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Chance favors the trained mind.
-- Louis Pasteur
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Puzzled by "is"

2007-08-09 Thread Erik Max Francis
John K Masters wrote:

> OK fiddling around with this and reading the docs I tried:-
> a = 'qq' #10 q's
> b = 'qq' #10 q's
> a is b
> true
> c = 'q' * 10
> c
> 'qq' #10 q's
> d = 'q' * 10
> d
> 'qq' #10 q's
> c is d
> false
> 
> So from what I've read "==" tests for equivalence, "is" tests for identity but
> that does not explain the behaviour above.

Using the `is` test between non-sentinel immutable objects (e.g., 
integers, floats, strings) is _completely pointless_.  Since immutable 
objects cannot be changed, it is up to the interpreter (and thus can 
vary from version to version and implementation to implementation) 
whether or not to "cache" the objects and reuse them, or whether or not 
to create new ones.  You should never be testing such objects for 
identity (`is`); you should only be testing them for equality (`==`).

The only time it makes sense to use the `is` operator with immutable 
objects is when you're dealing with a sentinel object, e.g., `None`, or 
a custom sentinel object (e.g., `mySentinel = object()`), because that 
is the only time you actually _are_ interested in identity.  All other 
times you are not really interested in identity.

Sample code as above is essentially showing unimportant implementation 
details that should never concern you.  Don't use `is`, use `==`.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Chance favors the trained mind.
-- Louis Pasteur
-- 
http://mail.python.org/mailman/listinfo/python-list


Gotcha I never ran into before

2007-08-09 Thread Brian Cole
I've been programming in Python for about 6 years now. One of the
features I adore the most is the very useful error messages and stack
traces that make it easy to debug. However, today I ran into a
difficult to trace bug because the stack trace was reporting the
problem in the wrong place.

class Delegator(object):
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
return getattr(self.obj, attr)

class SpecializedDelegator(Delegator):
def get_blah(self):
return ["Returning Blah"].upper()
blah = property(fget=get_blah)

print SpecializedDelegator("Doesn't Matter").blah

The stack trace is:
Traceback (most recent call last):
  File "test.py", line 12, in ?
print SpecializedDelegator("Doesn't Matter").blah
  File "test.py", line 5, in __getattr__
return getattr(self.obj, attr)
AttributeError: 'str' object has no attribute 'blah'

Which is correct, but says nothing about the real problem inside the
get_blah method. Is there a good reason that when a property's fget
function throws an AttributeError that it should fall back on
__getattr__? I would think since the attribute was explicitly defined
as a property the property function should be allowed to fully crash
and burn.

Note: This example is broken up into two classes because that is how I
discovered it. Since both classes were in separate files it added to
the agony of debugging this. Luckily I was making a small incremental
change so I could just back up and figure out what went wrong.

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


Re: Puzzled by "is"

2007-08-09 Thread Grzegorz Słodkowicz
>
> Why? Because.
>
> Seriously, it's just an optimization by the implementers. There is no 
> need for more than one empty tuple, since tuples can never be modified 
> once created.
>
> But they decided not to create (1, ) in advance. They probably knew that 
> hardly anybody would want to create that tuple ;-) [Seriously: if you 
> started trying to predict which tuples would be used you would go 
> insane, but the empty tuple is the most likely candidate].
>   
That's just theorisation but I'd rather expect the interpreter simply 
not to create a second tuple while there already is an identical one. 
This could save some memory if the tuple was large (Although by the same 
token comparison of large tuples can be expensive). Admittedly the empty 
tuple is a special case but then 'Special cases aren't special enough to 
break the rules'.

A bit odd.

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


Re: Puzzled by "is"

2007-08-09 Thread Steve Holden
[EMAIL PROTECTED] wrote:
[...]
> 
> Steve,
> 
> I thought you'd probably weigh in on this esoteric matter. Very
> illuminating, as usual.
> 
Thank you!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: how to get command output using python

2007-08-09 Thread Arnau Sanchez
[EMAIL PROTECTED] escribió:

>> Any non cross-platform module should be avoided unless absolutely necessary.
>>
>> Subprocess is the right module to use.
>>
>> arnau
> 
> You forgot to mention that subprocess replaces commands, so in effect,
> commands is deprecated anyway.

It was implicit :-)

Anyway, these modules ("commands", "popen2", ...) are not officially deprecated 
(at least in 2.5), so it's not strange that newcomers sometimes choose 
(wrongly) 
them.

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


Re: Puzzled by "is"

2007-08-09 Thread Neil Cerutti
On 2007-08-09, John K Masters <[EMAIL PROTECTED]> wrote:
> On 15:53 Thu 09 Aug , Steve Holden wrote:
>> Dick Moores wrote:
>> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
>> >> Dick Moores wrote:
>> [...]
>> >> There is only one empty tuple.
>> >> Does that clear it up for you?
>> > 
>> > But isn't that the same as saying, "That's just the reality of 
>> > Python; it is what it is."? I want to know why there is only one 
>> > empty tuple, but more than one (1,).
>> > 
>> Why? Because.
>> 
>> Seriously, it's just an optimization by the implementers. There is no 
>> need for more than one empty tuple, since tuples can never be modified 
>> once created.
>> 
>> But they decided not to create (1, ) in advance. They probably knew that 
>> hardly anybody would want to create that tuple ;-) [Seriously: if you 
>> started trying to predict which tuples would be used you would go 
>> insane, but the empty tuple is the most likely candidate].
>> 
>> > Also,
>> >  >>> [] is []
>> > False
>> > 
>> In that case it would definitely NOT make sense to have them the same 
>> list. Python always ensures that the [] constructor creates a new list, 
>> since that list may be bound to one or more variables and mutated. You 
>> wouldn't want
>> 
>>a = []
>>b = []
>>a.append("boo!")
>> 
>> to change b so it was no longer an empty list. If you wanted a and b to 
>> reference the same list you would change the second statement to
>> 
>>b = a
>> 
>> regards
>>   Steve
>
> OK fiddling around with this and reading the docs I tried:-
> a = 'qq' #10 q's
> b = 'qq' #10 q's

CPython is full of cute little optimizations, and one of them is
that literal strings less than a certain length are 'interned'.
This makes them very fast to compare for equality, and cheaper to
store (maybe?).

> a is b
> true
> c = 'q' * 10
> c
> 'qq' #10 q's
> d = 'q' * 10
> d
> 'qq' #10 q's
> c is d
> false
>
> So from what I've read "==" tests for equivalence, "is" tests
> for identity but that does not explain the behaviour above.

The 10 q's constructed with string arithmetic were not interned,
because they were not literals.

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


Re: Puzzled by "is"

2007-08-09 Thread kyosohma
On Aug 9, 2:53 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Dick Moores wrote:
> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
> >> Dick Moores wrote:
> [...]
> >> There is only one empty tuple.
> >> Does that clear it up for you?
>
> > But isn't that the same as saying, "That's just the reality of
> > Python; it is what it is."? I want to know why there is only one
> > empty tuple, but more than one (1,).
>
> Why? Because.
>
> Seriously, it's just an optimization by the implementers. There is no
> need for more than one empty tuple, since tuples can never be modified
> once created.
>
> But they decided not to create (1, ) in advance. They probably knew that
> hardly anybody would want to create that tuple ;-) [Seriously: if you
> started trying to predict which tuples would be used you would go
> insane, but the empty tuple is the most likely candidate].
>
> > Also,
> >  >>> [] is []
> > False
>
> In that case it would definitely NOT make sense to have them the same
> list. Python always ensures that the [] constructor creates a new list,
> since that list may be bound to one or more variables and mutated. You
> wouldn't want
>
>a = []
>b = []
>a.append("boo!")
>
> to change b so it was no longer an empty list. If you wanted a and b to
> reference the same list you would change the second statement to
>
>b = a
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -

Steve,

I thought you'd probably weigh in on this esoteric matter. Very
illuminating, as usual.

Mike

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


Re: Puzzled by "is"

2007-08-09 Thread John K Masters
On 15:53 Thu 09 Aug , Steve Holden wrote:
> Dick Moores wrote:
> > At 10:46 AM 8/9/2007, Bill Scherer wrote:
> >> Dick Moores wrote:
> [...]
> >> There is only one empty tuple.
> >> Does that clear it up for you?
> > 
> > But isn't that the same as saying, "That's just the reality of 
> > Python; it is what it is."? I want to know why there is only one 
> > empty tuple, but more than one (1,).
> > 
> Why? Because.
> 
> Seriously, it's just an optimization by the implementers. There is no 
> need for more than one empty tuple, since tuples can never be modified 
> once created.
> 
> But they decided not to create (1, ) in advance. They probably knew that 
> hardly anybody would want to create that tuple ;-) [Seriously: if you 
> started trying to predict which tuples would be used you would go 
> insane, but the empty tuple is the most likely candidate].
> 
> > Also,
> >  >>> [] is []
> > False
> > 
> In that case it would definitely NOT make sense to have them the same 
> list. Python always ensures that the [] constructor creates a new list, 
> since that list may be bound to one or more variables and mutated. You 
> wouldn't want
> 
>a = []
>b = []
>a.append("boo!")
> 
> to change b so it was no longer an empty list. If you wanted a and b to 
> reference the same list you would change the second statement to
> 
>b = a
> 
> regards
>   Steve

OK fiddling around with this and reading the docs I tried:-
a = 'qq' #10 q's
b = 'qq' #10 q's
a is b
true
c = 'q' * 10
c
'qq' #10 q's
d = 'q' * 10
d
'qq' #10 q's
c is d
false

So from what I've read "==" tests for equivalence, "is" tests for identity but
that does not explain the behaviour above.

Regards, John
-- 
War is God's way of teaching Americans geography
Ambrose Bierce (1842 - 1914)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tempfile behavior

2007-08-09 Thread Marc 'BlackJack' Rintsch
On Thu, 09 Aug 2007 12:47:10 -0700, billiejoex wrote:

 fd, filename = tempfile.mkstemp()
 type(fd)
> 
> 
> I would expect a file descriptor, not and integer.
> How do I have to use it?

File descriptors are integers.  It's a low level C thing.  Either use the
low level functions in `os` or open the file with the `filename`.

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


Re: Puzzled by "is"

2007-08-09 Thread Steve Holden
Dick Moores wrote:
> At 10:46 AM 8/9/2007, Bill Scherer wrote:
>> Dick Moores wrote:
[...]
>> There is only one empty tuple.
>> Does that clear it up for you?
> 
> But isn't that the same as saying, "That's just the reality of 
> Python; it is what it is."? I want to know why there is only one 
> empty tuple, but more than one (1,).
> 
Why? Because.

Seriously, it's just an optimization by the implementers. There is no 
need for more than one empty tuple, since tuples can never be modified 
once created.

But they decided not to create (1, ) in advance. They probably knew that 
hardly anybody would want to create that tuple ;-) [Seriously: if you 
started trying to predict which tuples would be used you would go 
insane, but the empty tuple is the most likely candidate].

> Also,
>  >>> [] is []
> False
> 
In that case it would definitely NOT make sense to have them the same 
list. Python always ensures that the [] constructor creates a new list, 
since that list may be bound to one or more variables and mutated. You 
wouldn't want

   a = []
   b = []
   a.append("boo!")

to change b so it was no longer an empty list. If you wanted a and b to 
reference the same list you would change the second statement to

   b = a

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: tempfile behavior

2007-08-09 Thread billiejoex
On 9 Ago, 20:31, [EMAIL PROTECTED] wrote:
> On Aug 9, 11:21 am, billiejoex <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
> > I would like to use tempfile module to generate files having unique
> > names excepting that I don't want them to be removed after closing.
> > Does it is possible?
>
> Looks like tempfile.mkstemp() will do what you want.
>
> '''Unlike TemporaryFile(), the user of mkstemp() is responsible for
> deleting the temporary file when done with it.'''
>
> ~Sean

Thank you, it seems good.
Just another question:

>>> fd, filename = tempfile.mkstemp()
>>> type(fd)


I would expect a file descriptor, not and integer.
How do I have to use it?

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


Re: Puzzled by "is"

2007-08-09 Thread Dick Moores
At 10:46 AM 8/9/2007, Bill Scherer wrote:
>Dick Moores wrote:
> >  >>> () is ()
> > True
> >  >>> (1,) is (1,)
> > False
> >
> > Why?
> >
>
> >>> a = ()
> >>> b = ()
> >>> c = (1,)
> >>> d = (1,)
> >>> a is b
>True
> >>> c is d
>False
> >>> id(a)
>3086553132
> >>> id(b)
>3086553132
> >>> id(c)
>3086411340
> >>> id(d)
>3086390892
>
>
>There is only one empty tuple.
>Does that clear it up for you?

But isn't that the same as saying, "That's just the reality of 
Python; it is what it is."? I want to know why there is only one 
empty tuple, but more than one (1,).

Also,
 >>> [] is []
False

Dick  

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


Re: check if regeular expression has results

2007-08-09 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-08-09, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>>Hi,
>>I'm looking for the best way to check if regular expression return
>>true (it's mean - there is a match). for example, i want "if" that
>>check if this regular expression: .*born.*to.* has a match.
>>
>>What's the way to do that simply?
> 
> 
> Newgroups are a poor substitute for the docs. For one thing,
> newsgroups sometimes contain cranky people who say, "RTFM!" The
> docs will never do that.
> 
And for completness, here are the relevant parts of TheFineManual(tm):
http://docs.python.org/lib/module-re.html
http://www.amk.ca/python/howto/regex/
-- 
http://mail.python.org/mailman/listinfo/python-list


Querying Graphics Card Name

2007-08-09 Thread Benjamin Goldenberg
Hello,
I would like to find out the name of the graphics card of the machine
my program is running on. I have looked into the pyopengl module, and
using them to query the card, but it seems like there ought to be a
simpler way to find this out without setting up a glcontext. Does
anyone have any ideas?

Thanks,
Benjamin

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


Re: Threaded Design Question

2007-08-09 Thread Justin T.
On Aug 9, 11:25 am, [EMAIL PROTECTED] wrote:
>
> Here's how I have it designed so far.  The main thread starts a
> Watch(threading.Thread) class that loops and searches a directory for
> files.  It has been passed a Queue.Queue() object (watch_queue), and
> as it finds new files in the watch folder, it adds the file name to
> the queue.
>
> The main thread then grabs an item off the watch_queue, and kicks off
> processing on that file using another class Worker(threading.thread).
>
Sounds good.

>
> I made definite progress by creating two queues...watch_queue and
> processing_queue, and then used lists within the classes to store the
> state of which files are processing/watched.
>
This sounds ugly, synchronization is one of those evils of
multithreaded programming that should be avoided if possible. I see a
couple of dirt simple solutions:

1. Have the watch thread move the file into a "Processing" folder that
it doesn't scan
2. Have the watch thread copy the file into a python tempfile object
and push that onto the queue, then delete the real file. This can be
done efficiently (well, more efficiently than new.write(old.read())
with shutil.copyfileobj(old, new)

Both those take very few lines of code, don't require synchronization,
and don't require extending standard classes.

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


Re: how to get output.

2007-08-09 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> I corrected a typ below.
> 
> On Aug 9, 12:50 pm, [EMAIL PROTECTED] wrote:
>> Hey,
>>
>> I did write the following:
>> but it does not work.
>>
>> import subprocess as sp
>> try:
>> p = sp.Popen("DIR . /AD /B", stdout=sp.PIPE)
>> result = p.communicate()[0]
>> print result
>>  except:
>>  print "error"
>>
>> This throws error.
>> DIR . /AD /B will list out only directories in the current directory.
>>
>> Thanks,
>> Indu
>>
>> On Aug 9, 11:46 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> indu_shreenath schrieb:
 Hey,
 I want to get the output of "DIR /AD /B" command to a varriable using
 python. How can I do this?
>>> Using the subprocess-module.
>>> However, I'm not sure what DIR /AD /B does - but there are many
>>> functions in module os that might deliver what you want without invoking
>>> an external command.
>>> Diez- Hide quoted text -
>> - Show quoted text -
> 
> 
That is better done in python with:

import os
dirs=[d for d in os.listdir(os.curdir) if os.path.isdir(d)]

or

dirs=filter(os.path.isdir, os.listdir(os.curdir))

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


Re: tempfile behavior

2007-08-09 Thread half . italian
On Aug 9, 11:21 am, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi all,
> I would like to use tempfile module to generate files having unique
> names excepting that I don't want them to be removed after closing.
> Does it is possible?

Looks like tempfile.mkstemp() will do what you want.

'''Unlike TemporaryFile(), the user of mkstemp() is responsible for
deleting the temporary file when done with it.'''

~Sean

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


Threaded Design Question

2007-08-09 Thread half . italian
Hi all!  I'm implementing one of my first multithreaded apps, and have
gotten to a point where I think I'm going off track from a standard
idiom.  Wondering if anyone can point me in the right direction.

The script will run as a daemon and watch a given directory for new
files.  Once it determines that a file has finished moving into the
watch folder, it will kick off a process on one of the files.  Several
of these could be running at any given time up to a max number of
threads.

Here's how I have it designed so far.  The main thread starts a
Watch(threading.Thread) class that loops and searches a directory for
files.  It has been passed a Queue.Queue() object (watch_queue), and
as it finds new files in the watch folder, it adds the file name to
the queue.

The main thread then grabs an item off the watch_queue, and kicks off
processing on that file using another class Worker(threading.thread).

My problem is with communicating between the threads as to which files
are currently processing, or are already present in the watch_queue so
that the Watch thread does not continuously add unneeded files to the
watch_queue to be processed.  For example...Watch() finds a file to be
processed and adds it to the queue.  The main thread sees the file on
the queue and pops it off and begins processing.  Now the file has
been removed from the watch_queue, and Watch() thread has no way of
knowing that the other Worker() thread is processing it, and shouldn't
pick it up again.  So it will see the file as new and add it to the
queue again.  PS.. The file is deleted from the watch folder after it
has finished processing, so that's how i'll know which files to
process in the long term.

I made definite progress by creating two queues...watch_queue and
processing_queue, and then used lists within the classes to store the
state of which files are processing/watched.

I think I could pull it off, but it has got very confusing quickly,
trying to keep each thread's list and the queue always in sync with
one another.  The easiset solution I can see is if my threads could
read an item from the queue without removing it from the queue and
only remove it when I tell it to.  Then the Watch() thread could then
just follow what items are on the watch_queue to know what files to
add, and then the Worker() thread could intentionally remove the item
from the watch_queue once it has finished processing it.

Now that I'm writing this out, I see a solution by over-riding or
wrapping Queue.Queue().get() to give me the behavior I mention above.

I've noticed .join() and .task_done(), but I'm not sure of how to use
them properly.  Any suggestions would be greatly appreciated.

~Sean

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


how to call file from Jython?

2007-08-09 Thread Naveen kumar
Hi I want to excute a .cmd file on windows through jython.. How can i do that?
   
  I am using following code
   
  import os
   
  os.system("C:/testfile/anotherfolder/Startserver.cmd")
   
  can any body let me know how can excute Startserver.cmd from jython??
   
  thanks,
  Naveen

   
-
Be a better Globetrotter. Get better travel answers from someone who knows.
Yahoo! Answers - Check it out.-- 
http://mail.python.org/mailman/listinfo/python-list

tempfile behavior

2007-08-09 Thread billiejoex
Hi all,
I would like to use tempfile module to generate files having unique
names excepting that I don't want them to be removed after closing.
Does it is possible?

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


Re: Puzzled by "is"

2007-08-09 Thread Jay Loden


Jay Loden wrote:
> Dick Moores wrote:
>>  >>> () is ()
>> True
>>  >>> (1,) is (1,)
>> False
>>
>> Why?
>>
>> Thanks,
>>
>> Dick Moores
> 


>From the docs for 'is':

  The operators is and is not test for object identity: x is y is true if
  and only if x and y are the same object. x is not y yields the inverse
  truth value.



So you're actually testing whether or not the identity of the object is the
same, not whether (1,) == (1,):

>>> (1,) == (1,)
True
>>> id((0,)) == id((0,))
False

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


Re: how to get command output using python

2007-08-09 Thread kyosohma
On Aug 9, 12:01 pm, Arnau Sanchez <[EMAIL PROTECTED]> wrote:
> Steven Harms escribió:
>
> > In python it is quite easy:
>
> > import commands
> > status, output = commands.getstatusoutput("my command")
>
> Uhm, this module has a big issue:
>
> (http://docs.python.org/lib/module-commands.html)
> 
> 8.17 commands -- Utilities for running commands
>
> Availability: Unix.
> 
>
> Any non cross-platform module should be avoided unless absolutely necessary.
>
> Subprocess is the right module to use.
>
> arnau

You forgot to mention that subprocess replaces commands, so in effect,
commands is deprecated anyway.

Mike

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


Re: Puzzled by "is"

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Dick Moores <[EMAIL PROTECTED]> wrote:
> >>> () is ()
> True
> >>> (1,) is (1,)
> False
>
> Why?

>From _Python Reference Manual_: 5.2.4 List displays:

  An empty pair of parentheses yields an empty tuple object.
  Since tuples are immutable, the rules for literals apply (i.e.,
  two occurrences of the empty tuple may or may not yield the
  same object). 

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


Re: Puzzled by "is"

2007-08-09 Thread Bill Scherer
Dick Moores wrote:
>  >>> () is ()
> True
>  >>> (1,) is (1,)
> False
>
> Why?
>   

>>> a = ()
>>> b = ()
>>> c = (1,)
>>> d = (1,)
>>> a is b
True
>>> c is d
False
>>> id(a)
3086553132
>>> id(b)
3086553132
>>> id(c)
3086411340
>>> id(d)
3086390892


There is only one empty tuple.
Does that clear it up for you?

> Thanks,
>
> Dick Moores
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by "is"

2007-08-09 Thread Jay Loden
Dick Moores wrote:
>  >>> () is ()
> True
>  >>> (1,) is (1,)
> False
> 
> Why?
> 
> Thanks,
> 
> Dick Moores

>From the docs for 'is':

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


Puzzled by "is"

2007-08-09 Thread Dick Moores
 >>> () is ()
True
 >>> (1,) is (1,)
False

Why?

Thanks,

Dick Moores

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


Re: Stackless Integration

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Justin T. <[EMAIL PROTECTED]> wrote:
>
>> It's not Pythonic.
>>
>> Jean-Paul
>
> Ha! I wish there was a way to indicate sarcasm on the net. You
> almost got people all riled up!

Sorry. There's NO WAY to show sarcasm on the net. ;)

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


Re: how to get command output using python

2007-08-09 Thread Arnau Sanchez
Steven Harms escribió:

> In python it is quite easy:
> 
> import commands
> status, output = commands.getstatusoutput("my command")

Uhm, this module has a big issue:

(http://docs.python.org/lib/module-commands.html)

8.17 commands -- Utilities for running commands

Availability: Unix.


Any non cross-platform module should be avoided unless absolutely necessary.

Subprocess is the right module to use.

arnau

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


Re: Stackless Integration

2007-08-09 Thread Justin T.

> It's not Pythonic.
>
> Jean-Paul

Ha! I wish there was a way to indicate sarcasm on the net. You almost
got people all riled up!

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


Re: Stackless Integration

2007-08-09 Thread Justin T.
On Aug 9, 8:57 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> First, which 'stackless'?  The original continuation-stackless (of about 7
> years ago)?  Or the more current tasklet-stackless (which I think is much
> younger than that)?
>
The current iteration. I can certianly understand Guido's distaste for
continuations.

>
> overcome.  It is just not part of the stdlib.
And I wish it were! It wouldn't be such a pain to get to my developers
then.

> And as far as I know or
> could find in the PEP index, C. Tismer has never submitted a PEP asking
> that it be made so.  Doing so would mean a loss of control, so there is a
> downside as well as the obvious upside of distribution.
That's true. Though, hopefully, the powers that be would allow him to
maintain it while it's in the stdlib. Maybe we should file a PEP for
him... :)

Justin

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


Re: Stackless Integration

2007-08-09 Thread Steve Holden
Steve Holden wrote:
> Bruno Desthuilliers wrote:
>> Jean-Paul Calderone a écrit :
>>> On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> 
>>> wrote:
 Hi,

 I've been looking at stackless python a little bit, and it's awesome.
 My question is, why hasn't it been integrated into the upstream python
 tree? Does it cause problems with the current C-extensions? It seems
 like if something is fully compatible and better, then it would be
 adopted. However, it hasn't been in what appears to be 7 years of
 existence, so I assume there's a reason.
>>> It's not Pythonic.
>> Hum... Yes ? Really ? Care to argument ?
> 
> Unfortunately such arguments quickly descend to the "yes it is", "no it 
> isn't" level, as there is no objective measure of Pythonicity.
> 
> Twisted [...]
> 
Oops, did I say Twisted? When I last heard Chris Tismer talking about 
Stackless someone in the audience asked him about the prospects of 
incorporating Stackless into the core and he suggested he didn't 
necessarily think of that as a desirable change.

I would like to see it in the core, but integration would not be an easy 
task, and maintenance might be problematic.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: tests

2007-08-09 Thread Jay Loden
Steve Holden wrote:
> This discussion seems to assume that Excel spreadsheets are stored in 
> some canonical form so that two spreads with the same functionality are 
> always identical on disk to the last bit. I very much doubt this is true 
> (consider as an example the file properties that can be set).
> 
> So really you need to define "equality". So far the tests discussed have 
> concentrated on identifying identical files.
> 
> regards
>   Steve

I was wondering myself if the OP was actually interested in binary identical
files, or just duplicated content. If just duplicated content, perhaps this
could be used as a starting point:

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

and the actual data can be compared

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


Re: Issues of state

2007-08-09 Thread Jay Loden
Steve Holden wrote:
> As far as I'm concerned the major issue with trying to have "desktop web 
> apps" compete with true windowed applications is the difficulty of 
> maintaining sensible interactions with the interface. AJAX designs have 
> increased the interaction level at the expense of greater complexity - 
> there is more state to be transferred, and a much higher interaction 
> rate with the server. But the browser is a terrible front-end for AJAX 
> designs because it doesn't record the state changes that take place as a 
> result of requests for updated InnerHTML content, so if the user is 
> unwise enough to press the "back" button she loses all traces of the 
> non-page interactions that have taken place since the page was loaded.
> 
> So "desktop web apps" should ensure that they get displayed in browser 
> windows with minimal user interface decoration. But even then there's 
> always that chance that sophisticated users will use keyboard shortcuts 
> like ALT-left-arrow.
> 
> That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back 
> Button is Not Your Friend".
> 
> regards
>   Steve
> 
> [1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf

There's been some interesting work done in that area as well:

http://dev2dev.bea.com/pub/a/2006/01/ajax-back-button.html
http://www.isolani.co.uk/blog/javascript/FixingTheBackButtonThatAjaxBroke

In particular, the RSH (Really Simple History) Framework is an open source
solution to the problem:

http://www.onjava.com/pub/a/onjava/2005/10/26/ajax-handling-bookmarks-and-back-button.html

Like most things involving dynamic client side-javascript code and AJAX
technology, it's a lot harder than you'd like it to be to solve the problem, but
in cases where the Back button is really an issue, it's worth the effort.

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


Extending logging module

2007-08-09 Thread jay
Hello,

I've been using the python logging module a lot lately, and I've come
across an instance where I need some new levels.  Specifically, python
does not include ALERT and NOTICE in the default set of logging
levels.  I am wondering how trivial it would be to extend the logging
module to include these 2 levels that are standard with syslog?

My first test was just to use the addLevelName method to add the two
new levels, but syslog ignores them and logs at the next highest
priority, no matter what I use.

Looking further into the code and as a test, I changed the following
to see if this would even work

lib/python2.5/logging/__init__.py
  -> class Logger
  -> add new notice and alert root level functions
  -> new _levelNames for notice and alert
  -> new default level names for notice and alert

lib/python2.5/logging/handlers.py
  -> class SysLogHandler priority_map was changed to include notice
and alert

It actually worked, but this is not the way I would like to handle the
problem.  I would prefer to extend the classes instead.  However, I'm
not too familiar with that, and I had to change things in so many
places, I'm wondering if its even possible?  I don't like changing the
standard libraries, what happens if I have to upgrade python?  My
changes get overwritten.

Can anyone offer some help or suggestions?  Thanks

Jay

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
special_dragonfly a écrit :
> "Ben Finney" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> "special_dragonfly" <[EMAIL PROTECTED]> writes:
>>
>>> I've managed to solve the problem, I really was just being a
>>> dunce.
>> Doubtful; but at this stage we can't tell, because we still don't know
>> what it is you're actually trying to *do*.
>>
>>> Here's how incase anyone is wondering:
>>>
>>> class MyClass:
>>> def __init__(self):
>>> name=""
>>> dict={}
>>> dict[0]=[]
>>> dict[0].append(MyClass())
>>> dict[0][0].name="Hello"
>>> print dict[0][0].name
>> It's not clear why you are using the value 0 for a dictionary key
>> here; nor why you're assigning an attribute to an object after
>> creating the object. Neither of them are errors, but without context
>> it's hard to know what advice to give.
>>
> The 0 for a key is just an example. The code I actually have would be just 
> as meaningful at the end of the day. I could have changed MyClass for
> class Animals(object):
> def __init__(self, name="", type="", age=""):
> self.name=name
> self.type=type
> self.age=age
> 
> dict={'Mouse':[Animals('George','long eared',20)]}
> dict['Mouse'].append(Animals('Benny','hairy',30))
> dict['Cat']=[Animals('Inigo Montoya','spanish',10)]
> 
> and Neil, Bruno has the right idea of what I was trying to do. However, your 
> code came in handy still as I used your code elsewhere.see below.
> 
> def EnterDictionary(FieldsDictionary,key,data):
> for i in range(0,int(data[6:])):
> line=myfile.readline()
> line=line.strip()
> line=line[6:-1]
> if key in FieldsDictionary:
> FieldsDictionary[key].append(FieldClass(*line.split(",")))
> else:
> FieldsDictionary[key]=[FieldClass(*line.split(","))]

May I suggest a couple possible improvements ?

First : you're of course free to use any naming convention you like, and 
it's obviously better to stay consistent, but the canonical Python 
convention is to use all_lower for vars, functions (and methods) and 
modules, and MixedCase for classes.

About the code now:

def EnterDictionary(FieldsDictionary,key,data):
 for i in range(0,int(data[6:])):

1/ Golden rule : avoid the use of "magic numbers". This one stands true 
for any languages !-). The usual solution is to use symbolic constants. 
While Python doesn't have real symbolic constant, the convention is to 
write them ALL_UPPER.

2/ range() can be used with only one argument, which then will be use as 
the upper bound. IOW,
   range(0, X)
is the same as
   range(X)

 line=myfile.readline()

3/ where does this 'myfile' comes from ? (hint : don't use globals when 
you can avoid them)


 line=line.strip()
 line=line[6:-1]

4/ magic numbers again, cf /1. Question : does this 6 has anything to do 
with the other one ? What will happen when the file format will change ?

5/ you can do all this in a single line, adding the split() too:
 args = myfile.readline().strip()[XXX:-1].split(",")

 > if key in FieldsDictionary:
 > FieldsDictionary[key].append(FieldClass(*line.split(",")))
 > else:
 > FieldsDictionary[key]=[FieldClass(*line.split(","))]


If you expect key to most of the times be already in FieldsDictionnary, 
then a try/except block might be a bit faster. If you expect key to not 
be here most of the times, then your solution is right. Note that you 
can also use dict.setdefault(key, default):

# probably bad names but I don't have a clue what they should be
DATA_INDEX_OFFSET = 6
LINE_START = 6
LINE_END = -1

def update_fields_dict(fields_dict, key, data, datafile):
   for i in range(int(data[DATA_INDEX_OFFSET:])):
 args =datafile.readline().strip()[LINE_START:LINE_END].split(",")
 fields_dict.setdefault(key, []).append(FieldClass(*args))

Feel free to take or leave what you consider appropriate here. But by 
all means avoid magic numbers, except possibly for Q&D throw-away 
scripts (and even then...).

HTH

> In future I would ask however, if it's a really stupid question and you feel 
> that the answer can be found either by searching google (because in some 
> cases I don't know what to search for), or in one of the O'reilly books, 
> just say. In either case, if you could refer me to the search term to use or 
> the book to read I'd be grateful.

That's usually what happens then, don't worry.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython before MainLoop

2007-08-09 Thread 7stud
On Aug 8, 11:25 pm, "[david]" <[EMAIL PROTECTED]> wrote:
> I'd like to refresh the display before I start the main loop.
>
> I have code like this:
>
> app = App()
> app.Show()
> app.long_slow_init()
> app.MainLoop()
>
> The main frame partly loads at Show, but because the mainloop has not
> started yet, the display does not update until long_slow_init() finishes.
>
> Alternatively, I could code
>
> app = App()
> app.long_slow_init()
> app.Show()
> app.MainLoop()
>
> Which would give me a crisp Show, but there would be a long slow wait
> before the app showed any activity at all. I would need a splash screen.
>
> I'd rather not have a splash screen (and I don't know how anyway). I'd
> like to just make app.Show() finish correctly before running
> long_slow_init.
>
> Is there a wx internal method that I can use to give Windows the
> opportunity to finish painting the frame before I run long_slow_init()?
>
> Or is there a better idea?
>
> (david)

I don't see my original post, so here it is again


You can use another thread to execute long_slow_init():

--
import wx
import threading
import time

class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "My Window")

panel = wx.Panel(self, -1)
button = wx.Button(panel, -1, "click me, quick!", pos=(40,
40))
self.Bind(wx.EVT_BUTTON, self.onclick)

def onclick(self, event):
print "button clicked"

def receive_result(self, result):
print "Hey, I'm done with that long, slow initialization."
print "The result was:", result


class MyApp(wx.App):
def __init__(self):
wx.App.__init__(self, redirect=False)


def OnInit(self):  #called by wx.Python
the_frame = MyFrame()
the_frame.Show()

t = MyThread(the_frame)
t.start()  #calls t.run()

return True

class MyThread(threading.Thread):
def __init__(self, a_frame):
threading.Thread.__init__(self)
self.frame_obj = a_frame

def run(self):
result = self.long_slow_init()

wx.CallAfter(self.frame_obj.receive_result, result)
#CallAfter() calls the specified function with the
#specified argument when the next pause in execution
#occurs in this thread:

def long_slow_init(self):
print "starting long_slow_init()..."
time.sleep(6)
result = 20.5
return result


app = MyApp()
app.MainLoop()

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


Re: tests

2007-08-09 Thread Steve Holden
Jason wrote:
> On Aug 9, 8:46 am, "special_dragonfly" <[EMAIL PROTECTED]>
> wrote:
>> <[EMAIL PROTECTED]> wrote in message
>>> http://docs.python.org/lib/module-filecmp.html
>> My understanding of reading that is that it only looks at the file names
>> themselves and not their contents. So whether filename1=filename2 and in the
>> case of the function below it, whether one directory has files which are in
>> the other.
>> Correct me if I'm wrong.
>> Dom
>>
>> P.S. md5 or sha hash is what I'd go for, short of doing:
>>
>> MyFirstFile=file("file1.xls")
>> MySecondFile=file("file2.xls")
>> If MyFirstFile==MySecondFile:
>> print "True"
>>
>> although this won't tell you where they're different, just that they are...
> 
> You're incorrect.  If the shallow flag is not given or is true, the
> results of os.stat are used to compare the two files, so if they have
> the same size, change times, etc, they're considered the same.
> 
> If the shallow flag is given and is false, their contents are
> compared.  In either case, the results are cached for efficiency's
> sake.
> 
>   --Jason
> 
> 
> The documentation for filecmp.cmp is:
>   cmp(f1, f2[, shallow])
>   Compare the files named f1 and f2, returning True if they seem
> equal, False otherwise.
> 
>   Unless shallow is given and is false, files with identical
> os.stat() signatures are taken to be equal.
> 
>   Files that were compared using this function will not be
> compared again unless their os.stat() signature changes.
> 
>   Note that no external programs are called from this function,
> giving it portability and efficiency.
> 

This discussion seems to assume that Excel spreadsheets are stored in 
some canonical form so that two spreads with the same functionality are 
always identical on disk to the last bit. I very much doubt this is true 
(consider as an example the file properties that can be set).

So really you need to define "equality". So far the tests discussed have 
concentrated on identifying identical files.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Stackless Integration

2007-08-09 Thread Terry Reedy

"Justin T." <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| I've been looking at stackless python a little bit, and it's awesome.
| My question is, why hasn't it been integrated into the upstream python
| tree? Does it cause problems with the current C-extensions? It seems
| like if something is fully compatible and better, then it would be
| adopted. However, it hasn't been in what appears to be 7 years of
| existence, so I assume there's a reason.

First, which 'stackless'?  The original continuation-stackless (of about 7 
years ago)?  Or the more current tasklet-stackless (which I think is much 
younger than that)?

The original added a feature Guido did not want (continuations) and 
required major changes to the core that would have make maintainance 
probably more difficult for most of the developers, including GvR.  For 
more, see
http://www.python.org/dev/peps/pep-0219/

Second, what do you mean by integration?  The current tasklet version is, I 
am sure, as well integrated as Tismer can make it.  Last I looked, there 
were warnings about possible incompatibilities, but perhaps these have been 
overcome.  It is just not part of the stdlib.  And as far as I know or 
could find in the PEP index, C. Tismer has never submitted a PEP asking 
that it be made so.  Doing so would mean a loss of control, so there is a 
downside as well as the obvious upside of distribution.

tjr



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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Sion Arrowsmith
special_dragonfly <[EMAIL PROTECTED]> wrote:
>if key in FieldsDictionary:
>FieldsDictionary[key].append(FieldClass(*line.split(",")))
>else:
>FieldsDictionary[key]=[FieldClass(*line.split(","))]

These four lines can be replaced by:

FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(",")))

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Something in the function tutorial confused me.

2007-08-09 Thread Neil Cerutti
On 2007-08-09, Magnus Lycka <[EMAIL PROTECTED]> wrote:
> It's all a matter of understanding that all the juicy bits in
> the Python data model is in the actual values or objects.
> That's the stuff with type safety, a location in memory,
> qualities such as mutability etc. A "variable" is basically
> just a reference to an arbitrary object in a particular
> namespace.

Excellent post.

Languages like C tried to make the scope of names and the extent
of the objects they refer to be the same, probably for
efficiency.  One nice property of this is that the two concepts
can be conflated into the simpler single idea of "variables".
It's simple, that is, until you create references. Then you can
get into complicated trouble by creating references to things
that may be destroyed. In Python names have lexical scope, while
the objects they refer to are eternal.

> Assignments semantics is not about copying data as in C, and
> it's nothing arbitrarily defined in classes as in C++. It's all
> about deciding which object a name refers to.

Assignment semantics are not arbitrary in C++. You do have to
define them manually for new data types, but if you get it wrong
your code is pretty much useless. You are free to create your own
assignment semantics, as long as they match the semantics of the
built in types. Python has this property as well, though you're
limited to screwing up the "augmented assignment/arithmetic"
operators.

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


Re: Stackless Integration

2007-08-09 Thread Steve Holden
Bruno Desthuilliers wrote:
> Jean-Paul Calderone a écrit :
>> On Thu, 09 Aug 2007 09:00:27 -, "Justin T." <[EMAIL PROTECTED]> 
>> wrote:
>>> Hi,
>>>
>>> I've been looking at stackless python a little bit, and it's awesome.
>>> My question is, why hasn't it been integrated into the upstream python
>>> tree? Does it cause problems with the current C-extensions? It seems
>>> like if something is fully compatible and better, then it would be
>>> adopted. However, it hasn't been in what appears to be 7 years of
>>> existence, so I assume there's a reason.
>> It's not Pythonic.
> 
> Hum... Yes ? Really ? Care to argument ?

Unfortunately such arguments quickly descend to the "yes it is", "no it 
isn't" level, as there is no objective measure of Pythonicity.

Twisted is a complex set of packages which is difficult to understand 
from the outside,and is motivated by a specific approach to asynchronous 
operations that is neither well understood by the majority of 
programmers nor easily-explained to them. All the teaching sessions on 
Twisted I have attended have involved a certain amount of hand-waving or 
some over-heavy code examples with inadequate explanations.

However I would say that Twisted has improve enormously over the last 
five years, and should really be a candidate for inclusion in the 
standard library. It would be a large component, though, and so there 
would be a number of heavy tasks involved, not least of them updating 
the documentation. So maintenance might be a worry unless a group stood 
up and committed to the task.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Help with Dictionaries and Classes requested please.

2007-08-09 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-08-09, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>> Neil Cerutti a écrit :
>>> On 2007-08-09, special_dragonfly <[EMAIL PROTECTED]> wrote:
 Is there anyway for python to consider the values within a
 string when entering the data into a dictionary. I know that
 isn't very clear so here's an example:

 class MyClass(object):
 def __init__(self,name="",age=""):
 self.name=name
 self.age=age

 data="Gary,50"
 d={0:[MyClass(data)]}
 data="Adam,25"
 d[0].append(MyClass(data))

 The data is coming from a text file working on a line by line
 basis. I've just tried and I'm just getting the full string in
 the first field. That seems logical, now I don't want it to
 though!
>>> That's what happens if you use 0 for the key every time. ;)
>> Hmmm... Neil, I may be wrong but I think you didn't get the
>> point here. As I understand it,  Dominic's problem is that it
>> gets strings like "Gary,50" and would like to call MyClass
>> initializer this way : MyClass("Gary", "50")
> 
> My guess was he doesn't need a class at all,

Mmm... That's possible (and if all he has in MyClass are name and age 
data attributes, then you're obviously right). But then your answer was 
perhaps a bit confusing (at least it confused me...)

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


Re: Something in the function tutorial confused me.

2007-08-09 Thread Magnus Lycka
Lee Fleming wrote:
> Hello,
> I have a simple question. Say you have the following function:
> 
> def f(x, y = []):
...

> But this, the code that "fixes" the list accumulation confounds me:
> def  f(x, y=None):
> if y is None: y = []
...

> In other words, what's going on here? How is it that y accumulates
> argument values between function calls in the first function, but
> doesn't in the second one? 

I think the important thing to understand here is the
distinction between names/variables and objects/values
in Python.

While you could interpret C code like this...

void f() {
 ...
 int i = 5;
 ...
 int j = i;
 ...
}

... as "create a place in the namespace of the f function
where you can fit an integer value, and put the value 5
there. Later, create another place in the namespace of f
which is also big enough for an integer. Copy the contents
of the location named 'i', to the location named 'j'."

You would instead interpret this similar Python code...

def f():
 ...
 i = 5
 ...
 j = i
 ...

... as "create an integer object with the value 5. Then
define a name/tag/variable in the namespace of function
f which refers to the integer object with the value 5.
Later, make a new name/tag/variable in the namespace of
f which refers to the same object (happens to be an
integer with the value 5) as i refers to."

The semantics is very different.

If you understand this, Python will seem much less magical,
and you will never ask meaningless questions as whether
Python uses call by reference or call by value.

It's all a matter of understanding that all the juicy bits
in the Python data model is in the actual values or objects.
That's the stuff with type safety, a location in memory,
qualities such as mutability etc. A "variable" is basically
just a reference to an arbitrary object in a particular
namespace. Assignments semantics is not about copying
data as in C, and it's nothing arbitrarily defined in
classes as in C++. It's all about deciding which object
a name refers to.

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


Re: tests

2007-08-09 Thread Jason
On Aug 9, 8:46 am, "special_dragonfly" <[EMAIL PROTECTED]>
wrote:
> <[EMAIL PROTECTED]> wrote in message
> >http://docs.python.org/lib/module-filecmp.html
>
> My understanding of reading that is that it only looks at the file names
> themselves and not their contents. So whether filename1=filename2 and in the
> case of the function below it, whether one directory has files which are in
> the other.
> Correct me if I'm wrong.
> Dom
>
> P.S. md5 or sha hash is what I'd go for, short of doing:
>
> MyFirstFile=file("file1.xls")
> MySecondFile=file("file2.xls")
> If MyFirstFile==MySecondFile:
> print "True"
>
> although this won't tell you where they're different, just that they are...

You're incorrect.  If the shallow flag is not given or is true, the
results of os.stat are used to compare the two files, so if they have
the same size, change times, etc, they're considered the same.

If the shallow flag is given and is false, their contents are
compared.  In either case, the results are cached for efficiency's
sake.

  --Jason


The documentation for filecmp.cmp is:
  cmp(  f1, f2[, shallow])
  Compare the files named f1 and f2, returning True if they seem
equal, False otherwise.

  Unless shallow is given and is false, files with identical
os.stat() signatures are taken to be equal.

  Files that were compared using this function will not be
compared again unless their os.stat() signature changes.

  Note that no external programs are called from this function,
giving it portability and efficiency.

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


py2exe, command line parameter problem

2007-08-09 Thread Karsten W.
Hello,
my small program is a Tkinter-App which supports some command line
options. When the app is started within the python environment,
everything works fine. When the py2exe-frozen app is started,
everything works until I pass command line parameters. Then the gui
window is not displayed.

It's python 2.3 on WinXp with py2exe 0.6.6.

How can I debug this behaviour?

Any hint appreciated,
Karsten.

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


Re: Issues of state

2007-08-09 Thread Steve Holden
Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Paul Rubin   wrote:
>> [EMAIL PROTECTED] (Cameron Laird) writes:
>>> Others have answered this at other levels.  In elementary terms,
>>> there truly is a difference, Paul, and one that's widely reified:
>>> a "desktop client-server" application typically listens through
>>> one socket, which therefore constitutes an index of the connection
>>> or client, while a Web application communicates through a sequence
>>> of independent HTTP transactions.  The latter can manage state only
>>> to the extent it passes session information around.
>> Is this significant?  In the case of a single user http app running on
>> the same computer as the browser, the server should only listen on
>> 127.0.0.1.  Every http hit then almost certainly comes from the same
>> session.  If there's doubt, the app can always set a random cookie at
>> the initial screen and check that the cookie never changes.
>>
>> If there's only a small amount of session state (say up to a few
>> hundred bytes) you can put it entirely into browser cookies and send
>> it on every single http hit.
> 
> I'm not sure what we're discussing.  Yes, I agree those are 
> mechanisms by which Web applications manage state.  Apparently
> we agree that, in a general Web application, state management,
> or related persistence, requires *some* mechanism or assumption.

As far as I'm concerned the major issue with trying to have "desktop web 
apps" compete with true windowed applications is the difficulty of 
maintaining sensible interactions with the interface. AJAX designs have 
increased the interaction level at the expense of greater complexity - 
there is more state to be transferred, and a much higher interaction 
rate with the server. But the browser is a terrible front-end for AJAX 
designs because it doesn't record the state changes that take place as a 
result of requests for updated InnerHTML content, so if the user is 
unwise enough to press the "back" button she loses all traces of the 
non-page interactions that have taken place since the page was loaded.

So "desktop web apps" should ensure that they get displayed in browser 
windows with minimal user interface decoration. But even then there's 
always that chance that sophisticated users will use keyboard shortcuts 
like ALT-left-arrow.

That, in summary, is why my 2004 PyCon paper[1] was subtitled "The Back 
Button is Not Your Friend".

regards
  Steve

[1]: http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: tests

2007-08-09 Thread special_dragonfly

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Aug 9, 4:04 pm, brad <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>> > You should be able to read chunks of each file in binary mode and do a
>> > compare to check for equality. Some kind of loop should do the trick.
>>
>> Why not a simple md5 or sha with the hash library?
>
> Or even:
>
> http://docs.python.org/lib/module-filecmp.html
>

My understanding of reading that is that it only looks at the file names 
themselves and not their contents. So whether filename1=filename2 and in the 
case of the function below it, whether one directory has files which are in 
the other.
Correct me if I'm wrong.
Dom

P.S. md5 or sha hash is what I'd go for, short of doing:

MyFirstFile=file("file1.xls")
MySecondFile=file("file2.xls")
If MyFirstFile==MySecondFile:
print "True"

although this won't tell you where they're different, just that they are... 


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


Re: tests

2007-08-09 Thread dijkstra . arjen
On Aug 9, 4:04 pm, brad <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > You should be able to read chunks of each file in binary mode and do a
> > compare to check for equality. Some kind of loop should do the trick.
>
> Why not a simple md5 or sha with the hash library?

Or even:

http://docs.python.org/lib/module-filecmp.html

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


  1   2   >