Re: what are the most frequently used functions?

2006-10-28 Thread Theerasak Photha
On 28 Oct 2006 22:55:29 -0700, Xah Lee <[EMAIL PROTECTED]> wrote:
> Barry Margolin wrote:
> « For Lisp, just look for symbols that are immediately preceded by (
> ...»
>
> Thanks a lot! great thought.

An even cleaner way to do this would be to iterate over the list
s-exprs in any given lisp source, use read on them, then just use car
on the resulting list (or first for the infinitely superior common
lisp language).

This will get special forms and actual functions indiscriminately, but
they may be seen as equivalent from a sloppy perspective.

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


Re: question about True values

2006-10-28 Thread Chetan
Georg Brandl <[EMAIL PROTECTED]> writes:

> Chetan wrote:
>>> Steven D'Aprano wrote:
>>> > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote:
>>>  >
>>> >>> Finally, while True/False is a good mental mapping for numeric 
>>> >>> comparisons,
>>> >>> take the following:
>>> >>>
>>> >>>  >>> if "Cliff is a pillar of the open source community":
>>> >>> print "thank you"
>>> >>>  else:
>>> >>> print "bugger off"
>>> >>>
>>> >>> bugger off
>>> >>>
>>>
>>> First off, even though nobody has called me on it, this example really 
>>> prints
>>> "thank you", not "bugger off".  I got confused in my cutting and pasting.
>>> Sorry about that.
>>>
>>>
>>> >>> Clearly this is not true.  (Google Cliff/Dyer open source: only 11 
>>> >>> hits.),
>>> >>> but the string is *something* so the if block gets evaluated.
>>> >>>
>>> >>   >>> if "The above example was bollocks":
>>> >>   ...   print "You don't know what you are talking about"
>>> >>   ... else:
>>> >>   ...   print "Sorry: of course you are perfectly correct"
>>> >>   ...
>>> >> You don't know what you are talking about
>>> > Cliff is making a point about semantics, and he's absolutely correct about
>>> > it, although it is irrelevant since we're talking about two-value logic
>>> > not semantics.
>>> Cheers,
>>> Cliff
>>
>> I am joining after some network downtime here, so I seem to have missed what
>> the real issue here is. At the risk of being completely irrelevant to the
>> discussion here, I think it doesn't seem to be just about something or
>> nothing - is None something or nothing? It seems to be neither:
>
> If is, of course, nothing. You may have misunderstood the semantics of the
> "and" and "or" operators.

I have not. I just posted another message on the subject. All I am trying to
point out is that the "nothingness" evaluation does not occur at the level of
expressions. It is only when the expression is needed to make decisions about
control flow that this comes into picture. 

> None
> None and True
> None or True
>> True
> None and False
> None or False
>> False
> False or None
> False and None
>> False
> True and None
> True or None
>> True
> not None
>> True
>
> x and y | x something | x nothing
> ---
> y something | y   | x
> y nothing   | y   | x
>
> x or y  | x something | x nothing
> ---
> y something | x   | y
> y nothing   | x   | y
>
>
> Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-28 Thread Georg Brandl
Chetan wrote:
>> Steven D'Aprano wrote:
>> > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote:
>>  >
>> >>> Finally, while True/False is a good mental mapping for numeric 
>> >>> comparisons,
>> >>> take the following:
>> >>>
>> >>>  >>> if "Cliff is a pillar of the open source community":
>> >>>  print "thank you"
>> >>>  else:
>> >>>  print "bugger off"
>> >>>
>> >>> bugger off
>> >>>
>> 
>> First off, even though nobody has called me on it, this example really prints
>> "thank you", not "bugger off".  I got confused in my cutting and pasting.
>> Sorry about that.
>> 
>> 
>> >>> Clearly this is not true.  (Google Cliff/Dyer open source: only 11 
>> >>> hits.),
>> >>> but the string is *something* so the if block gets evaluated.
>> >>>
>> >>   >>> if "The above example was bollocks":
>> >>   ...   print "You don't know what you are talking about"
>> >>   ... else:
>> >>   ...   print "Sorry: of course you are perfectly correct"
>> >>   ...
>> >> You don't know what you are talking about
>> > Cliff is making a point about semantics, and he's absolutely correct about
>> > it, although it is irrelevant since we're talking about two-value logic
>> > not semantics.
>> Cheers,
>> Cliff
> 
> I am joining after some network downtime here, so I seem to have missed what
> the real issue here is. At the risk of being completely irrelevant to the 
> discussion here, I think it doesn't seem to be just about something or 
> nothing - is None something or nothing? It seems to be neither:

If is, of course, nothing. You may have misunderstood the semantics of the
"and" and "or" operators.

 None
 None and True
 None or True
> True
 None and False
 None or False
> False
 False or None
 False and None
> False
 True and None
 True or None
> True
 not None
> True

x and y | x something | x nothing
---
y something | y   | x
y nothing   | y   | x

x or y  | x something | x nothing
---
y something | x   | y
y nothing   | x   | y


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


logo design

2006-10-28 Thread Xah Lee
recently on #emacs irc of freenode, there's a discussion of a logo of
planet emacsen site.

I made some comments about such logo:

http://paste.lisp.org/display/28901

I have brought this topic here here before... that i think LISP really
need to have a logo. I'm aware of “made with alien technology lisp”
web-badge, but that is a lisp-peddling badge, not a lisp logo proper.

Python, did not really have a logo. I made a plaint more than once in
different periods of times to comp.lang.python. Them tech geeking
morons and assholes, as expected, made irrelevant and incoherent cries.
But look now, Python now has a logo inargurated around 2005, and is a
well-designed one.

For examples (most top quality) logos, see:
http://xahlee.org/UnixResource_dir/lambda_logo.html
(the lambda logo tour)

http://xahlee.org/UnixResource_dir/freebooks.html
(the unix pestilence)

http://xahlee.org/UnixResource_dir/complang.html
(computer language logos)

Again: the primary purpose of this message, is to beseach that the
power-that-be of lispers, seriously think about getting themselves a
official logo. Thanks. 

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: question about True values

2006-10-28 Thread Chetan
Gabriel Genellina <[EMAIL PROTECTED]> writes:

> At Friday 27/10/2006 23:13, Steve Holden wrote:
>
>>J. Clifford Dyer wrote:
>> > the one thing that Ms. Creighton points out that I can't get past is
>> > that Python, even with its bool type, *still* evaluates somethingness
>> > and nothingness, and True and False are just numbers with hats on.
>> >
>> >  >>> True + 3
>> > 4
>> >  >>> bool(True-1)
>> > False
>> >  >>> bool(True-2)
>> > True
>> >  >>> (10 > 5) + (10 < 5)
>> > 1
>>Seems pretty clear to me that the situations you discuss above involve
>>numeric coercions of a Boolean value.
>
> A "true" Boolean value should not be coerced into any other thing. True+1 is 
> as
> meaningless as "A"+1, or even "1"+1. The fact is, bool is just an integer in
> disguise.
> I always regretted that Python just went mid-way moving onto a true Boolean
> type; I'd prefer it to stay as it was before bool was introduced.
>
>> > Python is not evaluating the truth of the matter, but, as Ms. Creighton
>> > would say, the "somethingness" of that which 10 > 5 evaluates to.  (1
>> > aka True)
>> >
>>   >>> type(10>5)
>>
>>   >>>
>
 bool.__mro__
> (, , )
>
>>It does seem that there is a specific type associated with the result of
>>a comparison, even though you would really like to to be "a number with
>>a hat on".
>
> It *is* an integer with a hat on.
>
 isinstance(True,int)
> True
This has focussed on the relational operators, which seem to produce a number
with a hat on. However, logical operations do not do so. 
True and "This string" produces "This string", for example.

This is hardly surprising, though.
The way they are defined, booleans seem to be the syntactic sugar that some 
people like. Many of the projects that I have been associated with had such
a define because the language (C) does not provide it. On the other hand, 
there are many who do just fine without them. 

For expressions used in control flow, if the expression somehow produces a 0
(False included) or None, the behavior is as if the expression is false. 
Confusion may arise because the way that answer is produced may not be
immediately obvious. For constructs such as "if obj:" the answer depends on
which methods the object has defined and what the state of the object is at the
time, but this has nothing to do with whether the answer that was produced was
strictly a boolean or not.

Chetan

>
>
> -- 
> Gabriel Genellina
> Softlab SRL 
>
> __
> Correo Yahoo!
> Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta
> ya! - http://correo.yahoo.com.ar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are the most frequently used functions?

2006-10-28 Thread Xah Lee
Barry Margolin wrote:
« For Lisp, just look for symbols that are immediately preceded by (
...»

Thanks a lot! great thought.

I've done accordingly, which counts satisfactorily.
http://xahlee.org/emacs/function-frequency.html

Will take a break and think about Perl, Python, Java later...  For
Python and Java, i think the report will also have to count method
call since that what these langs deal with... slightly quite more
complex than just functional langs...

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Python crashed when importing SOAPpy, printing out 'usage:copy source destination'

2006-10-28 Thread [EMAIL PROTECTED]
Fredrik Lundh wrote:
> [EMAIL PROTECTED] wrote:
>
> > I still can't understand it. If i rename the 'copy.py' to 'a.py',
> > there will be no problem.
>
> hint: when it works, try typing the following into the interpreter:
>
>  >>> import copy
>  >>> copy.__file__
>
> 

I know, the copy module is imported by the SOAPpy module.
But SOAPpy imported an un-proper one from the CWD.

 Thank you very much :)

>Regards,
>jiang.haiyun

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


random module

2006-10-28 Thread Moishy Gluck
HiI am using the random module to generate a session tracker. I use this code to generate a random number "random.random() * 1" The session is stored in a mysql database under the field session_id. The problem is when I try to submit the random number into my database I get this error
IntegrityError: (1062, "Duplicate entry '2147483647' for key 1")
  args =
(1062, "Duplicate entry '2147483647' for key 1")With the same number every time. The  number being 2147483647. Does eneyone know what the problem is.

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

Re: What's the best IDE?

2006-10-28 Thread Theerasak Photha
On 10/27/06, Ramon Diaz-Uriarte <[EMAIL PROTECTED]> wrote:

> Actually, I've read similar things before and I don't quite get it. I
> guess all of us are Emacs begginers the first time we try emacs.
> Actually, I started using Emacs about 1 month after installing Linux;
> what hooked me was the possibility of editing code AND submit it to an
> inferior process, just like that (this I experienced first with R, but
> of course you can do the same with Python) and using the same
> environment for all of my editing and programming tasks.

I've used Emacs for a long time, but I think I might be going back to
Vim 7.0 now that they improved the scripting functionality with *real*
arrays and dicts. In some respects, this is now better than in Emacs,
where the hash functionality is...well...cumbersome at best.

Main reason would be that Vim is so much easier to customize and find
things in than Emacs. I long time ago, I actually submitted a bug
report for the perl plugin  I hate to appeal to popularity, but Vim's
greater popularity also contributes to higher quality in a number of
cases: consider Ruby support for instance. Light years ahead of what
Emacs has.

vimshell is a (nearly) full-blown terminal emulator facility for Vim
http://www.wana.at/vimshell/

In any case, chok dee khrab (good luck with it).

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


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread Steve Holden
[EMAIL PROTECTED] wrote:
[...]
> BTW, there is a mailing list specifically for mod_python. You might be
> better off asking questions directly there, as we have seen most
> problems. You can also search the mailing list archives from the
> mod_python site.
> 
> BTW, the quadruple backslashes is indeed because of the use of repr()
> when doing the error dump.

For gmane users the list is also available as newsgroup

   gmane.comp.python.mod_python

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Sending mouse events on Windows

2006-10-28 Thread Roger Upole

Radu Ciurlea wrote:
> Hello,
> I want to write a program that can generate mouse events. I'd like to
> actually be able to control the pointer and generate clicks. Any
> pointers on modules I could use for doing this? Any suggestions are
> welcome.
> tia
>
> Radu

Take a look at win32api.mouse_event.

   Roger





== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Name bindings for inner functions.

2006-10-28 Thread James Stroud
Andrea Griffini wrote:
> [EMAIL PROTECTED] wrote:
> 
>> The following code:
>>
>> def functions():
>> l=list()
>> for i in range(5):
>> def inner():
>> return i
>> l.append(inner)
>> return l
>>
>>
>> print [f() for f in functions()]
>>
>>
>> returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
>> this is something to do with the variable i getting re-bound every time
>> we go through the loop, or something, but I'm not sure how to fix this.
> 
> 
> The problem is that "i" inside the function is indeed
> the same variable for all the functions (the one you're
> using for looping).
> 
> If you want a different variable for each function
> you can use the somewhat ugly but idiomatic
> 
> def functions():
> l=list()
> for i in range(5):
> def inner(i=i):
> return i
> l.append(inner)
> return l
> 
> this way every function will have its own "i" variable,
> that is initialized with the value of the loop variable
> when executing the "def" statement.
> 
> Andrea

Yet another way to skin the same cat, maybe even less ugly, depending on taste.

def make_inner(i):
   def inner():
 return i
   return inner

def functions():
   return [make_inner(i) for i in range(5)]

print [f() for f in functions()]

James

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

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


Re: Name bindings for inner functions.

2006-10-28 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> The following code:
> 
> def functions():
> l=list()
> for i in range(5):
> def inner():
> return i
> l.append(inner)
> return l
> 
> 
> print [f() for f in functions()]
> 
> 
> returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
> this is something to do with the variable i getting re-bound every time
> we go through the loop

free variables bind to *names*, not objects.  all your functions will 
refer to the name "i" in "function"'s scope, which is bound to a 4 when 
the loop has finished.

you can use the default argument mechanism to explicitly bind to an 
object instead of a name:

def functions():
 l=list()
 for i in range(5):
 def inner(i=i):
 return i
 l.append(inner)
 return l



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


Re: unescape HTML entities

2006-10-28 Thread Fredrik Lundh
Rares Vernica wrote:

> How can I unescape HTML entities like " "?

run it through an HTML parser.

or use something like this:

 http://effbot.org/zone/re-sub.htm#strip-html

(if you want to keep elements, change the regular expression in the 
re.sub call to "(?s)&#?\w+;")

> I know about xml.sax.saxutils.unescape() but it only deals with "&", 
> "<", and ">".
> 
> Also, I know about htmlentitydefs.entitydefs, but not only this 
> dictionary is the opposite of what I need, it does not have " ".

 >>> htmlentitydefs.entitydefs.get("nbsp")
'\xa0'



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


Re: Name bindings for inner functions.

2006-10-28 Thread trevor_morgan
Thanks, that's exactly what I needed.
Andrea Griffini wrote:
> [EMAIL PROTECTED] wrote:
> > The following code:
> >
> > def functions():
> > l=list()
> > for i in range(5):
> > def inner():
> > return i
> > l.append(inner)
> > return l
> >
> >
> > print [f() for f in functions()]
> >
> >
> > returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
> > this is something to do with the variable i getting re-bound every time
> > we go through the loop, or something, but I'm not sure how to fix this.
>
> The problem is that "i" inside the function is indeed
> the same variable for all the functions (the one you're
> using for looping).
>
> If you want a different variable for each function
> you can use the somewhat ugly but idiomatic
>
> def functions():
>  l=list()
>  for i in range(5):
>  def inner(i=i):
>  return i
>  l.append(inner)
>  return l
>
> this way every function will have its own "i" variable,
> that is initialized with the value of the loop variable
> when executing the "def" statement.
> 
> Andrea

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


Re: http call.

2006-10-28 Thread haiyun
Steve Holden 写道:
> Kirt wrote:
>> Hi!
>>
>> I have a php program (test.php) on a server. eg:
>> http://abc.xyz.com/test.php
>>
>> I need my python scripts to make a http call to these program pass some
>> data and get back a secret key from the php program..
>>
>> Could anyone help me this, what will i need to make a http call to the
>> php application?
>>
> 
> import urllib
> nf = urllib.urlopen('http://abc.xyz.com/test.php')
> data = nf.read()
> 
> Should get you started. Look for the "mechanize" and "ClientForm" (?) 
> modules to help with the site interactions. It doesn't matter what 
> language the server uses: you will be talking HTTP to it!
> 
> regards
>  Steve
Use urllib2 library , you can take more control.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Safely renaming a file without overwriting

2006-10-28 Thread Diez B. Roggisch
Wolfgang Draxinger schrieb:
> Steven D'Aprano wrote:
> 
>> But the source file always exists, otherwise there is nothing
>> to rename! Do you mean, open the destination filename?
> 
> Of course I meant the destination file. Someone please spill some
> ice chilled water over me to get me awake again. Time to go to
> bed :-P before I make more dumb mistakes/typos...

But that doesn't help. Opening the destination file that way will only 
make a difference if _both_ processes that fight over that filename work 
that way. Which might be possible in the actual case, but not as a 
general recipe.

The link/unlink trick of Chetan sounds reasonable, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Metaclasses are not called in subclasses. What did I wrong?

2006-10-28 Thread Létező
I use Python 2.4.4. Please read the code below:

---
from new import classobj

def mymeta(name,bases,clsdict):
print 'meta: %s'%name
return classobj(name,bases,clsdict)

class A(object):
__metaclass__=mymeta

class B(A):
pass

---

This should print

meta: A
meta: B

when classes A and B are created. But only meta: B is missing,
since mymeta() is not called when class B is created.

Related python documentation states that mymeta() must be called when B is 
created, since metaclasses are looked up in bases classes if not found in 
the dictionary of the class itself.

>From Python 2.4.4's manual: "Otherwise, if there is at least one base class, 
its metaclass is used (this looks for a __class__ attribute first and if not 
found, uses its type)."

Thanks for your help.

Viktor 

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


Re: question about True values

2006-10-28 Thread Chetan
> Steven D'Aprano wrote:
> > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote:
>  >
> >>> Finally, while True/False is a good mental mapping for numeric 
> >>> comparisons,
> >>> take the following:
> >>>
> >>>  >>> if "Cliff is a pillar of the open source community":
> >>>   print "thank you"
> >>>  else:
> >>>   print "bugger off"
> >>>
> >>> bugger off
> >>>
> 
> First off, even though nobody has called me on it, this example really prints
> "thank you", not "bugger off".  I got confused in my cutting and pasting.
> Sorry about that.
> 
> 
> >>> Clearly this is not true.  (Google Cliff/Dyer open source: only 11 hits.),
> >>> but the string is *something* so the if block gets evaluated.
> >>>
> >>   >>> if "The above example was bollocks":
> >>   ...   print "You don't know what you are talking about"
> >>   ... else:
> >>   ...   print "Sorry: of course you are perfectly correct"
> >>   ...
> >> You don't know what you are talking about
> > Cliff is making a point about semantics, and he's absolutely correct about
> > it, although it is irrelevant since we're talking about two-value logic
> > not semantics.
> Cheers,
> Cliff

I am joining after some network downtime here, so I seem to have missed what
the real issue here is. At the risk of being completely irrelevant to the 
discussion here, I think it doesn't seem to be just about something or 
nothing - is None something or nothing? It seems to be neither:

>>> None
>>> None and True
>>> None or True
True
>>> None and False
>>> None or False
False
>>> False or None
>>> False and None
False
>>> True and None
>>> True or None
True
>>> not None
True

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Wolfgang Draxinger
Steven D'Aprano wrote:

> But the source file always exists, otherwise there is nothing
> to rename! Do you mean, open the destination filename?

Of course I meant the destination file. Someone please spill some
ice chilled water over me to get me awake again. Time to go to
bed :-P before I make more dumb mistakes/typos...

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
-- 
http://mail.python.org/mailman/listinfo/python-list


Metaclasses are not called in subclasses. What did I wrong?

2006-10-28 Thread Létező
I use Python 2.4.4. Please read the code below:

---
from new import classobj

def mymeta(name,bases,clsdict):
print 'meta: %s'%name
return classobj(name,bases,clsdict)

class A(object):
__metaclass__=mymeta

class B(A):
pass

---

This should print

meta: A
meta: B

when classes A and B are created. But only meta: B is missing,
since mymeta() is not called when class B is created.

Related python documentation states that mymeta() must be called when B is
created, since metaclasses are looked up in bases classes if not found in
the dictionary of the class itself.

>From Python 2.4.4's manual: "Otherwise, if there is at least one base class,
its metaclass is used (this looks for a __class__ attribute first and if not
found, uses its type)."

Thanks for your help.

Viktor 

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


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread grahamd
dan84 wrote:
> I don't understand this error , in the (Apache) errorlog I read this
> message :
>
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
> mod_python.apache.\n
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
> used "['C:Python24python24.zip', '.DLLs', '.lib',
> '.libplat-win', '.liblib-tk',
> 'C:ProgrammiApache GroupApache2bin']".
> [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter
> callback found.
> [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler:
> Can't get/create interpreter.
>
> I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3
> I have read all the manuals, but I don't understand where I am wrong.
>
> thanks so much
>Marco.

Read:


http://www.modpython.org/pipermail/mod_python/2006-October/022362.html

You may have to fiddle your Windows registry to add site-packages
directory.

BTW, there is a mailing list specifically for mod_python. You might be
better off asking questions directly there, as we have seen most
problems. You can also search the mailing list archives from the
mod_python site.

BTW, the quadruple backslashes is indeed because of the use of repr()
when doing the error dump.

Graham

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


Re: What is the cleanest way to for a module to access objects from the script that imports it?

2006-10-28 Thread ggmailalias-cgag

robert ha escrito:

> [EMAIL PROTECTED] wrote:
> > Hi,
> >
> > I am new to python and am currently writing my first application. One
> > of the problems I quickly ran into, however, is that python's imports
> > are very different from php/C++ includes in the sense that they
> > completely wrap the imported script in a module object. One of the
> > problems with this was that a plugin system that I am making requires
> > use of objects, classes and the such from the original script. Thus, on
> > one hand, I am hesitant to use execfile(), since I *do* want to wrap
> > the plugin up, but on the other hand, I want the plugin to be able to
> > use functions from the original script. Any ideas?
> >
>
> you can import __main__ in your module: import __main__; __main__.app_xfunc(y)
>
> But for most cases I'd say your "problem" is an indication of weak design 
> (thanks to Pythons clear module tech).
>
> Maybe:
>
> * if the funcs are tools, put them in an extra module
>
> * if its about app-global parameters(tools), make a module "myglob" or so
>
> * if the funcs have app-context, hand over/set them as "callback" functions 
> or iterators like ..
>
> def app_xfunc(par):pass
> mody.set_xhandler(app_xfunc)
> mody.yfunc(a,b,..., cbProgress=app_xfunc)
> def app_xstepper():
> yield next
> mody.yfunc2(a,b,..., step=app_xstepper)
> ...
>
>
> * if you have 2 moduls on equal dependency level and each needs the other 
> (sometimes) - thus you don't want to have one big module, then cross import 
> them ..
>
> #modx
> import mody
> def fx():
> mody.doy()
> #mody
> import modx
> def fy():
> modx.dox()
>
>
> Python allows everything most easy for that kind of problems of all langs I 
> know of. Mainly the fact that a module is a real object in Python provides 
> tremendous flexibility and self-similarity of techniques. Ruby for example is 
> weired - even really bad - in this.
> 
> -robert

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


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread skip

dan> I don't understand this error , in the (Apache) errorlog I read
dan> this message :

dan> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
dan> mod_python.apache.\n
dan> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
dan> used "['C:Python24python24.zip', '.DLLs', '.lib',
dan> '.libplat-win', '.liblib-tk',
dan> 'C:ProgrammiApache GroupApache2bin']".
dan> [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter
dan> callback found.
dan> [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler:
dan> Can't get/create interpreter.

Just a wild ass guess, but maybe Apache can't find the necessary python dll
to load?

Skip

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


Re: Name bindings for inner functions.

2006-10-28 Thread Andrea Griffini
[EMAIL PROTECTED] wrote:
> The following code:
> 
> def functions():
> l=list()
> for i in range(5):
> def inner():
> return i
> l.append(inner)
> return l
> 
> 
> print [f() for f in functions()]
> 
> 
> returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
> this is something to do with the variable i getting re-bound every time
> we go through the loop, or something, but I'm not sure how to fix this.

The problem is that "i" inside the function is indeed
the same variable for all the functions (the one you're
using for looping).

If you want a different variable for each function
you can use the somewhat ugly but idiomatic

def functions():
 l=list()
 for i in range(5):
 def inner(i=i):
 return i
 l.append(inner)
 return l

this way every function will have its own "i" variable,
that is initialized with the value of the loop variable
when executing the "def" statement.

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Steven D'Aprano
On Sun, 29 Oct 2006 00:29:06 +0200, Wolfgang Draxinger wrote:

> Steven D'Aprano wrote:
> 
>> Open "the" file? There are potentially two files -- the source
>> and destination. I only want to do the rename if the
>> destination *doesn't* exist, so there is no destination file to
>> open. How will it help me to lock the source file? Have I
>> misunderstood?
> 
> I forgot to say, to open the source file with O_CREAT | O_EXCL.
> The open will fail if the file already exists.

But the source file always exists, otherwise there is nothing to rename!
Do you mean, open the destination filename?



-- 
Steven.

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


Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-28 Thread Martin v. Löwis
sébastien martini schrieb:
> I don't know if it can hide some bugs or if the module has just never
> been updated to support this bytecode but LIST_APPEND is never emitted.
> In the module compiler, list comprehensions are implemented without
> emitting this bytecode, howewer the current implementation seems to be
> correct from syntax and execution point of view.

It's probably a matter of personal taste, but I think the compiler
library should perform the same way as the builtin compiler - except
that it might be "better" in some cases.

So feel free to report this as a bug at sf.net/projects/python.

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Wolfgang Draxinger
Steven D'Aprano wrote:

> Open "the" file? There are potentially two files -- the source
> and destination. I only want to do the rename if the
> destination *doesn't* exist, so there is no destination file to
> open. How will it help me to lock the source file? Have I
> misunderstood?

I forgot to say, to open the source file with O_CREAT | O_EXCL.
The open will fail if the file already exists. By locking the
file no other process will be able to access it, but the process
that holds the lock can do with it anything. This includes to
rename an existing file to the name of the opened one - the
previously created placeholder file will get unlinked before,
but there is _probably_ no way that any process can intercept
this. It is an interesting thing, that files that are opened
remain fully usable and accessible if you unlink them as long
you don't close them. You have to close it, to remove all
remains of it.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: latest numpy & scipy - incompatible ?

2006-10-28 Thread Robert Kern
robert wrote:
> I'm using latest numpy & scipy. What is this problem ? :
> 
 import scipy.stats
> RuntimeError: module compiled against version 102 of C-API but this 
> version of numpy is 109

The scipy binary available on sourceforge has not been recompiled for numpy 
1.0. 
All you need to do is recompile, though, and everything will work.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Regular Expression help for parsing html tables

2006-10-28 Thread Stefan Behnel
Hi Steve,

[EMAIL PROTECTED] wrote:
> I am having some difficulty creating a regular expression for the
> following string situation in html. I want to find a table that has
> specific text in it and then extract the html just for that immediate
> table.

Any reason why you can't use a real HTML parser and API (e.g. the one provided
by lxml)? That can really make things easier here.

http://codespeak.net/lxml/
http://codespeak.net/lxml/api.html#parsers
http://codespeak.net/lxml/api.html#trees-and-documents
http://effbot.org/zone/element-index.htm

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Steven D'Aprano
On Sat, 28 Oct 2006 16:48:37 +0200, Diez B. Roggisch wrote:

> Where does that help for new files? The OP was right in assuming that a 
> race condition could occur when he tests for a file & then tries to 
> create it, as in the meantime it could have been created.

Ah! "Race condition" -- that was the term I was looking for ... now maybe
I'll have some better results with Google.



-- 
Steven.

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Steven D'Aprano
On Sat, 28 Oct 2006 13:38:14 +0200, Wolfgang Draxinger wrote:

>> But on a multi-user system, it is possible that dest is created
>> in the time period between checking if it exists and attempting
>> the rename.
>> 
>> Is there any way to prevent this? Or do I just try to keep the
>> check and the rename as close together as possible, minimizing
>> the chances and hoping for the best?
> 
> 1: Open the file with os.open

Open "the" file? There are potentially two files -- the source and
destination. I only want to do the rename if the destination
*doesn't* exist, so there is no destination file to open. How will it help
me to lock the source file? Have I misunderstood?


-- 
Steven.

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


Re: question about True values

2006-10-28 Thread Steven D'Aprano
On Sat, 28 Oct 2006 03:24:50 -0700, Carl Banks wrote:

> Not all objects that have a state of emptiness consider emptiness to be
> false.

In which case they should define __nonzero__ appropriately.

In which case, calling code that assumes that len(obj) is a substitute for
truth-testing will do the wrong thing.


>> > Whether you test with "if a:" or "if len(a)>0", some objects are
>> > going to be denied.
>>
>> If a class doesn't define __nonzero__ or __len__, it should.
> 
> No, it often shouldn't.

Okay, I want to qualify my statement: if a class doesn't define
__nonzero__ or __len__, *and doesn't want the default Python behaviour of
all instances evaluating as True*, then they should.

> A. It's not always desirable for empty to be false.  Numpy defines a
> bunch of numeric array types that raise an exception when __nonzero__
> (actually nb_nonzero in the C API) is called.  This is the correct
> behavior for numpy.  It makes no sense for numpy arrays to be used in a
> boolean context, but they certainly can be empty.

And, appropriate to the class, numpy arrays raise an exception when
__nonzero__ is called -- just as they should.



> B. Sometimes it's impossible to determine the state of emptiness.  For
> example, iterators.

Since Guido has ruled that the protocol is that all iterators are True,
there is no need for __nonzero__ since the default behaviour does the job.


[snip]
>> Perhaps this behaviour has changed in version 2.5, if so, I'd like to
>> hear the rationalisation before I declare it a mistake.
> 
> You haven't been paying attention.
> 
> Yes, this behavior has been changed in 2.5.  The built-in iterators
> always return True in 2.5.  But even in 2.4, it was not true for
> iterators in general:

Yes, you are right. I was fooled by a coincidence.

> At no point could you count on an iterator returning False for empty,
> unless you'd made it yourself.  Neither "if a:" nor "if len(a)>0" is a
> valid test for an empty iterator.

Correct. Guido's decision is that iterators are always "Something" (that
is, True in a truth context) even if they are exhausted.


>> > P.S. binary trees do have length: it's the number of nodes, just as
>> > the number of keys is the length of a dict.
>>
>> I don't know what you were taught, but I was taught that binary trees
>> have height and breadth.
> 
> It doesn't really matter.  dicts and sets don't have a length, either.
> Or if they do, it's the length of the hash table, not the number of
> entries.  Weren't you taught that?  But Python uses len() to get the
> number of items in a container.  Any Pythonic implementation of a binary
> tree class would use len() to return the number of entries in it.
> Anything that uses indexing ought to define len(), if it can.

In the binary tree:

tree -->  A
A.left --> B, A.right --> C

what's tree[0]? Should it be A (preorder), or B (inorder) or C (postorder)?


> Overall, your objections don't really apply, since you're arguing what
> ought to be whereas my argument is pragmatic.  Practically speaking, in
> realistic situations, "if len(a)>0" will work for a wider range of types
> than "if a:".

Well, that's a quantitative claim you're making there. Have you
actually gone through, say, the built in types and checked how many
have a length versus how many work in a truth-context?

>>> import types
>>> if types:
... print "Modules work with bool"
...
Modules work with bool
>>> if len(types)>0:
... print "Modules work with len"
...
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: len() of unsized object

"if len(a)>0:" only works for objects that define __len__. 

"if a:" works for any object that doesn't go to the trouble of
specifically prohibiting it, as numpy arrays deliberately do. That's the
Python way, and it is a deliberate design.


-- 
Steven.

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


Name bindings for inner functions.

2006-10-28 Thread trevor_morgan
The following code:

def functions():
l=list()
for i in range(5):
def inner():
return i
l.append(inner)
return l


print [f() for f in functions()]


returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4].  I presume
this is something to do with the variable i getting re-bound every time
we go through the loop, or something, but I'm not sure how to fix this.
 I've found the ability in python to create functions on the fly and
store and index them for later use incredibly powerful, so it'd be nice
to get past this little roadblock.

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


Re: unescape HTML entities

2006-10-28 Thread Klaus Alexander Seistrup
Rares Vernica wrote:

> How can I unescape HTML entities like " "?
>
> I know about xml.sax.saxutils.unescape() but it only deals with
> "&", "<", and ">".
>
> Also, I know about htmlentitydefs.entitydefs, but not only this 
> dictionary is the opposite of what I need, it does not have 
> " ".

How about something like:

#v+
#!/usr/bin/env/python
'''dehtml.py'''

import re
import htmlentitydef

myrx = re.compile('&(' + '|'.join(htmlentitydefs.name2codepoint.keys()) + ');')

def dehtml(s):
return re.sub(
myrx,
lambda m: unichr(htmlentitydefs.name2codepoint[m.group(1)]),
s
)
# end def dehtml

if __name__ == '__main__':
import sys
print dehtml(sys.stdin.read()).encode('utf-8')
# end if

#v-

E.g.:

#v+

$ echo 'frække frølår' | ./dehtml.py
frække frølår
$ 

#v-

-- 
Klaus Alexander Seistrup
Copenhagen, Denmark, EU
http://klaus.seistrup.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Expression help for parsing html tables

2006-10-28 Thread steve551979
Hello,

I am having some difficulty creating a regular expression for the
following string situation in html. I want to find a table that has
specific text in it and then extract the html just for that immediate
table.

the string would look something like this:

...stuff here...

...stuff here...

...stuff here...

...
text i'm searching for
...

...stuff here...

...stuff here...

...stuff here...


My question:  is there a way in RE to say:   "when I find this text I'm
looking for, search backwards and find the immediate instance of the
string ""  and then search forwards and find the immediate
instance of the string "".  " ?

any help is appreciated.

Steve.

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


Re: question about True values

2006-10-28 Thread J. Clifford Dyer
Steven D'Aprano wrote:
> On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote:
 >
>>> Finally, while True/False is a good mental mapping for numeric 
>>> comparisons, take the following:
>>>
>>>  >>> if "Cliff is a pillar of the open source community":
>>> print "thank you"
>>>  else:
>>> print "bugger off"
>>>
>>> bugger off
>>>

First off, even though nobody has called me on it, this example really 
prints "thank you", not "bugger off".  I got confused in my cutting and 
pasting.  Sorry about that.


>>> Clearly this is not true.  (Google Cliff/Dyer open source: only 11 
>>> hits.), but the string is *something* so the if block gets evaluated.
>>>
>>   >>> if "The above example was bollocks":
>>   ...   print "You don't know what you are talking about"
>>   ... else:
>>   ...   print "Sorry: of course you are perfectly correct"
>>   ...
>> You don't know what you are talking about
> 
> Cliff is making a point about semantics, and he's absolutely correct about
> it, although it is irrelevant since we're talking about two-value logic
> not semantics.
> 
> 
> 
> 

Thank you for the clarification Steven (D'Aprano).  To a certain level, 
I agree that semantics are important.  I hesitated about including that 
example in my post to begin with.  However, my point, and hopefully I'll 
be able to make it more clearly now, was that true/false is a useful way 
to think regarding logical statements like x == 3, but that when you are 
dealing with strings, or more accurately strings that represent 
language, you really aren't talking about truth any more, because in 
that context, truth cannot be divorced from semantics--somethingness, on 
the other hand, can.

Conceptually, you have to go through "'something' is true, and 'nothing' 
is false" before it makes sense.

On the other hand, (to play devil's advocate for a moment), when you are 
dealing with comparison operators, you have to go through "true 
statements yield something and false statements yield nothing" before it 
makes sense, or rather "yield a nothing value."  So either way you think 
about it, you have to, in some cases, mentally convert from truthiness 
to somethingness or vice versa.  I don't find it as odious to mentally 
convert the comparison operators as I do the declarative statements.  I 
don't think it's just a personal preference either, because that way 
your mental processes are in sync with the way python works.  It 
evaluates if the statement is true and yields a something value, and a 
nothing value if it's false.  You are working with the Tao of Python, if 
you'll forgive the analogy.  However thinking in terms of truth and then 
saying that all statements that exist are true works, but runs counter 
to what is going on behind the scenes.

Or maybe it doesn't, if everything's getting converted implicitly to 
bool anyway.  Maybe it is just personal preference after all.  But then 
bools are assigned "something" and "nothing" values

This stuff is tricky, but I'm enjoying trying to wrap my mind around it, 
and appreciating the comments and critiques.

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


Get pexpect to work

2006-10-28 Thread Jurian Sluiman




Hi all,
I'm trying to build a program to set up a vpn connection. I'm using pexpect to handle this, but I can't get it to work. 
The sendline() is causing troubles. I tested it in the interactive promt, with these results:

>>> import pexpect
>>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf")
>>> child.expect(".* password .*: ")
0
>>> child.sendline("[here_my_password]")
7

The sendline returns an exit code 7, but I don't what it should be. I saw an example here, where sendline returns an exit code 10: http://www.jinx.com/forum/topic.asp?TOPIC_ID=53947. After this peace of code, I don't have a vpn connection. I'm sure my password is correct. What's going wrong?

Thanks in advance,
Jurian Sluiman



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

Re: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees

2006-10-28 Thread sébastien martini
Hi,

> I was primarily talking about language support. For quite some time,
> the compiler package wasn't able to compile the Python standard library,
> until Guido van Rossum (and others) brought it back to work at the last
> PyCon. It would simply reject certain more recent language constructs.
> In the process of fixing it, it was also found to deviate from the
> normal language definition, i.e. it would generate bad code.
>
> Many of these are fixed, but it wouldn't surprise me if there are
> still bugs remaining.

I don't know if it can hide some bugs or if the module has just never
been updated to support this bytecode but LIST_APPEND is never emitted.
In the module compiler, list comprehensions are implemented without
emitting this bytecode, howewer the current implementation seems to be
correct from syntax and execution point of view.

For example:
>>> src = "[a for a in range(3)]"
>>> co = compiler.compile(src, 'lc1', 'exec')
>>> co
 at 0x404927b8, file "lc1", line 1>
>>> dis.dis(co)
  1   0 BUILD_LIST   0
  3 DUP_TOP
  4 LOAD_ATTR0 (append)
  7 STORE_NAME   1 ($append0)
 10 LOAD_NAME2 (range)
 13 LOAD_CONST   1 (3)
 16 CALL_FUNCTION1
 19 GET_ITER
>>   20 FOR_ITER16 (to 39)
 23 STORE_NAME   3 (a)
 26 LOAD_NAME1 ($append0)
 29 LOAD_NAME3 (a)
 32 CALL_FUNCTION1
 35 POP_TOP
 36 JUMP_ABSOLUTE   20
>>   39 DELETE_NAME  1 ($append0)
 42 POP_TOP
 43 LOAD_CONST   0 (None)
 46 RETURN_VALUE
>>> co2 = compile(src, 'lc2', 'exec')
>>> co2
 at 0x40492770, file "lc2", line 1>
>>> dis.dis(co2)
  1   0 BUILD_LIST   0
  3 DUP_TOP
  4 STORE_NAME   0 (_[1])
  7 LOAD_NAME1 (range)
 10 LOAD_CONST   0 (3)
 13 CALL_FUNCTION1
 16 GET_ITER
>>   17 FOR_ITER13 (to 33)
 20 STORE_NAME   2 (a)
 23 LOAD_NAME0 (_[1])
 26 LOAD_NAME2 (a)
 29 LIST_APPEND
 30 JUMP_ABSOLUTE   17
>>   33 DELETE_NAME  0 (_[1])
 36 POP_TOP
 37 LOAD_CONST   1 (None)
 40 RETURN_VALUE

Cordially,

sébastien martini

-- 
http://seb.dbzteam.com

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


Re: unescape HTML entities

2006-10-28 Thread Jim

Rares Vernica wrote:
> How can I unescape HTML entities like " "?
Can I ask what you mean by "unescaping"?  Do you mean converting into
numeric references?  Into Unicode?

Jim

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


Re: question about True values

2006-10-28 Thread Georg Brandl
J. Clifford Dyer wrote:
> Georg Brandl wrote:
>> J. Clifford Dyer wrote:
>> 
>>>  >>> (1 > 0) < 1
>>> False
>>>  >>> 1 > 0 < 1
>>> True
>>>  >>> 1 > (0 < 1)
>>> False
>>>  >>> 10 > (0 < 1)
>>> True
>> 
>> I hope you know why this works the way it does.
>> 
>> Georg
> 
> Yes, I do understand why it works.  I couldn't have crafted it if I 
> didn't, but my point is that the reason why it works is not explainable 
> if you believe that you are dealing with booleans.

Okay, but you should have left off the second example, because it has nothing
to do with the others.

>  It's only 
> explainable if you recognize that you are actually dealing with 
> integers, and specifically, 1 and 0.  So the something/nothing dichotomy 
> combined with an understanding of what the comparison operation REALLY 
> does (yield a 1 or a 0) helps you understand where your result came 
> from, while thinking in terms of true/false will mislead you.

That's true. The only sensible thing to do, if you had "real" booleans, for
1 > True, would be to raise an exception.

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


Re: question about True values

2006-10-28 Thread J. Clifford Dyer
Georg Brandl wrote:
> J. Clifford Dyer wrote:
> 
>>  >>> (1 > 0) < 1
>> False
>>  >>> 1 > 0 < 1
>> True
>>  >>> 1 > (0 < 1)
>> False
>>  >>> 10 > (0 < 1)
>> True
> 
> I hope you know why this works the way it does.
> 
> Georg

Yes, I do understand why it works.  I couldn't have crafted it if I 
didn't, but my point is that the reason why it works is not explainable 
if you believe that you are dealing with booleans.  It's only 
explainable if you recognize that you are actually dealing with 
integers, and specifically, 1 and 0.  So the something/nothing dichotomy 
combined with an understanding of what the comparison operation REALLY 
does (yield a 1 or a 0) helps you understand where your result came 
from, while thinking in terms of true/false will mislead you.



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


unescape HTML entities

2006-10-28 Thread Rares Vernica
Hi,

How can I unescape HTML entities like " "?

I know about xml.sax.saxutils.unescape() but it only deals with "&", 
"<", and ">".

Also, I know about htmlentitydefs.entitydefs, but not only this 
dictionary is the opposite of what I need, it does not have " ".

It has to be in python 2.4.

Thanks a lot,
Ray

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


Re: correct parameter usage for "select * where id in ..."

2006-10-28 Thread saniac
paul wrote:
> Frank Millman schrieb:
> > If you want it to handle a variable number of values, you will have to
> > programmatically construct the sql statement with the appropriate
> > number of parameters.

Yes, I should have made it clear it was the variable part that was
hard.

> >>> vals = (1,2,3,4,5)
> >>> sql = "select * from table where value in ("+','.join("?"*len(vals))+")"
> >>> print sql
> 'select * from table where value in (?,?,?,?,?)'

Argh, I have a scripting language and I'm not building up strings
dynamically? What an idiot.

Thanks, that's just what I needed.

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


Re: gettext on Windows

2006-10-28 Thread Martin v. Löwis
[EMAIL PROTECTED] schrieb:
> Leo Kislov wrote:
> 
>> Try msgunfmt
>> http://www.gnu.org/software/gettext/manual/html_node/gettext_128.html#SEC128
>> to see if it can convert your files back to text.
> 
> Just tried it, and it was able to convert each of the .mo files back to
> text without any problems.

Then you should make a bug report (or, better yet, a patch). Apparently,
the Python gettext implementation is not able to process the MO files
you are passing.

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


Re: what is "@param" in docstrings?

2006-10-28 Thread Georg Brandl
[EMAIL PROTECTED] wrote:
> I'm starting to read about twisted and I keep seeing things like:
> [from twisted/internet/app.py]
> 
> def __init__(self, name, uid=None, gid=None, authorizer=None,
> authorizer_=None):
> """Initialize me.
> If uid and gid arguments are not provided, this application
> will
> default to having the uid and gid of the user and group who
> created it.
> 
> @param name: a name
> 
> @param uid: (optional) a POSIX user-id.  Only used on POSIX
> systems.
> 
> @param gid: (optional) a POSIX group-id.  Only used on POSIX
> systems.
> """
> _AbstractServiceCollection.__init__(self)
> self.name = name
> ...
> 
> What does the "@param" mean?  It looks like something meant to be
> machine readable.  Alas, googling on "@param" doesn't work...  It looks
> at first like a decorator, but that doesn't make much sense.

It's docstring markup that can be parsed by e.g. epydoc. It's borrowed
from JavaDoc's similar syntax.

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


Re: what is "@param" in docstrings?

2006-10-28 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
> What does the "@param" mean?  It looks like something meant to be
> machine readable.  Alas, googling on "@param" doesn't work...  It looks
> at first like a decorator, but that doesn't make much sense.

It's Epydoc's Epytext markup: .
-- 
http://mail.python.org/mailman/listinfo/python-list


what is "@param" in docstrings?

2006-10-28 Thread georgeryoung
I'm starting to read about twisted and I keep seeing things like:
[from twisted/internet/app.py]

def __init__(self, name, uid=None, gid=None, authorizer=None,
authorizer_=None):
"""Initialize me.
If uid and gid arguments are not provided, this application
will
default to having the uid and gid of the user and group who
created it.

@param name: a name

@param uid: (optional) a POSIX user-id.  Only used on POSIX
systems.

@param gid: (optional) a POSIX group-id.  Only used on POSIX
systems.
"""
_AbstractServiceCollection.__init__(self)
self.name = name
...

What does the "@param" mean?  It looks like something meant to be
machine readable.  Alas, googling on "@param" doesn't work...  It looks
at first like a decorator, but that doesn't make much sense.

-- George Young

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


Re: stripping parts of elements in a list

2006-10-28 Thread Paul Rubin
"CSUIDL PROGRAMMEr" <[EMAIL PROTECTED]> writes:
> ['amjad\n', 'kiki\n', 'jijiji\n']
> I am trying to  get rid of '\n' after each name.
>  to get list as
> ['amjad','kiki','jijiji']
> 
> But list does not have a strip function as string does have.
> 
> is there any solutions

a = ['amjad\n', 'kiki\n', 'jijiji\n']

b = [x.strip() for x in a]

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


stripping parts of elements in a list

2006-10-28 Thread CSUIDL PROGRAMMEr
folks,
I am  new to python.

I have a list made of elements

['amjad\n', 'kiki\n', 'jijiji\n']
I am trying to  get rid of '\n' after each name.
 to get list as
['amjad','kiki','jijiji']

But list does not have a strip function as string does have.

is there any solutions

Is there a way this can be done??

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Chetan
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> I want to rename a file, but only if the destination file name doesn't
> already exist.
> 
> I can do this:
> 
> if os.path.exists(dest):
> # skip file, raise an exception, make a backup...
> do_something_else() 
> else:
> os.rename(src, dest)
> 
> 
> But on a multi-user system, it is possible that dest is created in the
> time period between checking if it exists and attempting the rename.
> 
> Is there any way to prevent this? Or do I just try to keep the check and
> the rename as close together as possible, minimizing the chances and
> hoping for the best?
> 
> 
> -- 
> Steven.

The answer, unfortunately, depends on the platform. I haven't tried, but it
looks like rename() will fail on Win32 if the file already exists. On Unix, you
can use link to rename the file - which will not overwrite the file if it
exists. Then use unlink to remove the src file.

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


Re: ANN: wxPython 2.7.1.3

2006-10-28 Thread Tim N. van der Leeuw

Hendrik van Rooyen wrote:
> "Johann C. Rocholl" <[EMAIL PROTECTED]>wrote:
>
> 8<--
>
> > Oh, it's fun to be a speling fanatic! :-)
>
>
> six munce ago I could not even spell 'fatanic' - and now I are one...
>
> I wander what a speling fanatic is?
>

Someone who fanatically installs mod_speling every time he/she installs
Apache httpd anywhere

> - Hendrik

--Tim

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


Re: Where is __builtin__

2006-10-28 Thread Michel Claveau
Hi!

>> http://www.effbot.org/pyfaq/where-is-the-math-py-socket-py-regex-py-etc-source-file.htm

Yeaaahh!!!Finally a genuine URL;o)



-- 
@-salutations

Michel Claveau


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


Re: ANN: wxPython 2.7.1.3

2006-10-28 Thread Hendrik van Rooyen
"Johann C. Rocholl" <[EMAIL PROTECTED]>wrote:

8<--

> Oh, it's fun to be a speling fanatic! :-)


six munce ago I could not even spell 'fatanic' - and now I are one...

I wander what a speling fanatic is?

- Hendrik

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


Re: Where do nested functions live?

2006-10-28 Thread Diez B. Roggisch
> If I may turn the issue around, I could see a need for an inner function 
> to be able to access the variables of the outer function, the same way a 
> function can access globals. Why? Because inner functions serve to 
> de-multiply code segments one would otherwise need to repeat or to 
> provide a code segment with a name suggestive of its function. In either 
> case the code segment moved to the inner function loses contact with its 
> environment, which rather mitigates its benefit.

Maybe I'm dense here, but where is your point? Python has nested lexical 
scoping, and while some people complain about it's actual semantics, it 
works very well:

def outer():
outer_var = 10
def inner():
return outer_var * 20
return inner

print outer()()



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


Re: Where do nested functions live?

2006-10-28 Thread Frederic Rentsch
Fredrik Lundh wrote:
> Steven D'Aprano wrote:
>
>   
>> I defined a nested function:
>>
>> def foo():
>> def bar():
>> return "bar"
>> return "foo " + bar()
>>
>> which works. Knowing how Python loves namespaces, I thought I could do
>> this:
>>
>> 
> foo.bar()
>   
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> AttributeError: 'function' object has no attribute 'bar'
>>
>> but it doesn't work as I expected.
>>
>> where do nested functions live?
>> 
>
> in the local variable of an executing function, just like the variable 
> "bar" in the following function:
>
>  def foo():
>  bar = "who am I? where do I live?"
>
> (yes, an inner function is *created* every time you execute the outer 
> function.  but it's created from prefabricated parts, so that's not a 
> very expensive process).
>
> 
>
>   
If I may turn the issue around, I could see a need for an inner function 
to be able to access the variables of the outer function, the same way a 
function can access globals. Why? Because inner functions serve to 
de-multiply code segments one would otherwise need to repeat or to 
provide a code segment with a name suggestive of its function. In either 
case the code segment moved to the inner function loses contact with its 
environment, which rather mitigates its benefit.
   If I have an inner function that operates on quite a few outer 
variables it would be both convenient and surely more efficient, if I 
could start the inner function with a declaration analogous to a 
declaration of globals, listing the outer variables which I wish to 
remain writable directly.
   I guess I could put the outer variables into a list as argument to 
the inner function. But while this relieves the inner function of 
returning lots of values it burdens the outer function with handling the 
list which it wouldn't otherwise need.

Frederic


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


Re: Need help (Basic python)...what did I do wrong?

2006-10-28 Thread Fredrik Lundh
frankie_85 wrote:

> Hmmmafter more trials and errors, I think what I did wrong is along
> on these lines:
> 
> a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3)))
> b_2 = math.sqrt(math.fabs(b)) + 5((math.pow(b,3)))
> c_3 = math.sqrt(math.fabs(c)) + 5((math.pow(c,3)))
> d_4 = math.sqrt(math.fabs(d)) + 5((math.pow(d,3)))
> e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3)))
> 
> but I still don't understand though why the variable a, b, c, d, e
> becomes an int type even though I have already specified the user input
> to be floating point?

hint: besides the variables, what other values are involved in your 
calculations?  do you see any integers among them?



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


Re: Need help (Basic python)...what did I do wrong?

2006-10-28 Thread Paul Rubin
"frankie_85" <[EMAIL PROTECTED]> writes:
> e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3)))
> 
> but I still don't understand though why the variable a, b, c, d, e
> becomes an int type even though I have already specified the user input
> to be floating point?

if you want to multiply two numbers you need to put a * between them.
* is the multiplication symbol in Python and most other languages.

When you say f(x) that says "there is a function x and Python should
call it on the value x".  When you say 5(x), that says "there is
a function 5 and Python should call it with the value x".  And then
when you try to actually do that, Python says "hey I can't do that,
5 isn't a function, it's an integer".

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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Wolfgang Draxinger
Diez B. Roggisch wrote:

>> 1: Open the file with os.open
>> 
>> 2: Lock the file exclusively -> no other process can now
>> access it.
>> 
>> 3: Use rename to rename the file; this causes a file system
>> level implicit unlink of the old file (it dissappears from the
>> file system) but the opening process can still access it.
>> 
>> 4: close the file -> the lock is removed and the rename
>> finalized.

The open is to happen on the new file name with O_CREAT | O_EXCL
flags. Sorry, I forgot that to mention explicitly. However I
have not tried it yet, but it should work.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread J. Clifford Dyer
dan84 wrote:
> I don't understand this error , in the (Apache) errorlog I read this
> message :
> 
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
> mod_python.apache.\n
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
> used "['C:Python24python24.zip', '.DLLs', '.lib',
> '.libplat-win', '.liblib-tk',
> 'C:ProgrammiApache GroupApache2bin']".

The four backslashes look okay to me, since there are "s outside the 
list, viz:

 >>> mylist = [ r'C:\Python24' ]
 >>> mylist
['C:\\Python24']
 >>> repr(mylist)
"['C:Python24']"


Back to your question: Where is mod_python located?  Is it anywhere in 
this path?  Go to each directory/zip file, and see if you find 
mod_python.  If so, is your base directory where you think it is?  (use 
os.getcwd() to find out).  If mod_python is still not in there, where is 
it?  Now add THAT directory to your Python path.

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


Re: Need help (Basic python)...what did I do wrong?

2006-10-28 Thread frankie_85
Thanks for some of the helps guys.

Hmmmafter more trials and errors, I think what I did wrong is along
on these lines:

a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3)))
b_2 = math.sqrt(math.fabs(b)) + 5((math.pow(b,3)))
c_3 = math.sqrt(math.fabs(c)) + 5((math.pow(c,3)))
d_4 = math.sqrt(math.fabs(d)) + 5((math.pow(d,3)))
e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3)))

but I still don't understand though why the variable a, b, c, d, e
becomes an int type even though I have already specified the user input
to be floating point?

Once again thanks for all your help

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


Re: Where is __builtin__

2006-10-28 Thread Fredrik Lundh
ArdPy wrote:

> Most of the other modules have an accompanying python source file. But
> that is not the case with __builtin__. What might be the reason? Isn't
> __builtin__ written in python?

http://www.effbot.org/pyfaq/where-is-the-math-py-socket-py-regex-py-etc-source-file.htm



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


Where is __builtin__

2006-10-28 Thread ArdPy
Most of the other modules have an accompanying python source file. But
that is not the case with __builtin__. What might be the reason? Isn't
__builtin__ written in python?

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


Re: Need help (Basic python)...what did I do wrong?

2006-10-28 Thread Fredrik Lundh
Steven D'Aprano wrote:

> I don't think the restrictions against collusion are meant to prohibit
> simple "what does this error message mean?" type questions. It would be
> a funny sort of learning process that forced students to live in a
> vacuum, never discussing their topic with anyone else, never asking the
> most trivial questions.

the python-tutor policy is quite reasonable:

 http://effbot.org/pyfaq/tutor-what-is-the-policy-on-homework.htm



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


Re: PROBLEM with MOD_PYTHON

2006-10-28 Thread Chetan
"dan84" <[EMAIL PROTECTED]> writes:
> I don't understand this error , in the (Apache) errorlog I read this
> message :
> 
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
> mod_python.apache.\n
> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
> used "['C:Python24python24.zip', '.DLLs', '.lib',
> '.libplat-win', '.liblib-tk',
> 'C:ProgrammiApache GroupApache2bin']".
> [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter
> callback found.
> [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler:
> Can't get/create interpreter.
> 
> I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3
> I have read all the manuals, but I don't understand where I am wrong.
> 
> thanks so much
>Marco.
Even if there is nothing Apache specific, doesn't it look odd that the
path has 4 backslashes? Even accounting for half of those being added at the
time of printing, it would appear that Apache is trying to use the path that 
contains two backslashes as path separator but there needs to be only one. 

Chetan

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


Re: change keybindings for pygtk treeview

2006-10-28 Thread Fabian Braennstroem
Hi,

* Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am just testing pygtk/glade out and wonder, if I am able
> to change the keybindings. E.g. the treeview searches by
> default for the entries beginning with the typed keystroke;
> moving to the next row works as usual with the Down key. Now
> I would like to change the key bindings to e.g. 'j' to move
> to the next row (just like in vim) and to use a 'Ctrl' key
> combination to search for a certain word beginning with the
> typed key stroke.

I just found out, that I am able to turn it of with
'treeview.set_enable_search(False)'. Works nice.

An option would be, to toggle the searching function with
some keystroke, e.g. 'Ctrl-s'. And set a key binding for the
movement to 'j' and 'k' when the search mode is disabled. I
think I could do it somehow with the 'accelgroup' function,
but did not find enough information to get a clue out of it.

Does anybody have an idea?

In a small curses based file manager (lfm) there is an
assignment of keybindings via a keytable

keytable = {
# movement
ord('p'): 'cursor_up',
ord('k'): 'cursor_up',
ord('K'): 'cursor_up2',
ord('P'): 'cursor_up',
curses.KEY_UP: 'cursor_up',
ord('n'): 'cursor_down',
ord('j'): 'cursor_down',
ord('J'): 'cursor_down2',
ord('N'): 'cursor_down',
...

Would that work in any way for a pygtk program too?


Greetings!
 Fabian

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


Re: Python crashed when importing SOAPpy, printing out 'usage:copy source destination'

2006-10-28 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I still can't understand it. If i rename the 'copy.py' to 'a.py',
> there will be no problem.

hint: when it works, try typing the following into the interpreter:

 >>> import copy
 >>> copy.__file__



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


Re: Python crashed when importing SOAPpy, printing out 'usage:copy source destination'

2006-10-28 Thread [EMAIL PROTECTED]
Fredrik Lundh wrote:

>
> this is how things work: Python doesn't distinguish between script
> files and module files; a module is simply a script that defines a
> bunch of things.
>
> if you want to create something that can work both as a script and a
> module, see:
>
> http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm
>
> 

I still can't understand it. If i rename the 'copy.py' to 'a.py',
there will be no problem.
As follows:
###
haiyun# ls
copy.py
haiyun# python
Python 2.4.1 (#2, Mar 28 2006, 21:00:14)
[GCC 3.4.2 [FreeBSD] 20040728] on freebsd5
Type "help", "copyright", "credits" or "license" for more information.
>>> import SOAPpy
usage:copy source destination

haiyun# ls
copy.py  copy.pyc
##

it seems that the copy.py in the PWD has been interpreted as the
SOAPpy module imported.
So i rename the copy.py to a.py.
As follows:

haiyun# ls
copy.py  copy.pyc
haiyun# rm copy.pyc
haiyun# mv copy.py a.py
haiyun# ls
a.py
haiyun# python
Python 2.4.1 (#2, Mar 28 2006, 21:00:14)
[GCC 3.4.2 [FreeBSD] 20040728] on freebsd5
Type "help", "copyright", "credits" or "license" for more information.
>>> import SOAPpy
>>>
#

Everything is all right!
The content of the copy.py(a.py) is:
#
haiyun# cat a.py
#!env python
usage="usage:copy source destination\n"
import sys
len=len(sys.argv)
if len!=3 :
print usage
sys.exit()
#

I guess something in the SOAPpy module conflects with the copy.py in
the PWD.
So what it happened?

>Regards,
>jiang.haiyun

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


latest numpy & scipy - incompatible ?

2006-10-28 Thread robert
I'm using latest numpy & scipy. What is this problem ? :

>>> import scipy.stats
RuntimeError: module compiled against version 102 of C-API but this version 
of numpy is 109
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\PYTHON23\Lib\site-packages\scipy\stats\__init__.py", line 7, in ?
from stats import *
  File "C:\PYTHON23\Lib\site-packages\scipy\stats\stats.py", line 191, in ?
import scipy.special as special
  File "C:\PYTHON23\Lib\site-packages\scipy\special\__init__.py", line 8, in ?
from basic import *
  File "C:\PYTHON23\Lib\site-packages\scipy\special\basic.py", line 8, in ?
from _cephes import *
ImportError: numpy.core.multiarray failed to import
>>> import numpy.core.multiarray
>>> 
>>> import scipy
>>> scipy.__version__
'0.5.1'
>>> numpy.__version__
'1.0'
>>> 


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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Diez B. Roggisch
Wolfgang Draxinger schrieb:
> Steven D'Aprano wrote:
> 
>> I want to rename a file, but only if the destination file name
>> doesn't already exist.
>>
>> I can do this:
>>
>> if os.path.exists(dest):
>> # skip file, raise an exception, make a backup...
>> do_something_else()
>> else:
>> os.rename(src, dest)
>>
>>
>> But on a multi-user system, it is possible that dest is created
>> in the time period between checking if it exists and attempting
>> the rename.
>>
>> Is there any way to prevent this? Or do I just try to keep the
>> check and the rename as close together as possible, minimizing
>> the chances and hoping for the best?
> 
> 1: Open the file with os.open
> 
> 2: Lock the file exclusively -> no other process can now access
> it.
> 
> 3: Use rename to rename the file; this causes a file system level
> implicit unlink of the old file (it dissappears from the file
> system) but the opening process can still access it.
> 
> 4: close the file -> the lock is removed and the rename
> finalized.

Where does that help for new files? The OP was right in assuming that a 
race condition could occur when he tests for a file & then tries to 
create it, as in the meantime it could have been created.

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


Re: what are the most frequently used functions?

2006-10-28 Thread Barry Margolin
In article <[EMAIL PROTECTED]>,
 "Xah Lee" <[EMAIL PROTECTED]> wrote:

> I had a idea today.
> 
> I wanted to know what are the top most frequently used functions in the
> emacs lisp language. I thought i can write a quick script that go thru
> all the elisp library locations and get a word-frequency report i want.
> 
> I started with a simple program:
> http://xahlee.org/p/titus/count_word_frequency.py
> 
> and applied it to a Shakespeare text. Here's a sample result:
> http://xahlee.org/p/titus/word_frequency.html
> 
> Then, i wrote a more elaborate one that recurse thru directories to
> work on elisp code treasury.
> 
> The code is here:
> http://xahlee.org/x/count_word_frequency.py
> 
> and i got a strange result. The word “the” appeared on the top,
> along with many other English words. I quickly realized that these are
> due to lisp function's doc strings. (not comments)
> 
> At this point, it dawned on me that there's no easy way to work around
> this, Unless, i write this script in elisp which has functions that
> read lisp code and can easily filter out doc strings.

For Lisp, just look for symbols that are immediately preceded by ( or 
#'.  The tokens after ( are not always functions, since this is also 
used for constructing literal lists and for subforms of special 
operators (e.g. the variable names in LET bindings) but I think the ones 
that aren't functions will have low enough frequency that they won't 
impact the results.

Perl would be harder, I think.  For ordinary function calls you can look 
for a word followed by (, but built-in functions allow use without 
parentheses around the parameters.

-- 
Barry Margolin, [EMAIL PROTECTED]
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Reading standard input

2006-10-28 Thread Fredrik Lundh
MindClass wrote:

> The program shows a license text, then the user has to accept the
> license (or not).
> Is there another way to get text from console? (that using
> sys.stdin.read)

http://effbot.org/pyref/raw_input.htm

> I also would to trap the KeyboardInterrupt for that doesn't show that
> message. How would it be possible?

any reason you cannot use an ordinary try-except for that?




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


Re: Where do nested functions live?

2006-10-28 Thread Andrea Griffini
Fredrik Lundh wrote:
> Ben Finney wrote:
> 
>> If you want something that can be called *and* define its attributes,
>> you want something more complex than the default function type. Define
>> a class that has a '__call__' attribute, make an instance of that, and
>> you'll be able to access attributes and call it like a function.
> 
> I turned Steven's question and portions of the answers into a Python FAQ 
> entry:
> 
> http://effbot.org/pyfaq/where-do-nested-functions-live.htm
> 
> Hope none of the contributors mind.

I'd add that while in some respect "def x" is like
an assigment to x ...

 >>> def f():
global g
def g():
 return "Yoo!"
 >>> f()
 >>> g()
'Yoo!'

in some other respect (unfortunately) it's not a regular assignment

 >>> x = object()
 >>> def x.g():

SyntaxError: invalid syntax
 >>>

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


Re: using mmap on large (> 2 Gig) files

2006-10-28 Thread Chetan
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Martin v. Löwis wrote:
> > sturlamolden schrieb:
> >
> > > And why doesn't Python's mmap take an offset argument to handle large
> > > files?
> >
> > I don't know exactly; the most likely reason is that nobody has
> > contributed code to make it support that. That's, in turn, probably
> > because nobody had the problem yet, or nobody of those who did
> > cared enough to implement and contribute a patch.
> 
> Or because no one cared enough to test a patch that was produced 2.5
> years ago (not directed at Martin, just pointing out why the patch
> stalled).
> 
>   http://python.org/sf/708374
> 
> With just a little community support, this can go in.  I suppose now
> that we have the buildbots, we can check in untested code and test it
> that way.  The patch should be reviewed.
> 
> n
I made the changes before I saw this. However, the patch seems to be quite
dated and some of the changes are very interesting, especially if they were
tested for the special conditions they are supposed to handle and 
if they were made after some discussion. 
I can submit my patch as it is, but I am working on making some of the other
changes I had in mind for the mmap to be useful.
Some of the other changes would make more sense for py3k, if it supports a byte
array object, but I haven't looked at py3k at all.

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

Re: question about True values

2006-10-28 Thread Antoon Pardon
On 2006-10-28, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Fri, 27 Oct 2006 17:35:58 +, Antoon Pardon wrote:
>
>> On 2006-10-27, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> 
>> So
>> it seems that python has generalised the len function to provide
>> the number of elements in the container. 
>
> Sure. But what about a container where the number of elements isn't
> well-defined, e.g. iterators?

I see you already discovered iterators won't help you here.

> Or something like a binary tree, where
> counting the number of items is relatively expensive, but telling whether
> it is empty or not is cheaper than dirt?

Counting the items in a binary tree and a dictionary are about equally
expensive. I guess that in practice a count attribute will keep score.

> Here's a real example: it can be expensive to count the number of files in
> a directory -- on my PC, it takes almost a third of a second to count a
> mere 15,000 files in a single directory. (There may be a more sensible
> way of counting the number of files under Linux than ls | wc -l, but if
> so I don't know it.) But why slog through 15,000 files if all you need to
> know is if the directory is empty or not? As soon as you see one file, you
> know it isn't empty. Stop counting! Who cares whether there is one file or
> 15,000 files?

I don't know why you consider this a real example. The only time I care
whether a dictionary is empty or not is if I want to remove it and in
that case it better to just try to remove the dictionary and catch
the exception. Testing for emptyness or counting files in a directory
isn't robust anyway. You never know whether or not some other process
created a new file or deleted one between the time you tested and
the moment 

>> I have written a Tree class(*). It can be used as a drop in replacement
>> anywhere where a directory is used, as long as there is a full order
>> relationship in the key domain. That tree class provides a __len__
>> method that will anser with the number of items in the tree just
>> as a directory would and I see nothing wrong with that.
>
> And I'm happy for you. But imagine a container object that maps a URL to
> some piece of data fetched from the Internet. Counting the size of the
> Internet is infeasible -- even if you were willing to try, it could take
> *weeks* of computation to determine! But one can certainly tell if there
> is an Internet out there or not. Such an object would always be True,
> unless you had lost network connectivity.

Indeed and you could loose connectivity between your testing for it and
making your first connection and your URL's turn bogus

> My container object will work perfectly well with "if internet" but not
> with "if len(internet) > 0". You could even iterate over it, sort
> of, by following links from one site to another.

And in what way exactly would this container object of yours be
compatible with code that would expect a list like object? I guess
not very much.

> But why are you checking the length of a container before iterating over
> it? If you are writing something like this:
>
> if len(container) != 0:
> for item in container:
> do_something()
>
> then just stop it!

The same goes for

  if container:
  for iten in container:
  do_something()

If your are writing the above you should stop it just the same.

>> Of course I can't account for all possible ways someone wishes to
>> write a class, but I don't see what is wrong with counting on
>> the fact that an empty container has a length of zero.
>
> Because you shouldn't assume containers have well-defined lengths unless
> you actually care about the length, and you shouldn't assume that length
> of zero implies "nothing to see here" unless you *know* that this is the
> case.

I think these assumptions are equivallent with assuming it is a
container.

> You should leave defining empty up to the container class itself.
> Otherwise, you might be right 99 times in a hundred, but that hundredth
> time will bite you.

Just as your assumption will bite you in case of numpy arrays.

>> I can write a container class where the truth value of an object
>> is independent of whether or not the object is empty and then
>> the "if obj:" idiom will fail to provide true polymorphism too.
>
> A class that deliberate breaks the semantics of Python truth testing just
> for the sake of breaking code really is a pathological case. Polymorphism
> doesn't mean "will work with anything without exception".

I find that your idea of what a container can lack also against the
semantics of Python.

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


Re: question about True values

2006-10-28 Thread Antoon Pardon
On 2006-10-28, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Fri, 27 Oct 2006 18:22:28 +, Antoon Pardon wrote:
>
 And how do I express that a number has to be greater than
 100 into a Nothing vs Something dichotomy? Declare all
 greater numbers as Something and the rest as Nothing?
>>>
>>> Well, would you declare numbers less than 100 False?
>> 
>> No but the condition: x > 100, will map all numbers to
>> either True or False. Can you provide a condition that will
>> provide a mapping to Nothing and Something? Without
>> artificially mapping False to Nothing and True to Something?
>
> A > B maps to max(0, A-B)
>
> or more verbosely, "Remove B items from A items, stopping when there are
> no more items to remove. What is left over? Something or Nothing?"

This mapping no longer works if you are not working with numbers.

>>> A = [1,2] 
>>> B = [3]
>>> A > B
False
>>> max(0, A - B)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for -: 'list' and 'list'

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


Re: Mass-Renaming folders win32

2006-10-28 Thread Tim Chase
> I've a folder structure like this :
> 
> "Folder A"
> |--> "1"
> |--> "2"
> ---> "3"
> 
> "Folder B"
> |--> "4"
> ---> "5"
> 
> And I want to obtain a structure like this :
> 
> "Folder A - 1"
> "Folder A - 2"
> "Folder A - 3"
> "Folder B - 4"
> "Folder B - 5"
> 
> Can someone help me ? I am python beginner

I'd try something like:

import os
from shutil import move

for path, dirs, files in os.walk('.'):
   if path <> os.curdir and files:
 # the "2:" strips of the ".[os.sep]" at the beginning
 newdir = path[2:].replace(os.sep, ' - ')
 try:
   os.mkdir(newdir)
   for f in files:
 try:
   move(
 os.sep.join([path, f]),  #the old location
 os.sep.join([newdir, f]) #the new location
 )
 except:
   print 'Could not move %s to %s' % (f, newdir)
 except:
   print 'Could not create %s' % newdir



It doesn't clean up the original directories along the way, but 
that may be better, depending on the nesting depth of your 
directories...you'd want to make sure that you deal with all the 
files within a directory before deleting it.

Feel free to tweak as needed.

-tkc






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


Re: Sending mouse events on Windows

2006-10-28 Thread Radu Ciurlea
Looks good, but I downloaded it and it's not that helpful. It can only
simulate clicks to interface objects. I need to actually move the mouse
pointer around. I just want to write a small app that'll enable me to
use my mobile phone as a mouse via Bluetooth, but not being able to
move the pointer kind of holds me back :)

Radu

On Oct 28, 1:15 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Radu Ciurlea wrote:
> > I want to write a program that can generate mouse events. I'd like to
> > actually be able to control the pointer and generate clicks. Any
> > pointers on modules I could use for doing this? Any suggestions are
> > welcome.something like
>
>  http://www.tizmoi.net/watsup/intro.html
> 
> might be useful.
> 
> 

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


PROBLEM with MOD_PYTHON

2006-10-28 Thread dan84
I don't understand this error , in the (Apache) errorlog I read this
message :

[Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import
mod_python.apache.\n
[Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being
used "['C:Python24python24.zip', '.DLLs', '.lib',
'.libplat-win', '.liblib-tk',
'C:ProgrammiApache GroupApache2bin']".
[Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter
callback found.
[Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler:
Can't get/create interpreter.

I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3
I have read all the manuals, but I don't understand where I am wrong.

thanks so much
   Marco.

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


Reading standard input

2006-10-28 Thread MindClass
The program shows a license text, then the user has to accept the
license (or not).
Is there another way to get text from console? (that using
sys.stdin.read)

foo = sys.stdin.read(3)
if foo != 'yes'
sys.exit(0)

I also would to trap the KeyboardInterrupt for that doesn't show that
message. How would it be possible?

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


Re: PyQt-x11-gpl-3.16 compile error

2006-10-28 Thread David Boddie
On Saturday 28 October 2006 06:42, [EMAIL PROTECTED] wrote:

> here is th output :
> 
> [EMAIL PROTECTED] PyQt-x11-gpl-3.16]# python configure.py -q
> /usr/lib/qt-3.3/ -w

[...]

> Checking to see if the qtcanvas module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the qtnetwork module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the qttable module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the qtxml module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the qtgl module should be built...
> In file included from cfgtest.cpp:1:
> /usr/lib/qt-3.3/include/qgl.h:79:20: error: GL/gl.h: No such file or
> directory
> /usr/lib/qt-3.3/include/qgl.h:80:21: error: GL/glu.h: No such file or
> directory
> Checking to see if the qtui module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the qtsql module should be built...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Checking to see if the QAssistantClient class is available...
> /usr/bin/ld: cannot find -lmng
> collect2: ld returned 1 exit status
> Creating features file...
> /usr/bin/ld: cannot find -lXext
> collect2: ld returned 1 exit status
> Error: Unable to build mkfeatures utility.

OK. It looks like the directory you specified using the -q option
isn't the one you need. You haven't said whether you installed Qt from
source, or whether it was installed with the rest of your Linux
distribution.

If you need to use the -q option (if the script doesn't work without
it), try using /usr/share/qt3 - this works for Debian-based
distributions, and may also work for other distributions.

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


Re: what are the most frequently used functions?

2006-10-28 Thread Dr.Ruud
robert schreef:

> read more of the context and answer to the OP

That OP is invisible in most relevant contexts.

-- 
Affijn, Ruud

"Gewoon is een tijger."
-- 
http://mail.python.org/mailman/listinfo/python-list


Mass-Renaming folders win32

2006-10-28 Thread evaisse
I've a folder structure like this :

"Folder A"
|--> "1"
|--> "2"
---> "3"

"Folder B"
|--> "4"
---> "5"


And I want to obtain a structure like this :

"Folder A - 1"
"Folder A - 2"
"Folder A - 3"
"Folder B - 4"
"Folder B - 5"

Can someone help me ? I am python beginner

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


Re: Leo 4.4.2 final released: config bug

2006-10-28 Thread Edward K. Ream
Drat.  Leo does not remember recent files unless .leoRecentFiles.txt exists 
in Leo's config directory.  Alas, that file is (on purpose) not part of the 
distribution, and Leo only creates .leoRecentFiles.txt in the users home 
directory.

So most users will have to create .leoRecentFiles.txt in Leo's config 
directory 'by hand': it can start life as an empty text file.

My apologies for this error.  It will be fixed in Leo 4.4.2.1 in a few days.

Edward

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: gettext on Windows

2006-10-28 Thread russ . phillips . nospam
Leo Kislov wrote:

> Try msgunfmt
> http://www.gnu.org/software/gettext/manual/html_node/gettext_128.html#SEC128
> to see if it can convert your files back to text.

Just tried it, and it was able to convert each of the .mo files back to
text without any problems.

Russ

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


Re: Import if condition is correct

2006-10-28 Thread Steve Holden
MindClass wrote:
> Steve Holden wrote:
> 
>>I'm guessing that you think this might be necessary to avoid importing
>>the same module multiple times: it's not. Python only runs the module's
>>code the first time the module is imported into a program. A further
>>import statement effectively does noting, because the interpreter sees
>>(from an entry in the sys.modules dictionary) that the module is already
>>present.
>>
> 
> The problem is that I've to import different libraries according to the
> ORM (SQLObject, SQLAlchemy, etc)
> 
So why the need for global variables?

if MySQL_wanted:
 import MySQLdb as db
elif sqlite_wanted:
 import pysqlite as db
else:
 import psycopg2 as db

conn = db.connect(...)
...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: what are the most frequently used functions?

2006-10-28 Thread robert
Jürgen Exner wrote:
>> Xah Lee wrote:
>>> I had a idea today.
> 
> Oh, really? You should mark your calendar and celebrate the day annually!!!
> 
>>> I wanted to know what are the top most frequently used functions in
>>> the emacs lisp language.
> 
> And the relationship with Perl, Python, Java is exactly what?

read more of the context and answer to the OP
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python GUIs comparison (want)

2006-10-28 Thread Jarek Zgoda
Christophe napisał(a):

>> PyGtk:
>> Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular
>> on some platforms; active development community
>> Con: Not native on OS X
> 
> You forgot that it is rather buggy on Win32 ( in my experience )

Didn't observe any W32-specific bugy behaviour during over 2 years of
development of JPA using PyGTK.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the cleanest way to for a module to access objects from the script that imports it?

2006-10-28 Thread robert
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I am new to python and am currently writing my first application. One
> of the problems I quickly ran into, however, is that python's imports
> are very different from php/C++ includes in the sense that they
> completely wrap the imported script in a module object. One of the
> problems with this was that a plugin system that I am making requires
> use of objects, classes and the such from the original script. Thus, on
> one hand, I am hesitant to use execfile(), since I *do* want to wrap
> the plugin up, but on the other hand, I want the plugin to be able to
> use functions from the original script. Any ideas?
> 

you can import __main__ in your module: import __main__; __main__.app_xfunc(y)

But for most cases I'd say your "problem" is an indication of weak design 
(thanks to Pythons clear module tech).

Maybe:

* if the funcs are tools, put them in an extra module

* if its about app-global parameters(tools), make a module "myglob" or so

* if the funcs have app-context, hand over/set them as "callback" functions or 
iterators like ..

def app_xfunc(par):pass
mody.set_xhandler(app_xfunc)
mody.yfunc(a,b,..., cbProgress=app_xfunc)
def app_xstepper():
yield next
mody.yfunc2(a,b,..., step=app_xstepper)
...


* if you have 2 moduls on equal dependency level and each needs the other 
(sometimes) - thus you don't want to have one big module, then cross import 
them ..

#modx
import mody
def fx():
mody.doy()
#mody
import modx
def fy():
modx.dox()


Python allows everything most easy for that kind of problems of all langs I 
know of. Mainly the fact that a module is a real object in Python provides 
tremendous flexibility and self-similarity of techniques. Ruby for example is 
weired - even really bad - in this.

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


ANN: Leo 4.4.2 final released

2006-10-28 Thread Edward K. Ream
Leo 4.4.2 final is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

This release fixes a few bugs and adds support for controlling Leo from
Emacs using pymacs. There are no known significant bugs in this version of 
Leo.

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.2:

- You can now store settings in myLeoSettings.leo without fear of those
settings
  being changed by cvs updates or in future versions of Leo.
- Leo's vnode and tnode classes are now completely independent of the rest
of Leo.
  Some api's have been changed.  This 'big reorg' and may affect scripts and
plugins.
- Leo's vnode and tnode classes can optionally be compatible with ZODB
databases,
  i.e., they can optionally derive from ZODB.Persistence.Persistent.
  See Chapter 17: Using ZODB with Leo for details.
- The leoOPML plugin defines commands to read and write OPML files.
- The slideshow plugin allows Leo to run slideshows defined by @slideshow
and @slide nodes.
- The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo
outlines.
- Much faster navigation through the outline.
- When focus is in the outline pane, you can move to headlines by typing the
first letter of headlines.
- The find command now optionally closes nodes not needed to show the node
containing the present match.
- Numerous changes that make Leo easier to use without using a mouse,
including new commands and options.
- Many new minibuffer commands now appear in the Cmds menu.
- A sax parser can now optionally read .leo files.
- Fixed numerous bugs.

Links:
--
Leo:http://webpages.charter.net/edreamleo/front.html
What's new: http://webpages.charter.net/edreamleo/new-4-4-2.html
Home:   http://sourceforge.net/projects/leo/
Download:   http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:http://leo.tigris.org/source/browse/leo/
Leo's Wiki: http://leo.zwiki.org/FrontPage
Wikipedia:  http://en.wikipedia.org/wiki/Leo_%28text_editor%29
Quotes: http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


subprocess decoding?

2006-10-28 Thread MC
Hi!

On win-XP (french), when I read subprocess (stdout), I must use 
differents decoding (cp1252,cp850,cp437, or no decoding), depending of 
the "launch mode" of the same Python's script:
  - from command-line
  - from start+run
  - from icon
  - by Python-COM-server
  - etc.

(.py & .pyw can also contribute)


How to know, on the fly, the encoding used by subprocess?


Thanks by advance

-- 
@-salutations

Michel Claveau


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


Re: Safely renaming a file without overwriting

2006-10-28 Thread Wolfgang Draxinger
Steven D'Aprano wrote:

> I want to rename a file, but only if the destination file name
> doesn't already exist.
> 
> I can do this:
> 
> if os.path.exists(dest):
> # skip file, raise an exception, make a backup...
> do_something_else()
> else:
> os.rename(src, dest)
> 
> 
> But on a multi-user system, it is possible that dest is created
> in the time period between checking if it exists and attempting
> the rename.
> 
> Is there any way to prevent this? Or do I just try to keep the
> check and the rename as close together as possible, minimizing
> the chances and hoping for the best?

1: Open the file with os.open

2: Lock the file exclusively -> no other process can now access
it.

3: Use rename to rename the file; this causes a file system level
implicit unlink of the old file (it dissappears from the file
system) but the opening process can still access it.

4: close the file -> the lock is removed and the rename
finalized.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what are the most frequently used functions?

2006-10-28 Thread J�rgen Exner
> Xah Lee wrote:
>> I had a idea today.

Oh, really? You should mark your calendar and celebrate the day annually!!!

>> I wanted to know what are the top most frequently used functions in
>> the emacs lisp language.

And the relationship with Perl, Python, Java is exactly what?

jue 


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


Re: Import if condition is correct

2006-10-28 Thread MindClass

Steve Holden wrote:
> I'm guessing that you think this might be necessary to avoid importing
> the same module multiple times: it's not. Python only runs the module's
> code the first time the module is imported into a program. A further
> import statement effectively does noting, because the interpreter sees
> (from an entry in the sys.modules dictionary) that the module is already
> present.
>
The problem is that I've to import different libraries according to the
ORM (SQLObject, SQLAlchemy, etc)

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


Re: what are the most frequently used functions?

2006-10-28 Thread robert
Xah Lee wrote:
> I had a idea today.
> 
> I wanted to know what are the top most frequently used functions in the
> emacs lisp language. I thought i can write a quick script that go thru
> all the elisp library locations and get a word-frequency report i want.
> 
> I started with a simple program:
> http://xahlee.org/p/titus/count_word_frequency.py
> 
> and applied it to a Shakespeare text. Here's a sample result:
> http://xahlee.org/p/titus/word_frequency.html
> 
> Then, i wrote a more elaborate one that recurse thru directories to
> work on elisp code treasury.
> 
> The code is here:
> http://xahlee.org/x/count_word_frequency.py
> 
> and i got a strange result. The word “the” appeared on the top,
> along with many other English words. I quickly realized that these are
> due to lisp function's doc strings. (not comments)

Would be interesting to see if the type-checking "The" in lisp is still 
frequent. I doubt.

> At this point, it dawned on me that there's no easy way to work around
> this, Unless, i write this script in elisp which has functions that
> read lisp code and can easily filter out doc strings.
> 
> Originally, i planned to use the word-frequency script on Perl, Python,
> as well as Java, as well as Elisp. However, now it seems to me this
> task is nigh impossible. Each of these lang has their own doc string
> syntax. It's gonna be a heavy undertaking if the word-frequency script
> is to work with all these langs, since that amounts to writing a parser
> for each lang.
> 
> Alternatively, one can write multiple word-frequency scripts using each
> lang in question, since most lang has facilities to deal with its own
> syntax. However, this is still not trivial, and amounts to several
> programing efforts.

Editor code (best maybe scintilla/sc1, check also emacs itself, ...) has 
libraries for colorizing comments in all kinds of programming langs ...

> Anyone would be interested in this problem?

I have a theory, that "bad source code" has more if/else/elif/case/switch 
dispatching statements per number of code words (lines..) than "good code" - 
independent of the language.

If you can count these ratio and correlate it to maybe a sf-ranking and to 
languages, that would be highly interesting for me... (in case drop a pointer 
in this thread / repeated subject)



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

Re: question about True values

2006-10-28 Thread Steven D'Aprano
On Sat, 28 Oct 2006 11:42:42 +0200, Marc 'BlackJack' Rintsch wrote:

> In <[EMAIL PROTECTED]>, Steven
> D'Aprano wrote:
> 
>> On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote:
>> 
>>> Iterators do have overlapping uses with lists, but the "if a:" doesn't
>>> work for them, so it's moot.
>> 
>> Sure it works for iterators.
>> 
> it = iter([0])
> bool(it)
>> True
> it.next()
>> 0
> bool(it)
>> False
> 
> It works for *this* iterator.  By accident.

Blimey, you're right. That can't be good.

In fact, it made a certain BDFL pretty mad:

http://mail.python.org/pipermail/python-dev/2005-September/056594.html

Okay, so all iterators are intentionally *supposed* to be True, always,
even if they are exhausted. As Guido says, don't treat iterators as
containers.

Fair enough.


-- 
Steven.

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


Re: Import if condition is correct

2006-10-28 Thread Steve Holden
MindClass wrote:
> Georg Brandl wrote:
> 
>>MindClass wrote:
>>
>>>Is possible import a library according to a condition?
>>>
>>>if Foo == True:
>>>import bar
>>>
>>
>>Why don't you try it?
>>
> 
> I thinked that could be another way for import statement.
> 
> In that case I'll have to set a global variable before of the import
> statements although I'd prefer not use them.
> 

I'm guessing that you think this might be necessary to avoid importing 
the same module multiple times: it's not. Python only runs the module's 
code the first time the module is imported into a program. A further 
import statement effectively does noting, because the interpreter sees 
(from an entry in the sys.modules dictionary) that the module is already 
present.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Arrays? (Or lists if you prefer)

2006-10-28 Thread Paul McGuire
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Paul McGuire wrote:
>> As an example of using pyparsing, I chose a simple text adventure
>> application, and had to create a 2-D grid of rooms.  The presentation
>> materials are online at http://www.python.org/pycon/2006/papers/4/, and 
>> the
>> source code is included with the examples that ship with pyparsing
>
> I read your entire thing, but how much stuck is a testimate to how much
> I have yet to learn. Also, I didn't see the source code or downoad or
> anything there. Where is it again?
>
> Thanks for the responces.
>

Download pyparsing at http://sourceforge.net/projects/pyparsing .  Be sure 
to download either the source installation or the doc installation - the 
windows binary install omits the doc and example files.

The pyparsing home page is at http://pyparsing.wikispaces.com.

-- Paul


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


Re: Import if condition is correct

2006-10-28 Thread MindClass

Georg Brandl wrote:
> MindClass wrote:
> > Is possible import a library according to a condition?
> >
> > if Foo == True:
> > import bar
> >
>
> Why don't you try it?
>
I thinked that could be another way for import statement.

In that case I'll have to set a global variable before of the import
statements although I'd prefer not use them.

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


Re: correct parameter usage for "select * where id in ..."

2006-10-28 Thread paul
Frank Millman schrieb:
> If you want it to handle a variable number of values, you will have to
> programmatically construct the sql statement with the appropriate
> number of parameters.
>>> vals = (1,2,3,4,5)
>>> sql = "select * from table where value in ("+','.join("?"*len(vals))+")"
>>> print sql
'select * from table where value in (?,?,?,?,?)'

cheers
 Paul

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


  1   2   >