Re: Python GDB Wrapper

2008-03-07 Thread Raja
Hi All,
  Thanks for replies. Daniel- I am looking at just a wrapper
around GDB. I dont want to emulate the functionalities of GDB but
instead use them in python scripting.
Martin - Misc/gdbinit looks promising. Thanks a lot.

Thanks,
Raja.

On Mar 7, 12:43 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > Has anyone does this before ? Even some basic idea or code as to how
> > to proceed would be great.
>
> Have you seen Misc/gdbinit?
>
> Regards,
> Martin

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


Re: the problem of import module

2008-03-07 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> follow the dive into python
> -
 import sys
 sys.path
 sys.path.append('E
\achieve\book\diveintopython-pdfzh-cn-5.4b\diveintopythonzh-cn-5.4b\py')
> -
> I append the filepath of <>'s examples into
> sys.path,but
> -
 sys.path
> ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip',
> 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-
> win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\
> \site-packages', 'E:\x07chieve\x08ook\\diveintopython-pdfzh-cn-5.4b\
> \diveintopythonzh-cn-5.4b\\py']
 import fileinfo#fileinfo is a module in the path
> 
> Traceback (most recent call last):
>  File "", line 1, in 
>import fileinfo
> ImportError: No module named fileinfo
> 
> -
> Can anyone tell me the reason of the above and how to add  paths to
> python path except adding them in the enviroment path.
> Thanks.

The path you append to sys.path is not properly escaped:

>>> "E:\archive"
'E:\x07rchive' # \a has become the single character chr(7)

Use double backslashes or raw strings instead:

>>> "E:\\archive"
'E:\\archive'
>>> r"E:\archive"
'E:\\archive'

When you print it the extra backslash will be gone:

>>> print "E:\\archive" # \\ is the escape sequence for the backslash
E:\archive

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


Re: Python GDB Wrapper

2008-03-07 Thread Raja
On Mar 7, 1:21 pm, Raja <[EMAIL PROTECTED]> wrote:
> Hi All,
>   Thanks for replies. Daniel- I am looking at just a wrapper
> around GDB. I dont want to emulate the functionalities of GDB but
> instead use them in python scripting.
> Martin - Misc/gdbinit looks promising. Thanks a lot.
>
> Thanks,
> Raja.
>
> On Mar 7, 12:43 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>
> > > Has anyone does this before ? Even some basic idea or code as to how
> > > to proceed would be great.
>
> > Have you seen Misc/gdbinit?
>
> > Regards,
> > Martin

Hi All,
 Marting- I looked at the Misc/gdbinit but what I want is a Python
module which wraps around GDB and exposes its functionality, which has
some methods in it like pystack to which if I give the arguments as
program name and arguments displays the stack trace of that particular
program .

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


Re: system32 directory

2008-03-07 Thread Tim Golden
Robert Dailey wrote:
> On Thu, Mar 6, 2008 at 2:42 AM, Tim Golden <[EMAIL PROTECTED]> wrote:
>> 
>> First thing to do when asking "How do I do X in Python under Windows?"
>> is to stick -- python X -- into Google and you get, eg:
>>
>>
>> http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetSystemDirectory_meth.html
>>
>> which suggests that the win32api module from the pywin32 modules has
>> the function you need.
>> 
>>
>> And sure enough...
>>
>> 
>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
>> (Intel)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>  >>> import win32api
>>  >>> win32api.GetSystemDirectory ()
>> 'C:\\WINDOWS\\system32'
>>  >>>
>> 
>>
>> TJG
>>
> 
> I was aiming to figure out if the standard modules shipped with Python could
> do this already before I started using 3rd party libraries. Thanks.

Ah. Sorry. I'm sure you can call it via ctypes (built in
from Python 2.5). But even if I'd realised that's what
you'd wanted, I'd probably have given the original answer
because pywin32 pretty much *is* standard library for any
Python installation I do on Win32 :)

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


Re: Looking for very light weight template library (not framework)

2008-03-07 Thread Duncan Booth
"Malcolm Greene" <[EMAIL PROTECTED]> wrote:

> New to Python and looking for a template library that allows Python
> expressions embedded in strings to be evaluated in place. In other 
words
> something more powerful than the basic "%(variable)s" or "$variable"
> (Template) capabilities.
> 
> I know that some of the web frameworks support this type of template
> capability but I don't need a web framework, just a library that
> supports embedded expression evaluation.

You could try using the Template class:

>>> from string import Template
>>> class EvalTemplate(Template):
idpattern = '[^{}]+'


>>> class EvalDict(dict):
def __getitem__(self, name):
if name in self:
return dict.__getitem__(self, name)
return eval(name, globals(), self)


>>> class Invoice:
def __init__(self, total):
self.total = total


>>> i = Invoice(42)
>>> template = EvalTemplate("The total cost is ${invoice.total}")
>>> template.substitute(EvalDict(invoice=i))
'The total cost is 42'

The usual caveats about using 'eval' apply (maybe it should be called 
EvilDict), and I'm sure you could override substitute/safe_substitute to 
construct the EvalDict transparently.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python GDB Wrapper

2008-03-07 Thread Navtej Singh
Raja,

Check this http://fusil.hachoir.org/trac/wiki/Ptrace [gdb.py]

On Fri, Mar 7, 2008 at 2:11 PM, Raja <[EMAIL PROTECTED]> wrote:
> On Mar 7, 1:21 pm, Raja <[EMAIL PROTECTED]> wrote:
>  > Hi All,
>  >   Thanks for replies. Daniel- I am looking at just a wrapper
>  > around GDB. I dont want to emulate the functionalities of GDB but
>  > instead use them in python scripting.
>  > Martin - Misc/gdbinit looks promising. Thanks a lot.
>  >
>  > Thanks,
>  > Raja.
>  >
>  > On Mar 7, 12:43 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>  >
>  > > > Has anyone does this before ? Even some basic idea or code as to how
>  > > > to proceed would be great.
>  >
>  > > Have you seen Misc/gdbinit?
>  >
>  > > Regards,
>  > > Martin
>
>  Hi All,
>  Marting- I looked at the Misc/gdbinit but what I want is a Python
>  module which wraps around GDB and exposes its functionality, which has
>  some methods in it like pystack to which if I give the arguments as
>  program name and arguments displays the stack trace of that particular
>  program .
>
>  Thanks,
>  Raja.
>
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on file storage for split multi part download

2008-03-07 Thread Gabriel Genellina
En Fri, 07 Mar 2008 04:16:42 -0200, <[EMAIL PROTECTED]> escribi�:
> On Mar 7, 1:38 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>> En Thu, 06 Mar 2008 14:34:27 -0200, <[EMAIL PROTECTED]> escribi�:
>>
>> > storage class which can write the file splits that are currently being
>> > downloaded to the disk. this is exactly what other download
>> > accelerators do, i guess.
>>
>> Uh, unless I misundersand you, a standard file object is enough. First
>> create a file with the required size (open(...,'wb'), seek(n-1),
>> write(chr(0))). For each downloaded chunk you have to know its position  
>> in
>> the file; then just seek() and write() it.
>
> BUT the thing thats going in my mind is thread safety. i plan to start
> each part of the file download in a different thread. and then when
> each thread had downloaded more than 100kb (or eof or boundary
> reached) write the buffer to the disk. can this be achieved using
> mutex ? i have never shared objects between threads.

Use a different (single) thread to write the file; the others put write  
requests on a Queue.queue object, and the writer just gets the requests  
and processes them.

> is there a way to write this without using threads at all ???

Using asyncore, and perhaps the Twisted framework.

-- 
Gabriel Genellina

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

Re: Difference between 'function' and 'method'

2008-03-07 Thread Gabriel Genellina
En Thu, 06 Mar 2008 23:46:43 -0200, <[EMAIL PROTECTED]> escribi�:

> oss.message is a abstraction class that writes the method name into a
> string, then sends it to OSS... outgoingserver or serverside.
>
> Now that I'm writing it, and this is important, -to- the -newsgroup-,
> I realize you could do it with a simple wrapper... include the
> function name in parameters and call the pickler and send.
>
> OSS then looks like this:
>
> def something_happens( *ar ):
> self.user_act( something_about( *ar ) )
>
> So the message.out() instance pickles ( 'user_act', ar ) and sends
> it.  Then iss.incoming receives it, unpickles that string, gets
> 'user_act' from self, and invokes.
>
> The cool part is the declaration of user_act= message.out(), which
> uses a metaclass to assign its own name, and returns a function which
> includes the object in its signature.  Cool.
>
> Yes it's working and a little slack.  However-: this is the cool
> part.  I'd like messages to know which instance they came from, and
> perform the sending & receiving encapsulated on their own--- not to
> subclass class SS( Sending ): with various behaviors: that is, to
> assign them as class attributes rather than superclasses.

You may look at the SimpleXMLRPCServer class and see how it implements  
introspection. It's rather easy (and doesn't require metaclasses nor  
decorators nor any other fancy stuff; I think it works the same since  
Python 2.1). Apparently you're doing a similar thing, but using pickles  
instead of xmlrpc.

-- 
Gabriel Genellina

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

Re: Looking for very light weight template library (not framework)

2008-03-07 Thread Roman Bertle
* Malcolm Greene <[EMAIL PROTECTED]>:
>  New to Python and looking for a template library that allows Python
>  expressions embedded in strings to be evaluated in place. In other words
>  something more powerful than the basic "%(variable)s" or "$variable"
>  (Template) capabilities.
[...]
> 
>  Use case:
> 
>  myOutput = """\
> 
>  The total cost is {{invoice.total}}.
[...]

You might look at YAPTU
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305A
or YAPTOO
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465508,
very small but powerful templating engines. I use YAPTU myself for
invoice templating.

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


Re: Looking for very light weight template library (not framework)

2008-03-07 Thread Stefan Behnel
Jeff McNeil wrote:
> Isn't there some long
> running joke about new Python programmers creating their own template
> language or something, too? =)

http://article.gmane.org/gmane.comp.python.general/544922

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


Re: Altering imported modules

2008-03-07 Thread [EMAIL PROTECTED]
On 6 mar, 21:29, Tro <[EMAIL PROTECTED]> wrote:
> On Wednesday 05 March 2008, Bruno Desthuilliers wrote:
>
>
>
> > Tro a écrit :
(snip)
> > > I'd like to know if it's possible to make tlslite load *my* asyncore
> > > module without changing any of the tlslite code.
>
> > Not sure this apply to your case (depends on how asyncore is implemented
> > and the exact "modifications"), but monkeypatching is a possible solution.
>
> >http://en.wikipedia.org/wiki/Monkey_patch
> >http://wiki.zope.org/zope2/MonkeyPatch
> >http://mail.python.org/pipermail/python-dev/2008-January/076194.html
>
> Ooh. I didn't know this technique had a name. But that's basically how I'm
> modifying the built-in asyncore in my own class. I override its poll() and
> poll2() methods to do something extra.
>
> However, the issue with tlslite is that it imports the regular asyncore
> instead of the one I wrote,

One of us must be missing something here. The monkeypatch way is:

# -- mypatch.py --
import BaseModule
# backup original if we want to call it
_original_something = BaseModule.something

def my_patched_something(args):
  my_code_here_doing_stuff
  # eventually
  _original_something(args)
  more_code_here

BaseModule.something = my_patched_something

# -- main.py --

import mypatch
# From now on, any other module calling
# BaseModule.something will call my_patched_something.

import other_module_using_BaseModule

app_code_here


> which means that I'd have to somehow monkeypatch
> its "import" statement. I'm guessing that means simply monkeypatching both
> the original asyncore module AND the tlslite module's asyncore attribute with
> my own version.

Unless there are some really strange things happening in tlslite and
asyncore, if you import your monkeypatch before importing tlslite, you
shouldn't have to touch anything in tlslite. Which is the whole point
of monkeypatching.

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


Re: Please keep the full address

2008-03-07 Thread Michael Wieher
I normally find this kind of back & forth useless and annoying spam but the
irony is too much to avoid commenting.

(read the following, then ...)

>
> > > "His" posts?
> >
> > Whatever.  I'm too old to worry about searching for politically correct,
> > gender neutral pronouns.
>
>
> I'm pretty sure even the most PC people wouldn't suggest using a
> masculine pronoun for an inanimate objects.
>
>
> (Ok, some probably would.)
>
> Carl Banks



Mr Banks.  Technically, the sentence should be "...pronoun for inanimate
objects"  .. OR  "...pronoun for an inanimate object."

If you're going to nitpick, then at least do it right.
-- 
http://mail.python.org/mailman/listinfo/python-list

Your Fortune for the Day!!!

2008-03-07 Thread nkavitha551
Your Fortune for the Day!!!

Hi,

To know what it is?

Visit the website below and be cool !!!
--

 http://myprofilekavitha.blogspot.com/

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


Re: Licence confusion: distributing MSVC?71.DLL

2008-03-07 Thread Tom Wright
jim-on-linux wrote:
> This is what someone wrote  on 1-21-2007
> to this help site about this pain in the a...
> MSVCR71 stuff.
>
> " I believe this problem doesn't exist.
> (snip useful bit of EULA and explanation)

Thanks for that - just what I didn't manage to turn up with Google.  I'll go
ahead and publish then :-)


-- 
I'm at CAMbridge, not SPAMbridge
-- 
http://mail.python.org/mailman/listinfo/python-list


How to clear a list (3 ways).

2008-03-07 Thread francois . petitjean

(second try with an enhanced version)

Executive summary : What idiom do you use for resetting a list ?
   lst = |]  # (1)
   lst[:] = []  #  (2)
   del lst[:]  #  (3)


Consider the following code :
#!/usr/bin/env python
# -*- coding: latin_1 -*-

"""
container.py  how to clear a container
"""

class Container(object):
def __init__(self):
self.elts = {}
self.parts = []
def clear(self):
self.elts.clear()  #  for a dictionary it's clear :-)
self.parts = []   #  (1)
 #  self.parts[:] = []#  (2)
 #  del self.parts[:] #  (3)
def __len__(self):
return len(self.parts)
def add_predicate(self, part):
"""return True if part should be added (to override)"""
return True
def add(self, part):
"""return True if part is added"""
res = self.add_predicate(part)
if res:
self.parts.append(part)
self.elts[str(part)] = part # or wahtever
return res
def replace_parts(self, values):
"""return True if all values are added/replaced"""
acceptable = all(map(self.add_predicate, values))  # FIXME
itertools.imap ?
if not acceptable:
return acceptable
self.parts[:] = values
# TODO elts
return acceptable

Container1 = Container

class Container2(Container):
def clear(self):
self.elts.clear()  #  for a dictionary it's clear :-)
self.parts[:] = []#  (2)

class Container3(Container):
def clear(self):
self.elts.clear()  #  for a dictionary it's clear :-)
del self.parts[:] #  (3)


Solution (1) is somewhat broken  (see the test_container.rst hereafter) but
often used. For instance in configobj we have
def clear(self):
"""
A version of clear that also affects scalars/sections
Also clears comments and configspec.

Leaves other attributes alone :
depth/main/parent are not affected
"""
dict.clear(self)
self.scalars = []
self.sections = []
self.comments = {}
self.inline_comments = {}
self.configspec = {}

Solution (2) does not suffer the same problem, and (3) has the advantage of
not building an empty list.
What idiom do you use (and prefer) ?


test_container.rst  can be used like this :
>>> import doctest
>>> doctest.testfile('test_container.rst', encoding='latin_1')
(nfails, ntests) is printed.
===
test_container.rst
===

>>> from container import Container1, Container2, Container3
>>> cont1 = Container1()
>>> cont1.add(1)
True
>>> cont1.add(2)
True
>>> cont1.add(3)
True
>>> parts = cont1.parts
>>> parts
[1, 2, 3]

The client has cached the parts attribute.
Solution (1) is not robust, is the parts attribute in the public API ?
>>> cont1.clear()
>>> parts
[1, 2, 3]
>>> cont1.parts, parts
([], [1, 2, 3])

We now have two different objects.

>>> cont2 = Container2()
>>> cont2.add(21)
True

>>> cont2.add(22)
True
>>> cont2.add(23)
True
>>> parts2 = cont2.parts
>>> parts2
[21, 22, 23]
>>> cont2.clear()
>>> parts2
[]
>>> cont1.parts, parts
([], [1, 2, 3])

>>> cont3 = Container3()
>>> cont3.add(31)
True
>>> cont3.add(32)
True
>>> parts3 = cont3.parts
>>> cont3.add(33)
True
>>> parts3
[31, 32, 33]
>>> cont3.clear()
>>> parts3
[]

Test de replace_parts

>>> cont3 = Container3()
>>> len(cont3)
0
>>> parts3 = cont3.parts
>>> cont3.add(30)
True
>>> parts3
[30]
>>> cont3.replace_parts( (31, 32, 33) )
True
>>> parts3
[31, 32, 33]
>>>


Regards.
   NOTICE: This message contains information which is confidential and the
   copyright of our company or a third  party. If you are not the intended
   recipient of this message please delete it and destroy all copies. If
   you
   are the intended recipient of this message you should not disclose or
   distribute this message to third parties without the consent of our
   company. Our company does not represent, warrant and/or guarantee that
   the integrity of this message has been maintained nor that the
   communication is free of virus, interception or interference. The
   liability of our company is limited by our General Conditions of
   Services.
   Nota : Ce message contient des informations confidentielles propriété de
   notre société et/ou d'un tiers. Si vous n’êtes pas parmi les
   destinataires désignés de ce message, merci de l'effacer ainsi que
   toutes ses copies. Si vous êtes parmi les destinataires désignés de ce
   message, prière de ne pas le divulguer ni de le transmettre à des tiers
   sans l’accord de notre société. Notre société ne peut garantir que
   l’intégrité de ce message a été préservée ni que la présente
   communication est sans virus, interception ou interférence. La
   responsabilité de notre société est limitée par nos Conditions Générales
   de Services.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List all files using FTP

2008-03-07 Thread Anders Eriksson
On Thu, 6 Mar 2008 20:07:46 +, Simon Brunning wrote:

> This might be of use:
> 
> 

Nice, Just what I needed!

Thank you!

// Anders
-- 
English is not my first, or second, language
so anything strange, or insulting, is due to
the translation.
Please correct me so I may improve my English!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Classes and modules are singletons?

2008-03-07 Thread Steven D'Aprano
On Thu, 06 Mar 2008 06:30:41 -0800, Carl Banks wrote:

> On Mar 5, 8:44 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> But what about classes? Are they singletons? Obviously classes aren't
>> Singleton classes, that is, given an arbitrary class C you can create
>> multiple instances of C. But what about class objects themselves? I've
>> found a few odd references to "classes are singletons", but nothing in
>> the language reference.
> 
> 
> Probably because "singleton" is the wrong word.  A singleton means there
> is one instance of a type; classes are instances of "type" which can
> have many instances so classes are not singletons.

Right. I knew there was something funny about using the term "singleton" 
to refer to classes, but I couldn't put my finger on it.

[snip]

> For that matter, try this:
> 
import module
c1 = module.Someclass
module.Someclass = some_other_class() 
c2 = module.Someclass
c1 is c2

That example is cheating because you rebind the *name* module.Someclass. 
Of course you get something different.

But in any case, I'm satisfied now... the name singleton is inappropriate 
for modules and classes, although they are both singleton-like. I like 
Gabriel's term "named singleton" (from another thread).

Thank you to everybody who answered.


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


Re: What is a class?

2008-03-07 Thread Steven D'Aprano
On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote:

> you
> could say exec( open( 'modA.py' ).read() ) ==> import modA


Yes, you could say that, but you'd be wrong. Please test your code before 
making such claims in the future.


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


Re: for-else

2008-03-07 Thread Sion Arrowsmith
Jeffrey Barish  <[EMAIL PROTECTED]> wrote:
>Terry Reedy wrote:
>> A for-loop is equivalent to a while loop with the condition 'iterator is
>> not exhausted'.  So do_else when that condition is false -- the iterator
>> is exhausted.
>I think that this is the most important statement in this thread.  As others
>have expressed, I too found for-else surprising when I first encountered
>it.  It made sense to me when I analogized for with if: [ ... ]

And to pull those two together, I found while-else comprehensible by
analogy with if-else:

while stmt:
do_something() # stmt is True
else:
do_something_else() # stmt is False

I don't think I've ever used a for-else in the wild, but I have used
while-else. And knowing how that works, it's kind of obvious what
for-else does.

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

islice ==> [::]

2008-03-07 Thread bearophileHUGS
I find itertools.islice() useful, so for Python 3.x I may like to see
it removed from the itertools module, and the normal slicing syntax
[::] extended to work with generators/iterators too.

from itertools import islice
primes = (x for x in xrange(1,999) if all(x % y for y in xrange(2,
x)))
print list(islice(primes, 0, 20))
==>
print list(primes[:20])

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between 'function' and 'method'

2008-03-07 Thread Sion Arrowsmith
Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>En Thu, 06 Mar 2008 23:46:43 -0200, <[EMAIL PROTECTED]> escribi�:
>> [ ... ]
>You may look at the SimpleXMLRPCServer class and see how it implements  
>introspection. It's rather easy (and doesn't require metaclasses nor  
>decorators nor any other fancy stuff; I think it works the same since  
>Python 2.1). Apparently you're doing a similar thing, but using pickles  
>instead of xmlrpc.

It's not that difficult to graft pickles into SimpleXMLRPCServer --
I've done it, and if you're trying to sling large data structures
over the connection it's a massive performance win (even with
sgmlop in place to speed up XML parsing).

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

hidden built-in module

2008-03-07 Thread koara
Hello, is there a way to access a module that is hidden because
another module (of the same name) is found first?

More specifically, i have my own logging.py module, and inside this
module, depending on how initialization goes,  i may want to do 'from
logging import *' from the built-in logging.

I hope my description was clear, cheers.

I am using python2.4.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hidden built-in module

2008-03-07 Thread gigs
koara wrote:
> Hello, is there a way to access a module that is hidden because
> another module (of the same name) is found first?
> 
> More specifically, i have my own logging.py module, and inside this
> module, depending on how initialization goes,  i may want to do 'from
> logging import *' from the built-in logging.
> 
> I hope my description was clear, cheers.
> 
> I am using python2.4.
you can add your own logging module in extra directory that have __init__.py 
and 
import it like: from extradirectory.logging import *

and builtin: from logging import *
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hidden built-in module

2008-03-07 Thread koara
On Mar 5, 1:39 pm, gigs <[EMAIL PROTECTED]> wrote:
> koara wrote:
> > Hello, is there a way to access a module that is hidden because
> > another module (of the same name) is found first?
>
> > More specifically, i have my own logging.py module, and inside this
> > module, depending on how initialization goes,  i may want to do 'from
> > logging import *' from the built-in logging.
>
> > I hope my description was clear, cheers.
>
> > I am using python2.4.
>
> you can add your own logging module in extra directory that have __init__.py 
> and
> import it like: from extradirectory.logging import *
>
> and builtin: from logging import *


Thank you for your reply gigs. However, the point of this namespace
harakiri is that existing code which uses 'import logging' ...
'logging.info()'... etc. continues working without any change.
Renaming my logging.py file is not an option -- if it were, i wouldn't
bother naming my module same as a built-in :-)

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


Re: hidden built-in module

2008-03-07 Thread Michael Wieher
2008/3/7, koara <[EMAIL PROTECTED]>:
>
> On Mar 5, 1:39 pm, gigs <[EMAIL PROTECTED]> wrote:
> > koara wrote:
> > > Hello, is there a way to access a module that is hidden because
> > > another module (of the same name) is found first?
> >
> > > More specifically, i have my own logging.py module, and inside this
> > > module, depending on how initialization goes,  i may want to do 'from
> > > logging import *' from the built-in logging.
> >
> > > I hope my description was clear, cheers.
> >
> > > I am using python2.4.
> >
> > you can add your own logging module in extra directory that have
> __init__.py and
> > import it like: from extradirectory.logging import *
> >
> > and builtin: from logging import *
>
>
> Thank you for your reply gigs. However, the point of this namespace
> harakiri is that existing code which uses 'import logging' ...
> 'logging.info()'... etc. continues working without any change.
> Renaming my logging.py file is not an option -- if it were, i wouldn't
> bother naming my module same as a built-in :-)
>
> Cheers.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I've never had a problem like this, but I'd imagine that you could delve
into the inner-workings of import itself and figure a way to make this
happen.  There's probably a logical-order search path it follows, and if you
can find a way to insert your module before the other, in that path, or
modify the path and point its first entry at say, a directory containing
only your module, you'd be in business.
-- 
http://mail.python.org/mailman/listinfo/python-list

ANN: Wing IDE 3.0.4 released

2008-03-07 Thread Stephan Deibel
Hi,

We're happy to announce version 3.0.4 of Wing IDE, an advanced development
environment for the Python programming language. It is available from:

http://wingware.com/downloads

Version 3.0.4 is a bug fix release that reduces debugger overhead by about
50% per Python instruction executed, improves breakpoints tracking during edits,
expands support for PyGTK auto-completion, and makes 14 other minor 
improvements.

See the change log for details:

http://wingware.com/pub/wingide/3.0.4/CHANGELOG.txt

It is a free upgrade for all Wing 3.0 users.

*About Wing IDE*

Wing IDE is an integrated development environment for the Python programming
language.  It provides powerful debugging, editing, code intelligence,
testing, and search capabilities that reduce development and debugging
time, cut down on coding errors, and make it easier to understand
and navigate Python code.

New features added in Wing 3.0 include:

* Multi-threaded debugger
* Debug value tooltips in editor, debug probe, and interactive shell
* Autocompletion and call tips in debug probe and interactive shell
* Automatically updating project directories
* Testing tool, currently supporting unittest derived tests (*)
* OS Commands tool for executing and interacting with external commands (*)
* Rewritten indentation analysis and conversion (*)
* Introduction of Wing IDE 101, a free edition for beginning programmers
* Available as a .deb package for Debian and Ubuntu
* Support for Stackless Python
* Support for 64 bit Python on Windows and Linux

(*)'d items are available in Wing IDE Professional only.

System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or
Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit).

*Purchasing & Upgrading*

Wing IDE Professional & Wing IDE Personal are commercial software and require
a license to run.  To upgrade a 2.x license or purchase a new 3.x license:

Upgrade:https://wingware.com/store/upgrade
Purchase:   https://wingware.com/store/purchase

Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost
1/2 the normal price to upgrade.

-- 

The Wingware Team
Wingware | Python IDE
Advancing Software Development

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


Hyphenation: PyHyphen project now hosted on GoogleCode

2008-03-07 Thread [EMAIL PROTECTED]
This is to inform you that development of PyHyphen and issue tracking
takes now place at http://pyhyphen.googlecode.com. All interested
parties are encouraged to submit comments, suggestions and bug
reports. Snapshots of the source tree can be obtained using
subversion.

At this stage, the sources contain a number of minor improvements over
version 0.4.1 which is still available on the pypi. Windows installers
are though still lacking.

Regards

Leo


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


Edit and continue for debugging?

2008-03-07 Thread Bronner, Gregory

I haven't seen much on this for a few years:

I'm working on a GUI application that has lots of callbacks. Testing it
is very slow and quite boring, as every time I find an error, I have to
exit it, restart it, and repeat the series of clicks. It would be really
amazing if python supported a reasonable form of edit and continue.

Is there any way to do this? I'd like to be able to change my code and
have it apply to a running instance of a class. I wonder if it would be
possible to do this by configuring the interpreter to parse classes and
functions rather than whole modules, and to re-parse as necessary; also
to have byte-compiled modules be singletons rather than be standard
reference counted objects.






Thanks
Gregory R. Bronner
(212) 526-0102
[EMAIL PROTECTED] 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
- - - -

This message is intended only for the personal and confidential use of the 
designated recipient(s) named above.  If you are not the intended recipient of 
this message you are hereby notified that any review, dissemination, 
distribution or copying of this message is strictly prohibited.  This 
communication is for information purposes only and should not be regarded as an 
offer to sell or as a solicitation of an offer to buy any financial product, an 
official confirmation of any transaction, or as an official statement of Lehman 
Brothers.  Email transmission cannot be guaranteed to be secure or error-free.  
Therefore, we do not represent that this information is complete or accurate 
and it should not be relied upon as such.  All information is subject to change 
without notice.


IRS Circular 230 Disclosure:
Please be advised that any discussion of U.S. tax matters contained within this 
communication (including any attachments) is not intended or written to be used 
and cannot be used for the purpose of (i) avoiding U.S. tax related penalties 
or (ii) promoting, marketing or recommending to another party any transaction 
or matter addressed herein.
-- 
http://mail.python.org/mailman/listinfo/python-list


Quit-command not quiting

2008-03-07 Thread K Viltersten
I entered the code from tkinter.pdf, section 
2 but for reason, the application doesn't 
close as i press the quit-button.

The wondow itself vanishes if i click the 
cross in the upper-right corner but pressing
the quit-button only makes it "pressed". 
Then, the program freezes.

This is the code.

from Tkinter import *
class Demo (Frame):
def __init__ (self, master = None):
Frame.__init__ (self, master)
self.grid ()
self.doLayout ()
def doLayout (self):
self.quitButton = Button ( 
self, 
text = "Quit", 
command = self.quit)
self.quitButton.grid ()

d = Demo ()
d.master.title ("the coolest demo ever")
d.mainloop ()


--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: How to clear a list (3 ways).

2008-03-07 Thread Gabriel Genellina
En Fri, 07 Mar 2008 09:39:05 -0200, <[EMAIL PROTECTED]>  
escribi�:

> Executive summary : What idiom do you use for resetting a list ?
>lst = |]  # (1)
>lst[:] = []  #  (2)
>del lst[:]  #  (3)

(3) if I want to keep the same list else (1)

An example when (1) is desirable:

# generate lines of text not exceeding 40 chars
# yields a list of words forming a line
def gen_lines(words):
 line = []
 width = 0
 for word in words:
 if width + len(word) + 1 > 40:
 yield line  # <<<
 del line[:] # <<<
 width = 0
 line.append(word)
 width += len(word) + 1
 yield line

import string
words = string.__doc__.split() # some text
lines = list(gen_lines(words))
print lines
[['considered', 'printable'], ['considered', 'printable'], ['considered',  
'print
able'], ['considered', 'printable'], ['considered', 'printable'], ...

In this case, yielding always the same object isn't a good idea if the  
consumer doesn't process it immediately. Changing the generator function  
to use the method (1) gives the expected result (or, one could say,  
lessens the coupling between the generator and its consumer).

-- 
Gabriel Genellina

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

Re: hidden built-in module

2008-03-07 Thread Diez B. Roggisch
koara schrieb:
> On Mar 5, 1:39 pm, gigs <[EMAIL PROTECTED]> wrote:
>> koara wrote:
>>> Hello, is there a way to access a module that is hidden because
>>> another module (of the same name) is found first?
>>> More specifically, i have my own logging.py module, and inside this
>>> module, depending on how initialization goes,  i may want to do 'from
>>> logging import *' from the built-in logging.
>>> I hope my description was clear, cheers.
>>> I am using python2.4.
>> you can add your own logging module in extra directory that have __init__.py 
>> and
>> import it like: from extradirectory.logging import *
>>
>> and builtin: from logging import *
> 
> 
> Thank you for your reply gigs. However, the point of this namespace
> harakiri is that existing code which uses 'import logging' ...
> 'logging.info()'... etc. continues working without any change.
> Renaming my logging.py file is not an option -- if it were, i wouldn't
> bother naming my module same as a built-in :-)

You can only try and search the sys-path for the logging-module, using

sys.prefix

and then look for logging.py. Using

__import__(path)

you get a reference to that module.

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


Re: Converting a string to the most probable type

2008-03-07 Thread [EMAIL PROTECTED]
On Mar 6, 9:17 pm, Luis M. González <[EMAIL PROTECTED]> wrote:
> On 6 mar, 11:27, Pierre Quentel <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > I would like to know if there is a module that converts a string to a
> > value of the "most probable type" ; for instance :
> > - if the string is "abcd" the value is the same string "abcd"
> > - string "123" : value = the integer 123
> > - string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
> > = the float -1.23
> > - string "2008/03/06" (the format is also locale-dependant) : value =
> > datetime.date(2008,03,06)
>
> > Like in spreadsheets, special prefixes could be used to force the
> > type : for instance '123 would be converted to the *string* "123"
> > instead of the *integer* 123
>
> > I could code it myself, but this wheel is probably already invented
>
> > Regards,
> > Pierre
> >>> def convert(x):
>
> if '.' in x:
> try: return float(x)
> except ValueError: return x
> else:
> try: return int(x)
> except: return x
>
> >>> convert('123')
> 123
> >>> convert('123.99')
> 123.98
> >>> convert('hello')
>
> 'hello'

Neat solution. The real challenge though is whether to support
localised dates, these are all valid:
20/10/01
102001
20-10-2001
20011020
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hidden built-in module

2008-03-07 Thread Gabriel Genellina
En Fri, 07 Mar 2008 12:15:04 -0200, koara <[EMAIL PROTECTED]> escribi�:
> On Mar 5, 1:39 pm, gigs <[EMAIL PROTECTED]> wrote:
>> koara wrote:
>> > Hello, is there a way to access a module that is hidden because
>> > another module (of the same name) is found first?
>>
>> > More specifically, i have my own logging.py module, and inside this
>> > module, depending on how initialization goes,  i may want to do 'from
>> > logging import *' from the built-in logging.
>>
>> you can add your own logging module in extra directory that have  
>> __init__.py and
>> import it like: from extradirectory.logging import *
>> and builtin: from logging import *
>
> Thank you for your reply gigs. However, the point of this namespace
> harakiri is that existing code which uses 'import logging' ...
> 'logging.info()'... etc. continues working without any change.
> Renaming my logging.py file is not an option -- if it were, i wouldn't
> bother naming my module same as a built-in :-)

Read a very recent post from Bruno Desthuilliers with subject "Altering  
imported modules"

-- 
Gabriel Genellina

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

problem with join

2008-03-07 Thread nodrogbrown
hi
i am using python on WinXP..i have a string 'folder ' that i want to
join to a set of imagefile names to create complete qualified names so
that i can create objects out of them

folder='F:/brown/code/python/fgrp1'
filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
filenameslist=[]
for x in filenms:
myfile=join(folder,x)
filenameslist.append(myfile)

now when i print the filenameslist  i find that it looks like

['F:/brown/code/python/fgrp1\\amber1.jpg',
'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
\amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']

is there some problem with the way i use join? why do i get \\ infront
of  the basename?
i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',

can anyone pls help
gordon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Quit-command not quiting

2008-03-07 Thread Gabriel Genellina
En Fri, 07 Mar 2008 12:56:44 -0200, K Viltersten <[EMAIL PROTECTED]>  
escribi�:

> I entered the code from tkinter.pdf, section
> 2 but for reason, the application doesn't
> close as i press the quit-button.
>
> The wondow itself vanishes if i click the
> cross in the upper-right corner but pressing
> the quit-button only makes it "pressed".
> Then, the program freezes.

How did you run it? From inside IDLE? IDLE itself is written using Tk, and  
I think that your mainloop interferes with the one inside it.
If you run your program from the command line it should work fine.

> from Tkinter import *
> class Demo (Frame):
> def __init__ (self, master = None):
> Frame.__init__ (self, master)
> self.grid ()
> self.doLayout ()
> def doLayout (self):
> self.quitButton = Button (
> self,
> text = "Quit",
> command = self.quit)
> self.quitButton.grid ()
>
> d = Demo ()
> d.master.title ("the coolest demo ever")
> d.mainloop ()

There is only one thing I hate more than spaces after a parens: spaces  
before it :)
Please read PEP8, about the suggested style for writting Python code.
http://www.python.org/dev/peps/pep-0008/

-- 
Gabriel Genellina

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

Re: hidden built-in module

2008-03-07 Thread koara
> You can only try and search the sys-path for the logging-module, using
>
> sys.prefix
>
> and then look for logging.py. Using
>
> __import__(path)
>
> you get a reference to that module.
>
> Diez


Thank you Diez, that's the info i'd been looking for :-)

So the answer is sys module + __import__

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


Re: Embedding a literal "\u" in a unicode raw string.

2008-03-07 Thread rmano
On Mar 4, 1:00 pm, NickC <[EMAIL PROTECTED]> wrote:
>
> Python 3.0a3+ (py3k:61229, Mar  4 2008, 21:38:15)
> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> r"\u"
> '\\u'
> >>> r"\uparrow"
> '\\uparrow'

Nice to know... so it seems that the 3.0 doc was not updated. I think
this is the correct
behaviour. Thanks

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


Re: problem with join

2008-03-07 Thread corynissen
On Mar 7, 9:12 am, nodrogbrown <[EMAIL PROTECTED]> wrote:
> hi
> i am using python on WinXP..i have a string 'folder ' that i want to
> join to a set of imagefile names to create complete qualified names so
> that i can create objects out of them
>
> folder='F:/brown/code/python/fgrp1'
> filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist=[]
> for x in filenms:
> myfile=join(folder,x)
> filenameslist.append(myfile)
>
> now when i print the filenameslist  i find that it looks like
>
> ['F:/brown/code/python/fgrp1\\amber1.jpg',
> 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
>
> is there some problem with the way i use join? why do i get \\ infront
> of  the basename?
> i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',
>
> can anyone pls help
> gordon

see path.join in the os library.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with join

2008-03-07 Thread Robert Bossy
nodrogbrown wrote:
> hi
> i am using python on WinXP..i have a string 'folder ' that i want to
> join to a set of imagefile names to create complete qualified names so
> that i can create objects out of them
>
> folder='F:/brown/code/python/fgrp1'
> filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist=[]
> for x in filenms:
>   myfile=join(folder,x)
>   filenameslist.append(myfile)
>
> now when i print the filenameslist  i find that it looks like
>
> ['F:/brown/code/python/fgrp1\\amber1.jpg',
> 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
>
> is there some problem with the way i use join? why do i get \\ infront
> of  the basename?
> i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',
>   
os.path.join()
http://docs.python.org/lib/module-os.path.html#l2h-2185

vs.

string.join()
http://docs.python.org/lib/node42.html#l2h-379

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


Re: problem with join

2008-03-07 Thread Tim Golden
nodrogbrown wrote:
> hi
> i am using python on WinXP..i have a string 'folder ' that i want to
> join to a set of imagefile names to create complete qualified names so
> that i can create objects out of them
> 
> folder='F:/brown/code/python/fgrp1'
> filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist=[]
> for x in filenms:
>   myfile=join(folder,x)
>   filenameslist.append(myfile)
> 
> now when i print the filenameslist  i find that it looks like
> 
> ['F:/brown/code/python/fgrp1\\amber1.jpg',
> 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
> 
> is there some problem with the way i use join? why do i get \\ infront
> of  the basename?
> i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',

You've got a couple of options. Your "folder" to start
with is in the unixy form a/b/c and the .join function
doesn't do anything to change that, merely uses os.pathsep
to append the parts to each other.

You can either set your folder to be r"f:\brown\code..."
in the first case or use os.path.normpath or os.path.abspath
on the result.

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


SV: Quit-command not quiting

2008-03-07 Thread K Viltersten
>> The window itself vanishes if i click the
>> cross in the upper-right corner but pressing
>> the quit-button only makes it "pressed".
>> Then, the program freezes.
> 
> How did you run it? From inside IDLE? IDLE itself is written 
> using Tk, and  I think that your mainloop interferes with the 
> one inside it. If you run your program from the command line 
> it should work fine.

I press F5 while in the editor window. Is there a way to run the
program without going to the console window?

Perhaps i'm just making things unneccesarily complicated 
and Python IS supposed to be run from console window?

>> from Tkinter import *
>> class Demo (Frame):
>> def __init__ (self, master = None):
>> Frame.__init__ (self, master)
>> self.grid ()
>> self.doLayout ()
>> def doLayout (self):
>> self.quitButton = Button (
>> self,
>> text = "Quit",
>> command = self.quit)
>> self.quitButton.grid ()
>>
>> d = Demo ()
>> d.master.title ("the coolest demo ever")
>> d.mainloop ()
> 
> There is only one thing I hate more than spaces after a 
> parens: spaces  before it :)
> Please read PEP8, about the suggested style for writting 
> Python code. http://www.python.org/dev/peps/pep-0008/

I've got no issues one way or the other. Most likely i'll forget
from time to time but other than that, i'll try to keep it in mind.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


swig-python import error

2008-03-07 Thread abarun22
Hi
I am facing a problem while loading a SWIG generated shared module
from python. The development is under HP-UX 32b platform. I use gcc
version 4.0.2 to build the shared module.  This is how i try to build
the module.

# Compilation
GCC="$GCC -march=1.1"
$GCC -v -c -fpic ${ETUDE}.c ${ETUDE}_wrap.c -DDOUBLE_PRECISION -
DDON_DOUBLE_PRECISION  ${PYTHON_INCLUDE_PATH} ${CHAINE_INCLUDE_PATH}

# linking
ld -b binary -g -shared ${ETUDE}.o ${ETUDE}_wrap.o -o _${ETUDE}.so \
-a archive ${LIBS_CHAINE_PATH} -lfichiers_r8 -lmem -lutilitaires -
lsysteme -lcalcul -lmsgml -lcaractere \
-rpath -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/Sandbox/libs/
chaine/PYAPI/don -L/michprojects/ef/deli/Working/Source/deli9-PYAPI/
Sandbox/libs/chaine/hppa_portable-hp-hpux11.11/Debug

The module generated is called _don.so. In addition to that i set the
module path in LD_LIBRARY_PATH environment variable. Th error looks
like as follows.

Import error: module cannot be loaded.

But i am wondering how i am getting import error although every thing
looks OK. Any ideas are most welcome and thanks in advance.
Regards,
Arun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with join

2008-03-07 Thread Gabriel Genellina
En Fri, 07 Mar 2008 13:12:13 -0200, nodrogbrown <[EMAIL PROTECTED]>  
escribi�:

> i am using python on WinXP..i have a string 'folder ' that i want to
> join to a set of imagefile names to create complete qualified names so
> that i can create objects out of them
>
> folder='F:/brown/code/python/fgrp1'
> filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist=[]
> for x in filenms:
>   myfile=join(folder,x)
>   filenameslist.append(myfile)
>
> now when i print the filenameslist  i find that it looks like
>
> ['F:/brown/code/python/fgrp1\\amber1.jpg',
> 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
>
> is there some problem with the way i use join? why do i get \\ infront
> of  the basename?

join is fine. "\\" is a single character. \ is used as the escape  
character, and has to be doubled when representing itself. Print an  
individual element to see the effect:

print filenameslist[0]
F:/brown/code/python/fgrp1\amber1.jpg

(a list uses repr() on its elements instead of str()).

> i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',

If the string is only used to open a file, and never shown to the user,  
what you prefer is irrelevant, isn't it?
What is important here is what Windows prefers, and that's a backslash,  
although many times / is accepted too. You can convert the file names to  
their preferred spelling using os.path.normpath

Back to your code, try this:

 from os.path import join, normpath
folder = 'F:/brown/code/python/fgrp1'
names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
filenameslist = [normpath(join(folder, name)) for name in names]

-- 
Gabriel Genellina

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

Re: problem with join

2008-03-07 Thread corynissen
On Mar 7, 9:33 am, [EMAIL PROTECTED] wrote:
> On Mar 7, 9:12 am, nodrogbrown <[EMAIL PROTECTED]> wrote:
>
>
>
> > hi
> > i am using python on WinXP..i have a string 'folder ' that i want to
> > join to a set of imagefile names to create complete qualified names so
> > that i can create objects out of them
>
> > folder='F:/brown/code/python/fgrp1'
> > filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> > filenameslist=[]
> > for x in filenms:
> > myfile=join(folder,x)
> > filenameslist.append(myfile)
>
> > now when i print the filenameslist  i find that it looks like
>
> > ['F:/brown/code/python/fgrp1\\amber1.jpg',
> > 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> > \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
>
> > is there some problem with the way i use join? why do i get \\ infront
> > of  the basename?
> > i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',
>
> > can anyone pls help
> > gordon
>
> see path.join in the os library.

Upon further examination... it looks like you are using windows and
os.path.join.

The separator for windows is a '\'.  In python, you have to escape
that character with another '\'.  That's why you see '\\'.

That being said, I think what you have will still work to access a
file.  Windows is usually smart enough to deal with a front slash here
and there.

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


Timed execution in eval

2008-03-07 Thread alex . pedwysocki
I have various bits of code I want to interpret and run at runtime in
eval ...

I want to be able to detect if they fail with error, I want to be able
to time them, and I want to be able to stop them if they run too
long.  I cannot add code to the eval'd strings that will help me
accomplish this.

Is there a good way to do this?  I have it figured out for perl but
I'd rather use python if possible.

Thanks for any assistance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Regarding coding style

2008-03-07 Thread K Viltersten
I've been recommended reading of:
http://www.python.org/dev/peps/pep-0008/
and in there i saw two things that i 
need to get elaborated.


1. When writing English, Strunk and 
White apply.

Where can i download it? Am i actually
expected to read the whole book? How
many people actually do aply it?


2. You should use two spaces after a 
sentence-ending period.

For heavens sake, why? I've always been 
obstructed by the double blanks but 
tolerated them. Now, that i read that
it actually is a recommendation, i need 
to ask about the purpose.


Thanks for the input in advance.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Regarding coding style

2008-03-07 Thread Michael Wieher
Placing 2 spaces after a period is standard, grammatically correct English,
at least as I was taught...

I don't know who Strunk or White are.  Maybe Mr. Pink has a book you can
refer to instead.

2008/3/7, K Viltersten <[EMAIL PROTECTED]>:
>
> I've been recommended reading of:
> http://www.python.org/dev/peps/pep-0008/
> and in there i saw two things that i
> need to get elaborated.
>
>
> 1. When writing English, Strunk and
> White apply.
>
> Where can i download it? Am i actually
> expected to read the whole book? How
> many people actually do aply it?
>
>
> 2. You should use two spaces after a
> sentence-ending period.
>
> For heavens sake, why? I've always been
> obstructed by the double blanks but
> tolerated them. Now, that i read that
> it actually is a recommendation, i need
> to ask about the purpose.
>
>
> Thanks for the input in advance.
>
> --
> Regards
> Konrad Viltersten
> 
> sleep- a substitute for coffee for the poor
> ambition - lack of sense to be lazy
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Keep a python script running after browser window closed

2008-03-07 Thread sophie_newbie
Hi,

I have a cgi script that performs a very long computation that can
take several hours to complete. Is there any smart way that I can keep
this script running until it is finished (after the user has closed
the browser) and email them with the results. The email bit isn't the
problem, I just don't know how to keep the code running in the
background. I'm sure there is a smart way to do this...

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


Re: problem with join

2008-03-07 Thread nodrogbrown

> If the string is only used to open a file, and never shown to the user,
> what you prefer is irrelevant, isn't it?

guess thats right..

> Back to your code, try this:
>
>  from os.path import join, normpath
> folder = 'F:/brown/code/python/fgrp1'
> names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist = [normpath(join(folder, name)) for name in names]


thanks Gabriel..
gordon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keep a python script running after browser window closed

2008-03-07 Thread Mike Driscoll
On Mar 7, 10:28 am, sophie_newbie <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a cgi script that performs a very long computation that can
> take several hours to complete. Is there any smart way that I can keep
> this script running until it is finished (after the user has closed
> the browser) and email them with the results. The email bit isn't the
> problem, I just don't know how to keep the code running in the
> background. I'm sure there is a smart way to do this...
>
> Thanks!

You might have your cgi script use the subprocess module to open a
second script that does the long-running process.

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


Re: OT: Failed saving throw

2008-03-07 Thread Aahz
In article <[EMAIL PROTECTED]>, Aahz <[EMAIL PROTECTED]> wrote:
>
>For anyone who hasn't heard, E. Gary Gygax died yesterday.  Some people
>think we should build a tomb in his honor.  ;-)

...and xkcd finally weighs in:

http://xkcd.com/393/
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Simon Brunning
On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten <[EMAIL PROTECTED]> wrote:
>
>  1. When writing English, Strunk and
>  White apply.

I apply Fowler, PEP 8 be damned. ;-)

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Richard Brodie

"K Viltersten" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> 1. When writing English, Strunk and White apply.

Do they? I've never seen them ;)

> 2. You should use two spaces after a sentence-ending period.
>
> For heavens sake, why?

Most people find it easier to type two spaces than one and a half. 


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


Re: Regarding coding style

2008-03-07 Thread D'Arcy J.M. Cain
On Fri, 7 Mar 2008 17:31:35 +0100
"K Viltersten" <[EMAIL PROTECTED]> wrote:
> I've been recommended reading of:
> http://www.python.org/dev/peps/pep-0008/
> and in there i saw two things that i 
> need to get elaborated.
> 
> 
> 1. When writing English, Strunk and 
> White apply.
> 
> Where can i download it? Am i actually
> expected to read the whole book? How
> many people actually do aply it?

"The Elements of Style" by William Strunk Jr. and E.B. White.  The
original, revised edition was published in 1935.  The third edition is
copyright 1979 and published by MacMillan Publishing Co., Inc., NY,
NY.  There may be a later version with an ISBN but this one doesn't
have one.

It's a very small book, 4-1/2" by 7", 81 pages.  If you are writing
English it is worth browsing from time to time.

> 2. You should use two spaces after a 
> sentence-ending period.
> 
> For heavens sake, why? I've always been 
> obstructed by the double blanks but 
> tolerated them. Now, that i read that
> it actually is a recommendation, i need 
> to ask about the purpose.

Like many things of this nature, the purpose is to follow the rules of
correct English usage.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread D'Arcy J.M. Cain
On Fri, 7 Mar 2008 16:44:10 +
"Simon Brunning" <[EMAIL PROTECTED]> wrote:
> On Fri, Mar 7, 2008 at 4:31 PM, K Viltersten <[EMAIL PROTECTED]> wrote:
> >
> >  1. When writing English, Strunk and
> >  White apply.
> 
> I apply Fowler, PEP 8 be damned. ;-)

Fowler's is good too but much more comprehensive.  Strunk and White is
a pamphlet compared to Fowler's tome.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Jeff Schwab
K Viltersten wrote:
> I've been recommended reading of:
> http://www.python.org/dev/peps/pep-0008/
> and in there i saw two things that i need to get elaborated.
> 
> 
> 1. When writing English, Strunk and White apply.
> 
> Where can i download it? Am i actually
> expected to read the whole book?


It's a short book, and worth your time.  Searching does turn up free 
downloads, but I recommend the illustrated version (of which I own a copy).

http://www.libraryshop.org/elofstilbywi.html


> How many people actually do aply it?

The problem is how many people don't.


> 2. You should use two spaces after a sentence-ending period.
> 
> For heavens sake, why? I've always been obstructed by the double blanks 
> but tolerated them. Now, that i read that
> it actually is a recommendation, i need to ask about the purpose.

(a) It makes the ends of sentences more visually obvious.
(b) It makes text easier to parse reliably from scripts.
(c) Some text-editors can navigate such sentences out of the box, 
whereas others cannot.  (I recall this limitation with Emacs' 
text-editing major mode, though it may have been fixed since then; I 
switched to Vim about five years ago.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-07 Thread rockingred
Dates can be a pain.  I wrote my own date program, simply because
there are so many different ways to write a date:

Mar 8, 2008
March 8th, 08
03/08/08
03-08-2008

And so on and so forth.  The tricky bit is how to tell the difference
between Day, Month and Year.

I wrote a program to check the format used for a date.  I assumed that
any 4 digits together in a single group were the year.  Then I had a
list of Months, with the first 3 characters of each and compared that
to the field being checked, if found, then that was the month.  Then I
assumed any number greater than 12 was a day.  If I couldn't match
those criteria I assumed Month Day Year (the standard at the company I
worked for).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: system32 directory

2008-03-07 Thread Robert Dailey
On Fri, Mar 7, 2008 at 2:49 AM, Tim Golden <[EMAIL PROTECTED]> wrote:
>
> Ah. Sorry. I'm sure you can call it via ctypes (built in
> from Python 2.5). But even if I'd realised that's what
> you'd wanted, I'd probably have given the original answer
> because pywin32 pretty much *is* standard library for any
> Python installation I do on Win32 :)
>
> TJG
>

I didn't mean to convey that I was rejecting your initial answer, I was just
hoping that I wouldn't have to go download another library. Usually it means
I have to compile it myself, which in my experience is a total pain in the
neck to do on Windows. I'm definitely going to check out pywin32, since
ctypes seems like a tedious solution (as many have already pointed out).

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

Re: Regarding coding style

2008-03-07 Thread Jon Ribbens
On 2008-03-07, D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
>> 2. You should use two spaces after a sentence-ending period.
>> 
>> For heavens sake, why? I've always been obstructed by the double
>> blanks but tolerated them. Now, that i read that it actually is a
>> recommendation, i need to ask about the purpose.
>
> Like many things of this nature, the purpose is to follow the rules of
> correct English usage.

Well, no, it's to follow a particular person's choice out of the many
and various competing rules of "correct English usage". Personally,
I dislike double spaces after sentences, but it is not wrong to put
them there any more than it is wrong not to put them there.
Consistency is far more important (hence the rule, I presume).
-- 
http://mail.python.org/mailman/listinfo/python-list


SV: Regarding coding style

2008-03-07 Thread K Viltersten
>> 2. You should use two spaces after a 
>> sentence-ending period.
>> 
>> For heavens sake, why? I've always been 
>> obstructed by the double blanks but 
>> tolerated them. Now, that i read that
>> it actually is a recommendation, i need 
>> to ask about the purpose.
> 
> (a) It makes the ends of sentences more visually obvious.
> (b) It makes text easier to parse reliably from scripts.
> (c) Some text-editors can navigate such sentences out of 
> the box, whereas others cannot.

Got it. Thanks.   :)

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Regarding coding style

2008-03-07 Thread Grant Edwards
On 2008-03-07, Jon Ribbens <[EMAIL PROTECTED]> wrote:

> Personally, I dislike double spaces after sentences, but it is
> not wrong to put them there any more than it is wrong not to
> put them there.

You're lucky my high school typing teacher didn't hear you say
that...

-- 
Grant Edwards   grante Yow! I joined scientology
  at   at a garage sale!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments

2008-03-07 Thread Krishna
On Mar 6, 5:04 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Thu, 06 Mar 2008 22:48:42 -0200, Krishna <[EMAIL PROTECTED]>
> escribi�:
>
>
>
>  class Test(object):
> > ... def __init__(self):
> > ... self.a= 2
> > ... def func(self, k = self.a):
> > ... print k
> > ...
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "", line 4, in Test
> > NameError: name 'self' is not defined
>
> > In the 'definition of the class', what would the first argument 'self'
> > in the methods evaluate to; when we have an object defined, it is
> > bound to the object reference, but what happens while the class
> > definition is executed, which I believe happens when the module
> > containing the class definition is imported
>
> Function default arguments are evaluated when the function is defined
> (when the class is defined, in this case) so "self" itself has not a
> value. Try this instead:
>
>  def func(self, k=None):
>  if k is None:
>  k = self.a
>  print k
>
> If None is an allowed argument, use a special marker instead:
>
> _marker=object()
> ...
>
>  def func(self, k=_marker):
>  if k is _marker:
>  k = self.a
>  ...
>
> --
> Gabriel Genellina

Thanks for the reply. I am currently using the approach suggested by
you. But, I am more interested in knowing about the first argument
('self'), what does it hold to allow the evaluation of the method,
take the example you gave, 'self.a' as Rvalue inside the method, how
and why is this allowed, when the same 'self.a' is not allowed as the
default argument, considering the fact that I have already specified
'self' as first argument, only after whose evaluation, I believe would
the next statement (k = self.a, in def func(self, k = self.a) ) gets
evaluated

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

SV: Regarding coding style

2008-03-07 Thread K Viltersten
>> Personally, I dislike double spaces after 
>> sentences, but it is not wrong to put them 
>> there any more than it is wrong not to put 
>> them there.
> 
> You're lucky my high school typing teacher 
> didn't hear you say that...

I'm unclear if your teacher was a double or 
single spacer. It's only implied that he
felt strongly one way.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Regarding coding style

2008-03-07 Thread D'Arcy J.M. Cain
On 7 Mar 2008 17:40:08 GMT
Jon Ribbens <[EMAIL PROTECTED]> wrote:
> Well, no, it's to follow a particular person's choice out of the many
> and various competing rules of "correct English usage". Personally,
> I dislike double spaces after sentences, but it is not wrong to put
> them there any more than it is wrong not to put them there.
> Consistency is far more important (hence the rule, I presume).

Warning: Opinion follows possibly influenced by insufficient research.

I have read the arguments about single or double spacing and find that
they can be distilled down to the following:

You should use double space for monospaced fonts and single for
proportional.  I reject this argument for two reasons.  One is
consistency.  It is entirely possible for the same document to be
rendered in multiple ways and you may not be aware of them ahead of
time.  The second is that it seems to me that programs that use
proportional fonts should be able to make any space between sentences
render properly by their own rules so the number of spaces should be
irrelevant.  I am not swayed by arguments that they don't handle this
properly yet.

The arguments for one over the other fall into these basic ones.  Use
double spaces to make the document easier to read, especially by people
who read a lot and tend to skim to absorb as much information as
possible.  Use single space because it makes the document display
nicer.  This suggests to me that the schism is probably between two
different types of people, text/information oriented and
display/presentation oriented.  I don't see any way to appeal to both.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Jeroen Ruigrok van der Werven
-On [20080307 19:10], D'Arcy J.M. Cain ([EMAIL PROTECTED]) wrote:
>The arguments for one over the other fall into these basic ones.  Use
>double spaces to make the document easier to read, especially by people
>who read a lot and tend to skim to absorb as much information as
>possible.  Use single space because it makes the document display
>nicer.  This suggests to me that the schism is probably between two
>different types of people, text/information oriented and
>display/presentation oriented.  I don't see any way to appeal to both.

The double space came from the era of typewriters and monospace printers.
Technology nowadays with all kinds of rendering engines and font
specifications basically make the entire point of 'two spaces after a
period' a moot point.

In all my professional technical writing and documentation work I completely
gave up on two spaces after a period. It's archaic.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
When you are right, you cannot be too radical; When you are wrong, you
cannot be too conservative.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: SV: Regarding coding style

2008-03-07 Thread Grant Edwards
On 2008-03-07, K Viltersten <[EMAIL PROTECTED]> wrote:

>>> Personally, I dislike double spaces after sentences, but it is
>>> not wrong to put them there any more than it is wrong not to
>>> put them there.
>> 
>> You're lucky my high school typing teacher didn't hear you say
>> that...
>
> I'm unclear if your teacher was a double or single spacer.

Double.

> It's only implied that he felt strongly one way.

She, actually.  Leaving out one of the two spaces after the end
of a sentence was no less an error than leaving out the period
or forgetting to capitalize the first word of the next
sentence.

AFAIK, that's the way pretty much everybody was taught to type
back then (1977).

If you're using a word-processor or typesetting system that's
worth its weight in bits, it won't matter how many spaces you
type -- the paragraph layout algorithm will handle it.

-- 
Grant Edwards   grante Yow! I'm having fun
  at   HITCHHIKING to CINCINNATI
   visi.comor FAR ROCKAWAY!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't get items out of a set?

2008-03-07 Thread Cruxic
Hello, all.

Is it possible to get an object out of a set() given another object
that has the same hash code and equality (__hash__() and __eq__()
return the same)?

You can't do this with Java Sets either and I've needed it on multiple
occasions.  Doesn't it seem like it would be useful?  Consider:

class Person:
  def __init__(self, id, name):
self.id = id
self.name = name

  def __hash__(self):
return self.id

  def __eq__(self, other):
return self.id == other.id


people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )
...
p = people.get_equivalent(2)  #method doesn't exist as far as I know
print p.name  #prints Sue


I'm not sure if the above code compiles but I hope you get the idea.
Is it possible?
Much Thanks.
- Cruxic
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: islice ==> [::]

2008-03-07 Thread Raymond Hettinger
[bearophileH]
> I find itertools.islice() useful, so for Python 3.x I may like to see
> it removed from the itertools module, and the normal slicing syntax
> [::] extended to work with generators/iterators too.

This is a can of worms.  First, remember iterations is a protocol, not
a type.  So, this would have to be added to every possible iterator
class (dict.iteritems() and enumerate() for example).  Second, he who
wants slicing, at some time will want getitem, but Guido ruled this
out long ago saying that it is a mistake to conflate sequences and
general iterables.  Third, the analogy breaks down quickly (i.e.
chain(it[:2], it[2:]) does not give the same result as iter(it) unless
working on a re-iterable sequence).  Fourth, this suggests other
related hyper-generalizations which also break down in practice (i.e.
using the plus operator for chain() breaks down when you write it+it
and find that the second one is fully consumed by the time chain()
gets to it).

Besides, if you know what you're doing it is simple to write a trivial
wrapper class that temporarily supports the slicing notation:

class W:
def __init__(self, it):
self.it = iter(it)
def __getitem__(self, n):
if isinstance(n, slice):
return islice(self.it, n.start, n.stop, n.step)
return islice(self.it, n, n+1)

>>> s = 'abcdefg'
>>> list(W(s)[2:])
['c', 'd', 'e', 'f', 'g']
>>> list(W(s)[:2])
['a', 'b']
>>> list(W(s)[::2])
['a', 'c', 'e', 'g']
>>> list(W(s)[2])
['c']



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


Re: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments

2008-03-07 Thread castironpi
On Mar 7, 11:49 am, Krishna <[EMAIL PROTECTED]> wrote:
> On Mar 6, 5:04 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > En Thu, 06 Mar 2008 22:48:42 -0200, Krishna <[EMAIL PROTECTED]>
> > escribi�:
>
> >  class Test(object):
> > > ...     def __init__(self):
> > > ...             self.a= 2
> > > ...     def func(self, k = self.a):
> > > ...             print k
> > > ...
> > > Traceback (most recent call last):
> > >   File "", line 1, in ?
> > >   File "", line 4, in Test
> > > NameError: name 'self' is not defined
>
> > > In the 'definition of the class', what would the first argument 'self'
> > > in the methods evaluate to; when we have an object defined, it is
> > > bound to the object reference, but what happens while the class
> > > definition is executed, which I believe happens when the module
> > > containing the class definition is imported
>
> > Function default arguments are evaluated when the function is defined
> > (when the class is defined, in this case) so "self" itself has not a
> > value. Try this instead:
>
> >      def func(self, k=None):
> >          if k is None:
> >              k = self.a
> >          print k
>
> > If None is an allowed argument, use a special marker instead:
>
> > _marker=object()
> > ...
>
> >      def func(self, k=_marker):
> >          if k is _marker:
> >              k = self.a
> >          ...
>
> > --
> > Gabriel Genellina
>
> Thanks for the reply. I am currently using the approach suggested by
> you. But, I am more interested in knowing about the first argument
> ('self'), what does it hold to allow the evaluation of the method,
> take the example you gave, 'self.a' as Rvalue inside the method, how
> and why is this allowed, when the same 'self.a' is not allowed as the
> default argument, considering the fact that I have already specified
> 'self' as first argument, only after whose evaluation, I believe would
> the next statement (k = self.a, in def func(self, k = self.a) ) gets
> evaluated
>
> Thanks,
> Krishna- Hide quoted text -
>
> - Show quoted text -

Is there enough information at that point in the statement to assign
to k as specified by this language?

No.

Does there exist a possible language in which there is?

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

Re: Can't get items out of a set?

2008-03-07 Thread Raymond Hettinger
[Cruxic]
> Is it possible to get an object out of a set() given another object
> that has the same hash code and equality (__hash__() and __eq__()
> return the same)?

Yes, but it requires an indirect approach.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299


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


Re: islice ==> [::]

2008-03-07 Thread castironpi
> > I find itertools.islice() useful, so for Python 3.x I may like to see
> general iterables.  Third, the analogy breaks down quickly (i.e.
> chain(it[:2], it[2:]) does not give the same result as iter(it) unless

> >>> s = 'abcdefg'
> >>> list(W(s)[2:])

Slice literals are a logical next step, precedented by raw strings and
bytes.  slice= islice is too, precedented by range= xrange.

Does s[2:] evaluate to an infinity?  What is the natural meaning of
skipping finitely many terms at the head of an iterable?  itertools
can also grow 'skip(n=0)' and 'drop(step=3)' operations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between 'function' and 'method'

2008-03-07 Thread castironpi
On Mar 7, 6:44 am, Sion Arrowsmith <[EMAIL PROTECTED]>
wrote:
> Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> >En Thu, 06 Mar 2008 23:46:43 -0200, <[EMAIL PROTECTED]> escribi�:
> >> [ ... ]
> >You may look at the SimpleXMLRPCServer class and see how it implements  
> >introspection. It's rather easy (and doesn't require metaclasses nor  
> >decorators nor any other fancy stuff; I think it works the same since  
> >Python 2.1). Apparently you're doing a similar thing, but using pickles  
> >instead of xmlrpc.
>
> It's not that difficult to graft pickles into SimpleXMLRPCServer --
> I've done it, and if you're trying to sling large data structures
> over the connection it's a massive performance win (even with
> sgmlop in place to speed up XML parsing).

>    her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

Yeah, but I'd be grafting a non-blocking RPC sequence too.

-Instantiate- attributes of ISS upon instantiation.

class C:
  d= D

c= C()
assert isinstance( c.d, D )
assert c.d is c.d

Which ones?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-07 Thread castironpi
> And so on and so forth.  The tricky bit is how to tell the difference
> between Day, Month and Year.

There isn't one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: islice ==> [::]

2008-03-07 Thread Raymond Hettinger
[castiro]
> Slice literals are a logical next step, precedented by raw strings and
> bytes.  slice= islice is too, precedented by range= xrange.

Looking closely at the [::] notation, I think it can easily be
confused with an open box of fleas.  IMO, the one unequivocal,
explicit way of checking for lice is itertools.is_lice().


Raymond

 _ ~
 @ @
 \_/

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


Re: Timed execution in eval

2008-03-07 Thread castironpi
On Mar 7, 10:12 am, [EMAIL PROTECTED] wrote:
> I have various bits of code I want to interpret and run at runtime in
> eval ...
>
> I want to be able to detect if they fail with error, I want to be able
> to time them, and I want to be able to stop them if they run too
> long.  I cannot add code to the eval'd strings that will help me
> accomplish this.
>
> Is there a good way to do this?  I have it figured out for perl but
> I'd rather use python if possible.
>
> Thanks for any assistance.

How does this sound?  Write back if it's way far off from what you
want.

for line in break in put on line break
   push in interactive console
   extra linebreak at function ends
return list of functions?

... and I'll stop before I actually write it.  Bets off!
-- 
http://mail.python.org/mailman/listinfo/python-list


I cannot evaluate this statement...

2008-03-07 Thread waltbrad
The script comes from Mark Lutz's Programming Python.  It is the
second line of a script that will launch a python program on any
platform.

import os, sys
pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'

Okay, run on a win32 machine, pyfile evaluates to python.exe

That makes sense. Because the first condition is true and 'python.exe'
is true. So the next comparison is 'python.exe' or 'python'  Well,
python.exe is true. So that value is returned to pyfile.

Now. Run this on linux. The first condition evaluates sys.platform[:3]
== 'win' as false. So, the next comparison should be  'False' or
'python'   -- This is because 'and' returns the first false value.
But, again, on linux pyfile evaluates to python.exe

Where am I going wrong.  And when will this statment make pyfile
evaluate to 'python' ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I cannot evaluate this statement...

2008-03-07 Thread Jerry Hill
On Fri, Mar 7, 2008 at 3:38 PM, waltbrad <[EMAIL PROTECTED]> wrote:
>  Now. Run this on linux. The first condition evaluates sys.platform[:3]
>  == 'win' as false. So, the next comparison should be  'False' or
>  'python'   -- This is because 'and' returns the first false value.
>  But, again, on linux pyfile evaluates to python.exe

This seems to work as expected on my Ubuntu box.

Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
>>> pyfile
'python'
>>>

What do you get for sys.platform when you run this code under linux?

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


Want - but cannot get - a nested class to inherit from outer class

2008-03-07 Thread DBak
I want - but cannot get - a nested class to inherit from an outer
class.  (I searched the newsgroup and the web for this, couldn't find
anything - if I missed an answer to this please let me know!)

I would like to build a class for a data structure such that nodes of
the data structure - of interest only to the data structure
implementation itself and not to the consumer - are instances of one
of two class types.  I thought to encapsulate the nodes' classes like
this:

class Tree(object):
...class _MT(Tree):
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
...class _Node(Tree):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
...def merge(self, T):
..def __init__(): return _MT()
..

In other words, some methods would be implemented on instances'
classes (like isEmpty and insert) and some on the outer class (like
merge).  Users of the data structure never need to know about the
nodes, much less the nodes' classes, so I wanted to encapsulate them

However I can't do this, because, of course, the name Tree isn't
available at the time that the classes _MT and _Node are defined, so
_MT and _Node can't inherit from Tree.

What is the Pythonic thing I should be doing instead?

(Easy answer:  Put this code in a module, exposing only a factory
function.  I could do that, but wanted to know if I could encapsulate
it as described so I could actually put several similar data
structures into one module.)

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


Re: I cannot evaluate this statement...

2008-03-07 Thread Tim Chase
> import os, sys
> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
> 
> Okay, run on a win32 machine, pyfile evaluates to python.exe
[snip]
> Now. Run this on linux. The first condition evaluates sys.platform[:3]
> == 'win' as false.
[snip]
> Where am I going wrong.  And when will this statment make pyfile
> evaluate to 'python' ?

Your reasoning is correct.  I'm guessing you're typing something 
wrong?  Or typing the right thing in the wrong window (so that 
the command is run on a Windows box)?  Or perhaps you're running 
on some weird build of Python?  It does indeed work on my Debian box:

[EMAIL PROTECTED]:~$ uname -a
Linux rubbish 2.6.22-2-686 #1 SMP Fri Aug 31 00:24:01 UTC 2007 
i686 GNU/Linux
[EMAIL PROTECTED]:~$ python
Python 2.4.4 (#2, Jan  3 2008, 13:36:28)
[GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> import sys
 >>> sys.platform
'linux2'
 >>> sys.platform[:3]=="win" and "python.exe" or "python"
'python'
 >>> (sys.platform[:3]=="win" and "python.exe") or "python"
'python'


Whereas on my Windows machine:

c:\> python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> import sys
 >>> sys.platform
'win32'
 >>> sys.platform[:3] == "win" and "python.exe" or "python"
'python.exe'

That's both with and without the parens.  Same happens in 
assignments.

-tkc


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


Re: I cannot evaluate this statement...

2008-03-07 Thread Chris Mellon
On Fri, Mar 7, 2008 at 2:38 PM, waltbrad <[EMAIL PROTECTED]> wrote:
> The script comes from Mark Lutz's Programming Python.  It is the
>  second line of a script that will launch a python program on any
>  platform.
>
>  import os, sys
>  pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
>
>  Okay, run on a win32 machine, pyfile evaluates to python.exe
>
>  That makes sense. Because the first condition is true and 'python.exe'
>  is true. So the next comparison is 'python.exe' or 'python'  Well,
>  python.exe is true. So that value is returned to pyfile.
>
>  Now. Run this on linux. The first condition evaluates sys.platform[:3]
>  == 'win' as false. So, the next comparison should be  'False' or
>  'python'   -- This is because 'and' returns the first false value.
>  But, again, on linux pyfile evaluates to python.exe
>
>  Where am I going wrong.  And when will this statment make pyfile
>  evaluate to 'python' ?
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>


In Python 2.5, this is written:

pyfile = 'python.exe' if 'win' in sys.platform else 'python'

However, this is a pretty bad way of doing this at all. sys.executable
is better. I'm not sure when sys.executable was added but I assume
it's more recent than whatever version Lutz used in his book.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for a light weighted library/tool to write simple GUI above the text based application

2008-03-07 Thread petr . jakes . tpc
Finaly, after few experiments, I am using pygame.
It comunicates directly with the framebuffer and the performance is
excellent.

Thanks for your help.

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


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-07 Thread DBak
Sorry - code for the class should read:

class Tree(object):
...class _MT(Tree):
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
...class _Node(Tree):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
...def __init__(): return _MT()
...def merge(self, T):
..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-07 Thread Jeff
Use metaclasses?

DBak wrote:
> I want - but cannot get - a nested class to inherit from an outer
> class.  (I searched the newsgroup and the web for this, couldn't find
> anything - if I missed an answer to this please let me know!)
>
> I would like to build a class for a data structure such that nodes of
> the data structure - of interest only to the data structure
> implementation itself and not to the consumer - are instances of one
> of two class types.  I thought to encapsulate the nodes' classes like
> this:
>
> class Tree(object):
> ...class _MT(Tree):
> ..def isEmpty(self): return True
> ..def insert(self, X): return Tree._Node(X)
> ...class _Node(Tree):
> ..def isEmpty(self): return False
> ..def insert(self, X): return _Node(X, self, Tree._MT())
> ...def merge(self, T):
> ..def __init__(): return _MT()
> ..
>
> In other words, some methods would be implemented on instances'
> classes (like isEmpty and insert) and some on the outer class (like
> merge).  Users of the data structure never need to know about the
> nodes, much less the nodes' classes, so I wanted to encapsulate them
>
> However I can't do this, because, of course, the name Tree isn't
> available at the time that the classes _MT and _Node are defined, so
> _MT and _Node can't inherit from Tree.
>
> What is the Pythonic thing I should be doing instead?
>
> (Easy answer:  Put this code in a module, exposing only a factory
> function.  I could do that, but wanted to know if I could encapsulate
> it as described so I could actually put several similar data
> structures into one module.)
>
> Thanks! -- David
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Timed execution in eval

2008-03-07 Thread castironpi
On Mar 7, 10:12 am, [EMAIL PROTECTED] wrote:
> I have various bits of code I want to interpret and run at runtime in
> eval ...

import sys
from time import clock, sleep
from threading import Timer
TimeoutError= type('TimeoutError',(Exception,),{})

class Elapse:
def __init__( self ):
self.flag= False
def set( self ):
self.flag= True

def tr( frame, event, arg ):
if elapse.flag:
raise TimeoutError
return tr

def sleeper():
while 1:
sleep( .3 )
print( 'tick' )

def factercomp( n ):
val= 1
for i in range( 1, n ):
val*= i
return val

def facter( n ):
print( factercomp( n ) )

def runit( f, *ar ):
global elapse
elapse= Elapse()
t= Timer( 1, elapse.set )
t.start()
sys.settrace( tr )
try:
f( *ar )
except TimeoutError:
print( 'time elapse' )

runit( sleeper )
runit( facter, 10 )
runit( facter, 20 )
runit( facter, 1 )
runit( facter, 10 )

'''
tick
tick
tick
time elapse
362880
121645100408832000
time elapse
time elapse
'''
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Steven D'Aprano
On Fri, 07 Mar 2008 11:58:38 -0500, D'Arcy J.M. Cain wrote:

>> 2. You should use two spaces after a
>> sentence-ending period.
>> 
>> For heavens sake, why? I've always been obstructed by the double blanks
>> but
>> tolerated them. Now, that i read that it actually is a recommendation,
>> i need to ask about the purpose.
> 
> Like many things of this nature, the purpose is to follow the rules of
> correct English usage.

Except English grammar does not and never has specified using two spaces 
after a period. The (bad) habit of doing so was introduced by typists, in 
the old days of manual typewriters, in the belief (completely bogus, in 
my opinion) that a larger gap between sentences would make them more 
readable. I believe that the larger gap is a distraction, one of the 
reasons that typewriter text is generally harder to read than properly 
typeset text.

I believe it is one of those things that everybody (for some value of 
"everybody") does because that's what they were taught to do, and they 
were taught to do it because that's what their teachers were taught, and 
so on all the way back to some nutter who just decided that *he* was 
going to use two spaces after a period because the Great and Mighty 
Pumpkin told him to.

Professional typesetters, using proportional fonts, don't use double-
spaces because it throws off word spacing and line justification and just 
plain looks ugly. I suppose that since coders typically use non-
proportional fonts, we can at least justify the use of two spaces with a 
claim that it aids readability for "typewriter fonts" -- if you believe 
such a thing, which I do not.



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


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-07 Thread Chris Mellon
On Fri, Mar 7, 2008 at 3:00 PM, DBak <[EMAIL PROTECTED]> wrote:
> I want - but cannot get - a nested class to inherit from an outer
>  class.  (I searched the newsgroup and the web for this, couldn't find
>  anything - if I missed an answer to this please let me know!)
>
>  I would like to build a class for a data structure such that nodes of
>  the data structure - of interest only to the data structure
>  implementation itself and not to the consumer - are instances of one
>  of two class types.  I thought to encapsulate the nodes' classes like
>  this:
>
>  class Tree(object):
>  ...class _MT(Tree):
>  ..def isEmpty(self): return True
>  ..def insert(self, X): return Tree._Node(X)
>  ...class _Node(Tree):
>  ..def isEmpty(self): return False
>  ..def insert(self, X): return _Node(X, self, Tree._MT())
>  ...def merge(self, T):
>  ..def __init__(): return _MT()
>  ..
>
>  In other words, some methods would be implemented on instances'
>  classes (like isEmpty and insert) and some on the outer class (like
>  merge).  Users of the data structure never need to know about the
>  nodes, much less the nodes' classes, so I wanted to encapsulate them
>
>  However I can't do this, because, of course, the name Tree isn't
>  available at the time that the classes _MT and _Node are defined, so
>  _MT and _Node can't inherit from Tree.
>

Not only is the name not defined, the class doesn't even exist yet.

>  What is the Pythonic thing I should be doing instead?
>

Don't nest them. The single underscore is all you need to keep any
from using them (don't forget that even if your method worked, they'd
be perfectly visible as attributes of the Tree class, or as the types
of returned values). Worrying too much about visibility is a waste of
time in Python.

>  (Easy answer:  Put this code in a module, exposing only a factory
>  function.  I could do that, but wanted to know if I could encapsulate
>  it as described so I could actually put several similar data
>  structures into one module.)
>

There's no reason to use a factory function. If you do put them in a
module, you can use __all__ to document your exports. As with all
visibility issues in Python, this is advisory only - the only code it
affects is the symbols that are exported by "from module import *".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Grant Edwards
On 2008-03-07, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> Professional typesetters, using proportional fonts, don't use double-
> spaces because it throws off word spacing and line justification and just 
> plain looks ugly.

They do, however, put more space between sentences than they do
between words within a sentence.  It is that practice which the
"two spaces after a period" rule in typewriting is attempting
to emulate.

> I suppose that since coders typically use non- proportional
> fonts, we can at least justify the use of two spaces with a 
> claim that it aids readability for "typewriter fonts" -- if
> you believe such a thing, which I do not.

My thumb has been putting two spaces after a period for 30
years, so the chances that it's going to change are rather
slim. :)

-- 
Grant Edwards   grante Yow! A shapely CATHOLIC
  at   SCHOOLGIRL is FIDGETING
   visi.cominside my costume..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I cannot evaluate this statement...

2008-03-07 Thread Steven D'Aprano
On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote:

> The script comes from Mark Lutz's Programming Python.  It is the second
> line of a script that will launch a python program on any platform.
> 
> import os, sys
> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
> 
> Okay, run on a win32 machine, pyfile evaluates to python.exe
> 
> That makes sense. Because the first condition is true and 'python.exe'
> is true. So the next comparison is 'python.exe' or 'python'  Well,
> python.exe is true. So that value is returned to pyfile.
> 
> Now. Run this on linux. The first condition evaluates sys.platform[:3]
> == 'win' as false. So, the next comparison should be  'False' or
> 'python'   -- This is because 'and' returns the first false value. But,
> again, on linux pyfile evaluates to python.exe

Not on my Linux box.


>>> import os, sys
>>> sys.platform
'linux2'
>>> (sys.platform[:3] == 'win' and 'python.exe') or 'python'
'python'



> Where am I going wrong.  And when will this statment make pyfile
> evaluate to 'python' ?

When the first three letters of sys.platform aren't 'win'.




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


Re: I cannot evaluate this statement...

2008-03-07 Thread John Machin
On Mar 8, 7:38 am, waltbrad <[EMAIL PROTECTED]> wrote:
> The script comes from Mark Lutz's Programming Python.  It is the
> second line of a script that will launch a python program on any
> platform.
>
> import os, sys
> pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
>
> Okay, run on a win32 machine, pyfile evaluates to python.exe
>
> That makes sense. Because the first condition is true and 'python.exe'
> is true. So the next comparison is 'python.exe' or 'python'  Well,
> python.exe is true. So that value is returned to pyfile.
>
> Now. Run this on linux. The first condition evaluates sys.platform[:3]
> == 'win' as false. So, the next comparison should be  'False' or
> 'python'   -- This is because 'and' returns the first false value.

The next comparison is NOT ('False' or 'python'); it is (False or
'python'). 'False' is NOT false, 'False' (like any string of non-zero
length) is true.

(trueobject and expression) evaluates to the value of expression.
(falseobject and expression) evaluates to falseobject [and doesn't
evaluate expression].
(trueobject or expression) evaluates to trueobject [and doesn't
evaluate expression].
(falseobject or expression) evaluates to the value of expression.

So:
('NOT-win' == 'win' and 'python.exe') or 'python'
(False and 'python.exe') or 'python'
False or 'python'
'python'

> But, again, on linux pyfile evaluates to python.exe

Does it? Have you tried it?

>
> Where am I going wrong.  And when will this statment make pyfile
> evaluate to 'python' ?

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


Time Zone application after strptime?

2008-03-07 Thread Jim Carroll
It's taken me a couple of hours to give up on strptime with %Z for recognizing
time zones... but that still leaves me in the wrong zone:

def paypal_to_mysql_date(ppDate):
# a typical paypal date is 10:29:52 Feb 29, 2008 PST
date_parts = ppDate.split()
withouttz = " ".join(date_parts[:-1])

# eventually we need to apply the timezone
timezone = date_parts[-1]

dt = datetime.strptime(withouttz, "%H:%M:%S %b %d, %Y")
return dt.strftime("%Y-%m-%d %H:%M")


How can I use the "PST" (or any other time zone name) to adjust dt by the
correct number of hours to get it into UTC before storing in MySQL?

Thanks!


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


Re: Regarding coding style

2008-03-07 Thread Aahz
In article <[EMAIL PROTECTED]>,
Grant Edwards  <[EMAIL PROTECTED]> wrote:
>
>My thumb has been putting two spaces after a period for 30
>years, so the chances that it's going to change are rather
>slim. :)

+1 QOTW
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I cannot evaluate this statement...

2008-03-07 Thread Michael Wieher
The parentheses are there for a reason

2008/3/7, Steven D'Aprano <[EMAIL PROTECTED]>:
>
> On Fri, 07 Mar 2008 12:38:11 -0800, waltbrad wrote:
>
> > The script comes from Mark Lutz's Programming Python.  It is the second
> > line of a script that will launch a python program on any platform.
> >
> > import os, sys
> > pyfile = (sys.platform[:3] == 'win' and 'python.exe') or 'python'
> >
> > Okay, run on a win32 machine, pyfile evaluates to python.exe
> >
> > That makes sense. Because the first condition is true and 'python.exe'
> > is true. So the next comparison is 'python.exe' or 'python'  Well,
> > python.exe is true. So that value is returned to pyfile.
> >
> > Now. Run this on linux. The first condition evaluates sys.platform[:3]
> > == 'win' as false. So, the next comparison should be  'False' or
> > 'python'   -- This is because 'and' returns the first false value. But,
> > again, on linux pyfile evaluates to python.exe
>
> Not on my Linux box.
>
>
> >>> import os, sys
> >>> sys.platform
> 'linux2'
> >>> (sys.platform[:3] == 'win' and 'python.exe') or 'python'
> 'python'
>
>
>
> > Where am I going wrong.  And when will this statment make pyfile
> > evaluate to 'python' ?
>
> When the first three letters of sys.platform aren't 'win'.
>
>
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Location and size of a frame

2008-03-07 Thread K Viltersten
I'm disliking the size of my frame and
also i'm disappointed regarding it's 
location. So, i wish to change them.

At this link
http://infohost.nmt.edu/tcc/help/pubs/tkinter/frame.html
the frame object is discussed but as
far i can tell, there are only 
suggestions regarding what to put in
the constructor.

So, how/where do i check how to 
affect the location and size?

I'm guessing it has to do with 
"location", "width" and "heinght"
but i didn't  make it work.

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Better grammar.txt

2008-03-07 Thread MartinRinehart


Jeroen Ruigrok van der Werven wrote:
> >http://www.martinrinehart.com/articles/python-grammar.html:
> >Unknown host www.martinrinehart.com
>
> Works for me.

Very interesting. The link I posted works for me, while the links
quoted are 404 errors, though they look identical. This really is a
superior version of the EBNF, so I wish it would work for everyone.
Any ideas?

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


Re: While executing the class definition which object is referenced by the first argument of the class method, Y r Object attributes not allowed as default arguments

2008-03-07 Thread Steven D'Aprano
On Fri, 07 Mar 2008 09:49:58 -0800, Krishna wrote:

> I am more interested in knowing about the first argument ('self'), what
> does it hold to allow the evaluation of the method, take the example you
> gave, 'self.a' as Rvalue inside the method, how and why is this allowed,

"self" is treated as an argument like any other argument, except that 
when you call a method on an instance Python automatically provides the 
self for you.

Consider the following piece of code:

>>> class Parrot(object):
... def squawk(self, n):
... return "spam " * n
...
>>> instance = Parrot()
>>> instance.squawk(3)
'spam spam spam '
>>> Parrot.squawk(instance, 3)
'spam spam spam '


In the first call, I call the squawk() method from the instance, and 
Python automatically fills in the self argument.

In the second call, I call the squawk() method from the class. Since the 
class doesn't know what instance I'm using, I have to manually provide 
the self argument.

But inside the method, self is just a name in a namespace, like any other 
name. It's not special. You can do anything you like to it. You can even 
re-assign to it, or delete it:

>>> class Spam(object):
... def spam(self):
... print "I am", self
... self = "foo"
... print "Now I am", self
...
>>> x = Spam()
>>> x.spam()
I am <__main__.Spam object at 0xb7f5192c>
Now I am foo
>>> x
<__main__.Spam object at 0xb7f5192c>



> when the same 'self.a' is not allowed as the default argument,

It isn't that self.a is "not allowed". Python doesn't contain any code 
that says "if the default value contains "self", raise an error. You can 
prove that for yourself:

>>> def foo(x=self):
... return x
...
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'self' is not defined
>>>
>>> self = 2
>>> def foo(x=self):
... return x
...
>>> foo()
2



> considering the fact that I have already specified 'self' as first
> argument, only after whose evaluation, I believe would the next
> statement (k = self.a, in def func(self, k = self.a) ) gets evaluated

You believe wrong. You've already been told that the function default 
"k=self.a" is evaluated when the method is compiled, not at runtime. 
Since "self" doesn't exist at compile time, it is an error.

There is no way to create a reference to a class instance before the 
class is even defined.




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


distutils - Is is possible to install without the .py extensions

2008-03-07 Thread Jari Aalto

Given following setup.py stanza:

#!/usr/bin/python

from distutils.core import setup
import glob

setup(name='program',
  description='',
  keywords='',
  version='',
  url='',
  download_url='',
  license='',
  author='',
  author_email='',
  long_description="""
  """,
  scripts = ['program,py'],
  packages = ['''],
  )

Is there any way to fix the installation (postinstall or something), so
that the the result is:

/usr/bin/program

instead of:

/usr/bin/program.py

Jari

-- 
Welcome to FOSS revolution: we fix and modify until it shines

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


Re: Better grammar.txt

2008-03-07 Thread Steven D'Aprano
On Fri, 07 Mar 2008 13:42:56 -0800, MartinRinehart wrote:

> Jeroen Ruigrok van der Werven wrote:
>> >http://www.martinrinehart.com/articles/python-grammar.html: Unknown
>> >host www.martinrinehart.com
>>
>> Works for me.
> 
> Very interesting. The link I posted works for me, while the links quoted
> are 404 errors, though they look identical. This really is a superior
> version of the EBNF, so I wish it would work for everyone. Any ideas?

I get 404.

Perhaps you need to move this discussion to a mailing list for web 
admins, rather than Python developers? What I know about hosting a web 
site I could engrave on a poppy seed. In letters ten feet high.

Doesn't mean I won't express an opinion though :)

Perhaps it works for you because you are inside your firewall, rather 
than outside it?

Also, I would be concerned that some people (one person?) is reporting an 
Unknown Host error. Who is your domain registrar?


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


Re: Timed execution in eval

2008-03-07 Thread Steven D'Aprano
On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote:

> I have various bits of code I want to interpret and run at runtime in
> eval ...

I hope that code doesn't contain any data coming from an untrusted user.


> I want to be able to detect if they fail with error,

That's what try...except blocks are for.

try:
x = eval('1 + 1 = 2')
except SyntaxError:
x = 3


> I want to be able to time them, 

That's what the timeit module is for.

If you do time them, you will find that eval(expr) is MUCH MUCH slower 
than just executing expr as normal.

>>> from timeit import Timer
>>> Timer('1+1').timeit()
0.25557518005371094
>>> Timer('eval("1+1")').timeit()
21.816912174224854

If you use eval() a lot, you will have a SLOW program.


> and I want to be able to stop them if they run too long. 

That's tricky. As far as I know, the only way for a Python program to 
stop an arbitrary calculation after a certain period of time it to run it 
in a thread. You then monitor the elapsed time, and when the timer 
expires, ask the thread to die. And hope it listens.


> I cannot add code to the eval'd strings that will help me accomplish
> this.

You can't? Why ever not?

Note: that's almost certainly the wrong way to solve your problem, but 
I'm curious as to why you can't.


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


Intelligent Date & Time parsing

2008-03-07 Thread shakefu
I'm new to python and I was wondering if there are any intelligent
date/time parsing modules out there. I've looked at strptime (or
whichever it is) and mxDateTime from the eGenix package. I need
something to parse user input for a django app, and it's awesome to be
able to write "last monday", "a year ago", or "10pm tuesday" like
PHP's strtotime.

So are there any modules that allow for that kind of parsing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intelligent Date & Time parsing

2008-03-07 Thread Mike Driscoll
On Mar 7, 4:08 pm, [EMAIL PROTECTED] wrote:
> I'm new to python and I was wondering if there are any intelligent
> date/time parsing modules out there. I've looked at strptime (or
> whichever it is) and mxDateTime from the eGenix package. I need
> something to parse user input for a django app, and it's awesome to be
> able to write "last monday", "a year ago", or "10pm tuesday" like
> PHP's strtotime.
>
> So are there any modules that allow for that kind of parsing?

There's the dateutil module that's a fancy wrapper for the datetime
module. The author's site has lots of examples as well as the source:

http://labix.org/python-dateutil

I use it quite a bit.

HTH

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


  1   2   >